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
 
21
/**
22
 * A session cache.
23
 *
24
 * This class is used for session caches returned by the cache::make methods.
25
 *
26
 * It differs from the application loader in a couple of noteable ways:
27
 *    1. Sessions are always expected to exist.
28
 *       Because of this we don't ever use the static acceleration array.
29
 *    2. Session data for a loader instance (store + definition) is consolidate into a
30
 *       single array for storage within the store.
31
 *       Along with this we embed a lastaccessed time with the data. This way we can
32
 *       check sessions for a last access time.
33
 *    3. Session stores are required to support key searching and must
34
 *       implement searchable_cache_interface. This ensures stores used for the cache can be
35
 *       targetted for garbage collection of session data.
36
 *
37
 * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
38
 * It is technically possible to call those methods through this class however there is no guarantee that you will get an
39
 * instance of this class back again.
40
 *
41
 * @todo we should support locking in the session as well. Should be pretty simple to set up.
42
 *
43
 * @internal don't use me directly.
44
 * @method store|searchable_cache_interface get_store() Returns the cache store which must implement
45
 *                                                      both searchable_cache_interface.
46
 *
47
 * @package    core_cache
48
 * @category   cache
49
 * @copyright  2012 Sam Hemelryk
50
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51
 */
52
class session_cache extends cache {
53
    /**
54
     * The user the session has been established for.
55
     * @var int
56
     */
57
    protected static $loadeduserid = null;
58
 
59
    /**
60
     * The userid this cache is currently using.
61
     * @var int
62
     */
63
    protected $currentuserid = null;
64
 
65
    /**
66
     * The session id we are currently using.
67
     * @var array
68
     */
69
    protected $sessionid = null;
70
 
71
    /**
72
     * The session data for the above session id.
73
     * @var array
74
     */
75
    protected $session = null;
76
 
77
    /**
78
     * Constant used to prefix keys.
79
     */
80
    const KEY_PREFIX = 'sess_';
81
 
82
    /**
83
     * This is the key used to track last access.
84
     */
85
    const LASTACCESS = '__lastaccess__';
86
 
87
    /**
88
     * Override the cache::construct method.
89
     *
90
     * This function gets overriden so that we can process any invalidation events if need be.
91
     * If the definition doesn't have any invalidation events then this occurs exactly as it would for the cache class.
92
     * Otherwise we look at the last invalidation time and then check the invalidation data for events that have occured
93
     * between then now.
94
     *
95
     * You should not call this method from your code, instead you should use the cache::make methods.
96
     *
97
     * @param definition $definition
98
     * @param store $store
99
     * @param loader_interface|data_source_interface $loader
100
     */
101
    public function __construct(definition $definition, store $store, $loader = null) {
102
        // First up copy the loadeduserid to the current user id.
103
        $this->currentuserid = self::$loadeduserid;
104
        $this->set_session_id();
105
        parent::__construct($definition, $store, $loader);
106
 
107
        // This will trigger check tracked user. If this gets removed a call to that will need to be added here in its place.
108
        $this->set(self::LASTACCESS, cache::now());
109
 
110
        $this->handle_invalidation_events();
111
    }
112
 
113
    /**
114
     * Sets the session id for the loader.
115
     */
116
    protected function set_session_id() {
117
        $this->sessionid = preg_replace('#[^a-zA-Z0-9_]#', '_', session_id());
118
    }
119
 
120
    /**
121
     * Returns the prefix used for all keys.
122
     * @return string
123
     */
124
    protected function get_key_prefix() {
125
        return 'u' . $this->currentuserid . '_' . $this->sessionid;
126
    }
127
 
128
    /**
129
     * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
130
     *
131
     * This function is called for every operation that uses keys. For this reason we use this function to also check
132
     * that the current user is the same as the user who last used this cache.
133
     *
134
     * On top of that if prepends the string 'sess_' to the start of all keys. The _ ensures things are easily identifiable.
135
     *
136
     * @param string|int $key As passed to get|set|delete etc.
137
     * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
138
     */
139
    protected function parse_key($key) {
140
        $prefix = $this->get_key_prefix();
141
        if ($key === self::LASTACCESS) {
142
            return $key . $prefix;
143
        }
144
        return $prefix . '_' . parent::parse_key($key);
145
    }
146
 
147
    /**
148
     * Check that this cache instance is tracking the current user.
149
     */
150
    protected function check_tracked_user() {
151
        if (isset($_SESSION['USER']->id) && $_SESSION['USER']->id !== null) {
152
            // Get the id of the current user.
153
            $new = $_SESSION['USER']->id;
154
        } else {
155
            // No user set up yet.
156
            $new = 0;
157
        }
158
        if ($new !== self::$loadeduserid) {
159
            // The current user doesn't match the tracked userid for this request.
160
            if (!is_null(self::$loadeduserid)) {
161
                // Purge the data we have for the old user.
162
                // This way we don't bloat the session.
163
                $this->purge();
164
            }
165
            self::$loadeduserid = $new;
166
            $this->currentuserid = $new;
167
        } else if ($new !== $this->currentuserid) {
168
            // The current user matches the loaded user but not the user last used by this cache.
169
            $this->purge_current_user();
170
            $this->currentuserid = $new;
171
        }
172
    }
173
 
174
    /**
175
     * Purges the session cache of all data belonging to the current user.
176
     */
177
    public function purge_current_user() {
178
        $keys = $this->get_store()->find_by_prefix($this->get_key_prefix());
179
        $this->get_store()->delete_many($keys);
180
    }
181
 
182
    /**
183
     * Retrieves the value for the given key from the cache.
184
     *
185
     * @param string|int $key The key for the data being requested.
186
     *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
187
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
188
     * @param int $requiredversion Minimum required version of the data or cache::VERSION_NONE
189
     * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
190
     * @param mixed &$actualversion If specified, will be set to the actual version number retrieved
191
     * @return mixed|false The data from the cache or false if the key did not exist within the cache.
192
     * @throws coding_exception
193
     */
194
    protected function get_implementation($key, int $requiredversion, int $strictness, &$actualversion = null) {
195
        // Check the tracked user.
196
        $this->check_tracked_user();
197
 
198
        // Use parent code.
199
        return parent::get_implementation($key, $requiredversion, $strictness, $actualversion);
200
    }
201
 
202
    /**
203
     * Sends a key => value pair to the cache.
204
     *
205
     * <code>
206
     * // This code will add four entries to the cache, one for each url.
207
     * $cache->set('main', 'http://moodle.org');
208
     * $cache->set('docs', 'http://docs.moodle.org');
209
     * $cache->set('tracker', 'http://tracker.moodle.org');
210
     * $cache->set('qa', 'http://qa.moodle.net');
211
     * </code>
212
     *
213
     * @param string|int $key The key for the data being requested.
214
     *      It can be any structure although using a scalar string or int is recommended in the interests of performance.
215
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
216
     * @param mixed $data The data to set against the key.
217
     * @return bool True on success, false otherwise.
218
     */
219
    public function set($key, $data) {
220
        $this->check_tracked_user();
221
        $loader = $this->get_loader();
222
        if ($loader !== false) {
223
            // We have a loader available set it there as well.
224
            // We have to let the loader do its own parsing of data as it may be unique.
225
            $loader->set($key, $data);
226
        }
227
        if (is_object($data) && $data instanceof cacheable_object_interface) {
228
            $data = new cached_object($data);
229
        } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($data)) {
230
            // If data is an object it will be a reference.
231
            // If data is an array if may contain references.
232
            // We want to break references so that the cache cannot be modified outside of itself.
233
            // Call the function to unreference it (in the best way possible).
234
            $data = $this->unref($data);
235
        }
236
        // We dont' support native TTL here as we consolidate data for sessions.
237
        if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
238
            $data = new ttl_wrapper($data, $this->get_definition()->get_ttl());
239
        }
