Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace core_cache;
18
 
19
use core\exception\coding_exception;
20
use stdClass;
21
 
22
/**
23
 * The main cache class.
24
 *
25
 * This class if the first class that any end developer will interact with.
26
 * In order to create an instance of a cache that they can work with they must call one of the static make methods belonging
27
 * to this class.
28
 *
29
 * @package    core_cache
30
 * @category   cache
31
 * @copyright  2012 Sam Hemelryk
32
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33
 */
34
class cache implements loader_interface {
35
    /**
36
     * @var int Constant for cache entries that do not have a version number
37
     */
38
    const VERSION_NONE = -1;
39
 
40
    /**
41
     * We need a timestamp to use within the cache API.
42
     * This stamp needs to be used for all ttl and time based operations to ensure that we don't end up with
43
     * timing issues.
44
     * @var int
45
     */
46
    protected static $now;
47
 
48
    /**
49
     * A purge token used to distinguish between multiple cache purges in the same second.
50
     * This is in the format <microtime>-<random string>.
51
     *
52
     * @var string
53
     */
54
    protected static $purgetoken;
55
 
56
    /**
57
     * The definition used when loading this cache if there was one.
58
     * @var definition
59
     */
60
    private $definition = false;
61
 
62
    /**
63
     * The cache store that this loader will make use of.
64
     * @var store
65
     */
66
    private $store;
67
 
68
    /**
69
     * The next cache loader in the chain if there is one.
70
     * If a cache request misses for the store belonging to this loader then the loader
71
     * stored here will be checked next.
72
     * If there is a loader here then $datasource must be false.
73
     * @var loader_interface|false
74
     */
75
    private $loader = false;
76
 
77
    /**
78
     * The data source to use if we need to load data (because if doesn't exist in the cache store).
79
     * If there is a data source here then $loader above must be false.
80
     * @var data_source_interface|false
81
     */
82
    private $datasource = false;
83
 
84
    /**
85
     * Used to quickly check if the store supports key awareness.
86
     * This is set when the cache is initialised and is used to speed up processing.
87
     * @var bool
88
     */
89
    private $supportskeyawareness = null;
90
 
91
    /**
92
     * Used to quickly check if the store supports ttl natively.
93
     * This is set when the cache is initialised and is used to speed up processing.
94
     * @var bool
95
     */
96
    private $supportsnativettl = null;
97
 
98
    /**
99
     * Gets set to true if the cache is going to be using a static array for acceleration.
100
     * The array statically caches items used during the lifetime of the request. This greatly speeds up interaction
101
     * with the cache in areas where it will be repetitively hit for the same information such as with strings.
102
     * There are several other variables to control how this static acceleration array works.
103
     * @var bool
104
     */
105
    private $staticacceleration = false;
106
 
107
    /**
108
     * The static acceleration array.
109
     * Items will be stored in this cache as they were provided. This ensure there is no unnecessary processing taking place.
110
     * @var array
111
     */
112
    private $staticaccelerationarray = [];
113
 
114
    /**
115
     * The number of items in the static acceleration array. Avoids count calls like you wouldn't believe.
116
     * @var int
117
     */
118
    private $staticaccelerationcount = 0;
119
 
120
    /**
121
     * An array containing just the keys being used in the static acceleration array.
122
     * This seems redundant perhaps but is used when managing the size of the static acceleration array.
123
     * Items are added to the end of the array and the when we need to reduce the size of the cache we use the
124
     * key that is first on this array.
125
     * @var array
126
     */
127
    private $staticaccelerationkeys = [];
128
 
129
    /**
130
     * The maximum size of the static acceleration array.
131
     *
132
     * If set to false there is no max size.
133
     * Caches that make use of static acceleration should seriously consider setting this to something reasonably small, but
134
     * still large enough to offset repetitive calls.
135
     *
136
     * @var int|false
137
     */
138
    private $staticaccelerationsize = false;
139
 
140
    /**
141
     * Gets set to true during initialisation if the definition is making use of a ttl.
142
     * Used to speed up processing.
143
     * @var bool
144
     */
145
    private $hasattl = false;
146
 
147
    /**
148
     * Gets set to the class name of the store during initialisation. This is used several times in the cache class internally
149
     * and having it here helps speed up processing.
150
     * @var strubg
151
     */
152
    protected $storetype = 'unknown';
153
 
154
    /**
155
     * Gets set to true if we want to collect performance information about the cache API.
156
     * @var bool
157
     */
158
    protected $perfdebug = false;
159
 
160
    /**
161
     * Determines if this loader is a sub loader, not the top of the chain.
162
     * @var bool
163
     */
164
    protected $subloader = false;
165
 
166
    /**
167
     * Gets set to true if the cache writes (set|delete) must have a manual lock created first.
168
     * @var bool
169
     */
170
    protected $requirelockingbeforewrite = false;
171
 
172
    /**
173
     * Gets set to true if the cache's primary store natively supports locking.
174
     * If it does then we use that, otherwise we need to instantiate a second store to use for locking.
175
     * @var store|null
176
     */
177
    protected $nativelocking = null;
178
 
179
    /**
180
     * Creates a new cache instance for a pre-defined definition.
181
     *
182
     * @param string $component The component for the definition
183
     * @param string $area The area for the definition
184
     * @param array $identifiers Any additional identifiers that should be provided to the definition.
185
     * @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
186
     * @return application_cache|session_cache|store
187
     */
188
    public static function make($component, $area, array $identifiers = [], $unused = null) {
189
        $factory = factory::instance();
190
        return $factory->create_cache_from_definition($component, $area, $identifiers);
191
    }
192
 
193
    /**
194
     * Creates a new cache instance based upon the given params.
195
     *
196
     * @param int $mode One of store::MODE_*
197
     * @param string $component The component this cache relates to.
198
     * @param string $area The area this cache relates to.
199
     * @param array $identifiers Any additional identifiers that should be provided to the definition.
200
     * @param array $options An array of options, available options are:
201
     *   - simplekeys : Set to true if the keys you will use are a-zA-Z0-9_
202
     *   - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
203
     *   - staticacceleration : If set to true the cache will hold onto data passing through it.
204
     *   - staticaccelerationsize : The max size for the static acceleration array.
205
     * @return application_cache|session_cache|request_cache
206
     */
207
    public static function make_from_params($mode, $component, $area, array $identifiers = [], array $options = []) {
208
        $factory = factory::instance();
209
        return $factory->create_cache_from_params($mode, $component, $area, $identifiers, $options);
210
    }
211
 
212
    /**
213
     * Constructs a new cache instance.
214
     *
215
     * You should not call this method from your code, instead you should use the cache::make methods.
216
     *
217
     * This method is public so that the factory is able to instantiate cache instances.
218
     * Ideally we would make this method protected and expose its construction to the factory method internally somehow.
219
     * The factory class is responsible for this in order to centralise the storage of instances once created. This way if needed
220
     * we can force a reset of the cache API (used during unit testing).
221
     *
222
     * @param definition $definition The definition for the cache instance.
223
     * @param store $store The store that cache should use.
224
     * @param loader_interface|data_source_interface $loader The next loader in the chain or the data source if there is one
225
     *                                                       and there are no other loader_interfaces in the chain.
226
     */
227
    public function __construct(definition $definition, store $store, $loader = null) {
228
        global $CFG;
229
        $this->definition = $definition;
230
        $this->store = $store;
231
        $this->storetype = get_class($store);
232
        $this->perfdebug = (!empty($CFG->perfdebug) and $CFG->perfdebug > 7);
233
        if ($loader instanceof loader_interface) {
234
            $this->set_loader($loader);
235
        } else if ($loader instanceof data_source_interface) {
236
            $this->set_data_source($loader);
237
        }
238
        $this->definition->generate_definition_hash();
239
        $this->staticacceleration = $this->definition->use_static_acceleration();
240
        if ($this->staticacceleration) {
241
            $this->staticaccelerationsize = $this->definition->get_static_acceleration_size();
242
        }
243
        $this->hasattl = ($this->definition->get_ttl() > 0);
244
    }
245
 
246
    /**
247
     * Set the loader for this cache.
248
     *
249
     * @param   loader_interface $loader
250
     */
251
    protected function set_loader(loader_interface $loader): void {
252
        $this->loader = $loader;
253
 
254
        // Mark the loader as a sub (chained) loader.
255
        $this->loader->set_is_sub_loader(true);
256
    }
257
 
258
    /**
259
     * Set the data source for this cache.
260
     *
261
     * @param   data_source_interface $datasource
262
     */
263
    protected function set_data_source(data_source_interface $datasource): void {
264
        $this->datasource = $datasource;
265
    }
266
 
267
    /**
268
     * Used to inform the loader of its state as a sub loader, or as the top of the chain.
269
     *
270
     * This is important as it ensures that we do not have more than one loader keeping static acceleration data.
271
     * Subloaders need to be "pure" loaders in the sense that they are used to store and retrieve information from stores or the
272
     * next loader/data source in the chain.
273
     * Nothing fancy, nothing flash.
274
     *
275
     * @param bool $setting
276
     */
277
    protected function set_is_sub_loader($setting = true) {
278
        if ($setting) {
279
            $this->subloader = true;
280
            // Subloaders should not keep static acceleration data.
281
            $this->staticacceleration = false;
282
            $this->staticaccelerationsize = false;
283
        } else {
284
            $this->subloader = true;
285
            $this->staticacceleration = $this->definition->use_static_acceleration();
286
            if ($this->staticacceleration) {
287
                $this->staticaccelerationsize = $this->definition->get_static_acceleration_size();
288
            }
289
        }
290
    }
291
 
292
    /**
293
     * Alters the identifiers that have been provided to the definition.
294
     *
295
     * This is an advanced method and should not be used unless really needed.
296
     * It allows the developer to slightly alter the definition without having to re-establish the cache.
297
     * It will cause more processing as the definition will need to clear and reprepare some of its properties.
298
     *
299
     * @param array $identifiers
300
     */
301
    public function set_identifiers(array $identifiers) {
302
        if ($this->definition->set_identifiers($identifiers)) {
303
            // As static acceleration uses input keys and not parsed keys
304
            // it much be cleared when the identifier set is changed.
305
            $this->staticaccelerationarray = [];
306
            if ($this->staticaccelerationsize !== false) {
307
                $this->staticaccelerationkeys = [];
308
                $this->staticaccelerationcount = 0;
309
            }
310
        }
311
    }
312
 
313
    /**
314
     * Process any outstanding invalidation events for the cache we are registering,
315
     *
316
     * Identifiers and event invalidation are not compatible with each other at this time.
317
     * As a result the cache does not need to consider identifiers when working out what to invalidate.
318
     */
319
    protected function handle_invalidation_events() {
320
        if (!$this->definition->has_invalidation_events()) {
321
            return;
322
        }
323
 
324
        // Each cache stores the current 'lastinvalidation' value within the cache itself.
325
        $lastinvalidation = $this->get('lastinvalidation');
326
        if ($lastinvalidation === false) {
327
            // There is currently no  value for the lastinvalidation token, therefore the token is not set, and there
328
            // can be nothing to invalidate.
329
            // Set the lastinvalidation value to the current purge token and return early.
330
            $this->set('lastinvalidation', self::get_purge_token());
331
            return;
332
        } else if ($lastinvalidation == self::get_purge_token()) {
333
            // The current purge request has already been fully handled by this cache.
334
            return;
335
        }
336
 
337
        /*
338
         * Now that the whole cache check is complete, we check the meaning of any specific cache invalidation events.
339
         * These are stored in the core/eventinvalidation cache as an multi-dimensinoal array in the form:
340
         *  [
341
         *      eventname => [
342
         *          keyname => purgetoken,
343
         *      ]
344
         *  ]
345
         *
346
         * The 'keyname' value is used to delete a specific key in the cache.
347
         * If the keyname is set to the special value 'purged', then the whole cache is purged instead.
348
         *
349
         * The 'purgetoken' is the token that this key was last purged.
350
         * a) If the purgetoken matches the last invalidation, then the key/cache is not purged.
351
         * b) If the purgetoken is newer than the last invalidation, then the key/cache is not purged.
352
         * c) If the purge token is older than the last invalidation, or it has a different token component, then the
353
         *    cache is purged.
354
         *
355
         * Option b should not happen under normal operation, but may happen in race condition whereby a long-running
356
         * request's cache is cleared in another process during that request, and prior to that long-running request
357
         * creating the cache. In such a condition, it would be incorrect to clear that cache.
358
         */
359
        $cache = self::make('core', 'eventinvalidation');
360
        $events = $cache->get_many($this->definition->get_invalidation_events());
361
        $todelete = [];
362
        $purgeall = false;
363
 
364
        // Iterate the returned data for the events.
365
        foreach ($events as $event => $keys) {
366
            if ($keys === false) {
367
                // No data to be invalidated yet.
368
                continue;
369
            }
370
 
371
            // Look at each key and check the timestamp.
372
            foreach ($keys as $key => $purgetoken) {
373
                // If the timestamp of the event is more than or equal to the last invalidation (happened between the last
374
                // invalidation and now), then we need to invaliate the key.
375
                if (self::compare_purge_tokens($purgetoken, $lastinvalidation) > 0) {
376
                    if ($key === 'purged') {
377
                        $purgeall = true;
378
                        break;
379
                    } else {
380
                        $todelete[] = $key;
381
                    }
382
                }
383
            }
384
        }
385
        if ($purgeall) {
386
            $this->purge();
387
        } else if (!empty($todelete)) {
388
            $todelete = array_unique($todelete);
389
            $this->delete_many($todelete);
390
        }
391
        // Set the time of the last invalidation.
392
        if ($purgeall || !empty($todelete)) {
393
            $this->set('lastinvalidation', self::get_purge_token(true));
394
        }
395
    }
396
 
397
    /**
398
     * Retrieves the value for the given key from the cache.
399
     *
400
     * @param string|int $key The key for the data being requested.
401
     *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
402
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
403
     * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
404
     * @return mixed|false The data from the cache or false if the key did not exist within the cache.
405
     * @throws coding_exception
406
     */
407
    public function get($key, $strictness = IGNORE_MISSING) {
408
        return $this->get_implementation($key, self::VERSION_NONE, $strictness);
409
    }
410
 
411
    /**
412
     * Retrieves the value and actual version for the given key, with at least the required version.
413
     *
414
     * If there is no value for the key, or there is a value but it doesn't have the required
415
     * version, then this function will return null (or throw an exception if you set strictness
416
     * to MUST_EXIST).
417
     *
418
     * This function can be used to make it easier to support localisable caches (where the cache
419
     * could be stored on a local server as well as a shared cache). Specifying the version means
420
     * that it will automatically retrieve the correct version if available, either from the local
421
     * server or [if that has an older version] from the shared server.
422
     *
423
     * If the cached version is newer than specified version, it will be returned regardless. For
424
     * example, if you request version 4, but the locally cached version is 5, it will be returned.
425
     * If you request version 6, and the locally cached version is 5, then the system will look in
426
     * higher-level caches (if any); if there still isn't a version 6 or greater, it will return
427
     * null.
428
     *
429
     * You must use this function if you use set_versioned.
430
     *
431
     * @param string|int $key The key for the data being requested.
432
     * @param int $requiredversion Minimum required version of the data
433
     * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
434
     * @param mixed $actualversion If specified, will be set to the actual version number retrieved
435
     * @return mixed Data from the cache, or false if the key did not exist or was too old
436
     * @throws \coding_exception If you call get_versioned on a non-versioned cache key
437
     */
438
    public function get_versioned($key, int $requiredversion, int $strictness = IGNORE_MISSING, &$actualversion = null) {
439
        return $this->get_implementation($key, $requiredversion, $strictness, $actualversion);
440
    }
441
 
442
    /**
443
     * Checks returned data to see if it matches the specified version number.
444
     *
445
     * For versioned data, this returns the version_wrapper object (or false). For other
446
     * data, it returns the actual data (or false).
447
     *
448
     * @param mixed $result Result data
449
     * @param int $requiredversion Required version number or VERSION_NONE if there must be no version
450
     * @return bool True if version is current, false if not (or if result is false)
451
     * @throws \coding_exception If unexpected type of data (versioned vs non-versioned) is found
452
     */
453
    protected static function check_version($result, int $requiredversion): bool {
454
        if ($requiredversion === self::VERSION_NONE) {
455
            if ($result instanceof \core_cache\version_wrapper) {
456
                throw new \coding_exception('Unexpectedly found versioned cache entry');
457
            } else {
458
                // No version checks, so version is always correct.
459
                return true;
460
            }
461
        } else {
462
            // If there's no result, obviously it doesn't meet the required version.
463
            if (!helper::result_found($result)) {
464
                return false;
465
            }
466
            if (!($result instanceof \core_cache\version_wrapper)) {
467
                throw new \coding_exception('Unexpectedly found non-versioned cache entry');
468
            }
469
            // If the result doesn't match the required version tag, return false.
470
            if ($result->version < $requiredversion) {
471
                return false;
472
            }
473
            // The version meets the requirement.
474
            return true;
475
        }
476
    }
477
 
478
    /**
479
     * Retrieves the value for the given key from the cache.
480
     *
481
     * @param string|int $key The key for the data being requested.
482
     *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
483
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
484
     * @param int $requiredversion Minimum required version of the data or cache::VERSION_NONE
485
     * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
486
     * @param mixed $actualversion If specified, will be set to the actual version number retrieved
487
     * @return mixed|false The data from the cache or false if the key did not exist within the cache.
488
     * @throws coding_exception
489
     */
490
    protected function get_implementation($key, int $requiredversion, int $strictness, &$actualversion = null) {
491
        // 1. Get it from the static acceleration array if we can (only when it is enabled and it has already been requested/set).
492
        $usesstaticacceleration = $this->use_static_acceleration();
493
 
494
        if ($usesstaticacceleration) {
495
            $result = $this->static_acceleration_get($key);
496
            if (helper::result_found($result) && self::check_version($result, $requiredversion)) {
497
                if ($requiredversion === self::VERSION_NONE) {
498
                    return $result;
499
                } else {
500
                    $actualversion = $result->version;
501
                    return $result->data;
502
                }
503
            }
504
        }
505
 
506
        // 2. Parse the key.
507
        $parsedkey = $this->parse_key($key);
508
 
509
        // 3. Get it from the store. Obviously wasn't in the static acceleration array.
510
        $result = $this->store->get($parsedkey);
511
        if (helper::result_found($result)) {
512
            // Check the result has at least the required version.
513
            try {
514
                $validversion = self::check_version($result, $requiredversion);
515
            } catch (\coding_exception $e) {
516
                // In certain circumstances this could happen before users are taken to the upgrade
517
                // screen when upgrading from an earlier Moodle version that didn't use a versioned
518
                // cache for this item, so redirect instead of showing error if that's the case.
519
                redirect_if_major_upgrade_required();
520
 
521
                // If we still get an exception because there is incorrect data in the cache (not
522
                // versioned when it ought to be), delete it so this exception goes away next time.
523
                // The exception should only happen if there is a code bug (which is why we still
524
                // throw it) but there are unusual scenarios in development where it might happen
525
                // and that would be annoying if it doesn't fix itself.
526
                $this->store->delete($parsedkey);
527
                throw $e;
528
            }
529
 
530
            if (!$validversion) {
531
                // If the result was too old, don't use it.
532
                $result = false;
533
 
534
                // Also delete it immediately. This improves performance in the
535
                // case when the cache item is large and there may be multiple clients simultaneously
536
                // requesting it - they won't all have to do a megabyte of IO just in order to find
537
                // that it's out of date.
538
                $this->store->delete($parsedkey);
539
            }
540
        }
541
        if (helper::result_found($result)) {
542
            // Look to see if there's a TTL wrapper. It might be inside a version wrapper.
543
            if ($requiredversion !== self::VERSION_NONE) {
544
                $ttlconsider = $result->data;
545
            } else {
546
                $ttlconsider = $result;
547
            }
548
            if ($ttlconsider instanceof ttl_wrapper) {
549
                if ($ttlconsider->has_expired()) {
550
                    $this->store->delete($parsedkey);
551
                    $result = false;
552
                } else if ($requiredversion === self::VERSION_NONE) {
553
                    // Use the data inside the TTL wrapper as the result.
554
                    $result = $ttlconsider->data;
555
                } else {
556
                    // Put the data from the TTL wrapper directly inside the version wrapper.
557
                    $result->data = $ttlconsider->data;
558
                }
559
            }
560
            if ($usesstaticacceleration) {
561
                $this->static_acceleration_set($key, $result);
562
            }
563
            // Remove version wrapper if necessary.
564
            if ($requiredversion !== self::VERSION_NONE) {
565
                $actualversion = $result->version;
566
                $result = $result->data;
567
            }
568
            if ($result instanceof cached_object) {
569
                $result = $result->restore_object();
570
            }
571
        }
572
 
573
        // 4. Load if from the loader/datasource if we don't already have it.
574
        $setaftervalidation = false;
575
        if (!helper::result_found($result)) {
576
            if ($this->perfdebug) {
577
                helper::record_cache_miss($this->store, $this->definition);
578
            }
579
            if ($this->loader !== false) {
580
                // We must pass the original (unparsed) key to the next loader in the chain.
581
                // The next loader will parse the key as it sees fit. It may be parsed differently
582
                // depending upon the capabilities of the store associated with the loader.
583
                if ($requiredversion === self::VERSION_NONE) {
584
                    $result = $this->loader->get($key);
585
                } else {
586
                    $result = $this->loader->get_versioned($key, $requiredversion, IGNORE_MISSING, $actualversion);
587
                }
588
            } else if ($this->datasource !== false) {
589
                if ($requiredversion === self::VERSION_NONE) {
590
                    $result = $this->datasource->load_for_cache($key);
591
                } else {
592
                    if (!$this->datasource instanceof versionable_data_source_interface) {
593
                        throw new \coding_exception('Data source is not versionable');
594
                    }
595
                    $result = $this->datasource->load_for_cache_versioned($key, $requiredversion, $actualversion);
596
                    if ($result && $actualversion < $requiredversion) {
597
                        throw new \coding_exception('Data source returned outdated version');
598
                    }
599
                }
600
            }
601
            $setaftervalidation = (helper::result_found($result));
602
        } else if ($this->perfdebug) {
603
            $readbytes = $this->store->get_last_io_bytes();
604
            helper::record_cache_hit($this->store, $this->definition, 1, $readbytes);
605
        }
606
        // 5. Validate strictness.
607
        if ($strictness === MUST_EXIST && !helper::result_found($result)) {
608
            throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
609
        }
610
        // 6. Set it to the store if we got it from the loader/datasource. Only set to this direct
611
        // store; parent method will have set it to all stores if needed.
612
        if ($setaftervalidation) {
613
            $lock = false;
614
            try {
615
                // Only try to acquire a lock for this cache if we do not already have one.
616
                if (!empty($this->requirelockingbeforewrite) && !$this->check_lock_state($key)) {
617
                    $this->acquire_lock($key);
618
                    $lock = true;
619
                }
620
                if ($requiredversion === self::VERSION_NONE) {
621
                    $this->set_implementation($key, self::VERSION_NONE, $result, false);
622
                } else {
623
                    $this->set_implementation($key, $actualversion, $result, false);
624
                }
625
            } finally {
626
                if ($lock) {
627
                    $this->release_lock($key);
628
                }
629
            }
630
        }
631
        // 7. Make sure we don't pass back anything that could be a reference.
632
        // We don't want people modifying the data in the cache.
633
        if (!$this->store->supports_dereferencing_objects() && !is_scalar($result)) {
634
            // If data is an object it will be a reference.
635
            // If data is an array if may contain references.
636
            // We want to break references so that the cache cannot be modified outside of itself.
637
            // Call the function to unreference it (in the best way possible).
638
            $result = $this->unref($result);
639
        }
640
        return $result;
641
    }
642
 
643
    /**
644
     * Retrieves an array of values for an array of keys.
645
     *
646
     * Using this function comes with potential performance implications.
647
     * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
648
     * the equivalent singular method for each item provided.
649
     * This should not deter you from using this function as there is a performance benefit in situations where the cache store
650
     * does support it, but you should be aware of this fact.
651
     *
652
     * @param array $keys The keys of the data being requested.
653
     *      Each key can be any structure although using a scalar string or int is recommended in the interests of performance.
654
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
655
     * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
656
     * @return array An array of key value pairs for the items that could be retrieved from the cache.
657
     *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
658
     *      Otherwise any key that did not exist will have a data value of false within the results.
659
     * @throws coding_exception
660
     */
661
    public function get_many(array $keys, $strictness = IGNORE_MISSING) {
662
 
663
        $keysparsed = [];
664
        $parsedkeys = [];
665
        $resultpersist = [];
666
        $resultstore = [];
667
        $keystofind = [];
668
        $readbytes = store::IO_BYTES_NOT_SUPPORTED;
669
 
670
        // First up check the persist cache for each key.
671
        $isusingpersist = $this->use_static_acceleration();
672
        foreach ($keys as $key) {
673
            $pkey = $this->parse_key($key);
674
            if (is_array($pkey)) {
675
                $pkey = $pkey['key'];
676
            }
677
            $keysparsed[$key] = $pkey;
678
            $parsedkeys[$pkey] = $key;
679
            $keystofind[$pkey] = $key;
680
            if ($isusingpersist) {
681
                $value = $this->static_acceleration_get($key);
682
                if ($value !== false) {
683
                    $resultpersist[$pkey] = $value;
684
                    unset($keystofind[$pkey]);
685
                }
686
            }
687
        }
688
 
689
        // Next assuming we didn't find all of the keys in the persist cache try loading them from the store.
690
        if (count($keystofind)) {
691
            $resultstore = $this->store->get_many(array_keys($keystofind));
692
            if ($this->perfdebug) {
693
                $readbytes = $this->store->get_last_io_bytes();
694
            }
695
            // Process each item in the result to "unwrap" it.
696
            foreach ($resultstore as $key => $value) {
697
                if ($value instanceof ttl_wrapper) {
698
                    if ($value->has_expired()) {
699
                        $value = false;
700
                    } else {
701
                        $value = $value->data;
702
                    }
703
                }
704
                if ($value !== false && $this->use_static_acceleration()) {
705
                    $this->static_acceleration_set($keystofind[$key], $value);
706
                }
707
                if ($value instanceof cached_object) {
708
                    $value = $value->restore_object();
709
                }
710
                $resultstore[$key] = $value;
711
            }
712
        }
713
 
714
        // Merge the result from the persis cache with the results from the store load.
715
        $result = $resultpersist + $resultstore;
716
        unset($resultpersist);
717
        unset($resultstore);
718
 
719
        // Next we need to find any missing values and load them from the loader/datasource next in the chain.
720
        $usingloader = ($this->loader !== false);
721
        $usingsource = (!$usingloader && ($this->datasource !== false));
722
        if ($usingloader || $usingsource) {
723
            $missingkeys = [];
724
            foreach ($result as $key => $value) {
725
                if ($value === false) {
726
                    $missingkeys[] = $parsedkeys[$key];
727
                }
728
            }
729
            if (!empty($missingkeys)) {
730
                if ($usingloader) {
731
                    $resultmissing = $this->loader->get_many($missingkeys);
732
                } else {
733
                    $resultmissing = $this->datasource->load_many_for_cache($missingkeys);
734
                }
735
                foreach ($resultmissing as $key => $value) {
736
                    $result[$keysparsed[$key]] = $value;
737
                    $lock = false;
738
                    try {
739
                        if (!empty($this->requirelockingbeforewrite)) {
740
                            $this->acquire_lock($key);
741
                            $lock = true;
742
                        }
743
                        if ($value !== false) {
744
                            $this->set($key, $value);
745
                        }
746
                    } finally {
747
                        if ($lock) {
748
                            $this->release_lock($key);
749
                        }
750
                    }
751
                }
752
                unset($resultmissing);
753
            }
754
            unset($missingkeys);
755
        }
756
 
757
        // Create an array with the original keys and the found values. This will be what we return.
758
        $fullresult = [];
759
        foreach ($result as $key => $value) {
760
            if (!is_scalar($value)) {
761
                // If data is an object it will be a reference.
762
                // If data is an array if may contain references.
763
                // We want to break references so that the cache cannot be modified outside of itself.
764
                // Call the function to unreference it (in the best way possible).
765
                $value = $this->unref($value);
766
            }
767
            $fullresult[$parsedkeys[$key]] = $value;
768
        }
769
        unset($result);
770
 
771
        // Final step is to check strictness.
772
        if ($strictness === MUST_EXIST) {
773
            foreach ($keys as $key) {
774
                if (!array_key_exists($key, $fullresult)) {
775
                    throw new coding_exception('Not all the requested keys existed within the cache stores.');
776
                }
777
            }
778
        }
779
 
780
        if ($this->perfdebug) {
781
            $hits = 0;
782
            $misses = 0;
783
            foreach ($fullresult as $value) {
784
                if ($value === false) {
785
                    $misses++;
786
                } else {
787
                    $hits++;
788
                }
789
            }
790
            helper::record_cache_hit($this->store, $this->definition, $hits, $readbytes);
791
            helper::record_cache_miss($this->store, $this->definition, $misses);
792
        }
793
 
794
        // Return the result. Phew!
795
        return $fullresult;
796
    }
797
 
798
    /**
799
     * Sends a key => value pair to the cache.
800
     *
801
     * <code>
802
     * // This code will add four entries to the cache, one for each url.
803
     * $cache->set('main', 'http://moodle.org');
804
     * $cache->set('docs', 'http://docs.moodle.org');
805
     * $cache->set('tracker', 'http://tracker.moodle.org');
806
     * $cache->set('qa', 'http://qa.moodle.net');
807
     * </code>
808
     *
809
     * @param string|int $key The key for the data being requested.
810
     *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
811
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
812
     * @param mixed $data The data to set against the key.
813
     * @return bool True on success, false otherwise.
814
     */
815
    public function set($key, $data) {
816
        return $this->set_implementation($key, self::VERSION_NONE, $data);
817
    }
818
 
819
    /**
820
     * Sets the value for the given key with the given version.
821
     *
822
     * The cache does not store multiple versions - any existing version will be overwritten with
823
     * this one. This function should only be used if there is a known 'current version' (e.g.
824
     * stored in a database table). It only ensures that the cache does not return outdated data.
825
     *
826
     * This function can be used to help implement localisable caches (where the cache could be
827
     * stored on a local server as well as a shared cache). The version will be recorded alongside
828
     * the item and get_versioned will always return the correct version.
829
     *
830
     * The version number must be an integer that always increases. This could be based on the
831
     * current time, or a stored value that increases by 1 each time it changes, etc.
832
     *
833
     * If you use this function you must use get_versioned to retrieve the data.
834
     *
835
     * @param string|int $key The key for the data being set.
836
     * @param int $version Integer for the version of the data
837
     * @param mixed $data The data to set against the key.
838
     * @return bool True on success, false otherwise.
839
     */
840
    public function set_versioned($key, int $version, $data): bool {
841
        return $this->set_implementation($key, $version, $data);
842
    }
843
 
844
    /**
845
     * Sets the value for the given key, optionally with a version tag.
846
     *
847
     * @param string|int $key The key for the data being set.
848
     * @param int $version Version number for the data or cache::VERSION_NONE if none
849
     * @param mixed $data The data to set against the key.
850
     * @param bool $setparents If true, sets all parent loaders, otherwise only this one
851
     * @return bool True on success, false otherwise.
852
     */
853
    protected function set_implementation($key, int $version, $data, bool $setparents = true): bool {
854
        if ($this->loader !== false && $setparents) {
855
            // We have a loader available set it there as well.
856
            // We have to let the loader do its own parsing of data as it may be unique.
857
            if ($version === self::VERSION_NONE) {
858
                $this->loader->set($key, $data);
859
            } else {
860
                $this->loader->set_versioned($key, $version, $data);
861
            }
862
        }
863
        $usestaticacceleration = $this->use_static_acceleration();
864
 
865
        if (is_object($data) && $data instanceof cacheable_object_interface) {
866
            $data = new cached_object($data);
867
        } else if (!$this->store->supports_dereferencing_objects() && !is_scalar($data)) {
868
            // If data is an object it will be a reference.
869
            // If data is an array if may contain references.
870
            // We want to break references so that the cache cannot be modified outside of itself.
871
            // Call the function to unreference it (in the best way possible).
872
            $data = $this->unref($data);
873
        }
874
 
875
        if ($usestaticacceleration) {
876
            // Static acceleration cache should include the cache version wrapper, but not TTL.
877
            if ($version === self::VERSION_NONE) {
878
                $this->static_acceleration_set($key, $data);
879
            } else {
880
                $this->static_acceleration_set($key, new \core_cache\version_wrapper($data, $version));
881
            }
882
        }
883
 
884
        if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
885
            $data = new ttl_wrapper($data, $this->definition->get_ttl());
886
        }
887
        $parsedkey = $this->parse_key($key);
888
 
889
        if ($version !== self::VERSION_NONE) {
890
            $data = new \core_cache\version_wrapper($data, $version);
891
        }
892
 
893
        $success = $this->store->set($parsedkey, $data);
894
        if ($this->perfdebug) {
895
            helper::record_cache_set(
896
                $this->store,
897
                $this->definition,
898
                1,
899
                $this->store->get_last_io_bytes()
900
            );
901
        }
902
        return $success;
903
    }
