MDL-40903 cache: fixed up event invalidation
[moodle.git] / cache / classes / loaders.php
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/>.
17 /**
18  * Cache loaders
19  *
20  * This file is part of Moodle's cache API, affectionately called MUC.
21  * It contains the components that are required 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  */
29 defined('MOODLE_INTERNAL') || die();
31 /**
32  * The main cache class.
33  *
34  * This class if the first class that any end developer will interact with.
35  * In order to create an instance of a cache that they can work with they must call one of the static make methods belonging
36  * to this class.
37  *
38  * @package    core
39  * @category   cache
40  * @copyright  2012 Sam Hemelryk
41  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42  */
43 class cache implements cache_loader {
45     /**
46      * We need a timestamp to use within the cache API.
47      * This stamp needs to be used for all ttl and time based operations to ensure that we don't end up with
48      * timing issues.
49      * @var int
50      */
51     protected static $now;
53     /**
54      * The definition used when loading this cache if there was one.
55      * @var cache_definition
56      */
57     private $definition = false;
59     /**
60      * The cache store that this loader will make use of.
61      * @var cache_store
62      */
63     private $store;
65     /**
66      * The next cache loader in the chain if there is one.
67      * If a cache request misses for the store belonging to this loader then the loader
68      * stored here will be checked next.
69      * If there is a loader here then $datasource must be false.
70      * @var cache_loader|false
71      */
72     private $loader = false;
74     /**
75      * The data source to use if we need to load data (because if doesn't exist in the cache store).
76      * If there is a data source here then $loader above must be false.
77      * @var cache_data_source|false
78      */
79     private $datasource = false;
81     /**
82      * Used to quickly check if the store supports key awareness.
83      * This is set when the cache is initialised and is used to speed up processing.
84      * @var bool
85      */
86     private $supportskeyawareness = null;
88     /**
89      * Used to quickly check if the store supports ttl natively.
90      * This is set when the cache is initialised and is used to speed up processing.
91      * @var bool
92      */
93     private $supportsnativettl = null;
95     /**
96      * Gets set to true if the cache is going to be using the build in static "persist" cache.
97      * The persist cache statically caches items used during the lifetime of the request. This greatly speeds up interaction
98      * with the cache in areas where it will be repetitively hit for the same information such as with strings.
99      * There are several other variables to control how this persist cache works.
100      * @var bool
101      */
102     private $persistdata = false;
104     /**
105      * The persist cache itself.
106      * Items will be stored in this cache as they were provided. This ensure there is no unnecessary processing taking place.
107      * @var array
108      */
109     private $persistcache = array();
111     /**
112      * The number of items in the persist cache. Avoids count calls like you wouldn't believe.
113      * @var int
114      */
115     private $persistcount = 0;
117     /**
118      * An array containing just the keys being used in the persist cache.
119      * This seems redundant perhaps but is used when managing the size of the persist cache.
120      * Items are added to the end of the array and the when we need to reduce the size of the cache we use the
121      * key that is first on this array.
122      * @var array
123      */
124     private $persistkeys = array();
126     /**
127      * The maximum size of the persist cache. If set to false there is no max size.
128      * Caches that make use of the persist cache should seriously consider setting this to something reasonably small, but
129      * still large enough to offset repetitive calls.
130      * @var int|false
131      */
132     private $persistmaxsize = false;
134     /**
135      * Gets set to true during initialisation if the definition is making use of a ttl.
136      * Used to speed up processing.
137      * @var bool
138      */
139     private $hasattl = false;
141     /**
142      * Gets set to the class name of the store during initialisation. This is used several times in the cache class internally
143      * and having it here helps speed up processing.
144      * @var strubg
145      */
146     protected $storetype = 'unknown';
148     /**
149      * Gets set to true if we want to collect performance information about the cache API.
150      * @var bool
151      */
152     protected $perfdebug = false;
154     /**
155      * Determines if this loader is a sub loader, not the top of the chain.
156      * @var bool
157      */
158     protected $subloader = false;
160     /**
161      * Creates a new cache instance for a pre-defined definition.
162      *
163      * @param string $component The component for the definition
164      * @param string $area The area for the definition
165      * @param array $identifiers Any additional identifiers that should be provided to the definition.
166      * @param string $aggregate Super advanced feature. More docs later.
167      * @return cache_application|cache_session|cache_store
168      */
169     public static function make($component, $area, array $identifiers = array(), $aggregate = null) {
170         $factory = cache_factory::instance();
171         return $factory->create_cache_from_definition($component, $area, $identifiers, $aggregate);
172     }
174     /**
175      * Creates a new cache instance based upon the given params.
176      *
177      * @param int $mode One of cache_store::MODE_*
178      * @param string $component The component this cache relates to.
179      * @param string $area The area this cache relates to.
180      * @param array $identifiers Any additional identifiers that should be provided to the definition.
181      * @param array $options An array of options, available options are:
182      *   - simplekeys : Set to true if the keys you will use are a-zA-Z0-9_
183      *   - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
184      *   - persistent : If set to true the cache will persist construction requests.
185      * @return cache_application|cache_session|cache_store
186      */
187     public static function make_from_params($mode, $component, $area, array $identifiers = array(), array $options = array()) {
188         $factory = cache_factory::instance();
189         return $factory->create_cache_from_params($mode, $component, $area, $identifiers, $options);
190     }
192     /**
193      * Constructs a new cache instance.
194      *
195      * You should not call this method from your code, instead you should use the cache::make methods.
196      *
197      * This method is public so that the cache_factory is able to instantiate cache instances.
198      * Ideally we would make this method protected and expose its construction to the factory method internally somehow.
199      * The factory class is responsible for this in order to centralise the storage of instances once created. This way if needed
200      * we can force a reset of the cache API (used during unit testing).
201      *
202      * @param cache_definition $definition The definition for the cache instance.
203      * @param cache_store $store The store that cache should use.
204      * @param cache_loader|cache_data_source $loader The next loader in the chain or the data source if there is one and there
205      *      are no other cache_loaders in the chain.
206      */
207     public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
208         global $CFG;
209         $this->definition = $definition;
210         $this->store = $store;
211         $this->storetype = get_class($store);
212         $this->perfdebug = !empty($CFG->perfdebug);
213         if ($loader instanceof cache_loader) {
214             $this->loader = $loader;
215             // Mark the loader as a sub (chained) loader.
216             $this->loader->set_is_sub_loader(true);
217         } else if ($loader instanceof cache_data_source) {
218             $this->datasource = $loader;
219         }
220         $this->definition->generate_definition_hash();
221         $this->persistdata = $this->definition->data_should_be_persistent();
222         if ($this->persistdata) {
223             $this->persistmaxsize = $this->definition->get_persistent_max_size();
224         }
225         $this->hasattl = ($this->definition->get_ttl() > 0);
226     }
228     /**
229      * Used to inform the loader of its state as a sub loader, or as the top of the chain.
230      *
231      * This is important as it ensures that we do not have more than one loader keeping persistent data.
232      * Subloaders need to be "pure" loaders in the sense that they are used to store and retrieve information from stores or the
233      * next loader/data source in the chain.
234      * Nothing fancy, nothing flash.
235      *
236      * @param bool $setting
237      */
238     protected function set_is_sub_loader($setting = true) {
239         if ($setting) {
240             $this->subloader = true;
241             // Subloaders should not keep persistent data.
242             $this->persistdata = false;
243             $this->persistmaxsize = false;
244         } else {
245             $this->subloader = true;
246             $this->persistdata = $this->definition->data_should_be_persistent();
247             if ($this->persistdata) {
248                 $this->persistmaxsize = $this->definition->get_persistent_max_size();
249             }
250         }
251     }
253     /**
254      * Alters the identifiers that have been provided to the definition.
255      *
256      * This is an advanced method and should not be used unless really needed.
257      * It allows the developer to slightly alter the definition without having to re-establish the cache.
258      * It will cause more processing as the definition will need to clear and reprepare some of its properties.
259      *
260      * @param array $identifiers
261      */
262     public function set_identifiers(array $identifiers) {
263         $this->definition->set_identifiers($identifiers);
264     }
266     /**
267      * Retrieves the value for the given key from the cache.
268      *
269      * @param string|int $key The key for the data being requested.
270      *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
271      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
272      * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
273      * @return mixed|false The data from the cache or false if the key did not exist within the cache.
274      * @throws coding_exception
275      */
276     public function get($key, $strictness = IGNORE_MISSING) {
277         // 1. Parse the key.
278         $parsedkey = $this->parse_key($key);
279         // 2. Get it from the persist cache if we can (only when persist is enabled and it has already been requested/set).
280         $result = false;
281         if ($this->is_using_persist_cache()) {
282             $result = $this->get_from_persist_cache($parsedkey);
283         }
284         if ($result !== false) {
285             if (!is_scalar($result)) {
286                 // If data is an object it will be a reference.
287                 // If data is an array if may contain references.
288                 // We want to break references so that the cache cannot be modified outside of itself.
289                 // Call the function to unreference it (in the best way possible).
290                 $result = $this->unref($result);
291             }
292             return $result;
293         }
294         // 3. Get it from the store. Obviously wasn't in the persist cache.
295         $result = $this->store->get($parsedkey);
296         if ($result !== false) {
297             if ($result instanceof cache_ttl_wrapper) {
298                 if ($result->has_expired()) {
299                     $this->store->delete($parsedkey);
300                     $result = false;
301                 } else {
302                     $result = $result->data;
303                 }
304             }
305             if ($result instanceof cache_cached_object) {
306                 $result = $result->restore_object();
307             }
308             if ($this->is_using_persist_cache()) {
309                 $this->set_in_persist_cache($parsedkey, $result);
310             }
311         }
312         // 4. Load if from the loader/datasource if we don't already have it.
313         $setaftervalidation = false;
314         if ($result === false) {
315             if ($this->perfdebug) {
316                 cache_helper::record_cache_miss($this->storetype, $this->definition->get_id());
317             }
318             if ($this->loader !== false) {
319                 // We must pass the original (unparsed) key to the next loader in the chain.
320                 // The next loader will parse the key as it sees fit. It may be parsed differently
321                 // depending upon the capabilities of the store associated with the loader.
322                 $result = $this->loader->get($key);
323             } else if ($this->datasource !== false) {
324                 $result = $this->datasource->load_for_cache($key);
325             }
326             $setaftervalidation = ($result !== false);
327         } else if ($this->perfdebug) {
328             cache_helper::record_cache_hit($this->storetype, $this->definition->get_id());
329         }
330         // 5. Validate strictness.
331         if ($strictness === MUST_EXIST && $result === false) {
332             throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
333         }
334         // 6. Set it to the store if we got it from the loader/datasource.
335         if ($setaftervalidation) {
336             $this->set($key, $result);
337         }
338         // 7. Make sure we don't pass back anything that could be a reference.
339         //    We don't want people modifying the data in the cache.
340         if (!is_scalar($result)) {
341             // If data is an object it will be a reference.
342             // If data is an array if may contain references.
343             // We want to break references so that the cache cannot be modified outside of itself.
344             // Call the function to unreference it (in the best way possible).
345             $result = $this->unref($result);
346         }
347         return $result;
348     }
350     /**
351      * Retrieves an array of values for an array of keys.
352      *
353      * Using this function comes with potential performance implications.
354      * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
355      * the equivalent singular method for each item provided.
356      * This should not deter you from using this function as there is a performance benefit in situations where the cache store
357      * does support it, but you should be aware of this fact.
358      *
359      * @param array $keys The keys of the data being requested.
360      *      Each key can be any structure although using a scalar string or int is recommended in the interests of performance.
361      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
362      * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
363      * @return array An array of key value pairs for the items that could be retrieved from the cache.
364      *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
365      *      Otherwise any key that did not exist will have a data value of false within the results.
366      * @throws coding_exception
367      */
368     public function get_many(array $keys, $strictness = IGNORE_MISSING) {
370         $keysparsed = array();
371         $parsedkeys = array();
372         $resultpersist = array();
373         $resultstore = array();
374         $keystofind = array();
376         // First up check the persist cache for each key.
377         $isusingpersist = $this->is_using_persist_cache();
378         foreach ($keys as $key) {
379             $pkey = $this->parse_key($key);
380             $keysparsed[$key] = $pkey;
381             $parsedkeys[$pkey] = $key;
382             $keystofind[$pkey] = $key;
383             if ($isusingpersist) {
384                 $value = $this->get_from_persist_cache($pkey);
385                 if ($value !== false) {
386                     $resultpersist[$pkey] = $value;
387                     unset($keystofind[$pkey]);
388                 }
389             }
390         }
392         // Next assuming we didn't find all of the keys in the persist cache try loading them from the store.
393         if (count($keystofind)) {
394             $resultstore = $this->store->get_many(array_keys($keystofind));
395             // Process each item in the result to "unwrap" it.
396             foreach ($resultstore as $key => $value) {
397                 if ($value instanceof cache_ttl_wrapper) {
398                     if ($value->has_expired()) {
399                         $value = false;
400                     } else {
401                         $value = $value->data;
402                     }
403                 }
404                 if ($value instanceof cache_cached_object) {
405                     $value = $value->restore_object();
406                 }
407                 if ($value !== false && $this->is_using_persist_cache()) {
408                     $this->set_in_persist_cache($key, $value);
409                 }
410                 $resultstore[$key] = $value;
411             }
412         }
414         // Merge the result from the persis cache with the results from the store load.
415         $result = $resultpersist + $resultstore;
416         unset($resultpersist);
417         unset($resultstore);
419         // Next we need to find any missing values and load them from the loader/datasource next in the chain.
420         $usingloader = ($this->loader !== false);
421         $usingsource = (!$usingloader && ($this->datasource !== false));
422         if ($usingloader || $usingsource) {
423             $missingkeys = array();
424             foreach ($result as $key => $value) {
425                 if ($value === false) {
426                     $missingkeys[] = $parsedkeys[$key];
427                 }
428             }
429             if (!empty($missingkeys)) {
430                 if ($usingloader) {
431                     $resultmissing = $this->loader->get_many($missingkeys);
432                 } else {
433                     $resultmissing = $this->datasource->load_many_for_cache($missingkeys);
434                 }
435                 foreach ($resultmissing as $key => $value) {
436                     $result[$keysparsed[$key]] = $value;
437                     if ($value !== false) {
438                         $this->set($key, $value);
439                     }
440                 }
441                 unset($resultmissing);
442             }
443             unset($missingkeys);
444         }
446         // Create an array with the original keys and the found values. This will be what we return.
447         $fullresult = array();
448         foreach ($result as $key => $value) {
449             $fullresult[$parsedkeys[$key]] = $value;
450         }
451         unset($result);
453         // Final step is to check strictness.
454         if ($strictness === MUST_EXIST) {
455             foreach ($keys as $key) {
456                 if (!array_key_exists($key, $fullresult)) {
457                     throw new coding_exception('Not all the requested keys existed within the cache stores.');
458                 }
459             }
460         }
462         // Return the result. Phew!
463         return $fullresult;
464     }
466     /**
467      * Sends a key => value pair to the cache.
468      *
469      * <code>
470      * // This code will add four entries to the cache, one for each url.
471      * $cache->set('main', 'http://moodle.org');
472      * $cache->set('docs', 'http://docs.moodle.org');
473      * $cache->set('tracker', 'http://tracker.moodle.org');
474      * $cache->set('qa', 'http://qa.moodle.net');
475      * </code>
476      *
477      * @param string|int $key The key for the data being requested.
478      *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
479      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
480      * @param mixed $data The data to set against the key.
481      * @return bool True on success, false otherwise.
482      */
483     public function set($key, $data) {
484         if ($this->perfdebug) {
485             cache_helper::record_cache_set($this->storetype, $this->definition->get_id());
486         }
487         if ($this->loader !== false) {
488             // We have a loader available set it there as well.
489             // We have to let the loader do its own parsing of data as it may be unique.
490             $this->loader->set($key, $data);
491         }
492         if (is_object($data) && $data instanceof cacheable_object) {
493             $data = new cache_cached_object($data);
494         } else if (!is_scalar($data)) {
495             // If data is an object it will be a reference.
496             // If data is an array if may contain references.
497             // We want to break references so that the cache cannot be modified outside of itself.
498             // Call the function to unreference it (in the best way possible).
499             $data = $this->unref($data);
500         }
501         if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
502             $data = new cache_ttl_wrapper($data, $this->definition->get_ttl());
503         }
504         $parsedkey = $this->parse_key($key);
505         if ($this->is_using_persist_cache()) {
506             $this->set_in_persist_cache($parsedkey, $data);
507         }
508         return $this->store->set($parsedkey, $data);
509     }
511     /**
512      * Removes references where required.
513      *
514      * @param stdClass|array $data
515      * @return mixed What ever was put in but without any references.
516      */
517     protected function unref($data) {
518         if ($this->definition->uses_simple_data()) {
519             return $data;
520         }
521         // Check if it requires serialisation in order to produce a reference free copy.
522         if ($this->requires_serialisation($data)) {
523             // Damn, its going to have to be serialise.
524             $data = serialize($data);
525             // We unserialise immediately so that we don't have to do it every time on get.
526             $data = unserialize($data);
527         } else if (!is_scalar($data)) {
528             // Its safe to clone, lets do it, its going to beat the pants of serialisation.
529             $data = $this->deep_clone($data);
530         }
531         return $data;
532     }
534     /**
535      * Checks to see if a var requires serialisation.
536      *
537      * @param mixed $value The value to check.
538      * @param int $depth Used to ensure we don't enter an endless loop (think recursion).
539      * @return bool Returns true if the value is going to require serialisation in order to ensure a reference free copy
540      *      or false if its safe to clone.
541      */
542     protected function requires_serialisation($value, $depth = 1) {
543         if (is_scalar($value)) {
544             return false;
545         } else if (is_array($value) || $value instanceof stdClass || $value instanceof Traversable) {
546             if ($depth > 5) {
547                 // Skrew it, mega-deep object, developer you suck, we're just going to serialise.
548                 return true;
549             }
550             foreach ($value as $key => $subvalue) {
551                 if ($this->requires_serialisation($subvalue, $depth++)) {
552                     return true;
553                 }
554             }
555         }
556         // Its not scalar, array, or stdClass so we'll need to serialise.
557         return true;
558     }
560     /**
561      * Creates a reference free clone of the given value.
562      *
563      * @param mixed $value
564      * @return mixed
565      */
566     protected function deep_clone($value) {
567         if (is_object($value)) {
568             // Objects must be cloned to begin with.
569             $value = clone $value;
570         }
571         if (is_array($value) || is_object($value)) {
572             foreach ($value as $key => $subvalue) {
573                 $value[$key] = $this->deep_clone($subvalue);
574             }
575         }
576         return $value;
577     }
579     /**
580      * Sends several key => value pairs to the cache.
581      *
582      * Using this function comes with potential performance implications.
583      * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
584      * the equivalent singular method for each item provided.
585      * This should not deter you from using this function as there is a performance benefit in situations where the cache store
586      * does support it, but you should be aware of this fact.
587      *
588      * <code>
589      * // This code will add four entries to the cache, one for each url.
590      * $cache->set_many(array(
591      *     'main' => 'http://moodle.org',
592      *     'docs' => 'http://docs.moodle.org',
593      *     'tracker' => 'http://tracker.moodle.org',
594      *     'qa' => ''http://qa.moodle.net'
595      * ));
596      * </code>
597      *
598      * @param array $keyvaluearray An array of key => value pairs to send to the cache.
599      * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
600      *      ... if they care that is.
601      */
602     public function set_many(array $keyvaluearray) {
603         if ($this->loader !== false) {
604             // We have a loader available set it there as well.
605             // We have to let the loader do its own parsing of data as it may be unique.
606             $this->loader->set_many($keyvaluearray);
607         }
608         $data = array();
609         $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
610         $usepersistcache = $this->is_using_persist_cache();
611         foreach ($keyvaluearray as $key => $value) {
612             if (is_object($value) && $value instanceof cacheable_object) {
613                 $value = new cache_cached_object($value);
614             } else if (!is_scalar($value)) {
615                 // If data is an object it will be a reference.
616                 // If data is an array if may contain references.
617                 // We want to break references so that the cache cannot be modified outside of itself.
618                 // Call the function to unreference it (in the best way possible).
619                 $value = $this->unref($value);
620             }
621             if ($simulatettl) {
622                 $value = new cache_ttl_wrapper($value, $this->definition->get_ttl());
623             }
624             $data[$key] = array(
625                 'key' => $this->parse_key($key),
626                 'value' => $value
627             );
628             if ($usepersistcache) {
629                 $this->set_in_persist_cache($data[$key]['key'], $value);
630             }
631         }
632         if ($this->perfdebug) {
633             cache_helper::record_cache_set($this->storetype, $this->definition->get_id());
634         }
635         return $this->store->set_many($data);
636     }
638     /**
639      * Test is a cache has a key.
640      *
641      * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
642      * test and any subsequent action (get, set, delete etc).
643      * Instead it is recommended to write your code in such a way they it performs the following steps:
644      * <ol>
645      * <li>Attempt to retrieve the information.</li>
646      * <li>Generate the information.</li>
647      * <li>Attempt to set the information</li>
648      * </ol>
649      *
650      * Its also worth mentioning that not all stores support key tests.
651      * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
652      * Just one more reason you should not use these methods unless you have a very good reason to do so.
653      *
654      * @param string|int $key
655      * @param bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
656      *      data source then the code will try load the key value from the next item in the chain.
657      * @return bool True if the cache has the requested key, false otherwise.
658      */
659     public function has($key, $tryloadifpossible = false) {
660         $parsedkey = $this->parse_key($key);
661         if ($this->is_in_persist_cache($parsedkey)) {
662             // Hoorah, that was easy. It exists in the persist cache so we definitely have it.
663             return true;
664         }
665         if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
666             // The data has a TTL and the store doesn't support it natively.
667             // We must fetch the data and expect a ttl wrapper.
668             $data = $this->store->get($parsedkey);
669             $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
670         } else if (!$this->store_supports_key_awareness()) {
671             // The store doesn't support key awareness, get the data and check it manually... puke.
672             // Either no TTL is set of the store supports its handling natively.
673             $data = $this->store->get($parsedkey);
674             $has = ($data !== false);
675         } else {
676             // The store supports key awareness, this is easy!
677             // Either no TTL is set of the store supports its handling natively.
678             $has = $this->store->has($parsedkey);
679         }
680         if (!$has && $tryloadifpossible) {
681             if ($this->loader !== false) {
682                 $result = $this->loader->get($parsedkey);
683             } else if ($this->datasource !== null) {
684                 $result = $this->datasource->load_for_cache($key);
685             }
686             $has = ($result !== null);
687             if ($has) {
688                 $this->set($key, $result);
689             }
690         }
691         return $has;
692     }
694     /**
695      * Test is a cache has all of the given keys.
696      *
697      * It is strongly recommended to avoid the use of this function if not absolutely required.
698      * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
699      *
700      * Its also worth mentioning that not all stores support key tests.
701      * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
702      * Just one more reason you should not use these methods unless you have a very good reason to do so.
703      *
704      * @param array $keys
705      * @return bool True if the cache has all of the given keys, false otherwise.
706      */
707     public function has_all(array $keys) {
708         if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
709             foreach ($keys as $key) {
710                 if (!$this->has($key)) {
711                     return false;
712                 }
713             }
714             return true;
715         }
716         $parsedkeys = array_map(array($this, 'parse_key'), $keys);
717         return $this->store->has_all($parsedkeys);
718     }
720     /**
721      * Test if a cache has at least one of the given keys.
722      *
723      * It is strongly recommended to avoid the use of this function if not absolutely required.
724      * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
725      *
726      * Its also worth mentioning that not all stores support key tests.
727      * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
728      * Just one more reason you should not use these methods unless you have a very good reason to do so.
729      *
730      * @param array $keys
731      * @return bool True if the cache has at least one of the given keys
732      */
733     public function has_any(array $keys) {
734         if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
735             foreach ($keys as $key) {
736                 if ($this->has($key)) {
737                     return true;
738                 }
739             }
740             return false;
741         }
743         if ($this->is_using_persist_cache()) {
744             $parsedkeys = array();
745             foreach ($keys as $id => $key) {
746                 $parsedkey = $this->parse_key($key);
747                 if ($this->is_in_persist_cache($parsedkey)) {
748                     return true;
749                 }
750                 $parsedkeys[] = $parsedkey;
751             }
752         } else {
753             $parsedkeys = array_map(array($this, 'parse_key'), $keys);
754         }
755         return $this->store->has_any($parsedkeys);
756     }
758     /**
759      * Delete the given key from the cache.
760      *
761      * @param string|int $key The key to delete.
762      * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
763      *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
764      * @return bool True of success, false otherwise.
765      */
766     public function delete($key, $recurse = true) {
767         $parsedkey = $this->parse_key($key);
768         $this->delete_from_persist_cache($parsedkey);
769         if ($recurse && $this->loader !== false) {
770             // Delete from the bottom of the stack first.
771             $this->loader->delete($key, $recurse);
772         }
773         return $this->store->delete($parsedkey);
774     }
776     /**
777      * Delete all of the given keys from the cache.
778      *
779      * @param array $keys The key to delete.
780      * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
781      *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
782      * @return int The number of items successfully deleted.
783      */
784     public function delete_many(array $keys, $recurse = true) {
785         $parsedkeys = array_map(array($this, 'parse_key'), $keys);
786         if ($this->is_using_persist_cache()) {
787             foreach ($parsedkeys as $parsedkey) {
788                 $this->delete_from_persist_cache($parsedkey);
789             }
790         }
791         if ($recurse && $this->loader !== false) {
792             // Delete from the bottom of the stack first.
793             $this->loader->delete_many($keys, $recurse);
794         }
795         return $this->store->delete_many($parsedkeys);
796     }
798     /**
799      * Purges the cache store, and loader if there is one.
800      *
801      * @return bool True on success, false otherwise
802      */
803     public function purge() {
804         // 1. Purge the persist cache.
805         $this->persistcache = array();
806         if ($this->persistmaxsize !== false) {
807             $this->persistkeys = array();
808             $this->persistcount = 0;
809         }
810         // 2. Purge the store.
811         $this->store->purge();
812         // 3. Optionally pruge any stacked loaders.
813         if ($this->loader) {
814             $this->loader->purge();
815         }
816         return true;
817     }
819     /**
820      * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
821      *
822      * @param string|int $key As passed to get|set|delete etc.
823      * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
824      */
825     protected function parse_key($key) {
826         // First up if the store supports multiple keys we'll go with that.
827         if ($this->store->supports_multiple_identifiers()) {
828             $result = $this->definition->generate_multi_key_parts();
829             $result['key'] = $key;
830             return $result;
831         }
832         // If not we need to generate a hash and to for that we use the cache_helper.
833         return cache_helper::hash_key($key, $this->definition);
834     }
836     /**
837      * Returns true if the cache is making use of a ttl.
838      * @return bool
839      */
840     protected function has_a_ttl() {
841         return $this->hasattl;
842     }
844     /**
845      * Returns true if the cache store supports native ttl.
846      * @return bool
847      */
848     protected function store_supports_native_ttl() {
849         if ($this->supportsnativettl === null) {
850             $this->supportsnativettl = ($this->store->supports_native_ttl());
851         }
852         return $this->supportsnativettl;
853     }
855     /**
856      * Returns the cache definition.
857      *
858      * @return cache_definition
859      */
860     protected function get_definition() {
861         return $this->definition;
862     }
864     /**
865      * Returns the cache store
866      *
867      * @return cache_store
868      */
869     protected function get_store() {
870         return $this->store;
871     }
873     /**
874      * Returns the loader associated with this instance.
875      *
876      * @since 2.4.4
877      * @return cache|false
878      */
879     protected function get_loader() {
880         return $this->loader;
881     }
883     /**
884      * Returns the data source associated with this cache.
885      *
886      * @since 2.4.4
887      * @return cache_data_source|false
888      */
889     protected function get_datasource() {
890         return $this->datasource;
891     }
893     /**
894      * Returns true if the store supports key awareness.
895      *
896      * @return bool
897      */
898     protected function store_supports_key_awareness() {
899         if ($this->supportskeyawareness === null) {
900             $this->supportskeyawareness = ($this->store instanceof cache_is_key_aware);
901         }
902         return $this->supportskeyawareness;
903     }
905     /**
906      * Returns true if the store natively supports locking.
907      *
908      * @return bool
909      */
910     protected function store_supports_native_locking() {
911         if ($this->nativelocking === null) {
912             $this->nativelocking = ($this->store instanceof cache_is_lockable);
913         }
914         return $this->nativelocking;
915     }
917     /**
918      * Returns true if this cache is making use of the persist cache.
919      *
920      * @return bool
921      */
922     protected function is_using_persist_cache() {
923         return $this->persistdata;
924     }
926     /**
927      * Returns true if the requested key exists within the persist cache.
928      *
929      * @param string $key The parsed key
930      * @return bool
931      */
932     protected function is_in_persist_cache($key) {
933         // This method of checking if an array was supplied is faster than is_array.
934         if ($key === (array)$key) {
935             $key = $key['key'];
936         }
937         // This could be written as a single line, however it has been split because the ttl check is faster than the instanceof
938         // and has_expired calls.
939         if (!$this->persistdata || !array_key_exists($key, $this->persistcache)) {
940             return false;
941         }
942         if ($this->has_a_ttl() && $this->store_supports_native_ttl()) {
943              return !($this->persistcache[$key] instanceof cache_ttl_wrapper && $this->persistcache[$key]->has_expired());
944         }
945         return true;
946     }
948     /**
949      * Returns the item from the persist cache if it exists there.
950      *
951      * @param string $key The parsed key
952      * @return mixed|false The data from the persist cache or false if it wasn't there.
953      */
954     protected function get_from_persist_cache($key) {
955         // This method of checking if an array was supplied is faster than is_array.
956         if ($key === (array)$key) {
957             $key = $key['key'];
958         }
959         // This isset check is faster than array_key_exists but will return false
960         // for null values, meaning null values will come from backing store not
961         // the persist cache. We think this okay because null usage should be
962         // very rare (see comment in MDL-39472).
963         if (!$this->persistdata || !isset($this->persistcache[$key])) {
964             $result = false;
965         } else {
966             $data = $this->persistcache[$key];
967             if (!$this->has_a_ttl() || !$data instanceof cache_ttl_wrapper) {
968                 if ($data instanceof cache_cached_object) {
969                     $data = $data->restore_object();
970                 }
971                 $result = $data;
972             } else if ($data->has_expired()) {
973                 $this->delete_from_persist_cache($key);
974                 $result = false;
975             } else {
976                 if ($data instanceof cache_cached_object) {
977                     $data = $data->restore_object();
978                 }
979                 $result = $data->data;
980             }
981         }
982         if ($result) {
983             if ($this->perfdebug) {
984                 cache_helper::record_cache_hit('** static persist **', $this->definition->get_id());
985             }
986             if ($this->persistmaxsize > 1 && $this->persistcount > 1) {
987                 // Check to see if this is the last item on the persist keys array.
988                 if (end($this->persistkeys) !== $key) {
989                     // It isn't the last item.
990                     // Move the item to the end of the array so that it is last to be removed.
991                     unset($this->persistkeys[$key]);
992                     $this->persistkeys[$key] = $key;
993                 }
994             }
995             return $result;
996         } else {
997             if ($this->perfdebug) {
998                 cache_helper::record_cache_miss('** static persist **', $this->definition->get_id());
999             }
1000             return false;
1001         }
1002     }
1004     /**
1005      * Sets a key value pair into the persist cache.
1006      *
1007      * @param string $key The parsed key
1008      * @param mixed $data
1009      * @return bool
1010      */
1011     protected function set_in_persist_cache($key, $data) {
1012         // This method of checking if an array was supplied is faster than is_array.
1013         if ($key === (array)$key) {
1014             $key = $key['key'];
1015         }
1016         if ($this->persistmaxsize !== false && isset($this->persistkeys[$key])) {
1017             $this->persistcount--;
1018             unset($this->persistkeys[$key]);
1019         }
1020         $this->persistcache[$key] = $data;
1021         if ($this->persistmaxsize !== false) {
1022             $this->persistcount++;
1023             $this->persistkeys[$key] = $key;
1024             if ($this->persistcount > $this->persistmaxsize) {
1025                 $dropkey = array_shift($this->persistkeys);
1026                 unset($this->persistcache[$dropkey]);
1027                 $this->persistcount--;
1028             }
1029         }
1030         return true;
1031     }
1033     /**
1034      * Deletes an item from the persist cache.
1035      *
1036      * @param string|int $key As given to get|set|delete
1037      * @return bool True on success, false otherwise.
1038      */
1039     protected function delete_from_persist_cache($key) {
1040         unset($this->persistcache[$key]);
1041         if ($this->persistmaxsize !== false) {
1042             $dropkey = array_search($key, $this->persistkeys);
1043             if ($dropkey) {
1044                 unset($this->persistkeys[$dropkey]);
1045                 $this->persistcount--;
1046             }
1047         }
1048         return true;
1049     }
1051     /**
1052      * Returns the timestamp from the first request for the time from the cache API.
1053      *
1054      * This stamp needs to be used for all ttl and time based operations to ensure that we don't end up with
1055      * timing issues.
1056      *
1057      * @return int
1058      */
1059     public static function now() {
1060         if (self::$now === null) {
1061             self::$now = time();
1062         }
1063         return self::$now;
1064     }
1067 /**
1068  * An application cache.
1069  *
1070  * This class is used for application caches returned by the cache::make methods.
1071  * On top of the standard functionality it also allows locking to be required and or manually operated.
1072  *
1073  * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
1074  * It is technically possible to call those methods through this class however there is no guarantee that you will get an
1075  * instance of this class back again.
1076  *
1077  * @internal don't use me directly.
1078  *
1079  * @package    core
1080  * @category   cache
1081  * @copyright  2012 Sam Hemelryk
1082  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1083  */
1084 class cache_application extends cache implements cache_loader_with_locking {
1086     /**
1087      * Lock identifier.
1088      * This is used to ensure the lock belongs to the cache instance + definition + user.
1089      * @var string
1090      */
1091     protected $lockidentifier;
1093     /**
1094      * Gets set to true if the cache's primary store natively supports locking.
1095      * If it does then we use that, otherwise we need to instantiate a second store to use for locking.
1096      * @var cache_store
1097      */
1098     protected $nativelocking = null;
1100     /**
1101      * Gets set to true if the cache is going to be using locking.
1102      * This isn't a requirement, it doesn't need to use locking (most won't) and this bool is used to quickly check things.
1103      * If required then locking will be forced for the get|set|delete operation.
1104      * @var bool
1105      */
1106     protected $requirelocking = false;
1108     /**
1109      * Gets set to true if the cache must use read locking (get|has).
1110      * @var bool
1111      */
1112     protected $requirelockingread = false;
1114     /**
1115      * Gets set to true if the cache must use write locking (set|delete)
1116      * @var bool
1117      */
1118     protected $requirelockingwrite = false;
1120     /**
1121      * Gets set to a cache_store to use for locking if the caches primary store doesn't support locking natively.
1122      * @var cache_lock_interface
1123      */
1124     protected $cachelockinstance;
1126     /**
1127      * Overrides the cache construct method.
1128      *
1129      * You should not call this method from your code, instead you should use the cache::make methods.
1130      *
1131      * @param cache_definition $definition
1132      * @param cache_store $store
1133      * @param cache_loader|cache_data_source $loader
1134      */
1135     public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
1136         parent::__construct($definition, $store, $loader);
1137         $this->nativelocking = $this->store_supports_native_locking();
1138         if ($definition->require_locking()) {
1139             $this->requirelocking = true;
1140             $this->requirelockingread = $definition->require_locking_read();
1141             $this->requirelockingwrite = $definition->require_locking_write();
1142         }
1144         if ($definition->has_invalidation_events()) {
1145             $lastinvalidation = $this->get('lastinvalidation');
1146             if ($lastinvalidation === false) {
1147                 // This is a new session, there won't be anything to invalidate. Set the time of the last invalidation and
1148                 // move on.
1149                 $this->set('lastinvalidation', cache::now());
1150                 return;
1151             } else if ($lastinvalidation == cache::now()) {
1152                 // We've already invalidated during this request.
1153                 return;
1154             }
1156             // Get the event invalidation cache.
1157             $cache = cache::make('core', 'eventinvalidation');
1158             $events = $cache->get_many($definition->get_invalidation_events());
1159             $todelete = array();
1160             $purgeall = false;
1161             // Iterate the returned data for the events.
1162             foreach ($events as $event => $keys) {
1163                 if ($keys === false) {
1164                     // No data to be invalidated yet.
1165                     continue;
1166                 }
1167                 // Look at each key and check the timestamp.
1168                 foreach ($keys as $key => $timestamp) {
1169                     // If the timestamp of the event is more than or equal to the last invalidation (happened between the last
1170                     // invalidation and now)then we need to invaliate the key.
1171                     if ($timestamp >= $lastinvalidation) {
1172                         if ($key === 'purged') {
1173                             $purgeall = true;
1174                             break;
1175                         } else {
1176                             $todelete[] = $key;
1177                         }
1178                     }
1179                 }
1180             }
1181             if ($purgeall) {
1182                 $this->purge();
1183             } else if (!empty($todelete)) {
1184                 $todelete = array_unique($todelete);
1185                 $this->delete_many($todelete);
1186             }
1187             // Set the time of the last invalidation.
1188             $this->set('lastinvalidation', cache::now());
1189         }
1190     }
1192     /**
1193      * Returns the identifier to use
1194      *
1195      * @staticvar int $instances Counts the number of instances. Used as part of the lock identifier.
1196      * @return string
1197      */
1198     public function get_identifier() {
1199         static $instances = 0;
1200         if ($this->lockidentifier === null) {
1201             $this->lockidentifier = md5(
1202                 $this->get_definition()->generate_definition_hash() .
1203                 sesskey() .
1204                 $instances++ .
1205                 'cache_application'
1206             );
1207         }
1208         return $this->lockidentifier;
1209     }
1211     /**
1212      * Fixes the instance up after a clone.
1213      */
1214     public function __clone() {
1215         // Force a new idenfitier.
1216         $this->lockidentifier = null;
1217     }
1219     /**
1220      * Acquires a lock on the given key.
1221      *
1222      * This is done automatically if the definition requires it.
1223      * It is recommended to use a definition if you want to have locking although it is possible to do locking without having
1224      * it required by the definition.
1225      * The problem with such an approach is that you cannot ensure that code will consistently use locking. You will need to
1226      * rely on the integrators review skills.
1227      *
1228      * @param string|int $key The key as given to get|set|delete
1229      * @return bool Returns true if the lock could be acquired, false otherwise.
1230      */
1231     public function acquire_lock($key) {
1232         $key = $this->parse_key($key);
1233         if ($this->nativelocking) {
1234             return $this->get_store()->acquire_lock($key, $this->get_identifier());
1235         } else {
1236             $this->ensure_cachelock_available();
1237             return $this->cachelockinstance->lock($key, $this->get_identifier());
1238         }
1239     }
1241     /**
1242      * Checks if this cache has a lock on the given key.
1243      *
1244      * @param string|int $key The key as given to get|set|delete
1245      * @return bool|null Returns true if there is a lock and this cache has it, null if no one has a lock on that key, false if
1246      *      someone else has the lock.
1247      */
1248     public function check_lock_state($key) {
1249         $key = $this->parse_key($key);
1250         if ($this->nativelocking) {
1251             return $this->get_store()->check_lock_state($key, $this->get_identifier());
1252         } else {
1253             $this->ensure_cachelock_available();
1254             return $this->cachelockinstance->check_state($key, $this->get_identifier());
1255         }
1256     }
1258     /**
1259      * Releases the lock this cache has on the given key
1260      *
1261      * @param string|int $key
1262      * @return bool True if the operation succeeded, false otherwise.
1263      */
1264     public function release_lock($key) {
1265         $key = $this->parse_key($key);
1266         if ($this->nativelocking) {
1267             return $this->get_store()->release_lock($key, $this->get_identifier());
1268         } else {
1269             $this->ensure_cachelock_available();
1270             return $this->cachelockinstance->unlock($key, $this->get_identifier());
1271         }
1272     }
1274     /**
1275      * Ensure that the dedicated lock store is ready to go.
1276      *
1277      * This should only happen if the cache store doesn't natively support it.
1278      */
1279     protected function ensure_cachelock_available() {
1280         if ($this->cachelockinstance === null) {
1281             $this->cachelockinstance = cache_helper::get_cachelock_for_store($this->get_store());
1282         }
1283     }
1285     /**
1286      * Sends a key => value pair to the cache.
1287      *
1288      * <code>
1289      * // This code will add four entries to the cache, one for each url.
1290      * $cache->set('main', 'http://moodle.org');
1291      * $cache->set('docs', 'http://docs.moodle.org');
1292      * $cache->set('tracker', 'http://tracker.moodle.org');
1293      * $cache->set('qa', 'http://qa.moodle.net');
1294      * </code>
1295      *
1296      * @param string|int $key The key for the data being requested.
1297      * @param mixed $data The data to set against the key.
1298      * @return bool True on success, false otherwise.
1299      */
1300     public function set($key, $data) {
1301         if ($this->requirelockingwrite && !$this->acquire_lock($key)) {
1302             return false;
1303         }
1304         $result = parent::set($key, $data);
1305         if ($this->requirelockingwrite && !$this->release_lock($key)) {
1306             debugging('Failed to release cache lock on set operation... this should not happen.', DEBUG_DEVELOPER);
1307         }
1308         return $result;
1309     }
1311     /**
1312      * Sends several key => value pairs to the cache.
1313      *
1314      * Using this function comes with potential performance implications.
1315      * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
1316      * the equivalent singular method for each item provided.
1317      * This should not deter you from using this function as there is a performance benefit in situations where the cache store
1318      * does support it, but you should be aware of this fact.
1319      *
1320      * <code>
1321      * // This code will add four entries to the cache, one for each url.
1322      * $cache->set_many(array(
1323      *     'main' => 'http://moodle.org',
1324      *     'docs' => 'http://docs.moodle.org',
1325      *     'tracker' => 'http://tracker.moodle.org',
1326      *     'qa' => ''http://qa.moodle.net'
1327      * ));
1328      * </code>
1329      *
1330      * @param array $keyvaluearray An array of key => value pairs to send to the cache.
1331      * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
1332      *      ... if they care that is.
1333      */
1334     public function set_many(array $keyvaluearray) {
1335         if ($this->requirelockingwrite) {
1336             $locks = array();
1337             foreach ($keyvaluearray as $id => $pair) {
1338                 $key = $pair['key'];
1339                 if ($this->acquire_lock($key)) {
1340                     $locks[] = $key;
1341                 } else {
1342                     unset($keyvaluearray[$id]);
1343                 }
1344             }
1345         }
1346         $result = parent::set_many($keyvaluearray);
1347         if ($this->requirelockingwrite) {
1348             foreach ($locks as $key) {
1349                 if ($this->release_lock($key)) {
1350                     debugging('Failed to release cache lock on set_many operation... this should not happen.', DEBUG_DEVELOPER);
1351                 }
1352             }
1353         }
1354         return $result;
1355     }
1357     /**
1358      * Retrieves the value for the given key from the cache.
1359      *
1360      * @param string|int $key The key for the data being requested.
1361      * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
1362      * @return mixed|false The data from the cache or false if the key did not exist within the cache.
1363      */
1364     public function get($key, $strictness = IGNORE_MISSING) {
1365         if ($this->requirelockingread && $this->check_lock_state($key) === false) {
1366             // Read locking required and someone else has the read lock.
1367             return false;
1368         }
1369         return parent::get($key, $strictness);
1370     }
1372     /**
1373      * Retrieves an array of values for an array of keys.
1374      *
1375      * Using this function comes with potential performance implications.
1376      * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
1377      * the equivalent singular method for each item provided.
1378      * This should not deter you from using this function as there is a performance benefit in situations where the cache store
1379      * does support it, but you should be aware of this fact.
1380      *
1381      * @param array $keys The keys of the data being requested.
1382      * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
1383      * @return array An array of key value pairs for the items that could be retrieved from the cache.
1384      *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
1385      *      Otherwise any key that did not exist will have a data value of false within the results.
1386      * @throws coding_exception
1387      */
1388     public function get_many(array $keys, $strictness = IGNORE_MISSING) {
1389         if ($this->requirelockingread) {
1390             foreach ($keys as $id => $key) {
1391                 $lock =$this->acquire_lock($key);
1392                 if (!$lock) {
1393                     if ($strictness === MUST_EXIST) {
1394                         throw new coding_exception('Could not acquire read locks for all of the items being requested.');
1395                     } else {
1396                         // Can't return this as we couldn't get a read lock.
1397                         unset($keys[$id]);
1398                     }
1399                 }
1401             }
1402         }
1403         return parent::get_many($keys, $strictness);
1404     }
1406     /**
1407      * Delete the given key from the cache.
1408      *
1409      * @param string|int $key The key to delete.
1410      * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
1411      *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
1412      * @return bool True of success, false otherwise.
1413      */
1414     public function delete($key, $recurse = true) {
1415         if ($this->requirelockingwrite && !$this->acquire_lock($key)) {
1416             return false;
1417         }
1418         $result = parent::delete($key, $recurse);
1419         if ($this->requirelockingwrite && !$this->release_lock($key)) {
1420             debugging('Failed to release cache lock on delete operation... this should not happen.', DEBUG_DEVELOPER);
1421         }
1422         return $result;
1423     }
1425     /**
1426      * Delete all of the given keys from the cache.
1427      *
1428      * @param array $keys The key to delete.
1429      * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
1430      *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
1431      * @return int The number of items successfully deleted.
1432      */
1433     public function delete_many(array $keys, $recurse = true) {
1434         if ($this->requirelockingwrite) {
1435             $locks = array();
1436             foreach ($keys as $id => $key) {
1437                 if ($this->acquire_lock($key)) {
1438                     $locks[] = $key;
1439                 } else {
1440                     unset($keys[$id]);
1441                 }
1442             }
1443         }
1444         $result = parent::delete_many($keys, $recurse);
1445         if ($this->requirelockingwrite) {
1446             foreach ($locks as $key) {
1447                 if ($this->release_lock($key)) {
1448                     debugging('Failed to release cache lock on delete_many operation... this should not happen.', DEBUG_DEVELOPER);
1449                 }
1450             }
1451         }
1452         return $result;
1453     }
1456 /**
1457  * A session cache.
1458  *
1459  * This class is used for session caches returned by the cache::make methods.
1460  *
1461  * It differs from the application loader in a couple of noteable ways:
1462  *    1. Sessions are always expected to be persistent.
1463  *       Because of this we don't ever use the persist cache and instead a session array
1464  *       containing all of the data is maintained by this object.
1465  *    2. Session data for a loader instance (store + definition) is consolidate into a
1466  *       single array for storage within the store.
1467  *       Along with this we embed a lastaccessed time with the data. This way we can
1468  *       check sessions for a last access time.
1469  *    3. Session stores are required to support key searching and must
1470  *       implement cache_is_searchable. This ensures stores used for the cache can be
1471  *       targetted for garbage collection of session data.
1472  *
1473  * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
1474  * It is technically possible to call those methods through this class however there is no guarantee that you will get an
1475  * instance of this class back again.
1476  *
1477  * @todo we should support locking in the session as well. Should be pretty simple to set up.
1478  *
1479  * @internal don't use me directly.
1480  * @method cache_store|cache_is_searchable get_store() Returns the cache store which must implement both cache_is_searchable.
1481  *
1482  * @package    core
1483  * @category   cache
1484  * @copyright  2012 Sam Hemelryk
1485  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1486  */
1487 class cache_session extends cache {
1488     /**
1489      * The user the session has been established for.
1490      * @var int
1491      */
1492     protected static $loadeduserid = null;
1494     /**
1495      * The userid this cache is currently using.
1496      * @var int
1497      */
1498     protected $currentuserid = null;
1500     /**
1501      * The session id we are currently using.
1502      * @var array
1503      */
1504     protected $sessionid = null;
1506     /**
1507      * The session data for the above session id.
1508      * @var array
1509      */
1510     protected $session = null;
1512     /**
1513      * Constant used to prefix keys.
1514      */
1515     const KEY_PREFIX = 'sess_';
1517     /**
1518      * This is the key used to track last access.
1519      */
1520     const LASTACCESS = '__lastaccess__';
1522     /**
1523      * Override the cache::construct method.
1524      *
1525      * This function gets overriden so that we can process any invalidation events if need be.
1526      * If the definition doesn't have any invalidation events then this occurs exactly as it would for the cache class.
1527      * Otherwise we look at the last invalidation time and then check the invalidation data for events that have occured
1528      * between then now.
1529      *
1530      * You should not call this method from your code, instead you should use the cache::make methods.
1531      *
1532      * @param cache_definition $definition
1533      * @param cache_store $store
1534      * @param cache_loader|cache_data_source $loader
1535      */
1536     public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
1537         // First up copy the loadeduserid to the current user id.
1538         $this->currentuserid = self::$loadeduserid;
1539         parent::__construct($definition, $store, $loader);
1541         // This will trigger check tracked user. If this gets removed a call to that will need to be added here in its place.
1542         $this->set(self::LASTACCESS, cache::now());
1544         if ($definition->has_invalidation_events()) {
1545             $lastinvalidation = $this->get('lastsessioninvalidation');
1546             if ($lastinvalidation === false) {
1547                 // This is a new session, there won't be anything to invalidate. Set the time of the last invalidation and
1548                 // move on.
1549                 $this->set('lastsessioninvalidation', cache::now());
1550                 return;
1551             } else if ($lastinvalidation == cache::now()) {
1552                 // We've already invalidated during this request.
1553                 return;
1554             }
1556             // Get the event invalidation cache.
1557             $cache = cache::make('core', 'eventinvalidation');
1558             $events = $cache->get_many($definition->get_invalidation_events());
1559             $todelete = array();
1560             $purgeall = false;
1561             // Iterate the returned data for the events.
1562             foreach ($events as $event => $keys) {
1563                 if ($keys === false) {
1564                     // No data to be invalidated yet.
1565                     continue;
1566                 }
1567                 // Look at each key and check the timestamp.
1568                 foreach ($keys as $key => $timestamp) {
1569                     // If the timestamp of the event is more than or equal to the last invalidation (happened between the last
1570                     // invalidation and now)then we need to invaliate the key.
1571                     if ($timestamp >= $lastinvalidation) {
1572                         if ($key === 'purged') {
1573                             $purgeall = true;
1574                             break;
1575                         } else {
1576                             $todelete[] = $key;
1577                         }
1578                     }
1579                 }
1580             }
1581             if ($purgeall) {
1582                 $this->purge();
1583             } else if (!empty($todelete)) {
1584                 $todelete = array_unique($todelete);
1585                 $this->delete_many($todelete);
1586             }
1587             // Set the time of the last invalidation.
1588             $this->set('lastsessioninvalidation', cache::now());
1589         }
1590     }
1592     /**
1593      * Sets the session id for the loader.
1594      */
1595     protected function set_session_id() {
1596         $this->sessionid = preg_replace('#[^a-zA-Z0-9_]#', '_', session_id());
1597     }
1599     /**
1600      * Returns the prefix used for all keys.
1601      * @return string
1602      */
1603     protected function get_key_prefix() {
1604         return 'u'.$this->currentuserid.'_'.$this->sessionid;
1605     }
1607     /**
1608      * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
1609      *
1610      * This function is called for every operation that uses keys. For this reason we use this function to also check
1611      * that the current user is the same as the user who last used this cache.
1612      *
1613      * On top of that if prepends the string 'sess_' to the start of all keys. The _ ensures things are easily identifiable.
1614      *
1615      * @param string|int $key As passed to get|set|delete etc.
1616      * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
1617      */
1618     protected function parse_key($key) {
1619         $prefix = $this->get_key_prefix();
1620         if ($key === self::LASTACCESS) {
1621             return $key.$prefix;
1622         }
1623         return $prefix.'_'.parent::parse_key($key);
1624     }
1626     /**
1627      * Check that this cache instance is tracking the current user.
1628      */
1629     protected function check_tracked_user() {
1630         if (isset($_SESSION['USER']->id) && $_SESSION['USER']->id !== null) {
1631             // Get the id of the current user.
1632             $new = $_SESSION['USER']->id;
1633         } else {
1634             // No user set up yet.
1635             $new = 0;
1636         }
1637         if ($new !== self::$loadeduserid) {
1638             // The current user doesn't match the tracked userid for this request.
1639             if (!is_null(self::$loadeduserid)) {
1640                 // Purge the data we have for the old user.
1641                 // This way we don't bloat the session.
1642                 $this->purge();
1643                 // Update the session id just in case!
1644                 $this->set_session_id();
1645             }
1646             self::$loadeduserid = $new;
1647             $this->currentuserid = $new;
1648         } else if ($new !== $this->currentuserid) {
1649             // The current user matches the loaded user but not the user last used by this cache.
1650             $this->purge_current_user();
1651             $this->currentuserid = $new;
1652             // Update the session id just in case!
1653             $this->set_session_id();
1654         }
1655     }
1657     /**
1658      * Purges the session cache of all data belonging to the current user.
1659      */
1660     public function purge_current_user() {
1661         $keys = $this->get_store()->find_all($this->get_key_prefix());
1662         $this->get_store()->delete_many($keys);
1663     }
1665     /**
1666      * Retrieves the value for the given key from the cache.
1667      *
1668      * @param string|int $key The key for the data being requested.
1669      *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
1670      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
1671      * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
1672      * @return mixed|false The data from the cache or false if the key did not exist within the cache.
1673      * @throws coding_exception
1674      */
1675     public function get($key, $strictness = IGNORE_MISSING) {
1676         // Check the tracked user.
1677         $this->check_tracked_user();
1678         // 2. Parse the key.
1679         $parsedkey = $this->parse_key($key);
1680         // 3. Get it from the store.
1681         $result = $this->get_store()->get($parsedkey);
1682         if ($result !== false) {
1683             if ($result instanceof cache_ttl_wrapper) {
1684                 if ($result->has_expired()) {
1685                     $this->get_store()->delete($parsedkey);
1686                     $result = false;
1687                 } else {
1688                     $result = $result->data;
1689                 }
1690             }
1691             if ($result instanceof cache_cached_object) {
1692                 $result = $result->restore_object();
1693             }
1694         }
1695         // 4. Load if from the loader/datasource if we don't already have it.
1696         if ($result === false) {
1697             if ($this->perfdebug) {
1698                 cache_helper::record_cache_miss($this->storetype, $this->get_definition()->get_id());
1699             }
1700             if ($this->get_loader() !== false) {
1701                 // We must pass the original (unparsed) key to the next loader in the chain.
1702                 // The next loader will parse the key as it sees fit. It may be parsed differently
1703                 // depending upon the capabilities of the store associated with the loader.
1704                 $result = $this->get_loader()->get($key);
1705             } else if ($this->get_datasource() !== false) {
1706                 $result = $this->get_datasource()->load_for_cache($key);
1707             }
1708             // 5. Set it to the store if we got it from the loader/datasource.
1709             if ($result !== false) {
1710                 $this->set($key, $result);
1711             }
1712         } else if ($this->perfdebug) {
1713             cache_helper::record_cache_hit($this->storetype, $this->get_definition()->get_id());
1714         }
1715         // 5. Validate strictness.
1716         if ($strictness === MUST_EXIST && $result === false) {
1717             throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
1718         }
1719         // 6. Make sure we don't pass back anything that could be a reference.
1720         //    We don't want people modifying the data in the cache.
1721         if (!is_scalar($result)) {
1722             // If data is an object it will be a reference.
1723             // If data is an array if may contain references.
1724             // We want to break references so that the cache cannot be modified outside of itself.
1725             // Call the function to unreference it (in the best way possible).
1726             $result = $this->unref($result);
1727         }
1728         return $result;
1729     }
1731     /**
1732      * Sends a key => value pair to the cache.
1733      *
1734      * <code>
1735      * // This code will add four entries to the cache, one for each url.
1736      * $cache->set('main', 'http://moodle.org');
1737      * $cache->set('docs', 'http://docs.moodle.org');
1738      * $cache->set('tracker', 'http://tracker.moodle.org');
1739      * $cache->set('qa', 'http://qa.moodle.net');
1740      * </code>
1741      *
1742      * @param string|int $key The key for the data being requested.
1743      *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
1744      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
1745      * @param mixed $data The data to set against the key.
1746      * @return bool True on success, false otherwise.
1747      */
1748     public function set($key, $data) {
1749         $this->check_tracked_user();
1750         $loader = $this->get_loader();
1751         if ($loader !== false) {
1752             // We have a loader available set it there as well.
1753             // We have to let the loader do its own parsing of data as it may be unique.
1754             $loader->set($key, $data);
1755         }
1756         if ($this->perfdebug) {
1757             cache_helper::record_cache_set($this->storetype, $this->get_definition()->get_id());
1758         }
1759         if (is_object($data) && $data instanceof cacheable_object) {
1760             $data = new cache_cached_object($data);
1761         } else if (!is_scalar($data)) {
1762             // If data is an object it will be a reference.
1763             // If data is an array if may contain references.
1764             // We want to break references so that the cache cannot be modified outside of itself.
1765             // Call the function to unreference it (in the best way possible).
1766             $data = $this->unref($data);
1767         }
1768         // We dont' support native TTL here as we consolidate data for sessions.
1769         if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
1770             $data = new cache_ttl_wrapper($data, $this->get_definition()->get_ttl());
1771         }
1772         return $this->get_store()->set($this->parse_key($key), $data);
1773     }
1775     /**
1776      * Delete the given key from the cache.
1777      *
1778      * @param string|int $key The key to delete.
1779      * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
1780      *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
1781      * @return bool True of success, false otherwise.
1782      */
1783     public function delete($key, $recurse = true) {
1784         $parsedkey = $this->parse_key($key);
1785         if ($recurse && $this->get_loader() !== false) {
1786             // Delete from the bottom of the stack first.
1787             $this->get_loader()->delete($key, $recurse);
1788         }
1789         return $this->get_store()->delete($parsedkey);
1790     }
1792     /**
1793      * Retrieves an array of values for an array of keys.
1794      *
1795      * Using this function comes with potential performance implications.
1796      * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
1797      * the equivalent singular method for each item provided.
1798      * This should not deter you from using this function as there is a performance benefit in situations where the cache store
1799      * does support it, but you should be aware of this fact.
1800      *
1801      * @param array $keys The keys of the data being requested.
1802      *      Each key can be any structure although using a scalar string or int is recommended in the interests of performance.
1803      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
1804      * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
1805      * @return array An array of key value pairs for the items that could be retrieved from the cache.
1806      *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
1807      *      Otherwise any key that did not exist will have a data value of false within the results.
1808      * @throws coding_exception
1809      */
1810     public function get_many(array $keys, $strictness = IGNORE_MISSING) {
1811         $this->check_tracked_user();
1812         $parsedkeys = array();
1813         $keymap = array();
1814         foreach ($keys as $key) {
1815             $parsedkey = $this->parse_key($key);
1816             $parsedkeys[$key] = $parsedkey;
1817             $keymap[$parsedkey] = $key;
1818         }
1819         $result = $this->get_store()->get_many($parsedkeys);
1820         $return = array();
1821         $missingkeys = array();
1822         $hasmissingkeys = false;
1823         foreach ($result as $parsedkey => $value) {
1824             $key = $keymap[$parsedkey];
1825             if ($value instanceof cache_ttl_wrapper) {
1826                 /* @var cache_ttl_wrapper $value */
1827                 if ($value->has_expired()) {
1828                     $this->delete($keymap[$parsedkey]);
1829                     $value = false;
1830                 } else {
1831                     $value = $value->data;
1832                 }
1833             }
1834             if ($value instanceof cache_cached_object) {
1835                 /* @var cache_cached_object $value */
1836                 $value = $value->restore_object();
1837             }
1838             $return[$key] = $value;
1839             if ($value === false) {
1840                 $hasmissingkeys = true;
1841                 $missingkeys[$parsedkey] = $key;
1842             }
1843         }
1844         if ($hasmissingkeys) {
1845             // We've got missing keys - we've got to check any loaders or data sources.
1846             $loader = $this->get_loader();
1847             $datasource = $this->get_datasource();
1848             if ($loader !== false) {
1849                 foreach ($loader->get_many($missingkeys) as $key => $value) {
1850                     if ($value !== false) {
1851                         $return[$key] = $value;
1852                         unset($missingkeys[$parsedkeys[$key]]);
1853                     }
1854                 }
1855             }
1856             $hasmissingkeys = count($missingkeys) > 0;
1857             if ($datasource !== false && $hasmissingkeys) {
1858                 // We're still missing keys but we've got a datasource.
1859                 foreach ($datasource->load_many_for_cache($missingkeys) as $key => $value) {
1860                     if ($value !== false) {
1861                         $return[$key] = $value;
1862                         unset($missingkeys[$parsedkeys[$key]]);
1863                     }
1864                 }
1865                 $hasmissingkeys = count($missingkeys) > 0;
1866             }
1867         }
1868         if ($hasmissingkeys && $strictness === MUST_EXIST) {
1869             throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
1870         }
1872         return $return;
1874     }
1876     /**
1877      * Delete all of the given keys from the cache.
1878      *
1879      * @param array $keys The key to delete.
1880      * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
1881      *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
1882      * @return int The number of items successfully deleted.
1883      */
1884     public function delete_many(array $keys, $recurse = true) {
1885         $parsedkeys = array_map(array($this, 'parse_key'), $keys);
1886         if ($recurse && $this->get_loader() !== false) {
1887             // Delete from the bottom of the stack first.
1888             $this->get_loader()->delete_many($keys, $recurse);
1889         }
1890         return $this->get_store()->delete_many($parsedkeys);
1891     }
1893     /**
1894      * Sends several key => value pairs to the cache.
1895      *
1896      * Using this function comes with potential performance implications.
1897      * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
1898      * the equivalent singular method for each item provided.
1899      * This should not deter you from using this function as there is a performance benefit in situations where the cache store
1900      * does support it, but you should be aware of this fact.
1901      *
1902      * <code>
1903      * // This code will add four entries to the cache, one for each url.
1904      * $cache->set_many(array(
1905      *     'main' => 'http://moodle.org',
1906      *     'docs' => 'http://docs.moodle.org',
1907      *     'tracker' => 'http://tracker.moodle.org',
1908      *     'qa' => ''http://qa.moodle.net'
1909      * ));
1910      * </code>
1911      *
1912      * @param array $keyvaluearray An array of key => value pairs to send to the cache.
1913      * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
1914      *      ... if they care that is.
1915      */
1916     public function set_many(array $keyvaluearray) {
1917         $this->check_tracked_user();
1918         $loader = $this->get_loader();
1919         if ($loader !== false) {
1920             // We have a loader available set it there as well.
1921             // We have to let the loader do its own parsing of data as it may be unique.
1922             $loader->set_many($keyvaluearray);
1923         }
1924         $data = array();
1925         $definitionid = $this->get_definition()->get_ttl();
1926         $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
1927         foreach ($keyvaluearray as $key => $value) {
1928             if (is_object($value) && $value instanceof cacheable_object) {
1929                 $value = new cache_cached_object($value);
1930             } else if (!is_scalar($value)) {
1931                 // If data is an object it will be a reference.
1932                 // If data is an array if may contain references.
1933                 // We want to break references so that the cache cannot be modified outside of itself.
1934                 // Call the function to unreference it (in the best way possible).
1935                 $value = $this->unref($value);
1936             }
1937             if ($simulatettl) {
1938                 $value = new cache_ttl_wrapper($value, $definitionid);
1939             }
1940             $data[$key] = array(
1941                 'key' => $this->parse_key($key),
1942                 'value' => $value
1943             );
1944         }
1945         if ($this->perfdebug) {
1946             cache_helper::record_cache_set($this->storetype, $definitionid);
1947         }
1948         return $this->get_store()->set_many($data);
1949     }
1951     /**
1952      * Purges the cache store, and loader if there is one.
1953      *
1954      * @return bool True on success, false otherwise
1955      */
1956     public function purge() {
1957         $this->get_store()->purge();
1958         if ($this->get_loader()) {
1959             $this->get_loader()->purge();
1960         }
1961         return true;
1962     }
1964     /**
1965      * Test is a cache has a key.
1966      *
1967      * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
1968      * test and any subsequent action (get, set, delete etc).
1969      * Instead it is recommended to write your code in such a way they it performs the following steps:
1970      * <ol>
1971      * <li>Attempt to retrieve the information.</li>
1972      * <li>Generate the information.</li>
1973      * <li>Attempt to set the information</li>
1974      * </ol>
1975      *
1976      * Its also worth mentioning that not all stores support key tests.
1977      * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
1978      * Just one more reason you should not use these methods unless you have a very good reason to do so.
1979      *
1980      * @param string|int $key
1981      * @param bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
1982      *      data source then the code will try load the key value from the next item in the chain.
1983      * @return bool True if the cache has the requested key, false otherwise.
1984      */
1985     public function has($key, $tryloadifpossible = false) {
1986         $this->check_tracked_user();
1987         $parsedkey = $this->parse_key($key);
1988         $store = $this->get_store();
1989         if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
1990             // The data has a TTL and the store doesn't support it natively.
1991             // We must fetch the data and expect a ttl wrapper.
1992             $data = $store->get($parsedkey);
1993             $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
1994         } else if (!$this->store_supports_key_awareness()) {
1995             // The store doesn't support key awareness, get the data and check it manually... puke.
1996             // Either no TTL is set of the store supports its handling natively.
1997             $data = $store->get($parsedkey);
1998             $has = ($data !== false);
1999         } else {
2000             // The store supports key awareness, this is easy!
2001             // Either no TTL is set of the store supports its handling natively.
2002             /* @var cache_store|cache_is_key_aware $store */
2003             $has = $store->has($parsedkey);
2004         }
2005         if (!$has && $tryloadifpossible) {
2006             $result = null;
2007             if ($this->get_loader() !== false) {
2008                 $result = $this->get_loader()->get($parsedkey);
2009             } else if ($this->get_datasource() !== null) {
2010                 $result = $this->get_datasource()->load_for_cache($key);
2011             }
2012             $has = ($result !== null);
2013             if ($has) {
2014                 $this->set($key, $result);
2015             }
2016         }
2017         return $has;
2018     }
2020     /**
2021      * Test is a cache has all of the given keys.
2022      *
2023      * It is strongly recommended to avoid the use of this function if not absolutely required.
2024      * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
2025      *
2026      * Its also worth mentioning that not all stores support key tests.
2027      * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
2028      * Just one more reason you should not use these methods unless you have a very good reason to do so.
2029      *
2030      * @param array $keys
2031      * @return bool True if the cache has all of the given keys, false otherwise.
2032      */
2033     public function has_all(array $keys) {
2034         $this->check_tracked_user();
2035         if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
2036             foreach ($keys as $key) {
2037                 if (!$this->has($key)) {
2038                     return false;
2039                 }
2040             }
2041             return true;
2042         }
2043         // The cache must be key aware and if support native ttl if it a ttl is set.
2044         /* @var cache_store|cache_is_key_aware $store */
2045         $store = $this->get_store();
2046         return $store->has_all(array_map(array($this, 'parse_key'), $keys));
2047     }
2049     /**
2050      * Test if a cache has at least one of the given keys.
2051      *
2052      * It is strongly recommended to avoid the use of this function if not absolutely required.
2053      * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
2054      *
2055      * Its also worth mentioning that not all stores support key tests.
2056      * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
2057      * Just one more reason you should not use these methods unless you have a very good reason to do so.
2058      *
2059      * @param array $keys
2060      * @return bool True if the cache has at least one of the given keys
2061      */
2062     public function has_any(array $keys) {
2063         if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
2064             foreach ($keys as $key) {
2065                 if ($this->has($key)) {
2066                     return true;
2067                 }
2068             }
2069             return false;
2070         }
2071         /* @var cache_store|cache_is_key_aware $store */
2072         $store = $this->get_store();
2073         return $store->has_any(array_map(array($this, 'parse_key'), $keys));
2074     }
2076     /**
2077      * The session loader never uses the persist cache.
2078      * Instead it stores things in the static $session variable. Shared between all session loaders.
2079      *
2080      * @return bool
2081      */
2082     protected function is_using_persist_cache() {
2083         return false;
2084     }
2087 /**
2088  * An request cache.
2089  *
2090  * This class is used for request caches returned by the cache::make methods.
2091  *
2092  * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
2093  * It is technically possible to call those methods through this class however there is no guarantee that you will get an
2094  * instance of this class back again.
2095  *
2096  * @internal don't use me directly.
2097  *
2098  * @package    core
2099  * @category   cache
2100  * @copyright  2012 Sam Hemelryk
2101  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2102  */
2103 class cache_request extends cache {
2104     // This comment appeases code pre-checker ;) !