240
        $success = $this->get_store()->set($this->parse_key($key), $data);
241
        if ($this->perfdebug) {
242
            helper::record_cache_set(
243
                $this->get_store(),
244
                $this->get_definition(),
245
                1,
246
                $this->get_store()->get_last_io_bytes()
247
            );
248
        }
249
        return $success;
250
    }
251
 
252
    /**
253
     * Delete the given key from the cache.
254
     *
255
     * @param string|int $key The key to delete.
256
     * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
257
     *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
258
     * @return bool True of success, false otherwise.
259
     */
260
    public function delete($key, $recurse = true) {
261
        $parsedkey = $this->parse_key($key);
262
        if ($recurse && $this->get_loader() !== false) {
263
            // Delete from the bottom of the stack first.
264
            $this->get_loader()->delete($key, $recurse);
265
        }
266
        return $this->get_store()->delete($parsedkey);
267
    }
268
 
269
    /**
270
     * Retrieves an array of values for an array of keys.
271
     *
272
     * Using this function comes with potential performance implications.
273
     * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
274
     * the equivalent singular method for each item provided.
275
     * This should not deter you from using this function as there is a performance benefit in situations where the cache store
276
     * does support it, but you should be aware of this fact.
277
     *
278
     * @param array $keys The keys of the data being requested.
279
     *      Each key can be any structure although using a scalar string or int is recommended in the interests of performance.
280
     *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
281
     * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
282
     * @return array An array of key value pairs for the items that could be retrieved from the cache.
283
     *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
284
     *      Otherwise any key that did not exist will have a data value of false within the results.
285
     * @throws coding_exception
286
     */