904
 
905
    /**
906
     * Removes references where required.
907
     *
908
     * @param stdClass|array $data
909
     * @return mixed What ever was put in but without any references.
910
     */
911
    protected function unref($data) {
912
        if ($this->definition->uses_simple_data()) {
913
            return $data;
914
        }
915
        // Check if it requires serialisation in order to produce a reference free copy.
916
        if ($this->requires_serialisation($data)) {
917
            // Damn, its going to have to be serialise.
918
            $data = serialize($data);
919
            // We unserialise immediately so that we don't have to do it every time on get.
920
            $data = unserialize($data);
921
        } else if (!is_scalar($data)) {
922
            // Its safe to clone, lets do it, its going to beat the pants of serialisation.
923
            $data = $this->deep_clone($data);
924
        }
925
        return $data;
926
    }
927
 
928
    /**
929
     * Checks to see if a var requires serialisation.
930
     *
931
     * @param mixed $value The value to check.
932
     * @param int $depth Used to ensure we don't enter an endless loop (think recursion).
933
     * @return bool Returns true if the value is going to require serialisation in order to ensure a reference free copy
934
     *      or false if its safe to clone.
935
     */
936
    protected function requires_serialisation($value, $depth = 1) {
937
        if (is_scalar($value)) {
938
            return false;
939
        } else if (is_array($value) || $value instanceof stdClass || $value instanceof Traversable) {
940
            if ($depth > 5) {
941
                // Skrew it, mega-deep object, developer you suck, we're just going to serialise.
942
                return true;
943
            }
944
            foreach ($value as $key => $subvalue) {
945
                if ($this->requires_serialisation($subvalue, $depth++)) {
946
                    return true;
947
                }
948
            }
949
        }
950
        // Its not scalar, array, or stdClass so we'll need to serialise.
951
        return true;
952
    }
