2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * The library file for the session cache store.
20 * This file is part of the session cache store, it contains the API for interacting with an instance of the store.
21 * This is used as a default cache store within the Cache API. It should never be deleted.
23 * @package cachestore_session
25 * @copyright 2012 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * The session data store class.
34 * @copyright 2012 Sam Hemelryk
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 abstract class session_data_store extends cache_store {
40 * Used for the actual storage.
43 private static $sessionstore = null;
46 * Returns a static store by reference... REFERENCE SUPER IMPORTANT.
51 protected static function ®ister_store_id($id) {
52 if (is_null(self::$sessionstore)) {
54 if (!isset($SESSION->cachestore_session)) {
55 $SESSION->cachestore_session = array();
57 self::$sessionstore =& $SESSION->cachestore_session;
59 if (!array_key_exists($id, self::$sessionstore)) {
60 self::$sessionstore[$id] = array();
62 return self::$sessionstore[$id];
66 * Flushes the data belong to the given store id.
69 protected static function flush_store_by_id($id) {
70 unset(self::$sessionstore[$id]);
71 self::$sessionstore[$id] = array();
75 * Flushes the store of all data.
77 protected static function flush_store() {
78 $ids = array_keys(self::$sessionstore);
79 unset(self::$sessionstore);
80 self::$sessionstore = array();
81 foreach ($ids as $id) {
82 self::$sessionstore[$id] = array();
88 * The Session store class.
90 * @copyright 2012 Sam Hemelryk
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class cachestore_session extends session_data_store implements cache_is_key_aware, cache_is_searchable {
96 * The name of the store
102 * The store id (should be unique)
108 * The store we use for data.
114 * The ttl if there is one. Hopefully not.
120 * The maximum size for the store, or false if there isn't one.
123 protected $maxsize = false;
126 * The number of items currently being stored.
129 protected $storecount = 0;
132 * Constructs the store instance.
134 * Noting that this function is not an initialisation. It is used to prepare the store for use.
135 * The store will be initialised when required and will be provided with a cache_definition at that time.
137 * @param string $name
138 * @param array $configuration
140 public function __construct($name, array $configuration = array()) {
145 * Returns the supported features as a combined int.
147 * @param array $configuration
150 public static function get_supported_features(array $configuration = array()) {
151 return self::SUPPORTS_DATA_GUARANTEE +
152 self::SUPPORTS_NATIVE_TTL +
157 * Returns false as this store does not support multiple identifiers.
158 * (This optional function is a performance optimisation; it must be
159 * consistent with the value from get_supported_features.)
163 public function supports_multiple_identifiers() {
168 * Returns the supported modes as a combined int.
170 * @param array $configuration
173 public static function get_supported_modes(array $configuration = array()) {
174 return self::MODE_SESSION;
178 * Returns true if the store requirements are met.
182 public static function are_requirements_met() {
187 * Returns true if the given mode is supported by this store.
189 * @param int $mode One of cache_store::MODE_*
192 public static function is_supported_mode($mode) {
193 return ($mode === self::MODE_SESSION);
197 * Initialises the cache.
199 * Once this has been done the cache is all set to be used.
201 * @param cache_definition $definition
203 public function initialise(cache_definition $definition) {
204 $this->storeid = $definition->generate_definition_hash();
205 $this->store = &self::register_store_id($this->name.'-'.$definition->get_id());
206 $this->ttl = $definition->get_ttl();
207 $maxsize = $definition->get_maxsize();
208 if ($maxsize !== null) {
209 // Must be a positive int.
210 $this->maxsize = abs((int)$maxsize);
211 $this->storecount = count($this->store);
217 * Returns true once this instance has been initialised.
221 public function is_initialised() {
222 return (is_array($this->store));
226 * Retrieves an item from the cache store given its key.
228 * @param string $key The key to retrieve
229 * @return mixed The data that was associated with the key, or false if the key did not exist.
231 public function get($key) {
232 if (isset($this->store[$key])) {
233 if ($this->ttl == 0) {
234 $value = $this->store[$key][0];
235 if ($this->maxsize !== false) {
236 // Make sure the element is now in the end of array.
237 $this->set($key, $value);
240 } else if ($this->store[$key][1] >= (cache::now() - $this->ttl)) {
241 return $this->store[$key][0];
243 // Element is present but has expired.
251 * Retrieves several items from the cache store in a single transaction.
253 * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
255 * @param array $keys The array of keys to retrieve
256 * @return array An array of items from the cache. There will be an item for each key, those that were not in the store will
259 public function get_many($keys) {
262 if ($this->ttl != 0) {
263 $maxtime = cache::now() - $this->ttl;
266 $hasexpiredelements = false;
267 foreach ($keys as $key) {
268 $return[$key] = false;
269 if (isset($this->store[$key])) {
270 if ($this->ttl == 0) {
271 $return[$key] = $this->store[$key][0];
272 if ($this->maxsize !== false) {
273 // Make sure the element is now in the end of array.
274 $this->set($key, $return[$key], false);
276 } else if ($this->store[$key][1] >= $maxtime) {
277 $return[$key] = $this->store[$key][0];
279 $hasexpiredelements = true;
283 if ($hasexpiredelements) {
284 // There are some elements that are present but have expired.
291 * Sets an item in the cache given its key and data value.
293 * @param string $key The key to use.
294 * @param mixed $data The data to set.
295 * @param bool $testmaxsize If set to true then we test the maxsize arg and reduce if required. If this is set to false you will
296 * need to perform these checks yourself. This allows for bulk set's to be performed and maxsize tests performed once.
297 * @return bool True if the operation was a success false otherwise.
299 public function set($key, $data, $testmaxsize = true) {
300 $testmaxsize = ($testmaxsize && $this->maxsize !== false);
301 $increment = $this->maxsize !== false && !isset($this->store[$key]);
302 if (($this->maxsize !== false && !$increment) || $this->ttl != 0) {
303 // Make sure the element is added to the end of $this->store array.
304 unset($this->store[$key]);
306 if ($this->ttl === 0) {
307 $this->store[$key] = array($data, 0);
309 $this->store[$key] = array($data, cache::now());
314 if ($testmaxsize && $this->storecount > $this->maxsize) {
315 $this->reduce_for_maxsize();
321 * Sets many items in the cache in a single transaction.
323 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
324 * keys, 'key' and 'value'.
325 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
326 * sent ... if they care that is.
328 public function set_many(array $keyvaluearray) {
331 foreach ($keyvaluearray as $pair) {
333 $data = $pair['value'];
335 if ($this->maxsize !== false || $this->ttl !== 0) {
336 // Make sure the element is added to the end of $this->store array.
339 } else if (!isset($this->store[$key])) {
342 if ($this->ttl === 0) {
343 $this->store[$key] = array($data, 0);
345 $this->store[$key] = array($data, cache::now());
348 if ($this->maxsize !== false) {
349 $this->storecount += $increment;
350 if ($this->storecount > $this->maxsize) {
351 $this->reduce_for_maxsize();
358 * Checks if the store has a record for the given key and returns true if so.
363 public function has($key) {
364 if (isset($this->store[$key])) {
365 if ($this->ttl == 0) {
367 } else if ($this->store[$key][1] >= (cache::now() - $this->ttl)) {
375 * Returns true if the store contains records for all of the given keys.
380 public function has_all(array $keys) {
382 if ($this->ttl != 0) {
383 $maxtime = cache::now() - $this->ttl;
386 foreach ($keys as $key) {
387 if (!isset($this->store[$key])) {
390 if ($this->ttl != 0 && $this->store[$key][1] < $maxtime) {
398 * Returns true if the store contains records for any of the given keys.
403 public function has_any(array $keys) {
405 if ($this->ttl != 0) {
406 $maxtime = cache::now() - $this->ttl;
409 foreach ($keys as $key) {
410 if (isset($this->store[$key]) && ($this->ttl == 0 || $this->store[$key][1] >= $maxtime)) {
418 * Deletes an item from the cache store.
420 * @param string $key The key to delete.
421 * @return bool Returns true if the operation was a success, false otherwise.
423 public function delete($key) {
424 if (!isset($this->store[$key])) {
427 unset($this->store[$key]);
428 if ($this->maxsize !== false) {
435 * Deletes several keys from the cache in a single action.
437 * @param array $keys The keys to delete
438 * @return int The number of items successfully deleted.
440 public function delete_many(array $keys) {
441 // The number of items that have actually being removed.
443 foreach ($keys as $key) {
444 if (isset($this->store[$key])) {
447 unset($this->store[$key]);
449 if ($this->maxsize !== false) {
450 $this->storecount -= $reduction;
456 * Purges the cache deleting all items within it.
458 * @return boolean True on success. False otherwise.
460 public function purge() {
461 $this->store = array();
462 // Don't worry about checking if we're using max size just set it as thats as fast as the check.
463 $this->storecount = 0;
468 * Reduces the size of the array if maxsize has been hit.
470 * This function reduces the size of the store reducing it by 10% of its maxsize.
471 * It removes the oldest items in the store when doing this.
472 * The reason it does this an doesn't use a least recently used system is purely the overhead such a system
473 * requires. The current approach is focused on speed, MUC already adds enough overhead to static/session caches
474 * and avoiding more is of benefit.
478 protected function reduce_for_maxsize() {
479 $diff = $this->storecount - $this->maxsize;
483 // Reduce it by an extra 10% to avoid calling this repetitively if we are in a loop.
484 $diff += floor($this->maxsize / 10);
485 $this->store = array_slice($this->store, $diff, null, true);
486 $this->storecount -= $diff;
491 * Returns true if the user can add an instance of the store plugin.
495 public static function can_add_instance() {
500 * Performs any necessary clean up when the store instance is being deleted.
502 public function instance_deleted() {
507 * Generates an instance of the cache store that can be used for testing.
509 * @param cache_definition $definition
510 * @return cachestore_session
512 public static function initialise_test_instance(cache_definition $definition) {
513 // Do something here perhaps.
514 $cache = new cachestore_session('Session test');
515 $cache->initialise($definition);
520 * Returns the name of this instance.
523 public function my_name() {
528 * Removes expired elements.
529 * @return int number of removed elements
531 protected function check_ttl() {
532 if ($this->ttl === 0) {
535 $maxtime = cache::now() - $this->ttl;
537 for ($value = reset($this->store); $value !== false; $value = next($this->store)) {
538 if ($value[1] >= $maxtime) {
539 // We know that elements are sorted by ttl so no need to continue.
545 // Remove first $count elements as they are expired.
546 $this->store = array_slice($this->store, $count, null, true);
547 if ($this->maxsize !== false) {
548 $this->storecount -= $count;
555 * Finds all of the keys being stored in the cache store instance.
559 public function find_all() {
561 return array_keys($this->store);
565 * Finds all of the keys whose keys start with the given prefix.
567 * @param string $prefix
568 * @return array An array of keys.
570 public function find_by_prefix($prefix) {
572 foreach ($this->find_all() as $key) {
573 if (strpos($key, $prefix) === 0) {
581 * This store supports native TTL handling.
584 public function store_supports_native_ttl() {