287
    public function get_many(array $keys, $strictness = IGNORE_MISSING) {
288
        $this->check_tracked_user();
289
        $parsedkeys = [];
290
        $keymap = [];
291
        foreach ($keys as $key) {
292
            $parsedkey = $this->parse_key($key);
293
            $parsedkeys[$key] = $parsedkey;
294
            $keymap[$parsedkey] = $key;
295
        }
296
        $result = $this->get_store()->get_many($parsedkeys);
297
        if ($this->perfdebug) {
298
            $readbytes = $this->get_store()->get_last_io_bytes();
299
        }
300
        $return = [];
301
        $missingkeys = [];
302
        $hasmissingkeys = false;
303
        foreach ($result as $parsedkey => $value) {
304
            $key = $keymap[$parsedkey];
305
            if ($value instanceof ttl_wrapper) {
306
                /* @var ttl_wrapper $value */
307
                if ($value->has_expired()) {
308
                    $this->delete($keymap[$parsedkey]);
309
                    $value = false;
310
                } else {
311
                    $value = $value->data;
312
                }
313
            }
314
            if ($value instanceof cached_object) {
315
                /* @var cached_object $value */
316
                $value = $value->restore_object();
317
            } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($value)) {
318
                // If data is an object it will be a reference.
319
                // If data is an array if may contain references.
320
                // We want to break references so that the cache cannot be modified outside of itself.
321
                // Call the function to unreference it (in the best way possible).
322
                $value = $this->unref($value);
323
            }
324
            $return[$key] = $value;
325
            if ($value === false) {
326
                $hasmissingkeys = true;
327
                $missingkeys[$parsedkey] = $key;
328
            }
329
        }
330
        if ($hasmissingkeys) {
331
            // We've got missing keys - we've got to check any loaders or data sources.
332
            $loader = $this->get_loader();
333
            $datasource = $this->get_datasource();
334
            if ($loader !== false) {
335
                foreach ($loader->get_many($missingkeys) as $key => $value) {
336
                    if ($value !== false) {
337
                        $return[$key] = $value;
338
                        unset($missingkeys[$parsedkeys[$key]]);
339
                    }
340
                }
341
            }
342
            $hasmissingkeys = count($missingkeys) > 0;
343
            if ($datasource !== false && $hasmissingkeys) {
344
                // We're still missing keys but we've got a datasource.
345
                foreach ($datasource->load_many_for_cache($missingkeys) as $key => $value) {
346
                    if ($value !== false) {
347
                        $return[$key] = $value;
348
                        unset($missingkeys[$parsedkeys[$key]]);
349
                    }
350
                }
351
                $hasmissingkeys = count($missingkeys) > 0;
352
            }
353
        }
354
        if ($hasmissingkeys && $strictness === MUST_EXIST) {
355
            throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
356
        }