953
 
954
    /**
955
     * Creates a reference free clone of the given value.
956
     *
957
     * @param mixed $value
958
     * @return mixed
959
     */
960
    protected function deep_clone($value) {
961
        if (is_object($value)) {
962
            // Objects must be cloned to begin with.
963
            $value = clone $value;
964
        }
965
        if (is_array($value) || is_object($value)) {
966
            foreach ($value as $key => $subvalue) {
967
                $value[$key] = $this->deep_clone($subvalue);
968
            }
969
        }
970
        return $value;
971
    }
972
 
973
    /**
974
     * Sends several key => value pairs to the cache.
975
     *
976
     * Using this function comes with potential performance implications.
977
     * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
978
     * the equivalent singular method for each item provided.
979
     * This should not deter you from using this function as there is a performance benefit in situations where the cache store
980
     * does support it, but you should be aware of this fact.
981
     *
982
     * <code>
983
     * // This code will add four entries to the cache, one for each url.
984
     * $cache->set_many(array(
985
     *     'main' => 'http://moodle.org',
986
     *     'docs' => 'http://docs.moodle.org',
987
     *     'tracker' => 'http://tracker.moodle.org',
988
     *     'qa' => ''http://qa.moodle.net'
989
     * ));
990
     * </code>
991
     *
992
     * @param array $keyvaluearray An array of key => value pairs to send to the cache.
993
     * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
994
     *      ... if they care that is.
995
     */
