Merge branch 'MDL-47819-master' of git://github.com/jethac/moodle
[moodle.git] / cache / locallib.php
blob58dcdd897a63fc36e90da200c93b90dd77be24b5
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 = static::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 @chmod($cachefile, $CFG->filepermissions);
112 // Tell PHP to recompile the script.
113 core_component::invalidate_opcode_php_cache($cachefile);
114 } else {
115 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Unable to open the cache config file.');
120 * Generates a configuration array suitable to be written to the config file.
121 * @return array
123 protected function generate_configuration_array() {
124 $configuration = array();
125 $configuration['siteidentifier'] = $this->siteidentifier;
126 $configuration['stores'] = $this->configstores;
127 $configuration['modemappings'] = $this->configmodemappings;
128 $configuration['definitions'] = $this->configdefinitions;
129 $configuration['definitionmappings'] = $this->configdefinitionmappings;
130 $configuration['locks'] = $this->configlocks;
131 return $configuration;
135 * Adds a plugin instance.
137 * This function also calls save so you should redirect immediately, or at least very shortly after
138 * calling this method.
140 * @param string $name The name for the instance (must be unique)
141 * @param string $plugin The name of the plugin.
142 * @param array $configuration The configuration data for the plugin instance.
143 * @return bool
144 * @throws cache_exception
146 public function add_store_instance($name, $plugin, array $configuration = array()) {
147 if (array_key_exists($name, $this->configstores)) {
148 throw new cache_exception('Duplicate name specificed for cache plugin instance. You must provide a unique name.');
150 $class = 'cachestore_'.$plugin;
151 if (!class_exists($class)) {
152 $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
153 if (!array_key_exists($plugin, $plugins)) {
154 throw new cache_exception('Invalid plugin name specified. The plugin does not exist or is not valid.');
156 $file = $plugins[$plugin];
157 if (file_exists($file)) {
158 require_once($file);
160 if (!class_exists($class)) {
161 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.');
164 $reflection = new ReflectionClass($class);
165 if (!$reflection->isSubclassOf('cache_store')) {
166 throw new cache_exception('Invalid cache plugin specified. The plugin does not extend the required class.');
168 if (!$class::are_requirements_met()) {
169 throw new cache_exception('Unable to add new cache plugin instance. The requested plugin type is not supported.');
171 $this->configstores[$name] = array(
172 'name' => $name,
173 'plugin' => $plugin,
174 'configuration' => $configuration,
175 'features' => $class::get_supported_features($configuration),
176 'modes' => $class::get_supported_modes($configuration),
177 'mappingsonly' => !empty($configuration['mappingsonly']),
178 'class' => $class,
179 'default' => false
181 if (array_key_exists('lock', $configuration)) {
182 $this->configstores[$name]['lock'] = $configuration['lock'];
183 unset($this->configstores[$name]['configuration']['lock']);
185 // Call instance_created()
186 $store = new $class($name, $this->configstores[$name]['configuration']);
187 $store->instance_created();
189 $this->config_save();
190 return true;
194 * Adds a new lock instance to the config file.
196 * @param string $name The name the user gave the instance. PARAM_ALHPANUMEXT
197 * @param string $plugin The plugin we are creating an instance of.
198 * @param string $configuration Configuration data from the config instance.
199 * @throws cache_exception
201 public function add_lock_instance($name, $plugin, $configuration = array()) {
202 if (array_key_exists($name, $this->configlocks)) {
203 throw new cache_exception('Duplicate name specificed for cache lock instance. You must provide a unique name.');
205 $class = 'cachelock_'.$plugin;
206 if (!class_exists($class)) {
207 $plugins = core_component::get_plugin_list_with_file('cachelock', 'lib.php');
208 if (!array_key_exists($plugin, $plugins)) {
209 throw new cache_exception('Invalid lock name specified. The plugin does not exist or is not valid.');
211 $file = $plugins[$plugin];
212 if (file_exists($file)) {
213 require_once($file);
215 if (!class_exists($class)) {
216 throw new cache_exception('Invalid lock plugin specified. The plugin does not contain the required class.');
219 $reflection = new ReflectionClass($class);
220 if (!$reflection->implementsInterface('cache_lock_interface')) {
221 throw new cache_exception('Invalid lock plugin specified. The plugin does not implement the required interface.');
223 $this->configlocks[$name] = array_merge($configuration, array(
224 'name' => $name,
225 'type' => 'cachelock_'.$plugin,
226 'default' => false
228 $this->config_save();
232 * Deletes a lock instance given its name.
234 * @param string $name The name of the plugin, PARAM_ALPHANUMEXT.
235 * @return bool
236 * @throws cache_exception
238 public function delete_lock_instance($name) {
239 if (!array_key_exists($name, $this->configlocks)) {
240 throw new cache_exception('The requested store does not exist.');
242 if ($this->configlocks[$name]['default']) {
243 throw new cache_exception('You can not delete the default lock.');
245 foreach ($this->configstores as $store) {
246 if (isset($store['lock']) && $store['lock'] === $name) {
247 throw new cache_exception('You cannot delete a cache lock that is being used by a store.');
250 unset($this->configlocks[$name]);
251 $this->config_save();
252 return true;
256 * Sets the mode mappings.
258 * These determine the default caches for the different modes.
259 * This function also calls save so you should redirect immediately, or at least very shortly after
260 * calling this method.
262 * @param array $modemappings
263 * @return bool
264 * @throws cache_exception
266 public function set_mode_mappings(array $modemappings) {
267 $mappings = array(
268 cache_store::MODE_APPLICATION => array(),
269 cache_store::MODE_SESSION => array(),
270 cache_store::MODE_REQUEST => array(),
272 foreach ($modemappings as $mode => $stores) {
273 if (!array_key_exists($mode, $mappings)) {
274 throw new cache_exception('The cache mode for the new mapping does not exist');
276 $sort = 0;
277 foreach ($stores as $store) {
278 if (!array_key_exists($store, $this->configstores)) {
279 throw new cache_exception('The instance name for the new mapping does not exist');
281 if (array_key_exists($store, $mappings[$mode])) {
282 throw new cache_exception('This cache mapping already exists');
284 $mappings[$mode][] = array(
285 'store' => $store,
286 'mode' => $mode,
287 'sort' => $sort++
291 $this->configmodemappings = array_merge(
292 $mappings[cache_store::MODE_APPLICATION],
293 $mappings[cache_store::MODE_SESSION],
294 $mappings[cache_store::MODE_REQUEST]
297 $this->config_save();
298 return true;
302 * Edits a give plugin instance.
304 * The plugin instance is determined by its name, hence you cannot rename plugins.
305 * This function also calls save so you should redirect immediately, or at least very shortly after
306 * calling this method.
308 * @param string $name
309 * @param string $plugin
310 * @param array $configuration
311 * @return bool
312 * @throws cache_exception
314 public function edit_store_instance($name, $plugin, $configuration) {
315 if (!array_key_exists($name, $this->configstores)) {
316 throw new cache_exception('The requested instance does not exist.');
318 $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
319 if (!array_key_exists($plugin, $plugins)) {
320 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
322 $class = 'cachestore_'.$plugin;
323 $file = $plugins[$plugin];
324 if (!class_exists($class)) {
325 if (file_exists($file)) {
326 require_once($file);
328 if (!class_exists($class)) {
329 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.'.$class);
332 $this->configstores[$name] = array(
333 'name' => $name,
334 'plugin' => $plugin,
335 'configuration' => $configuration,
336 'features' => $class::get_supported_features($configuration),
337 'modes' => $class::get_supported_modes($configuration),
338 'mappingsonly' => !empty($configuration['mappingsonly']),
339 'class' => $class,
340 'default' => $this->configstores[$name]['default'] // Can't change the default.
342 if (array_key_exists('lock', $configuration)) {
343 $this->configstores[$name]['lock'] = $configuration['lock'];
344 unset($this->configstores[$name]['configuration']['lock']);
346 $this->config_save();
347 return true;
351 * Deletes a store instance.
353 * This function also calls save so you should redirect immediately, or at least very shortly after
354 * calling this method.
356 * @param string $name The name of the instance to delete.
357 * @return bool
358 * @throws cache_exception
360 public function delete_store_instance($name) {
361 if (!array_key_exists($name, $this->configstores)) {
362 throw new cache_exception('The requested store does not exist.');
364 if ($this->configstores[$name]['default']) {
365 throw new cache_exception('The can not delete the default stores.');
367 foreach ($this->configmodemappings as $mapping) {
368 if ($mapping['store'] === $name) {
369 throw new cache_exception('You cannot delete a cache store that has mode mappings.');
372 foreach ($this->configdefinitionmappings as $mapping) {
373 if ($mapping['store'] === $name) {
374 throw new cache_exception('You cannot delete a cache store that has definition mappings.');
378 // Call instance_deleted()
379 $class = 'cachestore_'.$this->configstores[$name]['plugin'];
380 $store = new $class($name, $this->configstores[$name]['configuration']);
381 $store->instance_deleted();
383 unset($this->configstores[$name]);
384 $this->config_save();
385 return true;
389 * Creates the default configuration and saves it.
391 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
392 * be called when there is no configuration file already.
394 * @param bool $forcesave If set to true then we will forcefully save the default configuration file.
395 * @return true|array Returns true if the default configuration was successfully created.
396 * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
398 public static function create_default_configuration($forcesave = false) {
399 // HACK ALERT.
400 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
401 // default store plugins are protected from deletion.
402 $writer = new self;
403 $writer->configstores = self::get_default_stores();
404 $writer->configdefinitions = self::locate_definitions();
405 $writer->configmodemappings = array(
406 array(
407 'mode' => cache_store::MODE_APPLICATION,
408 'store' => 'default_application',
409 'sort' => -1
411 array(
412 'mode' => cache_store::MODE_SESSION,
413 'store' => 'default_session',
414 'sort' => -1
416 array(
417 'mode' => cache_store::MODE_REQUEST,
418 'store' => 'default_request',
419 'sort' => -1
422 $writer->configlocks = array(
423 'default_file_lock' => array(
424 'name' => 'cachelock_file_default',
425 'type' => 'cachelock_file',
426 'dir' => 'filelocks',
427 'default' => true
431 $factory = cache_factory::instance();
432 // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
433 // we are now in a loop.
434 if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
435 return $writer->generate_configuration_array();
437 $factory->set_state(cache_factory::STATE_SAVING);
438 $writer->config_save();
439 return true;
443 * Returns an array of default stores for use.
445 * @return array
447 protected static function get_default_stores() {
448 global $CFG;
450 require_once($CFG->dirroot.'/cache/stores/file/lib.php');
451 require_once($CFG->dirroot.'/cache/stores/session/lib.php');
452 require_once($CFG->dirroot.'/cache/stores/static/lib.php');
454 return array(
455 'default_application' => array(
456 'name' => 'default_application',
457 'plugin' => 'file',
458 'configuration' => array(),
459 'features' => cachestore_file::get_supported_features(),
460 'modes' => cachestore_file::get_supported_modes(),
461 'default' => true,
463 'default_session' => array(
464 'name' => 'default_session',
465 'plugin' => 'session',
466 'configuration' => array(),
467 'features' => cachestore_session::get_supported_features(),
468 'modes' => cachestore_session::get_supported_modes(),
469 'default' => true,
471 'default_request' => array(
472 'name' => 'default_request',
473 'plugin' => 'static',
474 'configuration' => array(),
475 'features' => cachestore_static::get_supported_features(),
476 'modes' => cachestore_static::get_supported_modes(),
477 'default' => true,
483 * Updates the default stores within the MUC config file.
485 public static function update_default_config_stores() {
486 $factory = cache_factory::instance();
487 $factory->updating_started();
488 $config = $factory->create_config_instance(true);
489 $config->configstores = array_merge($config->configstores, self::get_default_stores());
490 $config->config_save();
491 $factory->updating_finished();
495 * Updates the definition in the configuration from those found in the cache files.
497 * Calls config_save further down, you should redirect immediately or asap after calling this method.
499 * @param bool $coreonly If set to true only core definitions will be updated.
501 public static function update_definitions($coreonly = false) {
502 $factory = cache_factory::instance();
503 $factory->updating_started();
504 $config = $factory->create_config_instance(true);
505 $config->write_definitions_to_cache(self::locate_definitions($coreonly));
506 $factory->updating_finished();
510 * Locates all of the definition files.
512 * @param bool $coreonly If set to true only core definitions will be updated.
513 * @return array
515 protected static function locate_definitions($coreonly = false) {
516 global $CFG;
518 $files = array();
519 if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
520 $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
523 if (!$coreonly) {
524 $plugintypes = core_component::get_plugin_types();
525 foreach ($plugintypes as $type => $location) {
526 $plugins = core_component::get_plugin_list_with_file($type, 'db/caches.php');
527 foreach ($plugins as $plugin => $filepath) {
528 $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
529 $files[$component] = $filepath;
534 $definitions = array();
535 foreach ($files as $component => $file) {
536 $filedefs = self::load_caches_file($file);
537 foreach ($filedefs as $area => $definition) {
538 $area = clean_param($area, PARAM_AREA);
539 $id = $component.'/'.$area;
540 $definition['component'] = $component;
541 $definition['area'] = $area;
542 if (array_key_exists($id, $definitions)) {
543 debugging('Error: duplicate cache definition found with id: '.$id, DEBUG_DEVELOPER);
544 continue;
546 $definitions[$id] = $definition;
550 return $definitions;
554 * Writes the updated definitions for the config file.
555 * @param array $definitions
557 private function write_definitions_to_cache(array $definitions) {
559 // Preserve the selected sharing option when updating the definitions.
560 // This is set by the user and should never come from caches.php.
561 foreach ($definitions as $key => $definition) {
562 unset($definitions[$key]['selectedsharingoption']);
563 unset($definitions[$key]['userinputsharingkey']);
564 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['selectedsharingoption'])) {
565 $definitions[$key]['selectedsharingoption'] = $this->configdefinitions[$key]['selectedsharingoption'];
567 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['userinputsharingkey'])) {
568 $definitions[$key]['userinputsharingkey'] = $this->configdefinitions[$key]['userinputsharingkey'];
572 $this->configdefinitions = $definitions;
573 foreach ($this->configdefinitionmappings as $key => $mapping) {
574 if (!array_key_exists($mapping['definition'], $definitions)) {
575 unset($this->configdefinitionmappings[$key]);
578 $this->config_save();
582 * Loads the caches file if it exists.
583 * @param string $file Absolute path to the file.
584 * @return array
586 private static function load_caches_file($file) {
587 if (!file_exists($file)) {
588 return array();
590 $definitions = array();
591 include($file);
592 return $definitions;
596 * Sets the mappings for a given definition.
598 * @param string $definition
599 * @param array $mappings
600 * @throws coding_exception
602 public function set_definition_mappings($definition, $mappings) {
603 if (!array_key_exists($definition, $this->configdefinitions)) {
604 throw new coding_exception('Invalid definition name passed when updating mappings.');
606 foreach ($mappings as $store) {
607 if (!array_key_exists($store, $this->configstores)) {
608 throw new coding_exception('Invalid store name passed when updating definition mappings.');
611 foreach ($this->configdefinitionmappings as $key => $mapping) {
612 if ($mapping['definition'] == $definition) {
613 unset($this->configdefinitionmappings[$key]);
616 $sort = count($mappings);
617 foreach ($mappings as $store) {
618 $this->configdefinitionmappings[] = array(
619 'store' => $store,
620 'definition' => $definition,
621 'sort' => $sort
623 $sort--;
626 $this->config_save();
630 * Update the site identifier stored by the cache API.
632 * @param string $siteidentifier
633 * @return string The new site identifier.
635 public function update_site_identifier($siteidentifier) {
636 $this->siteidentifier = md5((string)$siteidentifier);
637 $this->config_save();
638 return $this->siteidentifier;
642 * Sets the selected sharing options and key for a definition.
644 * @param string $definition The name of the definition to set for.
645 * @param int $sharingoption The sharing option to set.
646 * @param string|null $userinputsharingkey The user input key or null.
647 * @throws coding_exception
649 public function set_definition_sharing($definition, $sharingoption, $userinputsharingkey = null) {
650 if (!array_key_exists($definition, $this->configdefinitions)) {
651 throw new coding_exception('Invalid definition name passed when updating sharing options.');
653 if (!($this->configdefinitions[$definition]['sharingoptions'] & $sharingoption)) {
654 throw new coding_exception('Invalid sharing option passed when updating definition.');
656 $this->configdefinitions[$definition]['selectedsharingoption'] = (int)$sharingoption;
657 if (!empty($userinputsharingkey)) {
658 $this->configdefinitions[$definition]['userinputsharingkey'] = (string)$userinputsharingkey;
660 $this->config_save();
666 * A cache helper for administration tasks
668 * @package core
669 * @category cache
670 * @copyright 2012 Sam Hemelryk
671 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
673 abstract class cache_administration_helper extends cache_helper {
676 * Returns an array containing all of the information about stores a renderer needs.
677 * @return array
679 public static function get_store_instance_summaries() {
680 $return = array();
681 $default = array();
682 $instance = cache_config::instance();
683 $stores = $instance->get_all_stores();
684 $locks = $instance->get_locks();
685 foreach ($stores as $name => $details) {
686 $class = $details['class'];
687 $store = new $class($details['name'], $details['configuration']);
688 $lock = (isset($details['lock'])) ? $locks[$details['lock']] : $instance->get_default_lock();
689 $record = array(
690 'name' => $name,
691 'plugin' => $details['plugin'],
692 'default' => $details['default'],
693 'isready' => $store->is_ready(),
694 'requirementsmet' => $store->are_requirements_met(),
695 'mappings' => 0,
696 'lock' => $lock,
697 'modes' => array(
698 cache_store::MODE_APPLICATION =>
699 ($store->get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
700 cache_store::MODE_SESSION =>
701 ($store->get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
702 cache_store::MODE_REQUEST =>
703 ($store->get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
705 'supports' => array(
706 'multipleidentifiers' => $store->supports_multiple_identifiers(),
707 'dataguarantee' => $store->supports_data_guarantee(),
708 'nativettl' => $store->supports_native_ttl(),
709 'nativelocking' => ($store instanceof cache_is_lockable),
710 'keyawareness' => ($store instanceof cache_is_key_aware),
711 'searchable' => ($store instanceof cache_is_searchable)
713 'warnings' => $store->get_warnings()
715 if (empty($details['default'])) {
716 $return[$name] = $record;
717 } else {
718 $default[$name] = $record;
722 ksort($return);
723 ksort($default);
724 $return = $return + $default;
726 foreach ($instance->get_definition_mappings() as $mapping) {
727 if (!array_key_exists($mapping['store'], $return)) {
728 continue;
730 $return[$mapping['store']]['mappings']++;
733 return $return;
737 * Returns an array of information about plugins, everything a renderer needs.
738 * @return array
740 public static function get_store_plugin_summaries() {
741 $return = array();
742 $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php', true);
743 foreach ($plugins as $plugin => $path) {
744 $class = 'cachestore_'.$plugin;
745 $return[$plugin] = array(
746 'name' => get_string('pluginname', 'cachestore_'.$plugin),
747 'requirementsmet' => $class::are_requirements_met(),
748 'instances' => 0,
749 'modes' => array(
750 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
751 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
752 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
754 'supports' => array(
755 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
756 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
757 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
758 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
759 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
761 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
765 $instance = cache_config::instance();
766 $stores = $instance->get_all_stores();
767 foreach ($stores as $store) {
768 $plugin = $store['plugin'];
769 if (array_key_exists($plugin, $return)) {
770 $return[$plugin]['instances']++;
774 return $return;
778 * Returns an array about the definitions. All the information a renderer needs.
779 * @return array
781 public static function get_definition_summaries() {
782 $factory = cache_factory::instance();
783 $config = $factory->create_config_instance();
784 $storenames = array();
785 foreach ($config->get_all_stores() as $key => $store) {
786 if (!empty($store['default'])) {
787 $storenames[$key] = new lang_string('store_'.$key, 'cache');
788 } else {
789 $storenames[$store['name']] = $store['name'];
792 /* @var cache_definition[] $definitions */
793 $definitions = array();
794 foreach ($config->get_definitions() as $key => $definition) {
795 $definitions[$key] = cache_definition::load($definition['component'].'/'.$definition['area'], $definition);
797 foreach ($definitions as $id => $definition) {
798 $mappings = array();
799 foreach (cache_helper::get_stores_suitable_for_definition($definition) as $store) {
800 $mappings[] = $storenames[$store->my_name()];
802 $return[$id] = array(
803 'id' => $id,
804 'name' => $definition->get_name(),
805 'mode' => $definition->get_mode(),
806 'component' => $definition->get_component(),
807 'area' => $definition->get_area(),
808 'mappings' => $mappings,
809 'sharingoptions' => self::get_definition_sharing_options($definition->get_sharing_options(), false),
810 'selectedsharingoption' => self::get_definition_sharing_options($definition->get_selected_sharing_option(), true),
811 'userinputsharingkey' => $definition->get_user_input_sharing_key()
814 return $return;
818 * Given a sharing option hash this function returns an array of strings that can be used to describe it.
820 * @param int $sharingoption The sharing option hash to get strings for.
821 * @param bool $isselectedoptions Set to true if the strings will be used to view the selected options.
822 * @return array An array of lang_string's.
824 public static function get_definition_sharing_options($sharingoption, $isselectedoptions = true) {
825 $options = array();
826 $prefix = ($isselectedoptions) ? 'sharingselected' : 'sharing';
827 if ($sharingoption & cache_definition::SHARING_ALL) {
828 $options[cache_definition::SHARING_ALL] = new lang_string($prefix.'_all', 'cache');
830 if ($sharingoption & cache_definition::SHARING_SITEID) {
831 $options[cache_definition::SHARING_SITEID] = new lang_string($prefix.'_siteid', 'cache');
833 if ($sharingoption & cache_definition::SHARING_VERSION) {
834 $options[cache_definition::SHARING_VERSION] = new lang_string($prefix.'_version', 'cache');
836 if ($sharingoption & cache_definition::SHARING_INPUT) {
837 $options[cache_definition::SHARING_INPUT] = new lang_string($prefix.'_input', 'cache');
839 return $options;
843 * Returns all of the actions that can be performed on a definition.
844 * @param context $context
845 * @return array
847 public static function get_definition_actions(context $context, array $definition) {
848 if (has_capability('moodle/site:config', $context)) {
849 $actions = array();
850 // Edit mappings.
851 $actions[] = array(
852 'text' => get_string('editmappings', 'cache'),
853 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
855 // Edit sharing.
856 if (count($definition['sharingoptions']) > 1) {
857 $actions[] = array(
858 'text' => get_string('editsharing', 'cache'),
859 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionsharing', 'sesskey' => sesskey()))
862 // Purge.
863 $actions[] = array(
864 'text' => get_string('purge', 'cache'),
865 'url' => new moodle_url('/cache/admin.php', array('action' => 'purgedefinition', 'sesskey' => sesskey()))
867 return $actions;
869 return array();
873 * Returns all of the actions that can be performed on a store.
875 * @param string $name The name of the store
876 * @param array $storedetails
877 * @return array
879 public static function get_store_instance_actions($name, array $storedetails) {
880 $actions = array();
881 if (has_capability('moodle/site:config', context_system::instance())) {
882 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
883 if (empty($storedetails['default'])) {
884 $actions[] = array(
885 'text' => get_string('editstore', 'cache'),
886 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
888 $actions[] = array(
889 'text' => get_string('deletestore', 'cache'),
890 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
893 $actions[] = array(
894 'text' => get_string('purge', 'cache'),
895 'url' => new moodle_url($baseurl, array('action' => 'purgestore'))
898 return $actions;
903 * Returns all of the actions that can be performed on a plugin.
905 * @param string $name The name of the plugin
906 * @param array $plugindetails
907 * @return array
909 public static function get_store_plugin_actions($name, array $plugindetails) {
910 $actions = array();
911 if (has_capability('moodle/site:config', context_system::instance())) {
912 if (!empty($plugindetails['canaddinstance'])) {
913 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
914 $actions[] = array(
915 'text' => get_string('addinstance', 'cache'),
916 'url' => $url
920 return $actions;
924 * Returns a form that can be used to add a store instance.
926 * @param string $plugin The plugin to add an instance of
927 * @return cachestore_addinstance_form
928 * @throws coding_exception
930 public static function get_add_store_form($plugin) {
931 global $CFG; // Needed for includes.
932 $plugins = core_component::get_plugin_list('cachestore');
933 if (!array_key_exists($plugin, $plugins)) {
934 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
936 $plugindir = $plugins[$plugin];
937 $class = 'cachestore_addinstance_form';
938 if (file_exists($plugindir.'/addinstanceform.php')) {
939 require_once($plugindir.'/addinstanceform.php');
940 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
941 $class = 'cachestore_'.$plugin.'_addinstance_form';
942 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
943 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
948 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
950 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
951 return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
955 * Returns a form that can be used to edit a store instance.
957 * @param string $plugin
958 * @param string $store
959 * @return cachestore_addinstance_form
960 * @throws coding_exception
962 public static function get_edit_store_form($plugin, $store) {
963 global $CFG; // Needed for includes.
964 $plugins = core_component::get_plugin_list('cachestore');
965 if (!array_key_exists($plugin, $plugins)) {
966 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
968 $factory = cache_factory::instance();
969 $config = $factory->create_config_instance();
970 $stores = $config->get_all_stores();
971 if (!array_key_exists($store, $stores)) {
972 throw new coding_exception('Invalid store name given when trying to create an edit form.');
974 $plugindir = $plugins[$plugin];
975 $class = 'cachestore_addinstance_form';
976 if (file_exists($plugindir.'/addinstanceform.php')) {
977 require_once($plugindir.'/addinstanceform.php');
978 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
979 $class = 'cachestore_'.$plugin.'_addinstance_form';
980 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
981 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
986 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
988 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
989 $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
990 if (isset($stores[$store]['lock'])) {
991 $editform->set_data(array('lock' => $stores[$store]['lock']));
993 // See if the cachestore is going to want to load data for the form.
994 // If it has a customised add instance form then it is going to want to.
995 $storeclass = 'cachestore_'.$plugin;
996 $storedata = $stores[$store];
997 if (array_key_exists('configuration', $storedata) && array_key_exists('cache_is_configurable', class_implements($storeclass))) {
998 $storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
1000 return $editform;
1004 * Returns an array of suitable lock instances for use with this plugin, or false if the plugin handles locking itself.
1006 * @param string $plugindir
1007 * @param string $plugin
1008 * @return array|false
1010 protected static function get_possible_locks_for_stores($plugindir, $plugin) {
1011 global $CFG; // Needed for includes.
1012 $supportsnativelocking = false;
1013 if (file_exists($plugindir.'/lib.php')) {
1014 require_once($plugindir.'/lib.php');
1015 $pluginclass = 'cachestore_'.$plugin;
1016 if (class_exists($pluginclass)) {
1017 $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
1021 if (!$supportsnativelocking) {
1022 $config = cache_config::instance();
1023 $locks = array();
1024 foreach ($config->get_locks() as $lock => $conf) {
1025 if (!empty($conf['default'])) {
1026 $name = get_string($lock, 'cache');
1027 } else {
1028 $name = $lock;
1030 $locks[$lock] = $name;
1032 } else {
1033 $locks = false;
1036 return $locks;
1040 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
1041 * store in configuration.
1043 * @param stdClass $data The mform data.
1044 * @return array
1045 * @throws coding_exception
1047 public static function get_store_configuration_from_data(stdClass $data) {
1048 global $CFG;
1049 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
1050 if (!file_exists($file)) {
1051 throw new coding_exception('Invalid cache plugin provided. '.$file);
1053 require_once($file);
1054 $class = 'cachestore_'.$data->plugin;
1055 if (!class_exists($class)) {
1056 throw new coding_exception('Invalid cache plugin provided.');
1058 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1059 return $class::config_get_configuration_array($data);
1061 return array();
1065 * Get an array of stores that are suitable to be used for a given definition.
1067 * @param string $component
1068 * @param string $area
1069 * @return array Array containing 3 elements
1070 * 1. An array of currently used stores
1071 * 2. An array of suitable stores
1072 * 3. An array of default stores
1074 public static function get_definition_store_options($component, $area) {
1075 $factory = cache_factory::instance();
1076 $definition = $factory->create_definition($component, $area);
1077 $config = cache_config::instance();
1078 $currentstores = $config->get_stores_for_definition($definition);
1079 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
1081 $defaults = array();
1082 foreach ($currentstores as $key => $store) {
1083 if (!empty($store['default'])) {
1084 $defaults[] = $key;
1085 unset($currentstores[$key]);
1088 foreach ($possiblestores as $key => $store) {
1089 if ($store['default']) {
1090 unset($possiblestores[$key]);
1091 $possiblestores[$key] = $store;
1094 return array($currentstores, $possiblestores, $defaults);
1098 * Get the default stores for all modes.
1100 * @return array An array containing sub-arrays, one for each mode.
1102 public static function get_default_mode_stores() {
1103 global $OUTPUT;
1104 $instance = cache_config::instance();
1105 $adequatestores = cache_helper::get_stores_suitable_for_mode_default();
1106 $icon = new pix_icon('i/warning', new lang_string('inadequatestoreformapping', 'cache'));
1107 $storenames = array();
1108 foreach ($instance->get_all_stores() as $key => $store) {
1109 if (!empty($store['default'])) {
1110 $storenames[$key] = new lang_string('store_'.$key, 'cache');
1113 $modemappings = array(
1114 cache_store::MODE_APPLICATION => array(),
1115 cache_store::MODE_SESSION => array(),
1116 cache_store::MODE_REQUEST => array(),
1118 foreach ($instance->get_mode_mappings() as $mapping) {
1119 $mode = $mapping['mode'];
1120 if (!array_key_exists($mode, $modemappings)) {
1121 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
1122 continue;
1124 if (array_key_exists($mapping['store'], $storenames)) {
1125 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
1126 } else {
1127 $modemappings[$mode][$mapping['store']] = $mapping['store'];
1129 if (!array_key_exists($mapping['store'], $adequatestores)) {
1130 $modemappings[$mode][$mapping['store']] = $modemappings[$mode][$mapping['store']].' '.$OUTPUT->render($icon);
1133 return $modemappings;
1137 * Returns an array summarising the locks available in the system
1139 public static function get_lock_summaries() {
1140 $locks = array();
1141 $instance = cache_config::instance();
1142 $stores = $instance->get_all_stores();
1143 foreach ($instance->get_locks() as $lock) {
1144 $default = !empty($lock['default']);
1145 if ($default) {
1146 $name = new lang_string($lock['name'], 'cache');
1147 } else {
1148 $name = $lock['name'];
1150 $uses = 0;
1151 foreach ($stores as $store) {
1152 if (!empty($store['lock']) && $store['lock'] === $lock['name']) {
1153 $uses++;
1156 $lockdata = array(
1157 'name' => $name,
1158 'default' => $default,
1159 'uses' => $uses,
1160 'type' => get_string('pluginname', $lock['type'])
1162 $locks[$lock['name']] = $lockdata;
1164 return $locks;
1168 * Returns an array of lock plugins for which we can add an instance.
1170 * Suitable for use within an mform select element.
1172 * @return array
1174 public static function get_addable_lock_options() {
1175 $plugins = core_component::get_plugin_list_with_class('cachelock', '', 'lib.php');
1176 $options = array();
1177 $len = strlen('cachelock_');
1178 foreach ($plugins as $plugin => $class) {
1179 $method = "$class::can_add_instance";
1180 if (is_callable($method) && !call_user_func($method)) {
1181 // Can't add an instance of this plugin.
1182 continue;
1184 $options[substr($plugin, $len)] = get_string('pluginname', $plugin);
1186 return $options;
1190 * Gets the form to use when adding a lock instance.
1192 * @param string $plugin
1193 * @param array $lockplugin
1194 * @return cache_lock_form
1195 * @throws coding_exception
1197 public static function get_add_lock_form($plugin, array $lockplugin = null) {
1198 global $CFG; // Needed for includes.
1199 $plugins = core_component::get_plugin_list('cachelock');
1200 if (!array_key_exists($plugin, $plugins)) {
1201 throw new coding_exception('Invalid cache lock plugin requested when trying to create a form.');
1203 $plugindir = $plugins[$plugin];
1204 $class = 'cache_lock_form';
1205 if (file_exists($plugindir.'/addinstanceform.php') && in_array('cache_is_configurable', class_implements($class))) {
1206 require_once($plugindir.'/addinstanceform.php');
1207 if (class_exists('cachelock_'.$plugin.'_addinstance_form')) {
1208 $class = 'cachelock_'.$plugin.'_addinstance_form';
1209 if (!array_key_exists('cache_lock_form', class_parents($class))) {
1210 throw new coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
1214 return new $class(null, array('lock' => $plugin));
1218 * Gets configuration data from a new lock instance form.
1220 * @param string $plugin
1221 * @param stdClass $data
1222 * @return array
1223 * @throws coding_exception
1225 public static function get_lock_configuration_from_data($plugin, $data) {
1226 global $CFG;
1227 $file = $CFG->dirroot.'/cache/locks/'.$plugin.'/lib.php';
1228 if (!file_exists($file)) {
1229 throw new coding_exception('Invalid cache plugin provided. '.$file);
1231 require_once($file);
1232 $class = 'cachelock_'.$plugin;
1233 if (!class_exists($class)) {
1234 throw new coding_exception('Invalid cache plugin provided.');
1236 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1237 return $class::config_get_configuration_array($data);
1239 return array();