Merge branch 'MDL-38444_24' of https://github.com/ppichet/moodle into MOODLE_24_STABLE
[moodle.git] / cache / locallib.php
blobe2fcb9a9b3f16cbc1387dc1edfcee9ea0ac2edcc
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 * Sets the mode mappings.
193 * These determine the default caches for the different modes.
194 * This function also calls save so you should redirect immediately, or at least very shortly after
195 * calling this method.
197 * @param array $modemappings
198 * @return bool
199 * @throws cache_exception
201 public function set_mode_mappings(array $modemappings) {
202 $mappings = array(
203 cache_store::MODE_APPLICATION => array(),
204 cache_store::MODE_SESSION => array(),
205 cache_store::MODE_REQUEST => array(),
207 foreach ($modemappings as $mode => $stores) {
208 if (!array_key_exists($mode, $mappings)) {
209 throw new cache_exception('The cache mode for the new mapping does not exist');
211 $sort = 0;
212 foreach ($stores as $store) {
213 if (!array_key_exists($store, $this->configstores)) {
214 throw new cache_exception('The instance name for the new mapping does not exist');
216 if (array_key_exists($store, $mappings[$mode])) {
217 throw new cache_exception('This cache mapping already exists');
219 $mappings[$mode][] = array(
220 'store' => $store,
221 'mode' => $mode,
222 'sort' => $sort++
226 $this->configmodemappings = array_merge(
227 $mappings[cache_store::MODE_APPLICATION],
228 $mappings[cache_store::MODE_SESSION],
229 $mappings[cache_store::MODE_REQUEST]
232 $this->config_save();
233 return true;
237 * Edits a give plugin instance.
239 * The plugin instance is determined by its name, hence you cannot rename plugins.
240 * This function also calls save so you should redirect immediately, or at least very shortly after
241 * calling this method.
243 * @param string $name
244 * @param string $plugin
245 * @param array $configuration
246 * @return bool
247 * @throws cache_exception
249 public function edit_store_instance($name, $plugin, $configuration) {
250 if (!array_key_exists($name, $this->configstores)) {
251 throw new cache_exception('The requested instance does not exist.');
253 $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
254 if (!array_key_exists($plugin, $plugins)) {
255 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
257 $class = 'cachestore_'.$plugin;
258 $file = $plugins[$plugin];
259 if (!class_exists($class)) {
260 if (file_exists($file)) {
261 require_once($file);
263 if (!class_exists($class)) {
264 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.'.$class);
267 $this->configstores[$name] = array(
268 'name' => $name,
269 'plugin' => $plugin,
270 'configuration' => $configuration,
271 'features' => $class::get_supported_features($configuration),
272 'modes' => $class::get_supported_modes($configuration),
273 'mappingsonly' => !empty($configuration['mappingsonly']),
274 'class' => $class,
275 'default' => $this->configstores[$name]['default'] // Can't change the default.
277 if (array_key_exists('lock', $configuration)) {
278 $this->configstores[$name]['lock'] = $configuration['lock'];
279 unset($this->configstores[$name]['configuration']['lock']);
281 $this->config_save();
282 return true;
286 * Deletes a store instance.
288 * This function also calls save so you should redirect immediately, or at least very shortly after
289 * calling this method.
291 * @param string $name The name of the instance to delete.
292 * @return bool
293 * @throws cache_exception
295 public function delete_store_instance($name) {
296 if (!array_key_exists($name, $this->configstores)) {
297 throw new cache_exception('The requested store does not exist.');
299 if ($this->configstores[$name]['default']) {
300 throw new cache_exception('The can not delete the default stores.');
302 foreach ($this->configmodemappings as $mapping) {
303 if ($mapping['store'] === $name) {
304 throw new cache_exception('You cannot delete a cache store that has mode mappings.');
307 foreach ($this->configdefinitionmappings as $mapping) {
308 if ($mapping['store'] === $name) {
309 throw new cache_exception('You cannot delete a cache store that has definition mappings.');
313 // Call instance_deleted()
314 $class = 'cachestore_'.$this->configstores[$name]['plugin'];
315 $store = new $class($name, $this->configstores[$name]['configuration']);
316 $store->instance_deleted();
318 unset($this->configstores[$name]);
319 $this->config_save();
320 return true;
324 * Creates the default configuration and saves it.
326 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
327 * be called when there is no configuration file already.
329 * @return true|array Returns true if the default configuration was successfully created.
330 * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
332 public static function create_default_configuration() {
333 global $CFG;
335 // HACK ALERT.
336 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
337 // default store plugins are protected from deletion.
338 require_once($CFG->dirroot.'/cache/stores/file/lib.php');
339 require_once($CFG->dirroot.'/cache/stores/session/lib.php');
340 require_once($CFG->dirroot.'/cache/stores/static/lib.php');
342 $writer = new self;
343 $writer->configstores = array(
344 'default_application' => array(
345 'name' => 'default_application',
346 'plugin' => 'file',
347 'configuration' => array(),
348 'features' => cachestore_file::get_supported_features(),
349 'modes' => cache_store::MODE_APPLICATION,
350 'default' => true,
352 'default_session' => array(
353 'name' => 'default_session',
354 'plugin' => 'session',
355 'configuration' => array(),
356 'features' => cachestore_session::get_supported_features(),
357 'modes' => cache_store::MODE_SESSION,
358 'default' => true,
360 'default_request' => array(
361 'name' => 'default_request',
362 'plugin' => 'static',
363 'configuration' => array(),
364 'features' => cachestore_static::get_supported_features(),
365 'modes' => cache_store::MODE_REQUEST,
366 'default' => true,
369 $writer->configdefinitions = self::locate_definitions();
370 $writer->configmodemappings = array(
371 array(
372 'mode' => cache_store::MODE_APPLICATION,
373 'store' => 'default_application',
374 'sort' => -1
376 array(
377 'mode' => cache_store::MODE_SESSION,
378 'store' => 'default_session',
379 'sort' => -1
381 array(
382 'mode' => cache_store::MODE_REQUEST,
383 'store' => 'default_request',
384 'sort' => -1
387 $writer->configlocks = array(
388 'default_file_lock' => array(
389 'name' => 'cachelock_file_default',
390 'type' => 'cachelock_file',
391 'dir' => 'filelocks',
392 'default' => true
396 $factory = cache_factory::instance();
397 // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
398 // we are now in a loop.
399 if ($factory->get_state() !== cache_factory::STATE_INITIALISING) {
400 return $writer->generate_configuration_array();
402 $factory->set_state(cache_factory::STATE_SAVING);
403 $writer->config_save();
404 return true;
408 * Updates the definition in the configuration from those found in the cache files.
410 * Calls config_save further down, you should redirect immediately or asap after calling this method.
412 * @param bool $coreonly If set to true only core definitions will be updated.
414 public static function update_definitions($coreonly = false) {
415 $factory = cache_factory::instance();
416 $factory->updating_started();
417 $config = $factory->create_config_instance(true);
418 $config->write_definitions_to_cache(self::locate_definitions($coreonly));
419 $factory->updating_finished();
423 * Locates all of the definition files.
425 * @param bool $coreonly If set to true only core definitions will be updated.
426 * @return array
428 protected static function locate_definitions($coreonly = false) {
429 global $CFG;
431 $files = array();
432 if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
433 $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
436 if (!$coreonly) {
437 $plugintypes = get_plugin_types();
438 foreach ($plugintypes as $type => $location) {
439 $plugins = get_plugin_list_with_file($type, 'db/caches.php');
440 foreach ($plugins as $plugin => $filepath) {
441 $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
442 $files[$component] = $filepath;
447 $definitions = array();
448 foreach ($files as $component => $file) {
449 $filedefs = self::load_caches_file($file);
450 foreach ($filedefs as $area => $definition) {
451 $area = clean_param($area, PARAM_AREA);
452 $id = $component.'/'.$area;
453 $definition['component'] = $component;
454 $definition['area'] = $area;
455 if (array_key_exists($id, $definitions)) {
456 debugging('Error: duplicate cache definition found with id: '.$id, DEBUG_DEVELOPER);
457 continue;
459 $definitions[$id] = $definition;
463 return $definitions;
467 * Writes the updated definitions for the config file.
468 * @param array $definitions
470 private function write_definitions_to_cache(array $definitions) {
471 $this->configdefinitions = $definitions;
472 foreach ($this->configdefinitionmappings as $key => $mapping) {
473 if (!array_key_exists($mapping['definition'], $definitions)) {
474 unset($this->configdefinitionmappings[$key]);
477 $this->config_save();
481 * Loads the caches file if it exists.
482 * @param string $file Absolute path to the file.
483 * @return array
485 private static function load_caches_file($file) {
486 if (!file_exists($file)) {
487 return array();
489 $definitions = array();
490 include($file);
491 return $definitions;
495 * Sets the mappings for a given definition.
497 * @param string $definition
498 * @param array $mappings
499 * @throws coding_exception
501 public function set_definition_mappings($definition, $mappings) {
502 if (!array_key_exists($definition, $this->configdefinitions)) {
503 throw new coding_exception('Invalid definition name passed when updating mappings.');
505 foreach ($mappings as $store) {
506 if (!array_key_exists($store, $this->configstores)) {
507 throw new coding_exception('Invalid store name passed when updating definition mappings.');
510 foreach ($this->configdefinitionmappings as $key => $mapping) {
511 if ($mapping['definition'] == $definition) {
512 unset($this->configdefinitionmappings[$key]);
515 $sort = count($mappings);
516 foreach ($mappings as $store) {
517 $this->configdefinitionmappings[] = array(
518 'store' => $store,
519 'definition' => $definition,
520 'sort' => $sort
522 $sort--;
525 $this->config_save();
529 * Update the site identifier stored by the cache API.
531 * @param string $siteidentifier
532 * @return string The new site identifier.
534 public function update_site_identifier($siteidentifier) {
535 $this->siteidentifier = md5((string)$siteidentifier);
536 $this->config_save();
537 return $this->siteidentifier;
542 * A cache helper for administration tasks
544 * @package core
545 * @category cache
546 * @copyright 2012 Sam Hemelryk
547 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
549 abstract class cache_administration_helper extends cache_helper {
552 * Returns an array containing all of the information about stores a renderer needs.
553 * @return array
555 public static function get_store_instance_summaries() {
556 $return = array();
557 $default = array();
558 $instance = cache_config::instance();
559 $stores = $instance->get_all_stores();
560 foreach ($stores as $name => $details) {
561 $class = $details['class'];
562 $store = new $class($details['name'], $details['configuration']);
563 $record = array(
564 'name' => $name,
565 'plugin' => $details['plugin'],
566 'default' => $details['default'],
567 'isready' => $store->is_ready(),
568 'requirementsmet' => $store->are_requirements_met(),
569 'mappings' => 0,
570 'modes' => array(
571 cache_store::MODE_APPLICATION =>
572 ($store->get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
573 cache_store::MODE_SESSION =>
574 ($store->get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
575 cache_store::MODE_REQUEST =>
576 ($store->get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
578 'supports' => array(
579 'multipleidentifiers' => $store->supports_multiple_identifiers(),
580 'dataguarantee' => $store->supports_data_guarantee(),
581 'nativettl' => $store->supports_native_ttl(),
582 'nativelocking' => ($store instanceof cache_is_lockable),
583 'keyawareness' => ($store instanceof cache_is_key_aware),
586 if (empty($details['default'])) {
587 $return[$name] = $record;
588 } else {
589 $default[$name] = $record;
593 ksort($return);
594 ksort($default);
595 $return = $return + $default;
597 foreach ($instance->get_definition_mappings() as $mapping) {
598 if (!array_key_exists($mapping['store'], $return)) {
599 continue;
601 $return[$mapping['store']]['mappings']++;
604 return $return;
608 * Returns an array of information about plugins, everything a renderer needs.
609 * @return array
611 public static function get_store_plugin_summaries() {
612 $return = array();
613 $plugins = get_plugin_list_with_file('cachestore', 'lib.php', true);
614 foreach ($plugins as $plugin => $path) {
615 $class = 'cachestore_'.$plugin;
616 $return[$plugin] = array(
617 'name' => get_string('pluginname', 'cachestore_'.$plugin),
618 'requirementsmet' => $class::are_requirements_met(),
619 'instances' => 0,
620 'modes' => array(
621 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
622 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
623 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
625 'supports' => array(
626 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
627 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
628 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
629 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
630 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
632 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
636 $instance = cache_config::instance();
637 $stores = $instance->get_all_stores();
638 foreach ($stores as $store) {
639 $plugin = $store['plugin'];
640 if (array_key_exists($plugin, $return)) {
641 $return[$plugin]['instances']++;
645 return $return;
649 * Returns an array about the definitions. All the information a renderer needs.
650 * @return array
652 public static function get_definition_summaries() {
653 $instance = cache_config::instance();
654 $definitions = $instance->get_definitions();
656 $storenames = array();
657 foreach ($instance->get_all_stores() as $key => $store) {
658 if (!empty($store['default'])) {
659 $storenames[$key] = new lang_string('store_'.$key, 'cache');
663 $modemappings = array();
664 foreach ($instance->get_mode_mappings() as $mapping) {
665 $mode = $mapping['mode'];
666 if (!array_key_exists($mode, $modemappings)) {
667 $modemappings[$mode] = array();
669 if (array_key_exists($mapping['store'], $storenames)) {
670 $modemappings[$mode][] = $storenames[$mapping['store']];
671 } else {
672 $modemappings[$mode][] = $mapping['store'];
676 $definitionmappings = array();
677 foreach ($instance->get_definition_mappings() as $mapping) {
678 $definition = $mapping['definition'];
679 if (!array_key_exists($definition, $definitionmappings)) {
680 $definitionmappings[$definition] = array();
682 if (array_key_exists($mapping['store'], $storenames)) {
683 $definitionmappings[$definition][] = $storenames[$mapping['store']];
684 } else {
685 $definitionmappings[$definition][] = $mapping['store'];
689 $return = array();
691 foreach ($definitions as $id => $definition) {
693 $mappings = array();
694 if (array_key_exists($id, $definitionmappings)) {
695 $mappings = $definitionmappings[$id];
696 } else if (empty($definition['mappingsonly'])) {
697 $mappings = $modemappings[$definition['mode']];
700 $return[$id] = array(
701 'id' => $id,
702 'name' => cache_helper::get_definition_name($definition),
703 'mode' => $definition['mode'],
704 'component' => $definition['component'],
705 'area' => $definition['area'],
706 'mappings' => $mappings
709 return $return;
713 * Returns all of the actions that can be performed on a definition.
714 * @param context $context
715 * @return array
717 public static function get_definition_actions(context $context) {
718 if (has_capability('moodle/site:config', $context)) {
719 return array(
720 array(
721 'text' => get_string('editmappings', 'cache'),
722 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
726 return array();
730 * Returns all of the actions that can be performed on a store.
732 * @param string $name The name of the store
733 * @param array $storedetails
734 * @return array
736 public static function get_store_instance_actions($name, array $storedetails) {
737 $actions = array();
738 if (has_capability('moodle/site:config', get_system_context())) {
739 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
740 if (empty($storedetails['default'])) {
741 $actions[] = array(
742 'text' => get_string('editstore', 'cache'),
743 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
745 $actions[] = array(
746 'text' => get_string('deletestore', 'cache'),
747 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
750 $actions[] = array(
751 'text' => get_string('purge', 'cache'),
752 'url' => new moodle_url($baseurl, array('action' => 'purge'))
755 return $actions;
760 * Returns all of the actions that can be performed on a plugin.
762 * @param string $name The name of the plugin
763 * @param array $plugindetails
764 * @return array
766 public static function get_store_plugin_actions($name, array $plugindetails) {
767 $actions = array();
768 if (has_capability('moodle/site:config', context_system::instance())) {
769 if (!empty($plugindetails['canaddinstance'])) {
770 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
771 $actions[] = array(
772 'text' => get_string('addinstance', 'cache'),
773 'url' => $url
777 return $actions;
781 * Returns a form that can be used to add a store instance.
783 * @param string $plugin The plugin to add an instance of
784 * @return cachestore_addinstance_form
785 * @throws coding_exception
787 public static function get_add_store_form($plugin) {
788 global $CFG; // Needed for includes.
789 $plugins = get_plugin_list('cachestore');
790 if (!array_key_exists($plugin, $plugins)) {
791 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
793 $plugindir = $plugins[$plugin];
794 $class = 'cachestore_addinstance_form';
795 if (file_exists($plugindir.'/addinstanceform.php')) {
796 require_once($plugindir.'/addinstanceform.php');
797 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
798 $class = 'cachestore_'.$plugin.'_addinstance_form';
799 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
800 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
805 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
807 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
808 return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
812 * Returns a form that can be used to edit a store instance.
814 * @param string $plugin
815 * @param string $store
816 * @return cachestore_addinstance_form
817 * @throws coding_exception
819 public static function get_edit_store_form($plugin, $store) {
820 global $CFG; // Needed for includes.
821 $plugins = get_plugin_list('cachestore');
822 if (!array_key_exists($plugin, $plugins)) {
823 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
825 $factory = cache_factory::instance();
826 $config = $factory->create_config_instance();
827 $stores = $config->get_all_stores();
828 if (!array_key_exists($store, $stores)) {
829 throw new coding_exception('Invalid store name given when trying to create an edit form.');
831 $plugindir = $plugins[$plugin];
832 $class = 'cachestore_addinstance_form';
833 if (file_exists($plugindir.'/addinstanceform.php')) {
834 require_once($plugindir.'/addinstanceform.php');
835 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
836 $class = 'cachestore_'.$plugin.'_addinstance_form';
837 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
838 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
843 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
845 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
846 $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
847 // See if the cachestore is going to want to load data for the form.
848 // If it has a customised add instance form then it is going to want to.
849 $storeclass = 'cachestore_'.$plugin;
850 $storedata = $stores[$store];
851 if (array_key_exists('configuration', $storedata) && array_key_exists('cache_is_configurable', class_implements($storeclass))) {
852 $storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
854 return $editform;
858 * Returns an array of suitable lock instances for use with this plugin, or false if the plugin handles locking itself.
860 * @param string $plugindir
861 * @param string $plugin
862 * @return array|false
864 protected static function get_possible_locks_for_stores($plugindir, $plugin) {
865 global $CFG; // Needed for includes.
866 $supportsnativelocking = false;
867 if (file_exists($plugindir.'/lib.php')) {
868 require_once($plugindir.'/lib.php');
869 $pluginclass = 'cachestore_'.$plugin;
870 if (class_exists($pluginclass)) {
871 $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
875 if (!$supportsnativelocking) {
876 $config = cache_config::instance();
877 $locks = array();
878 foreach ($config->get_locks() as $lock => $conf) {
879 if (!empty($conf['default'])) {
880 $name = get_string($lock, 'cache');
881 } else {
882 $name = $lock;
884 $locks[$lock] = $name;
886 } else {
887 $locks = false;
890 return $locks;
894 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
895 * store in configuration.
897 * @param stdClass $data The mform data.
898 * @return array
899 * @throws coding_exception
901 public static function get_store_configuration_from_data(stdClass $data) {
902 global $CFG;
903 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
904 if (!file_exists($file)) {
905 throw new coding_exception('Invalid cache plugin provided. '.$file);
907 require_once($file);
908 $class = 'cachestore_'.$data->plugin;
909 if (!class_exists($class)) {
910 throw new coding_exception('Invalid cache plugin provided.');
912 if (array_key_exists('cache_is_configurable', class_implements($class))) {
913 return $class::config_get_configuration_array($data);
915 return array();
919 * Get an array of stores that are suitable to be used for a given definition.
921 * @param string $component
922 * @param string $area
923 * @return array Array containing 3 elements
924 * 1. An array of currently used stores
925 * 2. An array of suitable stores
926 * 3. An array of default stores
928 public static function get_definition_store_options($component, $area) {
929 $factory = cache_factory::instance();
930 $definition = $factory->create_definition($component, $area);
931 $config = cache_config::instance();
932 $currentstores = $config->get_stores_for_definition($definition);
933 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
935 $defaults = array();
936 foreach ($currentstores as $key => $store) {
937 if (!empty($store['default'])) {
938 $defaults[] = $key;
939 unset($currentstores[$key]);
942 foreach ($possiblestores as $key => $store) {
943 if ($store['default']) {
944 unset($possiblestores[$key]);
945 $possiblestores[$key] = $store;
948 return array($currentstores, $possiblestores, $defaults);
952 * Get the default stores for all modes.
954 * @return array An array containing sub-arrays, one for each mode.
956 public static function get_default_mode_stores() {
957 $instance = cache_config::instance();
958 $storenames = array();
959 foreach ($instance->get_all_stores() as $key => $store) {
960 if (!empty($store['default'])) {
961 $storenames[$key] = new lang_string('store_'.$key, 'cache');
964 $modemappings = array(
965 cache_store::MODE_APPLICATION => array(),
966 cache_store::MODE_SESSION => array(),
967 cache_store::MODE_REQUEST => array(),
969 foreach ($instance->get_mode_mappings() as $mapping) {
970 $mode = $mapping['mode'];
971 if (!array_key_exists($mode, $modemappings)) {
972 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
973 continue;
975 if (array_key_exists($mapping['store'], $storenames)) {
976 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
977 } else {
978 $modemappings[$mode][$mapping['store']] = $mapping['store'];
981 return $modemappings;
985 * Returns an array summarising the locks available in the system
987 public static function get_lock_summaries() {
988 $locks = array();
989 $instance = cache_config::instance();
990 $stores = $instance->get_all_stores();
991 foreach ($instance->get_locks() as $lock) {
992 $default = !empty($lock['default']);
993 if ($default) {
994 $name = new lang_string($lock['name'], 'cache');
995 } else {
996 $name = $lock['name'];
998 $uses = 0;
999 foreach ($stores as $store) {
1000 if (!empty($store['lock']) && $store['lock'] === $lock['name']) {
1001 $uses++;
1004 $lockdata = array(
1005 'name' => $name,
1006 'default' => $default,
1007 'uses' => $uses
1009 $locks[] = $lockdata;
1011 return $locks;