996
    public function set_many(array $keyvaluearray) {
997
        if ($this->loader !== false) {
998
            // We have a loader available set it there as well.
999
            // We have to let the loader do its own parsing of data as it may be unique.
1000
            $this->loader->set_many($keyvaluearray);
1001
        }
1002
        $data = array();
1003
        $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
1004
        $usestaticaccelerationarray = $this->use_static_acceleration();
1005
        $needsdereferencing = !$this->store->supports_dereferencing_objects();
1006
        foreach ($keyvaluearray as $key => $value) {
1007
            if (is_object($value) && $value instanceof cacheable_object_interface) {
1008
                $value = new cached_object($value);
1009
            } else if ($needsdereferencing && !is_scalar($value)) {
1010
                // If data is an object it will be a reference.
1011
                // If data is an array if may contain references.
1012
                // We want to break references so that the cache cannot be modified outside of itself.
1013
                // Call the function to unreference it (in the best way possible).
1014
                $value = $this->unref($value);
1015
            }
1016
            if ($usestaticaccelerationarray) {
1017
                $this->static_acceleration_set($key, $value);
1018
            }
1019
            if ($simulatettl) {
1020
                $value = new ttl_wrapper($value, $this->definition->get_ttl());
1021
            }
1022
            $data[$key] = [
1023
                'key' => $this->parse_key($key),
1024
                'value' => $value,
1025
            ];
1026
        }
1027
        $successfullyset = $this->store->set_many($data);
1028
        if ($this->perfdebug && $successfullyset) {
1029
            helper::record_cache_set(
1030
                $this->store,
1031
                $this->definition,
1032
                $successfullyset,
1033
                $this->store->get_last_io_bytes()
1034
            );
1035
        }
1036
        return $successfullyset;
1037
    }
