MDL-70959 completion: Documentation improvements
[moodle.git] / cache / locallib.php
blobc5c0d873e2b09f524759cfc8a8a219c66a738644
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 static $confighash = '';
72 $cachefile = static::get_config_file_path();
73 $directory = dirname($cachefile);
74 if ($directory !== $CFG->dataroot && !file_exists($directory)) {
75 $result = make_writable_directory($directory, false);
76 if (!$result) {
77 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory. Check the permissions on your moodledata directory.');
80 if (!file_exists($directory) || !is_writable($directory)) {
81 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Config directory is not writable. Check the permissions on the moodledata/muc directory.');
84 // Prepare a configuration array to store.
85 $configuration = $this->generate_configuration_array();
87 // Prepare the file content.
88 $content = "<?php defined('MOODLE_INTERNAL') || die();\n \$configuration = ".var_export($configuration, true).";";
90 // Do both file content and hash based detection because this might be called
91 // many times within a single request.
92 $hash = sha1($content);
93 if (($hash === $confighash) || (file_exists($cachefile) && $content === file_get_contents($cachefile))) {
94 // Config is unchanged so don't bother locking and writing.
95 $confighash = $hash;
96 return;
99 // We need to create a temporary cache lock instance for use here. Remember we are generating the config file
100 // it doesn't exist and thus we can't use the normal API for this (it'll just try to use config).
101 $lockconf = reset($this->configlocks);
102 if ($lockconf === false) {
103 debugging('Your cache configuration file is out of date and needs to be refreshed.', DEBUG_DEVELOPER);
104 // Use the default
105 $lockconf = array(
106 'name' => 'cachelock_file_default',
107 'type' => 'cachelock_file',
108 'dir' => 'filelocks',
109 'default' => true
112 $factory = cache_factory::instance();
113 $locking = $factory->create_lock_instance($lockconf);
114 if ($locking->lock('configwrite', 'config', true)) {
115 $tempcachefile = "{$cachefile}.tmp";
116 // Its safe to use w mode here because we have already acquired the lock.
117 $handle = fopen($tempcachefile, 'w');
118 fwrite($handle, $content);
119 fflush($handle);
120 fclose($handle);
121 $locking->unlock('configwrite', 'config');
122 @chmod($tempcachefile, $CFG->filepermissions);
123 rename($tempcachefile, $cachefile);
124 // Tell PHP to recompile the script.
125 core_component::invalidate_opcode_php_cache($cachefile);
126 } else {
127 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Unable to open the cache config file.');
132 * Generates a configuration array suitable to be written to the config file.
133 * @return array
135 protected function generate_configuration_array() {
136 $configuration = array();
137 $configuration['siteidentifier'] = $this->siteidentifier;
138 $configuration['stores'] = $this->configstores;
139 $configuration['modemappings'] = $this->configmodemappings;
140 $configuration['definitions'] = $this->configdefinitions;
141 $configuration['definitionmappings'] = $this->configdefinitionmappings;
142 $configuration['locks'] = $this->configlocks;
143 return $configuration;
147 * Adds a plugin instance.
149 * This function also calls save so you should redirect immediately, or at least very shortly after
150 * calling this method.
152 * @param string $name The name for the instance (must be unique)
153 * @param string $plugin The name of the plugin.
154 * @param array $configuration The configuration data for the plugin instance.
155 * @return bool
156 * @throws cache_exception
158 public function add_store_instance($name, $plugin, array $configuration = array()) {
159 if (array_key_exists($name, $this->configstores)) {
160 throw new cache_exception('Duplicate name specificed for cache plugin instance. You must provide a unique name.');
162 $class = 'cachestore_'.$plugin;
163 if (!class_exists($class)) {
164 $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
165 if (!array_key_exists($plugin, $plugins)) {
166 throw new cache_exception('Invalid plugin name specified. The plugin does not exist or is not valid.');
168 $file = $plugins[$plugin];
169 if (file_exists($file)) {
170 require_once($file);
172 if (!class_exists($class)) {
173 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.');
176 $reflection = new ReflectionClass($class);
177 if (!$reflection->isSubclassOf('cache_store')) {
178 throw new cache_exception('Invalid cache plugin specified. The plugin does not extend the required class.');
180 if (!$class::are_requirements_met()) {
181 throw new cache_exception('Unable to add new cache plugin instance. The requested plugin type is not supported.');
183 $this->configstores[$name] = array(
184 'name' => $name,
185 'plugin' => $plugin,
186 'configuration' => $configuration,
187 'features' => $class::get_supported_features($configuration),
188 'modes' => $class::get_supported_modes($configuration),
189 'mappingsonly' => !empty($configuration['mappingsonly']),
190 'class' => $class,
191 'default' => false
193 if (array_key_exists('lock', $configuration)) {
194 $this->configstores[$name]['lock'] = $configuration['lock'];
195 unset($this->configstores[$name]['configuration']['lock']);
197 // Call instance_created()
198 $store = new $class($name, $this->configstores[$name]['configuration']);
199 $store->instance_created();
201 $this->config_save();
202 return true;
206 * Adds a new lock instance to the config file.
208 * @param string $name The name the user gave the instance. PARAM_ALHPANUMEXT
209 * @param string $plugin The plugin we are creating an instance of.
210 * @param string $configuration Configuration data from the config instance.
211 * @throws cache_exception
213 public function add_lock_instance($name, $plugin, $configuration = array()) {
214 if (array_key_exists($name, $this->configlocks)) {
215 throw new cache_exception('Duplicate name specificed for cache lock instance. You must provide a unique name.');
217 $class = 'cachelock_'.$plugin;
218 if (!class_exists($class)) {
219 $plugins = core_component::get_plugin_list_with_file('cachelock', 'lib.php');
220 if (!array_key_exists($plugin, $plugins)) {
221 throw new cache_exception('Invalid lock name specified. The plugin does not exist or is not valid.');
223 $file = $plugins[$plugin];
224 if (file_exists($file)) {
225 require_once($file);
227 if (!class_exists($class)) {
228 throw new cache_exception('Invalid lock plugin specified. The plugin does not contain the required class.');
231 $reflection = new ReflectionClass($class);
232 if (!$reflection->implementsInterface('cache_lock_interface')) {
233 throw new cache_exception('Invalid lock plugin specified. The plugin does not implement the required interface.');
235 $this->configlocks[$name] = array_merge($configuration, array(
236 'name' => $name,
237 'type' => 'cachelock_'.$plugin,
238 'default' => false
240 $this->config_save();
244 * Deletes a lock instance given its name.
246 * @param string $name The name of the plugin, PARAM_ALPHANUMEXT.
247 * @return bool
248 * @throws cache_exception
250 public function delete_lock_instance($name) {
251 if (!array_key_exists($name, $this->configlocks)) {
252 throw new cache_exception('The requested store does not exist.');
254 if ($this->configlocks[$name]['default']) {
255 throw new cache_exception('You can not delete the default lock.');
257 foreach ($this->configstores as $store) {
258 if (isset($store['lock']) && $store['lock'] === $name) {
259 throw new cache_exception('You cannot delete a cache lock that is being used by a store.');
262 unset($this->configlocks[$name]);
263 $this->config_save();
264 return true;
268 * Sets the mode mappings.
270 * These determine the default caches for the different modes.
271 * This function also calls save so you should redirect immediately, or at least very shortly after
272 * calling this method.
274 * @param array $modemappings
275 * @return bool
276 * @throws cache_exception
278 public function set_mode_mappings(array $modemappings) {
279 $mappings = array(
280 cache_store::MODE_APPLICATION => array(),
281 cache_store::MODE_SESSION => array(),
282 cache_store::MODE_REQUEST => array(),
284 foreach ($modemappings as $mode => $stores) {
285 if (!array_key_exists($mode, $mappings)) {
286 throw new cache_exception('The cache mode for the new mapping does not exist');
288 $sort = 0;
289 foreach ($stores as $store) {
290 if (!array_key_exists($store, $this->configstores)) {
291 throw new cache_exception('The instance name for the new mapping does not exist');
293 if (array_key_exists($store, $mappings[$mode])) {
294 throw new cache_exception('This cache mapping already exists');
296 $mappings[$mode][] = array(
297 'store' => $store,
298 'mode' => $mode,
299 'sort' => $sort++
303 $this->configmodemappings = array_merge(
304 $mappings[cache_store::MODE_APPLICATION],
305 $mappings[cache_store::MODE_SESSION],
306 $mappings[cache_store::MODE_REQUEST]
309 $this->config_save();
310 return true;
314 * Edits a give plugin instance.
316 * The plugin instance is determined by its name, hence you cannot rename plugins.
317 * This function also calls save so you should redirect immediately, or at least very shortly after
318 * calling this method.
320 * @param string $name
321 * @param string $plugin
322 * @param array $configuration
323 * @return bool
324 * @throws cache_exception
326 public function edit_store_instance($name, $plugin, $configuration) {
327 if (!array_key_exists($name, $this->configstores)) {
328 throw new cache_exception('The requested instance does not exist.');
330 $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
331 if (!array_key_exists($plugin, $plugins)) {
332 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
334 $class = 'cachestore_'.$plugin;
335 $file = $plugins[$plugin];
336 if (!class_exists($class)) {
337 if (file_exists($file)) {
338 require_once($file);
340 if (!class_exists($class)) {
341 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.'.$class);
344 $this->configstores[$name] = array(
345 'name' => $name,
346 'plugin' => $plugin,
347 'configuration' => $configuration,
348 'features' => $class::get_supported_features($configuration),
349 'modes' => $class::get_supported_modes($configuration),
350 'mappingsonly' => !empty($configuration['mappingsonly']),
351 'class' => $class,
352 'default' => $this->configstores[$name]['default'] // Can't change the default.
354 if (array_key_exists('lock', $configuration)) {
355 $this->configstores[$name]['lock'] = $configuration['lock'];
356 unset($this->configstores[$name]['configuration']['lock']);
358 $this->config_save();
359 return true;
363 * Deletes a store instance.
365 * This function also calls save so you should redirect immediately, or at least very shortly after
366 * calling this method.
368 * @param string $name The name of the instance to delete.
369 * @return bool
370 * @throws cache_exception
372 public function delete_store_instance($name) {
373 if (!array_key_exists($name, $this->configstores)) {
374 throw new cache_exception('The requested store does not exist.');
376 if ($this->configstores[$name]['default']) {
377 throw new cache_exception('The can not delete the default stores.');
379 foreach ($this->configmodemappings as $mapping) {
380 if ($mapping['store'] === $name) {
381 throw new cache_exception('You cannot delete a cache store that has mode mappings.');
384 foreach ($this->configdefinitionmappings as $mapping) {
385 if ($mapping['store'] === $name) {
386 throw new cache_exception('You cannot delete a cache store that has definition mappings.');
390 // Call instance_deleted()
391 $class = 'cachestore_'.$this->configstores[$name]['plugin'];
392 $store = new $class($name, $this->configstores[$name]['configuration']);
393 $store->instance_deleted();
395 unset($this->configstores[$name]);
396 $this->config_save();
397 return true;
401 * Creates the default configuration and saves it.
403 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
404 * be called when there is no configuration file already.
406 * @param bool $forcesave If set to true then we will forcefully save the default configuration file.
407 * @return true|array Returns true if the default configuration was successfully created.
408 * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
410 public static function create_default_configuration($forcesave = false) {
411 // HACK ALERT.
412 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
413 // default store plugins are protected from deletion.
414 $writer = new self;
415 $writer->configstores = self::get_default_stores();
416 $writer->configdefinitions = self::locate_definitions();
417 $writer->configmodemappings = array(
418 array(
419 'mode' => cache_store::MODE_APPLICATION,
420 'store' => 'default_application',
421 'sort' => -1
423 array(
424 'mode' => cache_store::MODE_SESSION,
425 'store' => 'default_session',
426 'sort' => -1
428 array(
429 'mode' => cache_store::MODE_REQUEST,
430 'store' => 'default_request',
431 'sort' => -1
434 $writer->configlocks = array(
435 'default_file_lock' => array(
436 'name' => 'cachelock_file_default',
437 'type' => 'cachelock_file',
438 'dir' => 'filelocks',
439 'default' => true
443 $factory = cache_factory::instance();
444 // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
445 // we are now in a loop.
446 if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
447 return $writer->generate_configuration_array();
449 $factory->set_state(cache_factory::STATE_SAVING);
450 $writer->config_save();
451 return true;
455 * Returns an array of default stores for use.
457 * @return array
459 protected static function get_default_stores() {
460 global $CFG;
462 require_once($CFG->dirroot.'/cache/stores/file/lib.php');
463 require_once($CFG->dirroot.'/cache/stores/session/lib.php');
464 require_once($CFG->dirroot.'/cache/stores/static/lib.php');
466 return array(
467 'default_application' => array(
468 'name' => 'default_application',
469 'plugin' => 'file',
470 'configuration' => array(),
471 'features' => cachestore_file::get_supported_features(),
472 'modes' => cachestore_file::get_supported_modes(),
473 'default' => true,
475 'default_session' => array(
476 'name' => 'default_session',
477 'plugin' => 'session',
478 'configuration' => array(),
479 'features' => cachestore_session::get_supported_features(),
480 'modes' => cachestore_session::get_supported_modes(),
481 'default' => true,
483 'default_request' => array(
484 'name' => 'default_request',
485 'plugin' => 'static',
486 'configuration' => array(),
487 'features' => cachestore_static::get_supported_features(),
488 'modes' => cachestore_static::get_supported_modes(),
489 'default' => true,
495 * Updates the default stores within the MUC config file.
497 public static function update_default_config_stores() {
498 $factory = cache_factory::instance();
499 $factory->updating_started();
500 $config = $factory->create_config_instance(true);
501 $config->configstores = array_merge($config->configstores, self::get_default_stores());
502 $config->config_save();
503 $factory->updating_finished();
507 * Updates the definition in the configuration from those found in the cache files.
509 * Calls config_save further down, you should redirect immediately or asap after calling this method.
511 * @param bool $coreonly If set to true only core definitions will be updated.
513 public static function update_definitions($coreonly = false) {
514 $factory = cache_factory::instance();
515 $factory->updating_started();
516 $config = $factory->create_config_instance(true);
517 $config->write_definitions_to_cache(self::locate_definitions($coreonly));
518 $factory->updating_finished();
522 * Locates all of the definition files.
524 * @param bool $coreonly If set to true only core definitions will be updated.
525 * @return array
527 protected static function locate_definitions($coreonly = false) {
528 global $CFG;
530 $files = array();
531 if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
532 $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
535 if (!$coreonly) {
536 $plugintypes = core_component::get_plugin_types();
537 foreach ($plugintypes as $type => $location) {
538 $plugins = core_component::get_plugin_list_with_file($type, 'db/caches.php');
539 foreach ($plugins as $plugin => $filepath) {
540 $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
541 $files[$component] = $filepath;
546 $definitions = array();
547 foreach ($files as $component => $file) {
548 $filedefs = self::load_caches_file($file);
549 foreach ($filedefs as $area => $definition) {
550 $area = clean_param($area, PARAM_AREA);
551 $id = $component.'/'.$area;
552 $definition['component'] = $component;
553 $definition['area'] = $area;
554 if (array_key_exists($id, $definitions)) {
555 debugging('Error: duplicate cache definition found with id: '.$id, DEBUG_DEVELOPER);
556 continue;
558 $definitions[$id] = $definition;
562 return $definitions;
566 * Writes the updated definitions for the config file.
567 * @param array $definitions
569 private function write_definitions_to_cache(array $definitions) {
571 // Preserve the selected sharing option when updating the definitions.
572 // This is set by the user and should never come from caches.php.
573 foreach ($definitions as $key => $definition) {
574 unset($definitions[$key]['selectedsharingoption']);
575 unset($definitions[$key]['userinputsharingkey']);
576 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['selectedsharingoption'])) {
577 $definitions[$key]['selectedsharingoption'] = $this->configdefinitions[$key]['selectedsharingoption'];
579 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['userinputsharingkey'])) {
580 $definitions[$key]['userinputsharingkey'] = $this->configdefinitions[$key]['userinputsharingkey'];
584 $this->configdefinitions = $definitions;
585 foreach ($this->configdefinitionmappings as $key => $mapping) {
586 if (!array_key_exists($mapping['definition'], $definitions)) {
587 unset($this->configdefinitionmappings[$key]);
590 $this->config_save();
594 * Loads the caches file if it exists.
595 * @param string $file Absolute path to the file.
596 * @return array
598 private static function load_caches_file($file) {
599 if (!file_exists($file)) {
600 return array();
602 $definitions = array();
603 include($file);
604 return $definitions;
608 * Sets the mappings for a given definition.
610 * @param string $definition
611 * @param array $mappings
612 * @throws coding_exception
614 public function set_definition_mappings($definition, $mappings) {
615 if (!array_key_exists($definition, $this->configdefinitions)) {
616 throw new coding_exception('Invalid definition name passed when updating mappings.');
618 foreach ($mappings as $store) {
619 if (!array_key_exists($store, $this->configstores)) {
620 throw new coding_exception('Invalid store name passed when updating definition mappings.');
623 foreach ($this->configdefinitionmappings as $key => $mapping) {
624 if ($mapping['definition'] == $definition) {
625 unset($this->configdefinitionmappings[$key]);
628 $sort = count($mappings);
629 foreach ($mappings as $store) {
630 $this->configdefinitionmappings[] = array(
631 'store' => $store,
632 'definition' => $definition,
633 'sort' => $sort
635 $sort--;
638 $this->config_save();
642 * Update the site identifier stored by the cache API.
644 * @param string $siteidentifier
645 * @return string The new site identifier.
647 public function update_site_identifier($siteidentifier) {
648 $this->siteidentifier = md5((string)$siteidentifier);
649 $this->config_save();
650 return $this->siteidentifier;
654 * Sets the selected sharing options and key for a definition.
656 * @param string $definition The name of the definition to set for.
657 * @param int $sharingoption The sharing option to set.
658 * @param string|null $userinputsharingkey The user input key or null.
659 * @throws coding_exception
661 public function set_definition_sharing($definition, $sharingoption, $userinputsharingkey = null) {
662 if (!array_key_exists($definition, $this->configdefinitions)) {
663 throw new coding_exception('Invalid definition name passed when updating sharing options.');
665 if (!($this->configdefinitions[$definition]['sharingoptions'] & $sharingoption)) {
666 throw new coding_exception('Invalid sharing option passed when updating definition.');
668 $this->configdefinitions[$definition]['selectedsharingoption'] = (int)$sharingoption;
669 if (!empty($userinputsharingkey)) {
670 $this->configdefinitions[$definition]['userinputsharingkey'] = (string)$userinputsharingkey;
672 $this->config_save();
678 * A cache helper for administration tasks
680 * @package core
681 * @category cache
682 * @copyright 2012 Sam Hemelryk
683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
685 abstract class cache_administration_helper extends cache_helper {
688 * Returns an array containing all of the information about stores a renderer needs.
689 * @return array
691 public static function get_store_instance_summaries() {
692 $return = array();
693 $default = array();
694 $instance = cache_config::instance();
695 $stores = $instance->get_all_stores();
696 $locks = $instance->get_locks();
697 foreach ($stores as $name => $details) {
698 $class = $details['class'];
699 $store = false;
700 if ($class::are_requirements_met()) {
701 $store = new $class($details['name'], $details['configuration']);
703 $lock = (isset($details['lock'])) ? $locks[$details['lock']] : $instance->get_default_lock();
704 $record = array(
705 'name' => $name,
706 'plugin' => $details['plugin'],
707 'default' => $details['default'],
708 'isready' => $store ? $store->is_ready() : false,
709 'requirementsmet' => $class::are_requirements_met(),
710 'mappings' => 0,
711 'lock' => $lock,
712 'modes' => array(
713 cache_store::MODE_APPLICATION =>
714 ($class::get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
715 cache_store::MODE_SESSION =>
716 ($class::get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
717 cache_store::MODE_REQUEST =>
718 ($class::get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
720 'supports' => array(
721 'multipleidentifiers' => $store ? $store->supports_multiple_identifiers() : false,
722 'dataguarantee' => $store ? $store->supports_data_guarantee() : false,
723 'nativettl' => $store ? $store->supports_native_ttl() : false,
724 'nativelocking' => ($store instanceof cache_is_lockable),
725 'keyawareness' => ($store instanceof cache_is_key_aware),
726 'searchable' => ($store instanceof cache_is_searchable)
728 'warnings' => $store ? $store->get_warnings() : array()
730 if (empty($details['default'])) {
731 $return[$name] = $record;
732 } else {
733 $default[$name] = $record;
737 ksort($return);
738 ksort($default);
739 $return = $return + $default;
741 foreach ($instance->get_definition_mappings() as $mapping) {
742 if (!array_key_exists($mapping['store'], $return)) {
743 continue;
745 $return[$mapping['store']]['mappings']++;
748 return $return;
752 * Returns an array of information about plugins, everything a renderer needs.
754 * @return array for each store, an array containing various information about each store.
755 * See the code below for details
757 public static function get_store_plugin_summaries() {
758 $return = array();
759 $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php', true);
760 foreach ($plugins as $plugin => $path) {
761 $class = 'cachestore_'.$plugin;
762 $return[$plugin] = array(
763 'name' => get_string('pluginname', 'cachestore_'.$plugin),
764 'requirementsmet' => $class::are_requirements_met(),
765 'instances' => 0,
766 'modes' => array(
767 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
768 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
769 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
771 'supports' => array(
772 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
773 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
774 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
775 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
776 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
778 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
782 $instance = cache_config::instance();
783 $stores = $instance->get_all_stores();
784 foreach ($stores as $store) {
785 $plugin = $store['plugin'];
786 if (array_key_exists($plugin, $return)) {
787 $return[$plugin]['instances']++;
791 return $return;
795 * Returns an array about the definitions. All the information a renderer needs.
797 * @return array for each store, an array containing various information about each store.
798 * See the code below for details
800 public static function get_definition_summaries() {
801 $factory = cache_factory::instance();
802 $config = $factory->create_config_instance();
803 $storenames = array();
804 foreach ($config->get_all_stores() as $key => $store) {
805 if (!empty($store['default'])) {
806 $storenames[$key] = new lang_string('store_'.$key, 'cache');
807 } else {
808 $storenames[$store['name']] = $store['name'];
811 /* @var cache_definition[] $definitions */
812 $definitions = array();
813 foreach ($config->get_definitions() as $key => $definition) {
814 $definitions[$key] = cache_definition::load($definition['component'].'/'.$definition['area'], $definition);
816 foreach ($definitions as $id => $definition) {
817 $mappings = array();
818 foreach (cache_helper::get_stores_suitable_for_definition($definition) as $store) {
819 $mappings[] = $storenames[$store->my_name()];
821 $return[$id] = array(
822 'id' => $id,
823 'name' => $definition->get_name(),
824 'mode' => $definition->get_mode(),
825 'component' => $definition->get_component(),
826 'area' => $definition->get_area(),
827 'mappings' => $mappings,
828 'canuselocalstore' => $definition->can_use_localstore(),
829 'sharingoptions' => self::get_definition_sharing_options($definition->get_sharing_options(), false),
830 'selectedsharingoption' => self::get_definition_sharing_options($definition->get_selected_sharing_option(), true),
831 'userinputsharingkey' => $definition->get_user_input_sharing_key()
834 return $return;
838 * Given a sharing option hash this function returns an array of strings that can be used to describe it.
840 * @param int $sharingoption The sharing option hash to get strings for.
841 * @param bool $isselectedoptions Set to true if the strings will be used to view the selected options.
842 * @return array An array of lang_string's.
844 public static function get_definition_sharing_options($sharingoption, $isselectedoptions = true) {
845 $options = array();
846 $prefix = ($isselectedoptions) ? 'sharingselected' : 'sharing';
847 if ($sharingoption & cache_definition::SHARING_ALL) {
848 $options[cache_definition::SHARING_ALL] = new lang_string($prefix.'_all', 'cache');
850 if ($sharingoption & cache_definition::SHARING_SITEID) {
851 $options[cache_definition::SHARING_SITEID] = new lang_string($prefix.'_siteid', 'cache');
853 if ($sharingoption & cache_definition::SHARING_VERSION) {
854 $options[cache_definition::SHARING_VERSION] = new lang_string($prefix.'_version', 'cache');
856 if ($sharingoption & cache_definition::SHARING_INPUT) {
857 $options[cache_definition::SHARING_INPUT] = new lang_string($prefix.'_input', 'cache');
859 return $options;
863 * Returns all of the actions that can be performed on a definition.
865 * @param context $context the system context.
866 * @param array $definitionsummary information about this cache, from the array returned by
867 * cache_administration_helper::get_definition_summaries(). Currently only 'sharingoptions'
868 * element is used.
869 * @return array of actions. Each action is an array with two elements, 'text' and 'url'.
871 public static function get_definition_actions(context $context, array $definitionsummary) {
872 if (has_capability('moodle/site:config', $context)) {
873 $actions = array();
874 // Edit mappings.
875 $actions[] = array(
876 'text' => get_string('editmappings', 'cache'),
877 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
879 // Edit sharing.
880 if (count($definitionsummary['sharingoptions']) > 1) {
881 $actions[] = array(
882 'text' => get_string('editsharing', 'cache'),
883 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionsharing', 'sesskey' => sesskey()))
886 // Purge.
887 $actions[] = array(
888 'text' => get_string('purge', 'cache'),
889 'url' => new moodle_url('/cache/admin.php', array('action' => 'purgedefinition', 'sesskey' => sesskey()))
891 return $actions;
893 return array();
897 * Returns all of the actions that can be performed on a store.
899 * @param string $name The name of the store
900 * @param array $storedetails information about this store, from the array returned by
901 * cache_administration_helper::get_store_instance_summaries().
902 * @return array of actions. Each action is an array with two elements, 'text' and 'url'.
904 public static function get_store_instance_actions($name, array $storedetails) {
905 $actions = array();
906 if (has_capability('moodle/site:config', context_system::instance())) {
907 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
908 if (empty($storedetails['default'])) {
909 $actions[] = array(
910 'text' => get_string('editstore', 'cache'),
911 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
913 $actions[] = array(
914 'text' => get_string('deletestore', 'cache'),
915 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
918 $actions[] = array(
919 'text' => get_string('purge', 'cache'),
920 'url' => new moodle_url($baseurl, array('action' => 'purgestore'))
923 return $actions;
927 * Returns all of the actions that can be performed on a plugin.
929 * @param string $name The name of the plugin
930 * @param array $plugindetails information about this store, from the array returned by
931 * cache_administration_helper::get_store_plugin_summaries().
932 * @param array $plugindetails
933 * @return array
935 public static function get_store_plugin_actions($name, array $plugindetails) {
936 $actions = array();
937 if (has_capability('moodle/site:config', context_system::instance())) {
938 if (!empty($plugindetails['canaddinstance'])) {
939 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
940 $actions[] = array(
941 'text' => get_string('addinstance', 'cache'),
942 'url' => $url
946 return $actions;
950 * Returns a form that can be used to add a store instance.
952 * @param string $plugin The plugin to add an instance of
953 * @return cachestore_addinstance_form
954 * @throws coding_exception
956 public static function get_add_store_form($plugin) {
957 global $CFG; // Needed for includes.
958 $plugins = core_component::get_plugin_list('cachestore');
959 if (!array_key_exists($plugin, $plugins)) {
960 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
962 $plugindir = $plugins[$plugin];
963 $class = 'cachestore_addinstance_form';
964 if (file_exists($plugindir.'/addinstanceform.php')) {
965 require_once($plugindir.'/addinstanceform.php');
966 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
967 $class = 'cachestore_'.$plugin.'_addinstance_form';
968 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
969 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
974 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
976 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
977 return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
981 * Returns a form that can be used to edit a store instance.
983 * @param string $plugin
984 * @param string $store
985 * @return cachestore_addinstance_form
986 * @throws coding_exception
988 public static function get_edit_store_form($plugin, $store) {
989 global $CFG; // Needed for includes.
990 $plugins = core_component::get_plugin_list('cachestore');
991 if (!array_key_exists($plugin, $plugins)) {
992 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
994 $factory = cache_factory::instance();
995 $config = $factory->create_config_instance();
996 $stores = $config->get_all_stores();
997 if (!array_key_exists($store, $stores)) {
998 throw new coding_exception('Invalid store name given when trying to create an edit form.');
1000 $plugindir = $plugins[$plugin];
1001 $class = 'cachestore_addinstance_form';
1002 if (file_exists($plugindir.'/addinstanceform.php')) {
1003 require_once($plugindir.'/addinstanceform.php');
1004 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
1005 $class = 'cachestore_'.$plugin.'_addinstance_form';
1006 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
1007 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
1012 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
1014 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
1015 $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
1016 if (isset($stores[$store]['lock'])) {
1017 $editform->set_data(array('lock' => $stores[$store]['lock']));
1019 // See if the cachestore is going to want to load data for the form.
1020 // If it has a customised add instance form then it is going to want to.
1021 $storeclass = 'cachestore_'.$plugin;
1022 $storedata = $stores[$store];
1023 if (array_key_exists('configuration', $storedata) && array_key_exists('cache_is_configurable', class_implements($storeclass))) {
1024 $storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
1026 return $editform;
1030 * Returns an array of suitable lock instances for use with this plugin, or false if the plugin handles locking itself.
1032 * @param string $plugindir
1033 * @param string $plugin
1034 * @return array|false
1036 protected static function get_possible_locks_for_stores($plugindir, $plugin) {
1037 global $CFG; // Needed for includes.
1038 $supportsnativelocking = false;
1039 if (file_exists($plugindir.'/lib.php')) {
1040 require_once($plugindir.'/lib.php');
1041 $pluginclass = 'cachestore_'.$plugin;
1042 if (class_exists($pluginclass)) {
1043 $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
1047 if (!$supportsnativelocking) {
1048 $config = cache_config::instance();
1049 $locks = array();
1050 foreach ($config->get_locks() as $lock => $conf) {
1051 if (!empty($conf['default'])) {
1052 $name = get_string($lock, 'cache');
1053 } else {
1054 $name = $lock;
1056 $locks[$lock] = $name;
1058 } else {
1059 $locks = false;
1062 return $locks;
1066 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
1067 * store in configuration.
1069 * @param stdClass $data The mform data.
1070 * @return array
1071 * @throws coding_exception
1073 public static function get_store_configuration_from_data(stdClass $data) {
1074 global $CFG;
1075 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
1076 if (!file_exists($file)) {
1077 throw new coding_exception('Invalid cache plugin provided. '.$file);
1079 require_once($file);
1080 $class = 'cachestore_'.$data->plugin;
1081 if (!class_exists($class)) {
1082 throw new coding_exception('Invalid cache plugin provided.');
1084 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1085 return $class::config_get_configuration_array($data);
1087 return array();
1091 * Get an array of stores that are suitable to be used for a given definition.
1093 * @param string $component
1094 * @param string $area
1095 * @return array Array containing 3 elements
1096 * 1. An array of currently used stores
1097 * 2. An array of suitable stores
1098 * 3. An array of default stores
1100 public static function get_definition_store_options($component, $area) {
1101 $factory = cache_factory::instance();
1102 $definition = $factory->create_definition($component, $area);
1103 $config = cache_config::instance();
1104 $currentstores = $config->get_stores_for_definition($definition);
1105 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
1107 $defaults = array();
1108 foreach ($currentstores as $key => $store) {
1109 if (!empty($store['default'])) {
1110 $defaults[] = $key;
1111 unset($currentstores[$key]);
1114 foreach ($possiblestores as $key => $store) {
1115 if ($store['default']) {
1116 unset($possiblestores[$key]);
1117 $possiblestores[$key] = $store;
1120 return array($currentstores, $possiblestores, $defaults);
1124 * Get the default stores for all modes.
1126 * @return array An array containing sub-arrays, one for each mode.
1128 public static function get_default_mode_stores() {
1129 global $OUTPUT;
1130 $instance = cache_config::instance();
1131 $adequatestores = cache_helper::get_stores_suitable_for_mode_default();
1132 $icon = new pix_icon('i/warning', new lang_string('inadequatestoreformapping', 'cache'));
1133 $storenames = array();
1134 foreach ($instance->get_all_stores() as $key => $store) {
1135 if (!empty($store['default'])) {
1136 $storenames[$key] = new lang_string('store_'.$key, 'cache');
1139 $modemappings = array(
1140 cache_store::MODE_APPLICATION => array(),
1141 cache_store::MODE_SESSION => array(),
1142 cache_store::MODE_REQUEST => array(),
1144 foreach ($instance->get_mode_mappings() as $mapping) {
1145 $mode = $mapping['mode'];
1146 if (!array_key_exists($mode, $modemappings)) {
1147 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
1148 continue;
1150 if (array_key_exists($mapping['store'], $storenames)) {
1151 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
1152 } else {
1153 $modemappings[$mode][$mapping['store']] = $mapping['store'];
1155 if (!array_key_exists($mapping['store'], $adequatestores)) {
1156 $modemappings[$mode][$mapping['store']] = $modemappings[$mode][$mapping['store']].' '.$OUTPUT->render($icon);
1159 return $modemappings;
1163 * Returns an array summarising the locks available in the system
1165 public static function get_lock_summaries() {
1166 $locks = array();
1167 $instance = cache_config::instance();
1168 $stores = $instance->get_all_stores();
1169 foreach ($instance->get_locks() as $lock) {
1170 $default = !empty($lock['default']);
1171 if ($default) {
1172 $name = new lang_string($lock['name'], 'cache');
1173 } else {
1174 $name = $lock['name'];
1176 $uses = 0;
1177 foreach ($stores as $store) {
1178 if (!empty($store['lock']) && $store['lock'] === $lock['name']) {
1179 $uses++;
1182 $lockdata = array(
1183 'name' => $name,
1184 'default' => $default,
1185 'uses' => $uses,
1186 'type' => get_string('pluginname', $lock['type'])
1188 $locks[$lock['name']] = $lockdata;
1190 return $locks;
1194 * Returns an array of lock plugins for which we can add an instance.
1196 * Suitable for use within an mform select element.
1198 * @return array
1200 public static function get_addable_lock_options() {
1201 $plugins = core_component::get_plugin_list_with_class('cachelock', '', 'lib.php');
1202 $options = array();
1203 $len = strlen('cachelock_');
1204 foreach ($plugins as $plugin => $class) {
1205 $method = "$class::can_add_instance";
1206 if (is_callable($method) && !call_user_func($method)) {
1207 // Can't add an instance of this plugin.
1208 continue;
1210 $options[substr($plugin, $len)] = get_string('pluginname', $plugin);
1212 return $options;
1216 * Gets the form to use when adding a lock instance.
1218 * @param string $plugin
1219 * @param array $lockplugin
1220 * @return cache_lock_form
1221 * @throws coding_exception
1223 public static function get_add_lock_form($plugin, array $lockplugin = null) {
1224 global $CFG; // Needed for includes.
1225 $plugins = core_component::get_plugin_list('cachelock');
1226 if (!array_key_exists($plugin, $plugins)) {
1227 throw new coding_exception('Invalid cache lock plugin requested when trying to create a form.');
1229 $plugindir = $plugins[$plugin];
1230 $class = 'cache_lock_form';
1231 if (file_exists($plugindir.'/addinstanceform.php') && in_array('cache_is_configurable', class_implements($class))) {
1232 require_once($plugindir.'/addinstanceform.php');
1233 if (class_exists('cachelock_'.$plugin.'_addinstance_form')) {
1234 $class = 'cachelock_'.$plugin.'_addinstance_form';
1235 if (!array_key_exists('cache_lock_form', class_parents($class))) {
1236 throw new coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
1240 return new $class(null, array('lock' => $plugin));
1244 * Gets configuration data from a new lock instance form.
1246 * @param string $plugin
1247 * @param stdClass $data
1248 * @return array
1249 * @throws coding_exception
1251 public static function get_lock_configuration_from_data($plugin, $data) {
1252 global $CFG;
1253 $file = $CFG->dirroot.'/cache/locks/'.$plugin.'/lib.php';
1254 if (!file_exists($file)) {
1255 throw new coding_exception('Invalid cache plugin provided. '.$file);
1257 require_once($file);
1258 $class = 'cachelock_'.$plugin;
1259 if (!class_exists($class)) {
1260 throw new coding_exception('Invalid cache plugin provided.');
1262 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1263 return $class::config_get_configuration_array($data);
1265 return array();