MDL-25290 cache: Fixed up redirect loop with admin settings for cache stores
[moodle.git] / cache / locallib.php
CommitLineData
8139ad13
SH
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.
13//
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/>.
16
17/**
18 * The supplementary cache API.
19 *
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.
23 *
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
28 */
29
30defined('MOODLE_INTERNAL') || die();
31
32/**
33 * Cache configuration writer.
34 *
35 * This class should only be used when you need to write to the config, all read operations exist within the cache_config.
36 *
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
41 */
42class cache_config_writer extends cache_config {
43
44 /**
45 * Returns an instance of the configuration writer.
46 *
47 * @return cache_config_writer
48 */
49 public static function instance() {
50 $factory = cache_factory::instance();
51 return $factory->create_config_instance(true);
52 }
53
54 /**
55 * Saves the current configuration.
56 */
57 protected function config_save() {
58 global $CFG;
59 $cachefile = self::get_config_file_path();
60 $directory = dirname($cachefile);
61 if ($directory !== $CFG->dataroot && !file_exists($directory)) {
62 $result = make_writable_directory($directory, false);
63 if (!$result) {
64 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory.');
65 }
66 }
67 if (!file_exists($directory) || !is_writable($directory)) {
68 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Config directory is not writable.');
69 }
70
71 // Prepare a configuration array to store.
72 $configuration = array();
73 $configuration['stores'] = $this->configstores;
74 $configuration['modemappings'] = $this->configmodemappings;
75 $configuration['definitions'] = $this->configdefinitions;
76 $configuration['definitionmappings'] = $this->configdefinitionmappings;
77
78 // Prepare the file content.
79 $content = "<?php defined('MOODLE_INTERNAL') || die();\n \$configuration = ".var_export($configuration, true).";";
80
81 if (cache_lock::lock('config', false)) {
82 $handle = fopen($cachefile, 'w');
83 fwrite($handle, $content);
84 fflush($handle);
85 fclose($handle);
86 cache_lock::unlock('config');
87 } else {
88 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Unable to open the cache config file.');
89 }
90 }
91
92 /**
93 * Adds a plugin instance.
94 *
95 * This function also calls save so you should redirect immediately, or at least very shortly after
96 * calling this method.
97 *
98 * @param string $name The name for the instance (must be unique)
99 * @param string $plugin The name of the plugin.
100 * @param array $configuration The configuration data for the plugin instance.
101 * @return bool
102 * @throws cache_exception
103 */
104 public function add_plugin_instance($name, $plugin, array $configuration = array()) {
105 if (array_key_exists($name, $this->configstores)) {
106 throw new cache_exception('Duplicate name specificed for cache plugin instance. You must provide a unique name.');
107 }
108 $class = 'cache_store_'.$plugin;
109 if (!class_exists($class)) {
110 $plugins = get_plugin_list_with_file('cache', 'lib.php');
111 if (!array_key_exists($plugin, $plugins)) {
112 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not a valid cache plugin.');
113 }
114 $file = $plugins[$plugin];
115 if (file_exists($file)) {
116 require_once($file);
117 }
118 if (!class_exists($class)) {
119 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.');
120 }
121 }
122 if (!is_subclass_of($class, 'cache_store')) {
123 throw new cache_exception('Invalid cache plugin specified. The plugin does not extend the required class.');
124 }
125 if (!$class::are_requirements_met()) {
126 throw new cache_exception('Unable to add new cache plugin instance. The requested plugin type is not supported.');
127 }
128 $this->configstores[$name] = array(
129 'name' => $name,
130 'plugin' => $plugin,
131 'configuration' => $configuration,
132 'features' => $class::get_supported_features($configuration),
133 'modes' => $class::get_supported_modes($configuration),
134 'mappingsonly' => !empty($configuration['mappingsonly']),
135 'useforlocking' => !empty($configuration['useforlocking'])
136
137 );
138 $this->config_save();
139 return true;
140 }
141
142 /**
143 * Sets the mode mappings.
144 *
145 * These determine the default caches for the different modes.
146 * This function also calls save so you should redirect immediately, or at least very shortly after
147 * calling this method.
148 *
149 * @param array $modemappings
150 * @return bool
151 * @throws cache_exception
152 */
153 public function set_mode_mappings(array $modemappings) {
154 $mappings = array(
155 cache_store::MODE_APPLICATION => array(),
156 cache_store::MODE_SESSION => array(),
157 cache_store::MODE_REQUEST => array(),
158 );
159 foreach ($modemappings as $mode => $stores) {
160 if (!array_key_exists($mode, $mappings)) {
161 throw new cache_exception('The cache mode for the new mapping does not exist');
162 }
163 $sort = 0;
164 foreach ($stores as $store) {
165 if (!array_key_exists($store, $this->configstores)) {
166 throw new cache_exception('The instance name for the new mapping does not exist');
167 }
168 if (array_key_exists($store, $mappings[$mode])) {
169 throw new cache_exception('This cache mapping already exists');
170 }
171 $mappings[$mode][] = array(
172 'store' => $store,
173 'mode' => $mode,
174 'sort' => $sort++
175 );
176 }
177 }
178 $this->configmodemappings = array_merge(
179 $mappings[cache_store::MODE_APPLICATION],
180 $mappings[cache_store::MODE_SESSION],
181 $mappings[cache_store::MODE_REQUEST]
182 );
183
184 $this->config_save();
185 return true;
186 }
187
188 /**
189 * Edits a give plugin instance.
190 *
191 * The plugin instance if determined by its name, hence you cannot rename plugins.
192 * This function also calls save so you should redirect immediately, or at least very shortly after
193 * calling this method.
194 *
195 * @param string $name
196 * @param string $plugin
197 * @param array $configuration
198 * @return bool
199 * @throws cache_exception
200 */
201 public function edit_plugin_instance($name, $plugin, $configuration) {
202 if (!array_key_exists($name, $this->configstores)) {
203 throw new cache_exception('The requested instance does not exist.');
204 }
205 $plugins = get_plugin_list_with_file('cache', 'lib.php');
206 if (!array_key_exists($plugin, $plugins)) {
207 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
208 }
209 $class = 'cache_store_.'.$plugin;
210 $file = $plugins[$plugin];
211 if (!class_exists($class)) {
212 if (file_exists($file)) {
213 require_once($file);
214 }
215 if (!class_exists($class)) {
216 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the require class.');
217 }
218 }
219 $this->configstores[$name] = array(
220 'name' => $name,
221 'plugin' => $plugin,
222 'configuration' => $configuration,
223 'features' => $class::get_supported_features($configuration),
224 'modes' => $class::get_supported_modes($configuration),
225 'mappingsonly' => !empty($configuration['mappingsonly']),
226 'useforlocking' => !empty($configuration['useforlocking'])
227 );
228 $this->config_save();
229 return true;
230 }
231
232 /**
233 * Deletes a store instance.
234 *
235 * This function also calls save so you should redirect immediately, or at least very shortly after
236 * calling this method.
237 *
238 * @param string $name The name of the instance to delete.
239 * @return bool
240 * @throws cache_exception
241 */
242 public function delete_store($name) {
243 if (!array_key_exists($name, $this->configstores)) {
244 throw new cache_exception('The requested store does not exist.');
245 }
246 if ($this->configstores[$name]['default']) {
247 throw new cache_exception('The can not delete the default stores.');
248 }
249 foreach ($this->configmodemappings as $mapping) {
250 if ($mapping['store'] === $name) {
251 throw new cache_exception('You cannot delete a cache store that has mode mappings.');
252 }
253 }
254 foreach ($this->configdefinitionmappings as $mapping) {
255 if ($mapping['store'] === $name) {
256 throw new cache_exception('You cannot delete a cache store that has definition mappings.');
257 }
258 }
259 unset($this->configstores[$name]);
260 $this->config_save();
261 return true;
262 }
263
264 /**
265 * Creates the default configuration and saves it.
266 *
267 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
268 * be called when there is no configuration file already.
269 */
270 public static function create_default_configuration() {
271 global $CFG;
272
273 // HACK ALERT.
274 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
275 // default store plugins are protected from deletion.
276 require_once($CFG->dirroot.'/cache/stores/file/lib.php');
277 require_once($CFG->dirroot.'/cache/stores/session/lib.php');
278 require_once($CFG->dirroot.'/cache/stores/static/lib.php');
279
280 $writer = new self;
281 $writer->configstores = array(
282 'default_locking' => array(
283 'name' => 'default_locking',
284 'plugin' => 'file',
285 'configuration' => array(),
286 'features' => cache_store_file::get_supported_features(),
287 'modes' => cache_store::MODE_APPLICATION,
288 'useforlocking' => true,
289 'mappingsonly' => true,
290 'default' => true,
291 //'class' => 'cache_store_file'
292 ),
293 'default_application' => array(
294 'name' => 'default_application',
295 'plugin' => 'file',
296 'configuration' => array(),
297 'features' => cache_store_file::get_supported_features(),
298 'modes' => cache_store::MODE_APPLICATION,
299 'default' => true,
300 //'class' => 'cache_store_file'
301 ),
302 'default_session' => array(
303 'name' => 'default_session',
304 'plugin' => 'session',
305 'configuration' => array(),
306 'features' => cache_store_session::get_supported_features(),
307 'modes' => cache_store::MODE_SESSION,
308 'default' => true,
309 //'class' => 'cache_store_session'
310 ),
311 'default_request' => array(
312 'name' => 'default_request',
313 'plugin' => 'static',
314 'configuration' => array(),
315 'features' => cache_store_static::get_supported_features(),
316 'modes' => cache_store::MODE_REQUEST,
317 'default' => true,
318 //'class' => 'cache_store_static'
319 )
320 );
321 $writer->configdefinitions = self::locate_definitions();
322 $writer->configmodemappings = array(
323 array(
324 'mode' => cache_store::MODE_APPLICATION,
325 'store' => 'default_application',
326 'sort' => -1
327 ),
328 array(
329 'mode' => cache_store::MODE_SESSION,
330 'store' => 'default_session',
331 'sort' => -1
332 ),
333 array(
334 'mode' => cache_store::MODE_REQUEST,
335 'store' => 'default_request',
336 'sort' => -1
337 )
338 );
339 $writer->configdefinitionmappings = array(
340 array(
341 'store' => 'default_locking',
342 'definition' => 'core/locking',
343 'sort' => -1
344 )
345 );
346 $writer->config_save();
347 }
348
349 /**
350 * Updates the definition in the configuration from those found in the cache files.
351 *
352 * Calls config_save further down, you should redirect immediately or asap after calling this method.
353 */
354 public static function update_definitions() {
355 $config = cache_config_writer::instance();
356 $config->write_definitions_to_cache(self::locate_definitions());
357 }
358
359 /**
360 * Locates all of the definition files.
361 *
362 * @return array
363 */
364 protected static function locate_definitions() {
365 global $CFG;
366
367 $files = array();
368 if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
369 $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
370 }
371
372 $plugintypes = get_plugin_types();
373 foreach ($plugintypes as $type => $location) {
374 $plugins = get_plugin_list_with_file($type, 'db/caches.php');
375 foreach ($plugins as $plugin => $filepath) {
376 $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // standardised plugin name
377 $files[$component] = $filepath;
378 }
379 }
380
381 $definitions = array();
382 foreach ($files as $component => $file) {
383 $filedefs = self::load_caches_file($file);
384 foreach ($filedefs as $area => $definition) {
385 $area = clean_param($area, PARAM_AREA);
386 $id = $component.'/'.$area;
387 $definition['component'] = $component;
388 $definition['area'] = $area;
389 if (array_key_exists($id, $definitions)) {
390 debugging('Error: duplicate cache definition found with name '.$name, DEBUG_DEVELOPER);
391 continue;
392 }
393 $definitions[$id] = $definition;
394 }
395 }
396
397 return $definitions;
398 }
399
400 /**
401 * Writes the updated definitions for the config file.
402 * @param array $definitions
403 */
404 private function write_definitions_to_cache(array $definitions) {
405 $this->configdefinitions = $definitions;
406 foreach ($this->configdefinitionmappings as $key => $mapping) {
407 if (!array_key_exists($mapping['definition'], $definitions)) {
408 unset($this->configdefinitionmappings[$key]);
409 }
410 }
411 $this->config_save();
412 }
413
414 /**
415 * Loads the caches file if it exists.
416 * @param string $file Absolute path to the file.
417 * @return array
418 */
419 private static function load_caches_file($file) {
420 if (!file_exists($file)) {
421 return array();
422 }
423 $definitions = array();
424 include $file;
425 return $definitions;
426 }
427
428 /**
429 * Sets the mappings for a given definition.
430 *
431 * @param string $definition
432 * @param array $mappings
433 * @throws coding_exception
434 */
435 public function set_definition_mappings($definition, $mappings) {
436 if (!array_key_exists($definition, $this->configdefinitions)) {
437 throw new coding_exception('Invalid definition name passed when updating mappings.');
438 }
439 foreach ($mappings as $store) {
440 if (!array_key_exists($store, $this->configstores)) {
441 throw new coding_exception('Invalid store name passed when updating definition mappings.');
442 }
443 }
444 foreach ($this->configdefinitionmappings as $key => $mapping) {
445 if ($mapping['definition'] == $definition) {
446 unset($this->configdefinitionmappings[$key]);
447 }
448 }
449 $sort = count($mappings);
450 foreach ($mappings as $store) {
451 $this->configdefinitionmappings[] = array(
452 'store' => $store,
453 'definition' => $definition,
454 'sort' => $sort
455 );
456 $sort--;
457 }
458
459 $this->config_save();
460 }
461
462}
463
464/**
465 * A cache helper for administration tasks
466 *
467 * @package core
468 * @category cache
469 * @copyright 2012 Sam Hemelryk
470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
471 */
472abstract class cache_administration_helper extends cache_helper {
473
474 /**
475 * Returns an array containing all of the information about stores a renderer needs.
476 * @return array
477 */
478 public static function get_store_summaries() {
479 $return = array();
480 $default = array();
481 $instance = cache_config::instance();
482 $stores = $instance->get_all_stores();
483 foreach ($stores as $name => $details) {
484 $class = $details['class'];
485 $store = new $class($details['name'], $details['configuration']);
486 $record = array(
487 'name' => $name,
488 'plugin' => $details['plugin'],
489 'default' => $details['default'],
490 'isready' => $store->is_ready(),
491 'requirementsmet' => $store->are_requirements_met(),
492 'mappings' => 0,
493 'modes' => array(
494 cache_store::MODE_APPLICATION =>
495 ($store->get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
496 cache_store::MODE_SESSION =>
497 ($store->get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
498 cache_store::MODE_REQUEST =>
499 ($store->get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
500 ),
501 'supports' => array(
502 'multipleidentifiers' => $store->supports_multiple_indentifiers(),
503 'dataguarantee' => $store->supports_data_guarantee(),
504 'nativettl' => $store->supports_native_ttl(),
505 'nativelocking' => ($store instanceof cache_is_lockable),
506 'keyawareness' => ($store instanceof cache_is_key_aware),
507 )
508 );
509 if (empty($details['default'])) {
510 $return[$name] = $record;
511 } else {
512 $default[$name] = $record;
513 }
514 }
515
516 ksort($return);
517 ksort($default);
518 $return = $return + $default;
519
520 foreach ($instance->get_mode_mappings() as $mapping) {
521 if (!array_key_exists($mapping['store'], $return)) {
522 continue;
523 }
524 $return[$mapping['store']]['mappings']++;
525 }
526 foreach ($instance->get_definition_mappings() as $mapping) {
527 if (!array_key_exists($mapping['store'], $return)) {
528 continue;
529 }
530 $return[$mapping['store']]['mappings']++;
531 }
532
533 return $return;
534 }
535
536 /**
537 * Returns an array of information about plugins, everything a renderer needs.
538 * @return array
539 */
540 public static function get_plugin_summaries() {
541 $return = array();
542 $plugins = get_plugin_list_with_file('cache', 'lib.php', true);
543 foreach ($plugins as $plugin => $path) {
544 $class = 'cache_store_'.$plugin;
545 $return[$plugin] = array(
546 'name' => get_string('pluginname', 'cache_'.$plugin),
547 'requirementsmet' => $class::are_requirements_met(),
548 'instances' => 0,
549 'modes' => array(
550 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
551 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
552 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
553 ),
554 'supports' => array(
555 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
556 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
557 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
558 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
559 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
560 ),
561 'canaddinstance' => ($class::can_add_instance())
562 );
563 }
564
565 $instance = cache_config::instance();
566 $stores = $instance->get_all_stores();
567 foreach ($stores as $store) {
568 $plugin = $store['plugin'];
569 if (array_key_exists($plugin, $return)) {
570 $return[$plugin]['instances']++;
571 }
572 }
573
574 return $return;
575 }
576
577 /**
578 * Returns an array about the definitions. All the information a renderer needs.
579 * @return array
580 */
581 public static function get_definition_summaries() {
582 $instance = cache_config::instance();
583 $definitions = $instance->get_definitions();
584
585 $storenames = array();
586 foreach ($instance->get_all_stores() as $key => $store) {
587 if (!empty($store['default'])) {
588 $storenames[$key] = new lang_string('store_'.$key, 'cache');
589 }
590 }
591
592 $modemappings = array();
593 foreach ($instance->get_mode_mappings() as $mapping) {
594 $mode = $mapping['mode'];
595 if (!array_key_exists($mode, $modemappings)) {
596 $modemappings[$mode] = array();
597 }
598 if (array_key_exists($mapping['store'], $storenames)) {
599 $modemappings[$mode][] = $storenames[$mapping['store']];
600 } else {
601 $modemappings[$mode][] = $mapping['store'];
602 }
603 }
604
605 $definitionmappings = array();
606 foreach ($instance->get_definition_mappings() as $mapping) {
607 $definition = $mapping['definition'];
608 if (!array_key_exists($definition, $definitionmappings)) {
609 $definitionmappings[$definition] = array();
610 }
611 if (array_key_exists($mapping['store'], $storenames)) {
612 $definitionmappings[$definition][] = $storenames[$mapping['store']];
613 } else {
614 $definitionmappings[$definition][] = $mapping['store'];
615 }
616 }
617
618 $return = array();
619
620 foreach ($definitions as $id => $definition) {
621
622 $mappings = array();
623 if (array_key_exists($id, $definitionmappings)) {
624 $mappings = $definitionmappings[$id];
625 } else if (empty($definition['mappingsonly'])) {
626 $mappings = $modemappings[$definition['mode']];
627 }
628
629 $return[$id] = array(
630 'id' => $id,
631 'name' => cache_helper::get_definition_name($definition),
632 'mode' => $definition['mode'],
633 'component' => $definition['component'],
634 'area' => $definition['area'],
635 'mappings' => $mappings
636 );
637 }
638 return $return;
639 }
640
641 /**
642 * Returns all of the actions that can be performed on a definition.
643 * @param context $context
644 * @return array
645 */
646 public static function get_definition_actions(context $context) {
647 if (has_capability('moodle/site:config', $context)) {
648 return array(
649 array(
650 'text' => get_string('editmappings', 'cache'),
651 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
652 )
653 );
654 }
655 return array();
656 }
657
658 /**
659 * Returns all of the actions that can be performed on a store.
660 *
661 * @param string $name The name of the store
662 * @param array $storedetails
663 * @return array
664 */
665 public static function get_store_actions($name, array $storedetails) {
666 $actions = array();
667 if (has_capability('moodle/site:config', get_system_context())) {
668 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
669 if (empty($storedetails['default'])) {
670 $actions[] = array(
671 'text' => get_string('editstore', 'cache'),
672 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
673 );
674 $actions[] = array(
675 'text' => get_string('deletestore', 'cache'),
676 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
677 );
678 }
679 $actions[] = array(
680 'text' => get_string('purge', 'cache'),
681 'url' => new moodle_url($baseurl, array('action' => 'purge'))
682 );
683 }
684 return $actions;
685 }
686
687
688 /**
689 * Returns all of the actions that can be performed on a plugin.
690 *
691 * @param string $name The name of the plugin
692 * @param array $plugindetails
693 * @return array
694 */
695 public static function get_plugin_actions($name, array $plugindetails) {
696 $actions = array();
697 if (has_capability('moodle/site:config', get_system_context())) {
698 if (!empty($plugindetails['canaddinstance'])) {
699 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
700 $actions[] = array(
701 'text' => get_string('addinstance', 'cache'),
702 'url' => $url
703 );
704 }
705 }
706 return $actions;
707 }
708
709 /**
710 * Returns a form that can be used to add a store instance.
711 *
712 * @param string $plugin The plugin to add an instance of
713 * @return cache_store_addinstance_form
714 * @throws coding_exception
715 */
716 public static function get_add_store_form($plugin) {
717 global $CFG; // Needed for includes
718 $plugindir = get_plugin_directory('cache', $plugin);
719 $class = 'cache_store_addinstance_form';
720 if (file_exists($plugindir.'/addinstanceform.php')) {
721 require_once($plugindir.'/addinstanceform.php');
722 if (class_exists('cache_store_'.$plugin.'_addinstance_form')) {
723 $class = 'cache_store_'.$plugin.'_addinstance_form';
724 if (!array_key_exists('cache_store_addinstance_form', class_parents($class))) {
725 throw new coding_exception('Cache plugin add instance forms must extend cache_store_addinstance_form');
726 }
727 }
728 }
729
730 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
731 return new $class($url, array('plugin' => $plugin, 'store' => null));
732 }
733
734 /**
735 * Returns a form that can be used to edit a store instance.
736 *
737 * @param string $plugin
738 * @param string $store
739 * @return cache_store_addinstance_form
740 * @throws coding_exception
741 */
742 public static function get_edit_store_form($plugin, $store) {
743 global $CFG; // Needed for includes
744 $plugindir = get_plugin_directory('cache', $plugin);
745 $class = 'cache_store_addinstance_form';
746 if (file_exists($plugindir.'/addinstanceform.php')) {
747 require_once($plugindir.'/addinstanceform.php');
748 if (class_exists('cache_store_'.$plugin.'_addinstance_form')) {
749 $class = 'cache_store_'.$plugin.'_addinstance_form';
750 if (!array_key_exists('cache_store_addinstance_form', class_parents($class))) {
751 throw new coding_exception('Cache plugin add instance forms must extend cache_store_addinstance_form');
752 }
753 }
754 }
755
756 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore'));
757 return new $class($url, array('plugin' => $plugin, 'store' => $store));
758 }
759
760 /**
761 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
762 * store in configuration.
763 *
764 * @param stdClass $data The mform data.
765 * @return array
766 * @throws coding_exception
767 */
768 public static function get_store_configuration_from_data(stdClass $data) {
769 global $CFG;
770 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
771 if (!file_exists($file)) {
772 throw new coding_exception('Invalid cache plugin provided. '.$file);
773 }
774 require_once($file);
775 $class = 'cache_store_'.$data->plugin;
776 $method = 'config_get_configuration_array';
777 if (!class_exists($class)) {
778 throw new coding_exception('Invalid cache plugin provided.');
779 }
780 if (method_exists($class, $method)) {
781 return call_user_func(array($class, $method), $data);
782 }
783 return array();
784 }
785
786 /**
787 * Get an array of stores that are suitable to be used for a given definition.
788 *
789 * @param string $component
790 * @param string $area
791 * @return array Array containing 3 elements
792 * 1. An array of currently used stores
793 * 2. An array of suitable stores
794 * 3. An array of default stores
795 */
796 public static function get_definition_store_options($component, $area) {
797 $factory = cache_factory::instance();
798 $definition = $factory->create_definition($component, $area);
799 $config = cache_config::instance();
800 $currentstores = $config->get_stores_for_definition($definition);
801 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
802
803 $defaults = array();
804 foreach ($currentstores as $key => $store) {
805 if (!empty($store['default'])) {
806 $defaults[] = $key;
807 unset($currentstores[$key]);
808 }
809 }
810 foreach ($possiblestores as $key => $store) {
811 if ($key === 'default_locking') {
812 unset($possiblestores[$key]);
813 } else if ($store['default']) {
814 unset($possiblestores[$key]);
815 $possiblestores[$key] = $store;
816 }
817 }
818 return array($currentstores, $possiblestores, $defaults);
819 }
820
821 /**
822 * Get the default stores for all modes.
823 *
824 * @return array An array containing sub-arrays, one for each mode.
825 */
826 public static function get_default_mode_stores() {
827 $instance = cache_config::instance();
828 $storenames = array();
829 foreach ($instance->get_all_stores() as $key => $store) {
830 if (!empty($store['default'])) {
831 $storenames[$key] = new lang_string('store_'.$key, 'cache');
832 }
833 }
834 $modemappings = array(
835 cache_store::MODE_APPLICATION => array(),
836 cache_store::MODE_SESSION => array(),
837 cache_store::MODE_REQUEST => array(),
838 );
839 foreach ($instance->get_mode_mappings() as $mapping) {
840 $mode = $mapping['mode'];
841 if (!array_key_exists($mode, $modemappings)) {
842 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
843 continue;
844 }
845 if (array_key_exists($mapping['store'], $storenames)) {
846 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
847 } else {
848 $modemappings[$mode][$mapping['store']] = $mapping['store'];
849 }
850 }
851 return $modemappings;
852 }
853}