1038
 
1039
    /**
1040
     * Test is a cache has a key.
1041
     *
1042
     * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
1043
     * test and any subsequent action (get, set, delete etc).
1044
     * Instead it is recommended to write your code in such a way they it performs the following steps:
1045
     * <ol>
1046
     * <li>Attempt to retrieve the information.</li>
1047
     * <li>Generate the information.</li>
1048
     * <li>Attempt to set the information</li>
1049
     * </ol>
1050
     *
1051
     * Its also worth mentioning that not all stores support key tests.
1052
     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
1053
     * Just one more reason you should not use these methods unless you have a very good reason to do so.
1054
     *
1055
     * @param string|int $key
1056
     * @param bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
1057
     *      data source then the code will try load the key value from the next item in the chain.
1058
     * @return bool True if the cache has the requested key, false otherwise.
1059
     */
1060
    public function has($key, $tryloadifpossible = false) {
1061
        if ($this->static_acceleration_has($key)) {
1062
            // Hoorah, that was easy. It exists in the static acceleration array so we definitely have it.
1063
            return true;
1064
        }
1065
        $parsedkey = $this->parse_key($key);
1066
 
1067
        if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
1068
            // The data has a TTL and the store doesn't support it natively.
1069
            // We must fetch the data and expect a ttl wrapper.
1070
            $data = $this->store->get($parsedkey);
1071
            $has = ($data instanceof ttl_wrapper && !$data->has_expired());
1072
        } else if (!$this->store_supports_key_awareness()) {
1073
            // The store doesn't support key awareness, get the data and check it manually... puke.
1074
            // Either no TTL is set of the store supports its handling natively.
1075
            $data = $this->store->get($parsedkey);
1076
            $has = ($data !== false);
1077
        } else {
1078
            // The store supports key awareness, this is easy!
1079
            // Either no TTL is set of the store supports its handling natively.
1080
            $has = $this->store->has($parsedkey);
1081
        }