357
        if ($this->perfdebug) {
358
            $hits = 0;
359
            $misses = 0;
360
            foreach ($return as $value) {
361
                if ($value === false) {
362
                    $misses++;
363
                } else {
364
                    $hits++;
365
                }
366
            }
367
            helper::record_cache_hit($this->get_store(), $this->get_definition(), $hits, $readbytes);
368
            helper::record_cache_miss($this->get_store(), $this->get_definition(), $misses);
369
        }
370
        return $return;
371
    }
372
 
373
    /**
374
     * Delete all of the given keys from the cache.
375
     *
376
     * @param array $keys The key to delete.
377
     * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
378
     *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
379
     * @return int The number of items successfully deleted.
380
     */
381
    public function delete_many(array $keys, $recurse = true) {
382
        $parsedkeys = array_map([$this, 'parse_key'], $keys);
383
        if ($recurse && $this->get_loader() !== false) {
384
            // Delete from the bottom of the stack first.
385
            $this->get_loader()->delete_many($keys, $recurse);
386
        }
387
        return $this->get_store()->delete_many($parsedkeys);
388
    }
389
 
390
    /**
391
     * Sends several key => value pairs to the cache.
392
     *
393
     * Using this function comes with potential performance implications.
394
     * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
395
     * the equivalent singular method for each item provided.
396
     * This should not deter you from using this function as there is a performance benefit in situations where the cache store
397
     * does support it, but you should be aware of this fact.
398
     *
399
     * <code>
400
     * // This code will add four entries to the cache, one for each url.
401
     * $cache->set_many(array(
402
     *     'main' => 'http://moodle.org',
403
     *     'docs' => 'http://docs.moodle.org',
404
     *     'tracker' => 'http://tracker.moodle.org',
405
     *     'qa' => ''http://qa.moodle.net'
406
     * ));
407
     * </code>
408
     *
409
     * @param array $keyvaluearray An array of key => value pairs to send to the cache.
410
     * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
411
     *      ... if they care that is.
412
     */
413
    public function set_many(array $keyvaluearray) {
414
        $this->check_tracked_user();
415
        $loader = $this->get_loader();
416
        if ($loader !== false) {
417
            // We have a loader available set it there as well.
418
            // We have to let the loader do its own parsing of data as it may be unique.
419
            $loader->set_many($keyvaluearray);
420
        }
421
        $data = [];
422
        $definitionid = $this->get_definition()->get_ttl();
423
        $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
424
        foreach ($keyvaluearray as $key => $value) {
425
            if (is_object($value) && $value instanceof cacheable_object_interface) {
426
                $value = new cached_object($value);
427
            } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($value)) {
428
                // If data is an object it will be a reference.
429
                // If data is an array if may contain references.
430
                // We want to break references so that the cache cannot be modified outside of itself.
431
                // Call the function to unreference it (in the best way possible).
432
                $value = $this->unref($value);
433
            }
434
            if ($simulatettl) {
435
                $value = new ttl_wrapper($value, $definitionid);
436
            }
437
            $data[$key] = [
438
                'key' => $this->parse_key($key),
439
                'value' => $value,
440
            ];
441
        }
442
        $successfullyset = $this->get_store()->set_many($data);
443
        if ($this->perfdebug && $successfullyset) {
444
            helper::record_cache_set(
445
                $this->get_store(),
446
                $this->get_definition(),
447
                $successfullyset,
448
                $this->get_store()->get_last_io_bytes()
449
            );
450
        }
451
        return $successfullyset;
452
    }
453
 
454
    /**
455
     * Purges the cache store, and loader if there is one.
456
     *
457
     * @return bool True on success, false otherwise
458
     */
459
    public function purge() {
460
        $this->get_store()->purge();
461
        if ($this->get_loader()) {
462
            $this->get_loader()->purge();
463
        }
464
        return true;
465
    }
466
 
467
    /**
468
     * Test is a cache has a key.
469
     *
470
     * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
471
     * test and any subsequent action (get, set, delete etc).
472
     * Instead it is recommended to write your code in such a way they it performs the following steps:
473
     * <ol>
474
     * <li>Attempt to retrieve the information.</li>
475
     * <li>Generate the information.</li>
476
     * <li>Attempt to set the information</li>
477
     * </ol>
478
     *
479
     * Its also worth mentioning that not all stores support key tests.
480
     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
481
     * Just one more reason you should not use these methods unless you have a very good reason to do so.
482
     *
483
     * @param string|int $key
484
     * @param bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
485
     *      data source then the code will try load the key value from the next item in the chain.
486
     * @return bool True if the cache has the requested key, false otherwise.
487
     */
