1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Cache API interfaces
19 *
20 * This file is part of Moodle's cache API, affectionately called MUC.
21 * It contains the components that are requried in order to use caching.
22 *
23 * @package    core
24 * @category   cache
25 * @copyright  2012 Sam Hemelryk
26 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29defined('MOODLE_INTERNAL') || die();
30
31/**
32 * Cache Loader.
33 *
34 * This cache loader interface provides the required structure for classes that wish to be interacted with as a
35 * means of accessing and interacting with a cache.
36 *
37 * Can be implemented by any class wishing to be a cache loader.
38 */
39interface cache_loader {
40
41    /**
42     * Retrieves the value for the given key from the cache.
43     *
44     * @param string|int $key The key for the data being requested.
45     * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
46     * @return mixed The data retrieved from the cache, or false if the key did not exist within the cache.
47     *      If MUST_EXIST was used then an exception will be thrown if the key does not exist within the cache.
48     */
49    public function get($key, $strictness = IGNORE_MISSING);
50
51    /**
52     * Retrieves an array of values for an array of keys.
53     *
54     * Using this function comes with potential performance implications.
55     * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
56     * the equivalent singular method for each item provided.
57     * This should not deter you from using this function as there is a performance benefit in situations where the cache
58     * store does support it, but you should be aware of this fact.
59     *
60     * @param array $keys The keys of the data being requested.
61     * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
62     * @return array An array of key value pairs for the items that could be retrieved from the cache.
63     *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
64     *      Otherwise any key that did not exist will have a data value of false within the results.
65     */
66    public function get_many(array $keys, $strictness = IGNORE_MISSING);
67
68    /**
69     * Sends a key => value pair to the cache.
70     *
71     * <code>
72     * // This code will add four entries to the cache, one for each url.
73     * $cache->set('main', 'http://moodle.org');
74     * $cache->set('docs', 'http://docs.moodle.org');
75     * $cache->set('tracker', 'http://tracker.moodle.org');
76     * $cache->set('qa', 'http://qa.moodle.net');
77     * </code>
78     *
79     * @param string|int $key The key for the data being requested.
80     * @param mixed $data The data to set against the key.
81     * @return bool True on success, false otherwise.
82     */
83    public function set($key, $data);
84
85    /**
86     * Sends several key => value pairs to the cache.
87     *
88     * Using this function comes with potential performance implications.
89     * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
90     * the equivalent singular method for each item provided.
91     * This should not deter you from using this function as there is a performance benefit in situations where the cache store
92     * does support it, but you should be aware of this fact.
93     *
94     * <code>
95     * // This code will add four entries to the cache, one for each url.
96     * $cache->set_many(array(
97     *     'main' => 'http://moodle.org',
98     *     'docs' => 'http://docs.moodle.org',
99     *     'tracker' => 'http://tracker.moodle.org',
100     *     'qa' => ''http://qa.moodle.net'
101     * ));
102     * </code>
103     *
104     * @param array $keyvaluearray An array of key => value pairs to send to the cache.
105     * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
106     *      ... if they care that is.
107     */
108    public function set_many(array $keyvaluearray);
109
110    /**
111     * Test is a cache has a key.
112     *
113     * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
114     * test and any subsequent action (get, set, delete etc).
115     * Instead it is recommended to write your code in such a way they it performs the following steps:
116     * <ol>
117     * <li>Attempt to retrieve the information.</li>
118     * <li>Generate the information.</li>
119     * <li>Attempt to set the information</li>
120     * </ol>
121     *
122     * Its also worth mentioning that not all stores support key tests.
123     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
124     * Just one more reason you should not use these methods unless you have a very good reason to do so.
125     *
126     * @param string|int $key
127     * @return bool True if the cache has the requested key, false otherwise.
128     */
129    public function has($key);
130
131    /**
132     * Test if a cache has at least one of the given keys.
133     *
134     * It is strongly recommended to avoid the use of this function if not absolutely required.
135     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
136     *
137     * Its also worth mentioning that not all stores support key tests.
138     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
139     * Just one more reason you should not use these methods unless you have a very good reason to do so.
140     *
141     * @param array $keys
142     * @return bool True if the cache has at least one of the given keys
143     */
144    public function has_any(array $keys);
145
146    /**
147     * Test is a cache has all of the given keys.
148     *
149     * It is strongly recommended to avoid the use of this function if not absolutely required.
150     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
151     *
152     * Its also worth mentioning that not all stores support key tests.
153     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
154     * Just one more reason you should not use these methods unless you have a very good reason to do so.
155     *
156     * @param array $keys
157     * @return bool True if the cache has all of the given keys, false otherwise.
158     */
159    public function has_all(array $keys);
160
161    /**
162     * Delete the given key from the cache.
163     *
164     * @param string|int $key The key to delete.
165     * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
166     *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
167     * @return bool True of success, false otherwise.
168     */
169    public function delete($key, $recurse = true);
170
171    /**
172     * Delete all of the given keys from the cache.
173     *
174     * @param array $keys The key to delete.
175     * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
176     *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
177     * @return int The number of items successfully deleted.
178     */
179    public function delete_many(array $keys, $recurse = true);
180}
181
182/**
183 * Cache Loader supporting locking.
184 *
185 * This interface should be given to classes already implementing cache_loader that also wish to support locking.
186 * It outlines the required structure for utilising locking functionality when using a cache.
187 *
188 * Can be implemented by any class already implementing the cache_loader interface.
189 */
190interface cache_loader_with_locking {
191
192    /**
193     * Acquires a lock for the given key.
194     *
195     * Please note that this happens automatically if the cache definition requires locking.
196     * it is still made a public method so that adhoc caches can use it if they choose.
197     * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
198     * locks are acquired, checked, and released.
199     *
200     * @param string|int $key
201     * @return bool True if the lock could be acquired, false otherwise.
202     */
203    public function acquire_lock($key);
204
205    /**
206     * Checks if the cache loader owns the lock for the given key.
207     *
208     * Please note that this happens automatically if the cache definition requires locking.
209     * it is still made a public method so that adhoc caches can use it if they choose.
210     * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
211     * locks are acquired, checked, and released.
212     *
213     * @param string|int $key
214     * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it,
215     *      null if there is no lock.
216     */
217    public function check_lock_state($key);
218
219    /**
220     * Releases the lock for the given key.
221     *
222     * Please note that this happens automatically if the cache definition requires locking.
223     * it is still made a public method so that adhoc caches can use it if they choose.
224     * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
225     * locks are acquired, checked, and released.
226     *
227     * @param string|int $key
228     * @return bool True if the lock has been released, false if there was a problem releasing the lock.
229     */
230    public function release_lock($key);
231}
232
233/**
234 * Cache store feature: locking
235 *
236 * This is a feature that cache stores can implement if they wish to support locking themselves rather
237 * than having the cache loader handle it for them.
238 *
239 * Can be implemented by classes already implementing cache_store.
240 */
241interface cache_is_lockable {
242
243    /**
244     * Acquires a lock on the given key for the given identifier.
245     *
246     * @param string $key The key we are locking.
247     * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
248     *      The use of this property is entirely optional and implementations can act as they like upon it.
249     * @return bool True if the lock could be acquired, false otherwise.
250     */
251    public function acquire_lock($key, $ownerid);
252
253    /**
254     * Test if there is already a lock for the given key and if there is whether it belongs to the calling code.
255     *
256     * @param string $key The key we are locking.
257     * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
258     * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
259     *      is no lock.
260     */
261    public function check_lock_state($key, $ownerid);
262
263    /**
264     * Releases the lock on the given key.
265     *
266     * @param string $key The key we are locking.
267     * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
268     *      The use of this property is entirely optional and implementations can act as they like upon it.
269     * @return bool True if the lock has been released, false if there was a problem releasing the lock.
270     */
271    public function release_lock($key, $ownerid);
272}
273
274/**
275 * Cache store feature: key awareness.
276 *
277 * This is a feature that cache stores and cache loaders can both choose to implement.
278 * If a cache store implements this then it will be made responsible for tests for items within the cache.
279 * If the cache store being used doesn't implement this then it will be the responsibility of the cache loader to use the
280 * equivalent get methods to mimick the functionality of these tests.
281 *
282 * Cache stores should only override these methods if they natively support such features or if they have a better performing
283 * means of performing these tests than the handling that would otherwise take place in the cache_loader.
284 *
285 * Can be implemented by classes already implementing cache_store.
286 */
287interface cache_is_key_aware {
288
289    /**
290     * Test is a cache has a key.
291     *
292     * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
293     * test and any subsequent action (get, set, delete etc).
294     * Instead it is recommended to write your code in such a way they it performs the following steps:
295     * <ol>
296     * <li>Attempt to retrieve the information.</li>
297     * <li>Generate the information.</li>
298     * <li>Attempt to set the information</li>
299     * </ol>
300     *
301     * Its also worth mentioning that not all stores support key tests.
302     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
303     * Just one more reason you should not use these methods unless you have a very good reason to do so.
304     *
305     * @param string|int $key
306     * @return bool True if the cache has the requested key, false otherwise.
307     */
308    public function has($key);
309
310    /**
311     * Test if a cache has at least one of the given keys.
312     *
313     * It is strongly recommended to avoid the use of this function if not absolutely required.
314     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
315     *
316     * Its also worth mentioning that not all stores support key tests.
317     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
318     * Just one more reason you should not use these methods unless you have a very good reason to do so.
319     *
320     * @param array $keys
321     * @return bool True if the cache has at least one of the given keys
322     */
323    public function has_any(array $keys);
324
325    /**
326     * Test is a cache has all of the given keys.
327     *
328     * It is strongly recommended to avoid the use of this function if not absolutely required.
329     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
330     *
331     * Its also worth mentioning that not all stores support key tests.
332     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
333     * Just one more reason you should not use these methods unless you have a very good reason to do so.
334     *
335     * @param array $keys
336     * @return bool True if the cache has all of the given keys, false otherwise.
337     */
338    public function has_all(array $keys);
339}
340
341/**
342 * Cache store feature: keys are searchable.
343 *
344 * Cache stores can choose to implement this interface.
345 * In order for a store to be usable as a session cache it must implement this interface.
346 *
347 * @since Moodle 2.4.4
348 */
349interface cache_is_searchable {
350    /**
351     * Finds all of the keys being used by the cache store.
352     *
353     * @return array.
354     */
355    public function find_all();
356
357    /**
358     * Finds all of the keys whose keys start with the given prefix.
359     *
360     * @param string $prefix
361     */
362    public function find_by_prefix($prefix);
363}
364
365/**
366 * Cache store feature: configurable.
367 *
368 * This feature should be implemented by all cache stores that are configurable when adding an instance.
369 * It requires the implementation of methods required to convert form data into the a configuration array for the
370 * store instance, and then the reverse converting configuration data into an array that can be used to set the
371 * data for the edit form.
372 *
373 * Can be implemented by classes already implementing cache_store.
374 */
375interface cache_is_configurable {
376
377    /**
378     * Given the data from the add instance form this function creates a configuration array.
379     *
380     * @param stdClass $data
381     * @return array
382     */
383    public static function config_get_configuration_array($data);
384
385    /**
386     * Allows the cache store to set its data against the edit form before it is shown to the user.
387     *
388     * @param moodleform $editform
389     * @param array $config
390     */
391    public static function config_set_edit_form_data(moodleform $editform, array $config);
392}
393
394/**
395 * Cache Data Source.
396 *
397 * The cache data source interface can be implemented by any class within Moodle.
398 * If implemented then the class can be reference in a cache definition and will be used to load information that cannot be
399 * retrieved from the cache. As part of its retrieval that information will also be loaded into the cache.
400 *
401 * This allows developers to created a complete cache solution that can be used through code ensuring consistent cache
402 * interaction and loading. Allowing them in turn to centralise code and help keeps things more easily maintainable.
403 *
404 * Can be implemented by any class.
405 *
406 * @package    core
407 * @category   cache
408 * @copyright  2012 Sam Hemelryk
409 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
410 */
411interface cache_data_source {
412
413    /**
414     * Returns an instance of the data source class that the cache can use for loading data using the other methods
415     * specified by this interface.
416     *
417     * @param cache_definition $definition
418     * @return object
419     */
420    public static function get_instance_for_cache(cache_definition $definition);
421
422    /**
423     * Loads the data for the key provided ready formatted for caching.
424     *
425     * @param string|int $key The key to load.
426     * @return mixed What ever data should be returned, or false if it can't be loaded.
427     */
428    public function load_for_cache($key);
429
430    /**
431     * Loads several keys for the cache.
432     *
433     * @param array $keys An array of keys each of which will be string|int.
434     * @return array An array of matching data items.
435     */
436    public function load_many_for_cache(array $keys);
437}
438
439/**
440 * Cacheable object.
441 *
442 * This interface can be implemented by any class that is going to be passed into a cache and allows it to take control of the
443 * structure and the information about to be cached, as well as how to deal with it when it is retrieved from a cache.
444 * Think of it like serialisation and the __sleep and __wakeup methods.
445 * This is used because cache stores are responsible for how they interact with data and what they do when storing it. This
446 * interface ensures there is always a guaranteed action.
447 */
448interface cacheable_object {
449
450    /**
451     * Prepares the object for caching. Works like the __sleep method.
452     *
453     * @return mixed The data to cache, can be anything except a class that implements the cacheable_object... that would
454     *      be dumb.
455     */
456    public function prepare_to_cache();
457
458    /**
459     * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
460     *
461     * @param mixed $data
462     * @return object The instance for the given data.
463     */
464    public static function wake_from_cache($data);
465}
466
467/**
468 * Cache lock interface
469 *
470 * This interface needs to be inherited by all cache lock plugins.
471 */
472interface cache_lock_interface {
473    /**
474     * Constructs an instance of the cache lock given its name and its configuration data
475     *
476     * @param string $name The unique name of the lock instance
477     * @param array $configuration
478     */
479    public function __construct($name, array $configuration = array());
480
481    /**
482     * Acquires a lock on a given key.
483     *
484     * @param string $key The key to acquire a lock for.
485     * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
486     *      to use this. Each implementation can decide for themselves.
487     * @param bool $block If set to true the application will wait until a lock can be acquired
488     * @return bool True if the lock can be acquired false otherwise.
489     */
490    public function lock($key, $ownerid, $block = false);
491
492    /**
493     * Releases the lock held on a certain key.
494     *
495     * @param string $key The key to release the lock for.
496     * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
497     *      to use this. Each implementation can decide for themselves.
498     * @param bool $forceunlock If set to true the lock will be removed if it exists regardless of whether or not we own it.
499     */
500    public function unlock($key, $ownerid, $forceunlock = false);
501
502    /**
503     * Checks the state of the given key.
504     *
505     * Returns true if the key is locked and belongs to the ownerid.
506     * Returns false if the key is locked but does not belong to the ownerid.
507     * Returns null if there is no lock
508     *
509     * @param string $key The key we are checking for.
510     * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
511     * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
512     *      is no lock.
513     */
514    public function check_state($key, $ownerid);
515
516    /**
517     * Cleans up any left over locks.
518     *
519     * This function MUST clean up any locks that have been acquired and not released during processing.
520     * Although the situation of acquiring a lock and not releasing it should be insanely rare we need to deal with it.
521     * Things such as unfortunate timeouts etc could cause this situation.
522     */
523    public function __destruct();
524}