1082
        if (!$has && $tryloadifpossible) {
1083
            if ($this->loader !== false) {
1084
                $result = $this->loader->get($parsedkey);
1085
            } else if ($this->datasource !== null) {
1086
                $result = $this->datasource->load_for_cache($key);
1087
            }
1088
            $has = ($result !== null);
1089
            if ($has) {
1090
                $this->set($key, $result);
1091
            }
1092
        }
1093
        return $has;
1094
    }
1095
 
1096
    /**
1097
     * Test is a cache has all of the given keys.
1098
     *
1099
     * It is strongly recommended to avoid the use of this function if not absolutely required.
1100
     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
1101
     *
1102
     * Its also worth mentioning that not all stores support key tests.
1103
     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
1104
     * Just one more reason you should not use these methods unless you have a very good reason to do so.
1105
     *
1106
     * @param array $keys
1107
     * @return bool True if the cache has all of the given keys, false otherwise.
1108
     */
1109
    public function has_all(array $keys) {
1110
        if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
1111
            foreach ($keys as $key) {
1112
                if (!$this->has($key)) {
1113
                    return false;
1114
                }
1115
            }
1116
            return true;
1117
        }
1118
        $parsedkeys = array_map([$this, 'parse_key'], $keys);
1119
        return $this->store->has_all($parsedkeys);
1120
    }
