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