488
    public function has($key, $tryloadifpossible = false) {
489
        $this->check_tracked_user();
490
        $parsedkey = $this->parse_key($key);
491
        $store = $this->get_store();
492
        if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
493
            // The data has a TTL and the store doesn't support it natively.
494
            // We must fetch the data and expect a ttl wrapper.
495
            $data = $store->get($parsedkey);
496
            $has = ($data instanceof ttl_wrapper && !$data->has_expired());
497
        } else if (!$this->store_supports_key_awareness()) {
498
            // The store doesn't support key awareness, get the data and check it manually... puke.
499
            // Either no TTL is set of the store supports its handling natively.
500
            $data = $store->get($parsedkey);
501
            $has = ($data !== false);
502
        } else {
503
            // The store supports key awareness, this is easy!
504
            // Either no TTL is set of the store supports its handling natively.
505
            /* @var store|key_aware_cache_interface $store */
506
            $has = $store->has($parsedkey);
507
        }
508
        if (!$has && $tryloadifpossible) {
509
            $result = null;
510
            if ($this->get_loader() !== false) {
511
                $result = $this->get_loader()->get($parsedkey);
512
            } else if ($this->get_datasource() !== null) {
513
                $result = $this->get_datasource()->load_for_cache($key);
514
            }
515
            $has = ($result !== null);
516
            if ($has) {
517
                $this->set($key, $result);
518
            }
519
        }
520
        return $has;
521
    }
522
 
523
    /**
524
     * Test is a cache has all of the given keys.
525
     *
526
     * It is strongly recommended to avoid the use of this function if not absolutely required.
527
     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
528
     *
529
     * Its also worth mentioning that not all stores support key tests.
530
     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
531
     * Just one more reason you should not use these methods unless you have a very good reason to do so.
532
     *
533
     * @param array $keys
534
     * @return bool True if the cache has all of the given keys, false otherwise.
535
     */
536
    public function has_all(array $keys) {
537
        $this->check_tracked_user();
538
        if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
539
            foreach ($keys as $key) {
540
                if (!$this->has($key)) {
541
                    return false;
542
                }
543
            }
544
            return true;
545
        }
546
        // The cache must be key aware and if support native ttl if it a ttl is set.
547
        /* @var store|key_aware_cache_interface $store */
548
        $store = $this->get_store();
549
        return $store->has_all(array_map([$this, 'parse_key'], $keys));
550
    }
551
 
552
    /**
553
     * Test if a cache has at least one of the given keys.
554
     *
555
     * It is strongly recommended to avoid the use of this function if not absolutely required.
556
     * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
557
     *
558
     * Its also worth mentioning that not all stores support key tests.
559
     * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
560
     * Just one more reason you should not use these methods unless you have a very good reason to do so.
561
     *
562
     * @param array $keys
563
     * @return bool True if the cache has at least one of the given keys
564
     */
565
    public function has_any(array $keys) {
566
        if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
567
            foreach ($keys as $key) {
568
                if ($this->has($key)) {
569
                    return true;
570
                }
571
            }
572
            return false;
573
        }
574
        /* @var store|key_aware_cache_interface $store */
575
        $store = $this->get_store();
576
        return $store->has_any(array_map([$this, 'parse_key'], $keys));
577
    }
578
 
579
    /**
580
     * The session loader never uses static acceleration.
581
     * Instead it stores things in the static $session variable. Shared between all session loaders.
582
     *
583
     * @return bool
584
     */
585
    protected function use_static_acceleration() {
586
        return false;
587
    }
588
}
589
 
590
// Alias this class to the old name.
591
// This file will be autoloaded by the legacyclasses autoload system.
592
// In future all uses of this class will be corrected and the legacy references will be removed.
593
class_alias(session_cache::class, \cache_session::class);