1121
 
1122
    /**
1123
     * Test if a cache has at least one of the given keys.
1124
     *
1125
     * It is strongly recommended to avoid the use of this function if not absolutely required.
1126
     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
1127
     *
1128
     * Its also worth mentioning that not all stores support key tests.
1129
     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
1130
     * Just one more reason you should not use these methods unless you have a very good reason to do so.
1131
     *
1132
     * @param array $keys
1133
     * @return bool True if the cache has at least one of the given keys
1134
     */
1135
    public function has_any(array $keys) {
1136
        if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
1137
            foreach ($keys as $key) {
1138
                if ($this->has($key)) {
1139
                    return true;
1140
                }
1141
            }
1142
            return false;
1143
        }
1144
 
1145
        if ($this->use_static_acceleration()) {
1146
            foreach ($keys as $id => $key) {
1147
                if ($this->static_acceleration_has($key)) {
1148
                    return true;
1149
                }
1150
            }
1151
        }
1152
        $parsedkeys = array_map([$this, 'parse_key'], $keys);
1153
        return $this->store->has_any($parsedkeys);
1154
    }
1155
 
1156
    /**
1157
     * Delete the given key from the cache.
1158
     *
1159
     * @param string|int $key The key to delete.
1160
     * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
1161
     *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
1162
     * @return bool True of success, false otherwise.
1163
     */
1164
    public function delete($key, $recurse = true) {
1165
        $this->static_acceleration_delete($key);
1166
        if ($recurse && $this->loader !== false) {
1167
            // Delete from the bottom of the stack first.
1168
            $this->loader->delete($key, $recurse);
1169
        }
1170
        $parsedkey = $this->parse_key($key);
1171
        return $this->store->delete($parsedkey);
1172
    }
1173
 
1174
    /**
1175
     * Delete all of the given keys from the cache.
1176
     *
1177
     * @param array $keys The key to delete.
1178
     * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
1179
     *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
1180
     * @return int The number of items successfully deleted.
1181
     */
1182
    public function delete_many(array $keys, $recurse = true) {
1183
        if ($this->use_static_acceleration()) {
1184
            foreach ($keys as $key) {
1185
                $this->static_acceleration_delete($key);
1186
            }
1187
        }
1188
        if ($recurse && $this->loader !== false) {
1189
            // Delete from the bottom of the stack first.
1190
            $this->loader->delete_many($keys, $recurse);
1191
        }
1192
        $parsedkeys = array_map([$this, 'parse_key'], $keys);
1193
        return $this->store->delete_many($parsedkeys);
1194
    }
1195
 
1196
    /**
1197
     * Purges the cache store, and loader if there is one.
1198
     *
1199
     * @return bool True on success, false otherwise
1200
     */
1201
    public function purge() {
1202
        // 1. Purge the static acceleration array.
1203
        $this->static_acceleration_purge();
1204
        // 2. Purge the store.
1205
        $this->store->purge();
1206
        // 3. Optionally pruge any stacked loaders.
1207
        if ($this->loader) {
1208
            $this->loader->purge();
1209
        }
1210
        return true;
1211
    }
1212
 
1213
    /**
1214
     * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
1215
     *
1216
     * @param string|int $key As passed to get|set|delete etc.
1217
     * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
1218
     */
1219
    protected function parse_key($key) {
1220
        // First up if the store supports multiple keys we'll go with that.
1221
        if ($this->store->supports_multiple_identifiers()) {
1222
            $result = $this->definition->generate_multi_key_parts();
1223
            $result['key'] = $key;
1224
            return $result;
1225
        }
1226
        // If not we need to generate a hash and to for that we use the helper.
1227
        return helper::hash_key($key, $this->definition);
1228
    }
1229
 
1230
    /**
1231
     * Returns true if the cache is making use of a ttl.
1232
     * @return bool
1233
     */
1234
    protected function has_a_ttl() {
1235
        return $this->hasattl;
1236
    }
1237
 
1238
    /**
1239
     * Returns true if the cache store supports native ttl.
1240
     * @return bool
1241
     */
1242
    protected function store_supports_native_ttl() {
1243
        if ($this->supportsnativettl === null) {
1244
            $this->supportsnativettl = ($this->store->supports_native_ttl());
1245
        }
1246
        return $this->supportsnativettl;
1247
    }
1248
 
1249
    /**
1250
     * Returns the cache definition.
1251
     *
1252
     * @return definition
1253
     */
1254
    protected function get_definition() {
1255
        return $this->definition;
1256
    }
1257
 
1258
    /**
1259
     * Returns the cache store
1260
     *
1261
     * @return store
1262
     */
1263
    protected function get_store() {
1264
        return $this->store;
1265
    }
1266
 
1267
    /**
1268
     * Returns the loader associated with this instance.
1269
     *
1270
     * @since Moodle 2.4.4
1271
     * @return cache|false
1272
     */
1273
    protected function get_loader() {
1274
        return $this->loader;
1275
    }
1276
 
1277
    /**
1278
     * Returns the data source associated with this cache.
1279
     *
1280
     * @since Moodle 2.4.4
1281
     * @return data_source_interface|false
1282
     */
1283
    protected function get_datasource() {
1284
        return $this->datasource;
1285
    }
1286
 
1287
    /**
1288
     * Returns true if the store supports key awareness.
1289
     *
1290
     * @return bool
1291
     */
1292
    protected function store_supports_key_awareness() {
1293
        if ($this->supportskeyawareness === null) {
1294
            $this->supportskeyawareness = ($this->store instanceof key_aware_cache_interface);
1295
        }
1296
        return $this->supportskeyawareness;
1297
    }
1298
 
1299
    /**
1300
     * Returns true if the store natively supports locking.
1301
     *
1302
     * @return bool
1303
     */
1304
    protected function store_supports_native_locking() {
1305
        if ($this->nativelocking === null) {
1306
            $this->nativelocking = ($this->store instanceof lockable_cache_interface);
1307
        }
1308
        return $this->nativelocking;
1309
    }
1310
 
1311
    /**
1312
     * Returns true if this cache is making use of the static acceleration array.
1313
     *
1314
     * @return bool
1315
     */
1316
    protected function use_static_acceleration() {
1317
        return $this->staticacceleration;
1318
    }
1319
 
1320
    /**
1321
     * Returns true if the requested key exists within the static acceleration array.
1322
     *
1323
     * @param string $key The parsed key
1324
     * @return bool
1325
     */
1326
    protected function static_acceleration_has($key) {
1327
        // This could be written as a single line, however it has been split because the ttl check is faster than the instanceof
1328
        // and has_expired calls.
1329
        if (!$this->staticacceleration || !isset($this->staticaccelerationarray[$key])) {
1330
            return false;
1331
        }
1332
        return true;
1333
    }
1334
 
1335
    /**
1336
     * Returns the item from the static acceleration array if it exists there.
1337
     *
1338
     * @param string $key The parsed key
1339
     * @return mixed|false Dereferenced data from the static acceleration array or false if it wasn't there.
1340
     */
