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($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);
216 * Returns true once this instance has been initialised.
220 public function is_initialised() {
221 return (is_array($this->store));
225 * Returns true if this store instance is ready to be used.
228 public function is_ready() {
233 * Retrieves an item from the cache store given its key.
235 * @param string $key The key to retrieve
236 * @return mixed The data that was associated with the key, or false if the key did not exist.
238 public function get($key) {
239 if (isset($this->store[$key])) {
240 if ($this->ttl == 0) {
241 return $this->store[$key][0];
242 } else if ($this->store[$key][1] >= (cache::now() - $this->ttl)) {
243 return $this->store[$key][0];
250 * Retrieves several items from the cache store in a single transaction.
252 * 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.
254 * @param array $keys The array of keys to retrieve
255 * @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
258 public function get_many($keys) {
260 if ($this->ttl != 0) {
261 $maxtime = cache::now() - $this->ttl;
264 foreach ($keys as $key) {
265 $return[$key] = false;
266 if (isset($this->store[$key])) {
267 if ($this->ttl == 0) {
268 $return[$key] = $this->store[$key][0];
269 } else if ($this->store[$key][1] >= $maxtime) {
270 $return[$key] = $this->store[$key][0];
278 * Sets an item in the cache given its key and data value.
280 * @param string $key The key to use.
281 * @param mixed $data The data to set.
282 * @param bool $testmaxsize If set to true then we test the maxsize arg and reduce if required.
283 * @return bool True if the operation was a success false otherwise.
285 public function set($key, $data, $testmaxsize = true) {
286 $testmaxsize = ($testmaxsize && $this->maxsize !== false);
288 $increment = (!isset($this->store[$key]));
290 if ($this->ttl == 0) {
291 $this->store[$key][0] = $data;
293 $this->store[$key] = array($data, cache::now());
295 if ($testmaxsize && $increment) {
297 if ($this->storecount > $this->maxsize) {
298 $this->reduce_for_maxsize();
305 * Sets many items in the cache in a single transaction.
307 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
308 * keys, 'key' and 'value'.
309 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
310 * sent ... if they care that is.
312 public function set_many(array $keyvaluearray) {
314 foreach ($keyvaluearray as $pair) {
315 $this->set($pair['key'], $pair['value'], false);
318 if ($this->maxsize !== false) {
319 $this->storecount += $count;
320 if ($this->storecount > $this->maxsize) {
321 $this->reduce_for_maxsize();
328 * Checks if the store has a record for the given key and returns true if so.
333 public function has($key) {
334 if (isset($this->store[$key])) {
335 if ($this->ttl == 0) {
337 } else if ($this->store[$key][1] >= (cache::now() - $this->ttl)) {
345 * Returns true if the store contains records for all of the given keys.
350 public function has_all(array $keys) {
351 if ($this->ttl != 0) {
352 $maxtime = cache::now() - $this->ttl;
355 foreach ($keys as $key) {
356 if (!isset($this->store[$key])) {
359 if ($this->ttl != 0 && $this->store[$key][1] < $maxtime) {
367 * Returns true if the store contains records for any of the given keys.
372 public function has_any(array $keys) {
373 if ($this->ttl != 0) {
374 $maxtime = cache::now() - $this->ttl;
377 foreach ($keys as $key) {
378 if (isset($this->store[$key]) && ($this->ttl == 0 || $this->store[$key][1] >= $maxtime)) {
386 * Deletes an item from the cache store.
388 * @param string $key The key to delete.
389 * @return bool Returns true if the operation was a success, false otherwise.
391 public function delete($key) {
392 $result = isset($this->store[$key]);
393 unset($this->store[$key]);
394 if ($this->maxsize !== false) {
401 * Deletes several keys from the cache in a single action.
403 * @param array $keys The keys to delete
404 * @return int The number of items successfully deleted.
406 public function delete_many(array $keys) {
408 foreach ($keys as $key) {
409 if (isset($this->store[$key])) {
412 unset($this->store[$key]);
414 if ($this->maxsize !== false) {
415 $this->storecount -= $count;
421 * Purges the cache deleting all items within it.
423 * @return boolean True on success. False otherwise.
425 public function purge() {
426 $this->store = array();
427 // Don't worry about checking if we're using max size just set it as thats as fast as the check.
428 $this->storecount = 0;
433 * Reduces the size of the array if maxsize has been hit.
435 * This function reduces the size of the store reducing it by 10% of its maxsize.
436 * It removes the oldest items in the store when doing this.
437 * The reason it does this an doesn't use a least recently used system is purely the overhead such a system
438 * requires. The current approach is focused on speed, MUC already adds enough overhead to static/session caches
439 * and avoiding more is of benefit.
443 protected function reduce_for_maxsize() {
444 $diff = $this->storecount - $this->maxsize;
448 // Reduce it by an extra 10% to avoid calling this repetitively if we are in a loop.
449 $diff += floor($this->maxsize / 10);
450 $this->store = array_slice($this->store, $diff, null, true);
451 $this->storecount -= $diff;
456 * Returns true if the user can add an instance of the store plugin.
460 public static function can_add_instance() {
465 * Performs any necessary clean up when the store instance is being deleted.
467 public function instance_deleted() {
472 * Generates an instance of the cache store that can be used for testing.
474 * @param cache_definition $definition
475 * @return cachestore_session
477 public static function initialise_test_instance(cache_definition $definition) {
478 // Do something here perhaps.
479 $cache = new cachestore_session('Session test');
480 $cache->initialise($definition);
485 * Returns the name of this instance.
488 public function my_name() {
493 * Finds all of the keys being stored in the cache store instance.
497 public function find_all() {
498 return array_keys($this->store);
502 * Finds all of the keys whose keys start with the given prefix.
504 * @param string $prefix
506 public function find_by_prefix($prefix) {
508 foreach ($this->find_all() as $key) {
509 if (strpos($key, $prefix) === 0) {