Merge branch 'MDL-38731-25' of git://github.com/danpoltawski/moodle into MOODLE_25_STABLE
[moodle.git] / cache / locallib.php
blob8124fdc76a9cc02425de81978d58a06cd56d29c5
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.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * The supplementary cache API.
20 * This file is part of Moodle's cache API, affectionately called MUC.
21 * It contains elements of the API that are not required in order to use caching.
22 * Things in here are more in line with administration and management of the cache setup and configuration.
24 * @package core
25 * @category cache
26 * @copyright 2012 Sam Hemelryk
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 /**
33 * Cache configuration writer.
35 * This class should only be used when you need to write to the config, all read operations exist within the cache_config.
37 * @package core
38 * @category cache
39 * @copyright 2012 Sam Hemelryk
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class cache_config_writer extends cache_config {
44 /**
45 * Switch that gets set to true when ever a cache_config_writer instance is saving the cache configuration file.
46 * If this is set to true when save is next called we must avoid the trying to save and instead return the
47 * generated config so that is may be used instead of the file.
48 * @var bool
50 protected static $creatingconfig = false;
52 /**
53 * Returns an instance of the configuration writer.
55 * @return cache_config_writer
57 public static function instance() {
58 $factory = cache_factory::instance();
59 return $factory->create_config_instance(true);
62 /**
63 * Saves the current configuration.
65 * Exceptions within this function are tolerated but must be of type cache_exception.
66 * They are caught during initialisation and written to the error log. This is required in order to avoid
67 * infinite loop situations caused by the cache throwing exceptions during its initialisation.
69 protected function config_save() {
70 global $CFG;
71 $cachefile = self::get_config_file_path();
72 $directory = dirname($cachefile);
73 if ($directory !== $CFG->dataroot && !file_exists($directory)) {
74 $result = make_writable_directory($directory, false);
75 if (!$result) {
76 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory. Check the permissions on your moodledata directory.');
79 if (!file_exists($directory) || !is_writable($directory)) {
80 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Config directory is not writable. Check the permissions on the moodledata/muc directory.');
83 // Prepare a configuration array to store.
84 $configuration = $this->generate_configuration_array();
86 // Prepare the file content.
87 $content = "<?php defined('MOODLE_INTERNAL') || die();\n \$configuration = ".var_export($configuration, true).";";
89 // We need to create a temporary cache lock instance for use here. Remember we are generating the config file
90 // it doesn't exist and thus we can't use the normal API for this (it'll just try to use config).
91 $lockconf = reset($this->configlocks);
92 if ($lockconf === false) {
93 debugging('Your cache configuration file is out of date and needs to be refreshed.', DEBUG_DEVELOPER);
94 // Use the default
95 $lockconf = array(
96 'name' => 'cachelock_file_default',
97 'type' => 'cachelock_file',
98 'dir' => 'filelocks',
99 'default' => true
102 $factory = cache_factory::instance();
103 $locking = $factory->create_lock_instance($lockconf);
104 if ($locking->lock('configwrite', 'config', true)) {
105 // Its safe to use w mode here because we have already acquired the lock.
106 $handle = fopen($cachefile, 'w');
107 fwrite($handle, $content);
108 fflush($handle);
109 fclose($handle);
110 $locking->unlock('configwrite', 'config');
111 } else {
112 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Unable to open the cache config file.');
117 * Generates a configuration array suitable to be written to the config file.
118 * @return array
120 protected function generate_configuration_array() {
121 $configuration = array();
122 $configuration['siteidentifier'] = $this->siteidentifier;
123 $configuration['stores'] = $this->configstores;
124 $configuration['modemappings'] = $this->configmodemappings;
125 $configuration['definitions'] = $this->configdefinitions;
126 $configuration['definitionmappings'] = $this->configdefinitionmappings;
127 $configuration['locks'] = $this->configlocks;
128 return $configuration;
132 * Adds a plugin instance.
134 * This function also calls save so you should redirect immediately, or at least very shortly after
135 * calling this method.
137 * @param string $name The name for the instance (must be unique)
138 * @param string $plugin The name of the plugin.
139 * @param array $configuration The configuration data for the plugin instance.
140 * @return bool
141 * @throws cache_exception
143 public function add_store_instance($name, $plugin, array $configuration = array()) {
144 if (array_key_exists($name, $this->configstores)) {
145 throw new cache_exception('Duplicate name specificed for cache plugin instance. You must provide a unique name.');
147 $class = 'cachestore_'.$plugin;
148 if (!class_exists($class)) {
149 $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
150 if (!array_key_exists($plugin, $plugins)) {
151 throw new cache_exception('Invalid plugin name specified. The plugin does not exist or is not valid.');
153 $file = $plugins[$plugin];
154 if (file_exists($file)) {
155 require_once($file);
157 if (!class_exists($class)) {
158 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.');
161 $reflection = new ReflectionClass($class);
162 if (!$reflection->isSubclassOf('cache_store')) {
163 throw new cache_exception('Invalid cache plugin specified. The plugin does not extend the required class.');
165 if (!$class::are_requirements_met()) {
166 throw new cache_exception('Unable to add new cache plugin instance. The requested plugin type is not supported.');
168 $this->configstores[$name] = array(
169 'name' => $name,
170 'plugin' => $plugin,
171 'configuration' => $configuration,
172 'features' => $class::get_supported_features($configuration),
173 'modes' => $class::get_supported_modes($configuration),
174 'mappingsonly' => !empty($configuration['mappingsonly']),
175 'class' => $class,
176 'default' => false
178 if (array_key_exists('lock', $configuration)) {
179 $this->configstores[$name]['lock'] = $configuration['lock'];
180 unset($this->configstores[$name]['configuration']['lock']);
182 // Call instance_created()
183 $store = new $class($name, $this->configstores[$name]['configuration']);
184 $store->instance_created();
186 $this->config_save();
187 return true;
191 * Adds a new lock instance to the config file.
193 * @param string $name The name the user gave the instance. PARAM_ALHPANUMEXT
194 * @param string $plugin The plugin we are creating an instance of.
195 * @param string $configuration Configuration data from the config instance.
196 * @throws cache_exception
198 public function add_lock_instance($name, $plugin, $configuration = array()) {
199 if (array_key_exists($name, $this->configlocks)) {
200 throw new cache_exception('Duplicate name specificed for cache lock instance. You must provide a unique name.');
202 $class = 'cachelock_'.$plugin;
203 if (!class_exists($class)) {
204 $plugins = get_plugin_list_with_file('cachelock', 'lib.php');
205 if (!array_key_exists($plugin, $plugins)) {
206 throw new cache_exception('Invalid lock name specified. The plugin does not exist or is not valid.');
208 $file = $plugins[$plugin];
209 if (file_exists($file)) {
210 require_once($file);
212 if (!class_exists($class)) {
213 throw new cache_exception('Invalid lock plugin specified. The plugin does not contain the required class.');
216 $reflection = new ReflectionClass($class);
217 if (!$reflection->implementsInterface('cache_lock_interface')) {
218 throw new cache_exception('Invalid lock plugin specified. The plugin does not implement the required interface.');
220 $this->configlocks[$name] = array_merge($configuration, array(
221 'name' => $name,
222 'type' => 'cachelock_'.$plugin,
223 'default' => false
225 $this->config_save();
229 * Deletes a lock instance given its name.
231 * @param string $name The name of the plugin, PARAM_ALPHANUMEXT.
232 * @return bool
233 * @throws cache_exception
235 public function delete_lock_instance($name) {
236 if (!array_key_exists($name, $this->configlocks)) {
237 throw new cache_exception('The requested store does not exist.');
239 if ($this->configlocks[$name]['default']) {
240 throw new cache_exception('You can not delete the default lock.');
242 foreach ($this->configstores as $store) {
243 if (isset($store['lock']) && $store['lock'] === $name) {
244 throw new cache_exception('You cannot delete a cache lock that is being used by a store.');
247 unset($this->configlocks[$name]);
248 $this->config_save();
249 return true;
253 * Sets the mode mappings.
255 * These determine the default caches for the different modes.
256 * This function also calls save so you should redirect immediately, or at least very shortly after
257 * calling this method.
259 * @param array $modemappings
260 * @return bool
261 * @throws cache_exception
263 public function set_mode_mappings(array $modemappings) {
264 $mappings = array(
265 cache_store::MODE_APPLICATION => array(),
266 cache_store::MODE_SESSION => array(),
267 cache_store::MODE_REQUEST => array(),
269 foreach ($modemappings as $mode => $stores) {
270 if (!array_key_exists($mode, $mappings)) {
271 throw new cache_exception('The cache mode for the new mapping does not exist');
273 $sort = 0;
274 foreach ($stores as $store) {
275 if (!array_key_exists($store, $this->configstores)) {
276 throw new cache_exception('The instance name for the new mapping does not exist');
278 if (array_key_exists($store, $mappings[$mode])) {
279 throw new cache_exception('This cache mapping already exists');
281 $mappings[$mode][] = array(
282 'store' => $store,
283 'mode' => $mode,
284 'sort' => $sort++
288 $this->configmodemappings = array_merge(
289 $mappings[cache_store::MODE_APPLICATION],
290 $mappings[cache_store::MODE_SESSION],
291 $mappings[cache_store::MODE_REQUEST]
294 $this->config_save();
295 return true;
299 * Edits a give plugin instance.
301 * The plugin instance is determined by its name, hence you cannot rename plugins.
302 * This function also calls save so you should redirect immediately, or at least very shortly after
303 * calling this method.
305 * @param string $name
306 * @param string $plugin
307 * @param array $configuration
308 * @return bool
309 * @throws cache_exception
311 public function edit_store_instance($name, $plugin, $configuration) {
312 if (!array_key_exists($name, $this->configstores)) {
313 throw new cache_exception('The requested instance does not exist.');
315 $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
316 if (!array_key_exists($plugin, $plugins)) {
317 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
319 $class = 'cachestore_'.$plugin;
320 $file = $plugins[$plugin];
321 if (!class_exists($class)) {
322 if (file_exists($file)) {
323 require_once($file);
325 if (!class_exists($class)) {
326 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.'.$class);
329 $this->configstores[$name] = array(
330 'name' => $name,
331 'plugin' => $plugin,
332 'configuration' => $configuration,
333 'features' => $class::get_supported_features($configuration),
334 'modes' => $class::get_supported_modes($configuration),
335 'mappingsonly' => !empty($configuration['mappingsonly']),
336 'class' => $class,
337 'default' => $this->configstores[$name]['default'] // Can't change the default.
339 if (array_key_exists('lock', $configuration)) {
340 $this->configstores[$name]['lock'] = $configuration['lock'];
341 unset($this->configstores[$name]['configuration']['lock']);
343 $this->config_save();
344 return true;
348 * Deletes a store instance.
350 * This function also calls save so you should redirect immediately, or at least very shortly after
351 * calling this method.
353 * @param string $name The name of the instance to delete.
354 * @return bool
355 * @throws cache_exception
357 public function delete_store_instance($name) {
358 if (!array_key_exists($name, $this->configstores)) {
359 throw new cache_exception('The requested store does not exist.');
361 if ($this->configstores[$name]['default']) {
362 throw new cache_exception('The can not delete the default stores.');
364 foreach ($this->configmodemappings as $mapping) {
365 if ($mapping['store'] === $name) {
366 throw new cache_exception('You cannot delete a cache store that has mode mappings.');
369 foreach ($this->configdefinitionmappings as $mapping) {
370 if ($mapping['store'] === $name) {
371 throw new cache_exception('You cannot delete a cache store that has definition mappings.');
375 // Call instance_deleted()
376 $class = 'cachestore_'.$this->configstores[$name]['plugin'];
377 $store = new $class($name, $this->configstores[$name]['configuration']);
378 $store->instance_deleted();
380 unset($this->configstores[$name]);
381 $this->config_save();
382 return true;
386 * Creates the default configuration and saves it.
388 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
389 * be called when there is no configuration file already.
391 * @param bool $forcesave If set to true then we will forcefully save the default configuration file.
392 * @return true|array Returns true if the default configuration was successfully created.
393 * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
395 public static function create_default_configuration($forcesave = false) {
396 // HACK ALERT.
397 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
398 // default store plugins are protected from deletion.
399 $writer = new self;
400 $writer->configstores = self::get_default_stores();
401 $writer->configdefinitions = self::locate_definitions();
402 $writer->configmodemappings = array(
403 array(
404 'mode' => cache_store::MODE_APPLICATION,
405 'store' => 'default_application',
406 'sort' => -1
408 array(
409 'mode' => cache_store::MODE_SESSION,
410 'store' => 'default_session',
411 'sort' => -1
413 array(
414 'mode' => cache_store::MODE_REQUEST,
415 'store' => 'default_request',
416 'sort' => -1
419 $writer->configlocks = array(
420 'default_file_lock' => array(
421 'name' => 'cachelock_file_default',
422 'type' => 'cachelock_file',
423 'dir' => 'filelocks',
424 'default' => true
428 $factory = cache_factory::instance();
429 // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
430 // we are now in a loop.
431 if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
432 return $writer->generate_configuration_array();
434 $factory->set_state(cache_factory::STATE_SAVING);
435 $writer->config_save();
436 return true;
440 * Returns an array of default stores for use.
442 * @return array
444 protected static function get_default_stores() {
445 global $CFG;
447 require_once($CFG->dirroot.'/cache/stores/file/lib.php');
448 require_once($CFG->dirroot.'/cache/stores/session/lib.php');
449 require_once($CFG->dirroot.'/cache/stores/static/lib.php');
451 return array(
452 'default_application' => array(
453 'name' => 'default_application',
454 'plugin' => 'file',
455 'configuration' => array(),
456 'features' => cachestore_file::get_supported_features(),
457 'modes' => cachestore_file::get_supported_modes(),
458 'default' => true,
460 'default_session' => array(
461 'name' => 'default_session',
462 'plugin' => 'session',
463 'configuration' => array(),
464 'features' => cachestore_session::get_supported_features(),
465 'modes' => cachestore_session::get_supported_modes(),
466 'default' => true,
468 'default_request' => array(
469 'name' => 'default_request',
470 'plugin' => 'static',
471 'configuration' => array(),
472 'features' => cachestore_static::get_supported_features(),
473 'modes' => cachestore_static::get_supported_modes(),
474 'default' => true,
480 * Updates the default stores within the MUC config file.
482 public static function update_default_config_stores() {
483 $factory = cache_factory::instance();
484 $factory->updating_started();
485 $config = $factory->create_config_instance(true);
486 $config->configstores = array_merge($config->configstores, self::get_default_stores());
487 $config->config_save();
488 $factory->updating_finished();
492 * Updates the definition in the configuration from those found in the cache files.
494 * Calls config_save further down, you should redirect immediately or asap after calling this method.
496 * @param bool $coreonly If set to true only core definitions will be updated.
498 public static function update_definitions($coreonly = false) {
499 $factory = cache_factory::instance();
500 $factory->updating_started();
501 $config = $factory->create_config_instance(true);
502 $config->write_definitions_to_cache(self::locate_definitions($coreonly));
503 $factory->updating_finished();
507 * Locates all of the definition files.
509 * @param bool $coreonly If set to true only core definitions will be updated.
510 * @return array
512 protected static function locate_definitions($coreonly = false) {
513 global $CFG;
515 $files = array();
516 if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
517 $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
520 if (!$coreonly) {
521 $plugintypes = get_plugin_types();
522 foreach ($plugintypes as $type => $location) {
523 $plugins = get_plugin_list_with_file($type, 'db/caches.php');
524 foreach ($plugins as $plugin => $filepath) {
525 $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
526 $files[$component] = $filepath;
531 $definitions = array();
532 foreach ($files as $component => $file) {
533 $filedefs = self::load_caches_file($file);
534 foreach ($filedefs as $area => $definition) {
535 $area = clean_param($area, PARAM_AREA);
536 $id = $component.'/'.$area;
537 $definition['component'] = $component;
538 $definition['area'] = $area;
539 if (array_key_exists($id, $definitions)) {
540 debugging('Error: duplicate cache definition found with id: '.$id, DEBUG_DEVELOPER);
541 continue;
543 $definitions[$id] = $definition;
547 return $definitions;
551 * Writes the updated definitions for the config file.
552 * @param array $definitions
554 private function write_definitions_to_cache(array $definitions) {
556 // Preserve the selected sharing option when updating the definitions.
557 // This is set by the user and should never come from caches.php.
558 foreach ($definitions as $key => $definition) {
559 unset($definitions[$key]['selectedsharingoption']);
560 unset($definitions[$key]['userinputsharingkey']);
561 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['selectedsharingoption'])) {
562 $definitions[$key]['selectedsharingoption'] = $this->configdefinitions[$key]['selectedsharingoption'];
564 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['userinputsharingkey'])) {
565 $definitions[$key]['userinputsharingkey'] = $this->configdefinitions[$key]['userinputsharingkey'];
569 $this->configdefinitions = $definitions;
570 foreach ($this->configdefinitionmappings as $key => $mapping) {
571 if (!array_key_exists($mapping['definition'], $definitions)) {
572 unset($this->configdefinitionmappings[$key]);
575 $this->config_save();
579 * Loads the caches file if it exists.
580 * @param string $file Absolute path to the file.
581 * @return array
583 private static function load_caches_file($file) {
584 if (!file_exists($file)) {
585 return array();
587 $definitions = array();
588 include($file);
589 return $definitions;
593 * Sets the mappings for a given definition.
595 * @param string $definition
596 * @param array $mappings
597 * @throws coding_exception
599 public function set_definition_mappings($definition, $mappings) {
600 if (!array_key_exists($definition, $this->configdefinitions)) {
601 throw new coding_exception('Invalid definition name passed when updating mappings.');
603 foreach ($mappings as $store) {
604 if (!array_key_exists($store, $this->configstores)) {
605 throw new coding_exception('Invalid store name passed when updating definition mappings.');
608 foreach ($this->configdefinitionmappings as $key => $mapping) {
609 if ($mapping['definition'] == $definition) {
610 unset($this->configdefinitionmappings[$key]);
613 $sort = count($mappings);
614 foreach ($mappings as $store) {
615 $this->configdefinitionmappings[] = array(
616 'store' => $store,
617 'definition' => $definition,
618 'sort' => $sort
620 $sort--;
623 $this->config_save();
627 * Update the site identifier stored by the cache API.
629 * @param string $siteidentifier
630 * @return string The new site identifier.
632 public function update_site_identifier($siteidentifier) {
633 $this->siteidentifier = md5((string)$siteidentifier);
634 $this->config_save();
635 return $this->siteidentifier;
639 * Sets the selected sharing options and key for a definition.
641 * @param string $definition The name of the definition to set for.
642 * @param int $sharingoption The sharing option to set.
643 * @param string|null $userinputsharingkey The user input key or null.
644 * @throws coding_exception
646 public function set_definition_sharing($definition, $sharingoption, $userinputsharingkey = null) {
647 if (!array_key_exists($definition, $this->configdefinitions)) {
648 throw new coding_exception('Invalid definition name passed when updating sharing options.');
650 if (!($this->configdefinitions[$definition]['sharingoptions'] & $sharingoption)) {
651 throw new coding_exception('Invalid sharing option passed when updating definition.');
653 $this->configdefinitions[$definition]['selectedsharingoption'] = (int)$sharingoption;
654 if (!empty($userinputsharingkey)) {
655 $this->configdefinitions[$definition]['userinputsharingkey'] = (string)$userinputsharingkey;
657 $this->config_save();
663 * A cache helper for administration tasks
665 * @package core
666 * @category cache
667 * @copyright 2012 Sam Hemelryk
668 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
670 abstract class cache_administration_helper extends cache_helper {
673 * Returns an array containing all of the information about stores a renderer needs.
674 * @return array
676 public static function get_store_instance_summaries() {
677 $return = array();
678 $default = array();
679 $instance = cache_config::instance();
680 $stores = $instance->get_all_stores();
681 $locks = $instance->get_locks();
682 foreach ($stores as $name => $details) {
683 $class = $details['class'];
684 $store = new $class($details['name'], $details['configuration']);
685 $lock = (isset($details['lock'])) ? $locks[$details['lock']] : $instance->get_default_lock();
686 $record = array(
687 'name' => $name,
688 'plugin' => $details['plugin'],
689 'default' => $details['default'],
690 'isready' => $store->is_ready(),
691 'requirementsmet' => $store->are_requirements_met(),
692 'mappings' => 0,
693 'lock' => $lock,
694 'modes' => array(
695 cache_store::MODE_APPLICATION =>
696 ($store->get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
697 cache_store::MODE_SESSION =>
698 ($store->get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
699 cache_store::MODE_REQUEST =>
700 ($store->get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
702 'supports' => array(
703 'multipleidentifiers' => $store->supports_multiple_identifiers(),
704 'dataguarantee' => $store->supports_data_guarantee(),
705 'nativettl' => $store->supports_native_ttl(),
706 'nativelocking' => ($store instanceof cache_is_lockable),
707 'keyawareness' => ($store instanceof cache_is_key_aware),
708 'searchable' => ($store instanceof cache_is_searchable)
711 if (empty($details['default'])) {
712 $return[$name] = $record;
713 } else {
714 $default[$name] = $record;
718 ksort($return);
719 ksort($default);
720 $return = $return + $default;
722 foreach ($instance->get_definition_mappings() as $mapping) {
723 if (!array_key_exists($mapping['store'], $return)) {
724 continue;
726 $return[$mapping['store']]['mappings']++;
729 return $return;
733 * Returns an array of information about plugins, everything a renderer needs.
734 * @return array
736 public static function get_store_plugin_summaries() {
737 $return = array();
738 $plugins = get_plugin_list_with_file('cachestore', 'lib.php', true);
739 foreach ($plugins as $plugin => $path) {
740 $class = 'cachestore_'.$plugin;
741 $return[$plugin] = array(
742 'name' => get_string('pluginname', 'cachestore_'.$plugin),
743 'requirementsmet' => $class::are_requirements_met(),
744 'instances' => 0,
745 'modes' => array(
746 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
747 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
748 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
750 'supports' => array(
751 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
752 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
753 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
754 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
755 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
757 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
761 $instance = cache_config::instance();
762 $stores = $instance->get_all_stores();
763 foreach ($stores as $store) {
764 $plugin = $store['plugin'];
765 if (array_key_exists($plugin, $return)) {
766 $return[$plugin]['instances']++;
770 return $return;
774 * Returns an array about the definitions. All the information a renderer needs.
775 * @return array
777 public static function get_definition_summaries() {
778 $instance = cache_config::instance();
779 $definitions = $instance->get_definitions();
781 $storenames = array();
782 foreach ($instance->get_all_stores() as $key => $store) {
783 if (!empty($store['default'])) {
784 $storenames[$key] = new lang_string('store_'.$key, 'cache');
788 $modemappings = array();
789 foreach ($instance->get_mode_mappings() as $mapping) {
790 $mode = $mapping['mode'];
791 if (!array_key_exists($mode, $modemappings)) {
792 $modemappings[$mode] = array();
794 if (array_key_exists($mapping['store'], $storenames)) {
795 $modemappings[$mode][] = $storenames[$mapping['store']];
796 } else {
797 $modemappings[$mode][] = $mapping['store'];
801 $definitionmappings = array();
802 foreach ($instance->get_definition_mappings() as $mapping) {
803 $definition = $mapping['definition'];
804 if (!array_key_exists($definition, $definitionmappings)) {
805 $definitionmappings[$definition] = array();
807 if (array_key_exists($mapping['store'], $storenames)) {
808 $definitionmappings[$definition][] = $storenames[$mapping['store']];
809 } else {
810 $definitionmappings[$definition][] = $mapping['store'];
814 $return = array();
816 foreach ($definitions as $id => $definition) {
818 $mappings = array();
819 if (array_key_exists($id, $definitionmappings)) {
820 $mappings = $definitionmappings[$id];
821 } else if (empty($definition['mappingsonly'])) {
822 $mappings = $modemappings[$definition['mode']];
825 $return[$id] = array(
826 'id' => $id,
827 'name' => cache_helper::get_definition_name($definition),
828 'mode' => $definition['mode'],
829 'component' => $definition['component'],
830 'area' => $definition['area'],
831 'mappings' => $mappings,
832 'sharingoptions' => self::get_definition_sharing_options($definition['sharingoptions'], false),
833 'selectedsharingoption' => self::get_definition_sharing_options($definition['selectedsharingoption'], true),
834 'userinputsharingkey' => $definition['userinputsharingkey']
837 return $return;
841 * Given a sharing option hash this function returns an array of strings that can be used to describe it.
843 * @param int $sharingoption The sharing option hash to get strings for.
844 * @param bool $isselectedoptions Set to true if the strings will be used to view the selected options.
845 * @return array An array of lang_string's.
847 public static function get_definition_sharing_options($sharingoption, $isselectedoptions = true) {
848 $options = array();
849 $prefix = ($isselectedoptions) ? 'sharingselected' : 'sharing';
850 if ($sharingoption & cache_definition::SHARING_ALL) {
851 $options[cache_definition::SHARING_ALL] = new lang_string($prefix.'_all', 'cache');
853 if ($sharingoption & cache_definition::SHARING_SITEID) {
854 $options[cache_definition::SHARING_SITEID] = new lang_string($prefix.'_siteid', 'cache');
856 if ($sharingoption & cache_definition::SHARING_VERSION) {
857 $options[cache_definition::SHARING_VERSION] = new lang_string($prefix.'_version', 'cache');
859 if ($sharingoption & cache_definition::SHARING_INPUT) {
860 $options[cache_definition::SHARING_INPUT] = new lang_string($prefix.'_input', 'cache');
862 return $options;
866 * Returns all of the actions that can be performed on a definition.
867 * @param context $context
868 * @return array
870 public static function get_definition_actions(context $context, array $definition) {
871 if (has_capability('moodle/site:config', $context)) {
872 $actions = array();
873 // Edit mappings.
874 $actions[] = array(
875 'text' => get_string('editmappings', 'cache'),
876 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
878 // Edit sharing.
879 if (count($definition['sharingoptions']) > 1) {
880 $actions[] = array(
881 'text' => get_string('editsharing', 'cache'),
882 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionsharing', 'sesskey' => sesskey()))
885 // Purge.
886 $actions[] = array(
887 'text' => get_string('purge', 'cache'),
888 'url' => new moodle_url('/cache/admin.php', array('action' => 'purgedefinition', 'sesskey' => sesskey()))
890 return $actions;
892 return array();
896 * Returns all of the actions that can be performed on a store.
898 * @param string $name The name of the store
899 * @param array $storedetails
900 * @return array
902 public static function get_store_instance_actions($name, array $storedetails) {
903 $actions = array();
904 if (has_capability('moodle/site:config', get_system_context())) {
905 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
906 if (empty($storedetails['default'])) {
907 $actions[] = array(
908 'text' => get_string('editstore', 'cache'),
909 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
911 $actions[] = array(
912 'text' => get_string('deletestore', 'cache'),
913 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
916 $actions[] = array(
917 'text' => get_string('purge', 'cache'),
918 'url' => new moodle_url($baseurl, array('action' => 'purgestore'))
921 return $actions;
926 * Returns all of the actions that can be performed on a plugin.
928 * @param string $name The name of the plugin
929 * @param array $plugindetails
930 * @return array
932 public static function get_store_plugin_actions($name, array $plugindetails) {
933 $actions = array();
934 if (has_capability('moodle/site:config', context_system::instance())) {
935 if (!empty($plugindetails['canaddinstance'])) {
936 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
937 $actions[] = array(
938 'text' => get_string('addinstance', 'cache'),
939 'url' => $url
943 return $actions;
947 * Returns a form that can be used to add a store instance.
949 * @param string $plugin The plugin to add an instance of
950 * @return cachestore_addinstance_form
951 * @throws coding_exception
953 public static function get_add_store_form($plugin) {
954 global $CFG; // Needed for includes.
955 $plugins = get_plugin_list('cachestore');
956 if (!array_key_exists($plugin, $plugins)) {
957 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
959 $plugindir = $plugins[$plugin];
960 $class = 'cachestore_addinstance_form';
961 if (file_exists($plugindir.'/addinstanceform.php')) {
962 require_once($plugindir.'/addinstanceform.php');
963 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
964 $class = 'cachestore_'.$plugin.'_addinstance_form';
965 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
966 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
971 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
973 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
974 return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
978 * Returns a form that can be used to edit a store instance.
980 * @param string $plugin
981 * @param string $store
982 * @return cachestore_addinstance_form
983 * @throws coding_exception
985 public static function get_edit_store_form($plugin, $store) {
986 global $CFG; // Needed for includes.
987 $plugins = get_plugin_list('cachestore');
988 if (!array_key_exists($plugin, $plugins)) {
989 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
991 $factory = cache_factory::instance();
992 $config = $factory->create_config_instance();
993 $stores = $config->get_all_stores();
994 if (!array_key_exists($store, $stores)) {
995 throw new coding_exception('Invalid store name given when trying to create an edit form.');
997 $plugindir = $plugins[$plugin];
998 $class = 'cachestore_addinstance_form';
999 if (file_exists($plugindir.'/addinstanceform.php')) {
1000 require_once($plugindir.'/addinstanceform.php');
1001 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
1002 $class = 'cachestore_'.$plugin.'_addinstance_form';
1003 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
1004 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
1009 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
1011 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
1012 $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
1013 if (isset($stores[$store]['lock'])) {
1014 $editform->set_data(array('lock' => $stores[$store]['lock']));
1016 // See if the cachestore is going to want to load data for the form.
1017 // If it has a customised add instance form then it is going to want to.
1018 $storeclass = 'cachestore_'.$plugin;
1019 $storedata = $stores[$store];
1020 if (array_key_exists('configuration', $storedata) && array_key_exists('cache_is_configurable', class_implements($storeclass))) {
1021 $storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
1023 return $editform;
1027 * Returns an array of suitable lock instances for use with this plugin, or false if the plugin handles locking itself.
1029 * @param string $plugindir
1030 * @param string $plugin
1031 * @return array|false
1033 protected static function get_possible_locks_for_stores($plugindir, $plugin) {
1034 global $CFG; // Needed for includes.
1035 $supportsnativelocking = false;
1036 if (file_exists($plugindir.'/lib.php')) {
1037 require_once($plugindir.'/lib.php');
1038 $pluginclass = 'cachestore_'.$plugin;
1039 if (class_exists($pluginclass)) {
1040 $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
1044 if (!$supportsnativelocking) {
1045 $config = cache_config::instance();
1046 $locks = array();
1047 foreach ($config->get_locks() as $lock => $conf) {
1048 if (!empty($conf['default'])) {
1049 $name = get_string($lock, 'cache');
1050 } else {
1051 $name = $lock;
1053 $locks[$lock] = $name;
1055 } else {
1056 $locks = false;
1059 return $locks;
1063 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
1064 * store in configuration.
1066 * @param stdClass $data The mform data.
1067 * @return array
1068 * @throws coding_exception
1070 public static function get_store_configuration_from_data(stdClass $data) {
1071 global $CFG;
1072 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
1073 if (!file_exists($file)) {
1074 throw new coding_exception('Invalid cache plugin provided. '.$file);
1076 require_once($file);
1077 $class = 'cachestore_'.$data->plugin;
1078 if (!class_exists($class)) {
1079 throw new coding_exception('Invalid cache plugin provided.');
1081 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1082 return $class::config_get_configuration_array($data);
1084 return array();
1088 * Get an array of stores that are suitable to be used for a given definition.
1090 * @param string $component
1091 * @param string $area
1092 * @return array Array containing 3 elements
1093 * 1. An array of currently used stores
1094 * 2. An array of suitable stores
1095 * 3. An array of default stores
1097 public static function get_definition_store_options($component, $area) {
1098 $factory = cache_factory::instance();
1099 $definition = $factory->create_definition($component, $area);
1100 $config = cache_config::instance();
1101 $currentstores = $config->get_stores_for_definition($definition);
1102 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
1104 $defaults = array();
1105 foreach ($currentstores as $key => $store) {
1106 if (!empty($store['default'])) {
1107 $defaults[] = $key;
1108 unset($currentstores[$key]);
1111 foreach ($possiblestores as $key => $store) {
1112 if ($store['default']) {
1113 unset($possiblestores[$key]);
1114 $possiblestores[$key] = $store;
1117 return array($currentstores, $possiblestores, $defaults);
1121 * Get the default stores for all modes.
1123 * @return array An array containing sub-arrays, one for each mode.
1125 public static function get_default_mode_stores() {
1126 $instance = cache_config::instance();
1127 $storenames = array();
1128 foreach ($instance->get_all_stores() as $key => $store) {
1129 if (!empty($store['default'])) {
1130 $storenames[$key] = new lang_string('store_'.$key, 'cache');
1133 $modemappings = array(
1134 cache_store::MODE_APPLICATION => array(),
1135 cache_store::MODE_SESSION => array(),
1136 cache_store::MODE_REQUEST => array(),
1138 foreach ($instance->get_mode_mappings() as $mapping) {
1139 $mode = $mapping['mode'];
1140 if (!array_key_exists($mode, $modemappings)) {
1141 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
1142 continue;
1144 if (array_key_exists($mapping['store'], $storenames)) {
1145 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
1146 } else {
1147 $modemappings[$mode][$mapping['store']] = $mapping['store'];
1150 return $modemappings;
1154 * Returns an array summarising the locks available in the system
1156 public static function get_lock_summaries() {
1157 $locks = array();
1158 $instance = cache_config::instance();
1159 $stores = $instance->get_all_stores();
1160 foreach ($instance->get_locks() as $lock) {
1161 $default = !empty($lock['default']);
1162 if ($default) {
1163 $name = new lang_string($lock['name'], 'cache');
1164 } else {
1165 $name = $lock['name'];
1167 $uses = 0;
1168 foreach ($stores as $store) {
1169 if (!empty($store['lock']) && $store['lock'] === $lock['name']) {
1170 $uses++;
1173 $lockdata = array(
1174 'name' => $name,
1175 'default' => $default,
1176 'uses' => $uses,
1177 'type' => get_string('pluginname', $lock['type'])
1179 $locks[$lock['name']] = $lockdata;
1181 return $locks;
1185 * Returns an array of lock plugins for which we can add an instance.
1187 * Suitable for use within an mform select element.
1189 * @return array
1191 public static function get_addable_lock_options() {
1192 $plugins = get_plugin_list_with_class('cachelock', '', 'lib.php');
1193 $options = array();
1194 $len = strlen('cachelock_');
1195 foreach ($plugins as $plugin => $class) {
1196 $method = "$class::can_add_instance";
1197 if (is_callable($method) && !call_user_func($method)) {
1198 // Can't add an instance of this plugin.
1199 continue;
1201 $options[substr($plugin, $len)] = get_string('pluginname', $plugin);
1203 return $options;
1207 * Gets the form to use when adding a lock instance.
1209 * @param string $plugin
1210 * @param array $lockplugin
1211 * @return cache_lock_form
1212 * @throws coding_exception
1214 public static function get_add_lock_form($plugin, array $lockplugin = null) {
1215 global $CFG; // Needed for includes.
1216 $plugins = get_plugin_list('cachelock');
1217 if (!array_key_exists($plugin, $plugins)) {
1218 throw new coding_exception('Invalid cache lock plugin requested when trying to create a form.');
1220 $plugindir = $plugins[$plugin];
1221 $class = 'cache_lock_form';
1222 if (file_exists($plugindir.'/addinstanceform.php') && in_array('cache_is_configurable', class_implements($class))) {
1223 require_once($plugindir.'/addinstanceform.php');
1224 if (class_exists('cachelock_'.$plugin.'_addinstance_form')) {
1225 $class = 'cachelock_'.$plugin.'_addinstance_form';
1226 if (!array_key_exists('cache_lock_form', class_parents($class))) {
1227 throw new coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
1231 return new $class(null, array('lock' => $plugin));
1235 * Gets configuration data from a new lock instance form.
1237 * @param string $plugin
1238 * @param stdClass $data
1239 * @return array
1240 * @throws coding_exception
1242 public static function get_lock_configuration_from_data($plugin, $data) {
1243 global $CFG;
1244 $file = $CFG->dirroot.'/cache/locks/'.$plugin.'/lib.php';
1245 if (!file_exists($file)) {
1246 throw new coding_exception('Invalid cache plugin provided. '.$file);
1248 require_once($file);
1249 $class = 'cachelock_'.$plugin;
1250 if (!class_exists($class)) {
1251 throw new coding_exception('Invalid cache plugin provided.');
1253 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1254 return $class::config_get_configuration_array($data);
1256 return array();