1341
    protected function static_acceleration_get($key) {
1342
        if (!$this->staticacceleration || !isset($this->staticaccelerationarray[$key])) {
1343
            $result = false;
1344
        } else {
1345
            $data = $this->staticaccelerationarray[$key]['data'];
1346
 
1347
            if ($data instanceof cached_object) {
1348
                $result = $data->restore_object();
1349
            } else if ($this->staticaccelerationarray[$key]['serialized']) {
1350
                $result = unserialize($data);
1351
            } else {
1352
                $result = $data;
1353
            }
1354
        }
1355
        if (helper::result_found($result)) {
1356
            if ($this->perfdebug) {
1357
                helper::record_cache_hit(store::STATIC_ACCEL, $this->definition);
1358
            }
1359
            if ($this->staticaccelerationsize > 1 && $this->staticaccelerationcount > 1) {
1360
                // Check to see if this is the last item on the static acceleration keys array.
1361
                if (end($this->staticaccelerationkeys) !== $key) {
1362
                    // It isn't the last item.
1363
                    // Move the item to the end of the array so that it is last to be removed.
1364
                    unset($this->staticaccelerationkeys[$key]);
1365
                    $this->staticaccelerationkeys[$key] = $key;
1366
                }
1367
            }
1368
            return $result;
1369
        } else {
1370
            if ($this->perfdebug) {
1371
                helper::record_cache_miss(store::STATIC_ACCEL, $this->definition);
1372
            }
1373
            return false;
1374
        }
1375
    }
1376
 
1377
    /**
1378
     * Sets a key value pair into the static acceleration array.
1379
     *
1380
     * @param string $key The parsed key
1381
     * @param mixed $data
1382
     * @return bool
1383
     */
1384
    protected function static_acceleration_set($key, $data) {
1385
        if ($this->staticaccelerationsize !== false && isset($this->staticaccelerationkeys[$key])) {
1386
            $this->staticaccelerationcount--;
1387
            unset($this->staticaccelerationkeys[$key]);
1388
        }
1389
 
1390
        // We serialize anything that's not;
1391
        // 1. A known scalar safe value.
1392
        // 2. A definition that says it's simpledata.  We trust it that it doesn't contain dangerous references.
1393
        // 3. An object that handles dereferencing by itself.
1394
        if (
1395
            is_scalar($data) || $this->definition->uses_simple_data()
1396
                || $data instanceof cached_object
1397
        ) {
1398
            $this->staticaccelerationarray[$key]['data'] = $data;
1399
            $this->staticaccelerationarray[$key]['serialized'] = false;
1400
        } else {
1401
            $this->staticaccelerationarray[$key]['data'] = serialize($data);
1402
            $this->staticaccelerationarray[$key]['serialized'] = true;
1403
        }
1404
        if ($this->staticaccelerationsize !== false) {
1405
            $this->staticaccelerationcount++;
1406
            $this->staticaccelerationkeys[$key] = $key;
1407
            if ($this->staticaccelerationcount > $this->staticaccelerationsize) {
1408
                $dropkey = array_shift($this->staticaccelerationkeys);
1409
                unset($this->staticaccelerationarray[$dropkey]);
1410
                $this->staticaccelerationcount--;
1411
            }
1412
        }
1413
        return true;
1414
    }
1415
 
1416
    /**
1417
     * Deletes an item from the static acceleration array.
1418
     *
1419
     * @param string|int $key As given to get|set|delete
1420
     * @return bool True on success, false otherwise.
1421
     */
1422
    protected function static_acceleration_delete($key) {
1423
        unset($this->staticaccelerationarray[$key]);
1424
        if ($this->staticaccelerationsize !== false && isset($this->staticaccelerationkeys[$key])) {
1425
            unset($this->staticaccelerationkeys[$key]);
1426
            $this->staticaccelerationcount--;
1427
        }
1428
        return true;
1429
    }
1430
 
1431
    /**
1432
     * Purge the static acceleration cache.
1433
     */
1434
    protected function static_acceleration_purge() {
1435
        $this->staticaccelerationarray = [];
1436
        if ($this->staticaccelerationsize !== false) {
1437
            $this->staticaccelerationkeys = [];
1438
            $this->staticaccelerationcount = 0;
1439
        }
1440
    }
1441
 
1442
    /**
1443
     * Returns the timestamp from the first request for the time from the cache API.
1444
     *
1445
     * This stamp needs to be used for all ttl and time based operations to ensure that we don't end up with
1446
     * timing issues.
1447
     *
1448
     * @param   bool    $float Whether to use floating precision accuracy.
1449
     * @return  int|float
1450
     */
1451
    public static function now($float = false) {
1452
        if (self::$now === null) {
1453
            self::$now = microtime(true);
1454
        }
1455
 
1456
        if ($float) {
1457
            return self::$now;
1458
        } else {
1459
            return (int) self::$now;
1460
        }
1461
    }
1462
 
1463
    /**
1464
     * Get a 'purge' token used for cache invalidation handling.
1465
     *
1466
     * Note: This function is intended for use from within the Cache API only and not by plugins, or cache stores.
1467
     *
1468
     * @param   bool    $reset  Whether to reset the token and generate a new one.
1469
     * @return  string
1470
     */
1471
    public static function get_purge_token($reset = false) {
1472
        if (self::$purgetoken === null || $reset) {
1473
            self::$now = null;
1474
            self::$purgetoken = self::now(true) . '-' . uniqid('', true);
1475
        }
1476
 
1477
        return self::$purgetoken;
1478
    }
1479
 
1480
    /**
1481
     * Compare a pair of purge tokens.
1482
     *
1483
     * If the two tokens are identical, then the return value is 0.
1484
     * If the time component of token A is newer than token B, then a positive value is returned.
1485
     * If the time component of token B is newer than token A, then a negative value is returned.
1486
     *
1487
     * Note: This function is intended for use from within the Cache API only and not by plugins, or cache stores.
1488
     *
1489
     * @param   string  $tokena
1490
     * @param   string  $tokenb
1491
     * @return  int
1492
     */
1493
    public static function compare_purge_tokens($tokena, $tokenb) {
1494
        if ($tokena === $tokenb) {
1495
            // There is an exact match.
1496
            return 0;
1497
        }
1498
 
1499
        // The token for when the cache was last invalidated.
1500
        [$atime] = explode('-', "{$tokena}-", 2);
1501
 
1502
        // The token for this cache.
1503
        [$btime] = explode('-', "{$tokenb}-", 2);
1504
 
1505
        if ($atime >= $btime) {
1506
            // Token A is newer.
1507
            return 1;
1508
        } else {
1509
            // Token A is older.
1510
            return -1;
1511
        }
1512
    }
1513
 
1514
    /**
1515
     * Subclasses may support purging cache of all data belonging to the
1516
     * current user.
1517
     */
1518
    public function purge_current_user() {
1519
    }
1520
}
1521
 
1522
// Alias this class to the old name.
1523
// This file will be autoloaded by the legacyclasses autoload system.
1524
// In future all uses of this class will be corrected and the legacy references will be removed.
1525
class_alias(cache::class, \cache::class);