on demand release 2.5beta+
[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
7383a7e2
SH
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
49 */
50 protected static $creatingconfig = false;
51
8139ad13
SH
52 /**
53 * Returns an instance of the configuration writer.
54 *
55 * @return cache_config_writer
56 */
57 public static function instance() {
58 $factory = cache_factory::instance();
59 return $factory->create_config_instance(true);
60 }
61
62 /**
63 * Saves the current configuration.
7383a7e2
SH
64 *
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.
8139ad13
SH
68 */
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) {
7383a7e2 76 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory. Check the permissions on your moodledata directory.');
8139ad13
SH
77 }
78 }
79 if (!file_exists($directory) || !is_writable($directory)) {
7383a7e2 80 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Config directory is not writable. Check the permissions on the moodledata/muc directory.');
8139ad13
SH
81 }
82
83 // Prepare a configuration array to store.
7383a7e2 84 $configuration = $this->generate_configuration_array();
8139ad13
SH
85
86 // Prepare the file content.
87 $content = "<?php defined('MOODLE_INTERNAL') || die();\n \$configuration = ".var_export($configuration, true).";";
88
34c84c72
SH
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).
573a6c8e
SH
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
100 );
101 }
34c84c72 102 $factory = cache_factory::instance();
573a6c8e 103 $locking = $factory->create_lock_instance($lockconf);
34c84c72
SH
104 if ($locking->lock('configwrite', 'config', true)) {
105 // Its safe to use w mode here because we have already acquired the lock.
8139ad13
SH
106 $handle = fopen($cachefile, 'w');
107 fwrite($handle, $content);
108 fflush($handle);
109 fclose($handle);
34c84c72 110 $locking->unlock('configwrite', 'config');
8139ad13
SH
111 } else {
112 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Unable to open the cache config file.');
113 }
114 }
115
7383a7e2
SH
116 /**
117 * Generates a configuration array suitable to be written to the config file.
118 * @return array
119 */
120 protected function generate_configuration_array() {
121 $configuration = array();
7866b094 122 $configuration['siteidentifier'] = $this->siteidentifier;
7383a7e2
SH
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;
129 }
130
8139ad13
SH
131 /**
132 * Adds a plugin instance.
133 *
134 * This function also calls save so you should redirect immediately, or at least very shortly after
135 * calling this method.
136 *
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
142 */
26ce56fd 143 public function add_store_instance($name, $plugin, array $configuration = array()) {
8139ad13
SH
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.');
146 }
6fec1820 147 $class = 'cachestore_'.$plugin;
8139ad13 148 if (!class_exists($class)) {
6fec1820 149 $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
8139ad13 150 if (!array_key_exists($plugin, $plugins)) {
170f821b 151 throw new cache_exception('Invalid plugin name specified. The plugin does not exist or is not valid.');
8139ad13
SH
152 }
153 $file = $plugins[$plugin];
154 if (file_exists($file)) {
155 require_once($file);
156 }
157 if (!class_exists($class)) {
158 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.');
159 }
160 }
d4797177 161 $reflection = new ReflectionClass($class);
75cde6b9 162 if (!$reflection->isSubclassOf('cache_store')) {
8139ad13
SH
163 throw new cache_exception('Invalid cache plugin specified. The plugin does not extend the required class.');
164 }
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.');
167 }
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),
42f2c59e
SH
174 'mappingsonly' => !empty($configuration['mappingsonly']),
175 'class' => $class,
176 'default' => false
8139ad13 177 );
167ad91e
SH
178 if (array_key_exists('lock', $configuration)) {
179 $this->configstores[$name]['lock'] = $configuration['lock'];
180 unset($this->configstores[$name]['configuration']['lock']);
181 }
730cf5ac
MS
182 // Call instance_created()
183 $store = new $class($name, $this->configstores[$name]['configuration']);
184 $store->instance_created();
185
8139ad13
SH
186 $this->config_save();
187 return true;
188 }
189
acf49f4b
SH
190 /**
191 * Adds a new lock instance to the config file.
192 *
193 * @param string $name The name the user gave the instance. PARAM_ALHPANUMEXT
194 * @param string $plugin The plugin we are creating an instance of.
195 * @param string $configuration Configuration data from the config instance.
196 * @throws cache_exception
197 */
198 public function add_lock_instance($name, $plugin, $configuration = array()) {
199 if (array_key_exists($name, $this->configlocks)) {
200 throw new cache_exception('Duplicate name specificed for cache lock instance. You must provide a unique name.');
201 }
202 $class = 'cachelock_'.$plugin;
203 if (!class_exists($class)) {
204 $plugins = get_plugin_list_with_file('cachelock', 'lib.php');
205 if (!array_key_exists($plugin, $plugins)) {
206 throw new cache_exception('Invalid lock name specified. The plugin does not exist or is not valid.');
207 }
208 $file = $plugins[$plugin];
209 if (file_exists($file)) {
210 require_once($file);
211 }
212 if (!class_exists($class)) {
213 throw new cache_exception('Invalid lock plugin specified. The plugin does not contain the required class.');
214 }
215 }
216 $reflection = new ReflectionClass($class);
217 if (!$reflection->implementsInterface('cache_lock_interface')) {
218 throw new cache_exception('Invalid lock plugin specified. The plugin does not implement the required interface.');
219 }
220 $this->configlocks[$name] = array_merge($configuration, array(
221 'name' => $name,
222 'type' => 'cachelock_'.$plugin,
223 'default' => false
224 ));
225 $this->config_save();
226 }
227
228 /**
229 * Deletes a lock instance given its name.
230 *
231 * @param string $name The name of the plugin, PARAM_ALPHANUMEXT.
232 * @return bool
233 * @throws cache_exception
234 */
235 public function delete_lock_instance($name) {
236 if (!array_key_exists($name, $this->configlocks)) {
237 throw new cache_exception('The requested store does not exist.');
238 }
239 if ($this->configlocks[$name]['default']) {
240 throw new cache_exception('You can not delete the default lock.');
241 }
242 foreach ($this->configstores as $store) {
243 if (isset($store['lock']) && $store['lock'] === $name) {
244 throw new cache_exception('You cannot delete a cache lock that is being used by a store.');
245 }
246 }
247 unset($this->configlocks[$name]);
248 $this->config_save();
249 return true;
250 }
251
8139ad13
SH
252 /**
253 * Sets the mode mappings.
254 *
255 * These determine the default caches for the different modes.
256 * This function also calls save so you should redirect immediately, or at least very shortly after
257 * calling this method.
258 *
259 * @param array $modemappings
260 * @return bool
261 * @throws cache_exception
262 */
263 public function set_mode_mappings(array $modemappings) {
264 $mappings = array(
265 cache_store::MODE_APPLICATION => array(),
266 cache_store::MODE_SESSION => array(),
267 cache_store::MODE_REQUEST => array(),
268 );
269 foreach ($modemappings as $mode => $stores) {
270 if (!array_key_exists($mode, $mappings)) {
271 throw new cache_exception('The cache mode for the new mapping does not exist');
272 }
273 $sort = 0;
274 foreach ($stores as $store) {
275 if (!array_key_exists($store, $this->configstores)) {
276 throw new cache_exception('The instance name for the new mapping does not exist');
277 }
278 if (array_key_exists($store, $mappings[$mode])) {
279 throw new cache_exception('This cache mapping already exists');
280 }
281 $mappings[$mode][] = array(
282 'store' => $store,
283 'mode' => $mode,
284 'sort' => $sort++
285 );
286 }
287 }
288 $this->configmodemappings = array_merge(
289 $mappings[cache_store::MODE_APPLICATION],
290 $mappings[cache_store::MODE_SESSION],
291 $mappings[cache_store::MODE_REQUEST]
292 );
293
294 $this->config_save();
295 return true;
296 }
297
298 /**
299 * Edits a give plugin instance.
300 *
42f2c59e 301 * The plugin instance is determined by its name, hence you cannot rename plugins.
8139ad13
SH
302 * This function also calls save so you should redirect immediately, or at least very shortly after
303 * calling this method.
304 *
305 * @param string $name
306 * @param string $plugin
307 * @param array $configuration
308 * @return bool
309 * @throws cache_exception
310 */
26ce56fd 311 public function edit_store_instance($name, $plugin, $configuration) {
8139ad13
SH
312 if (!array_key_exists($name, $this->configstores)) {
313 throw new cache_exception('The requested instance does not exist.');
314 }
6fec1820 315 $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
8139ad13
SH
316 if (!array_key_exists($plugin, $plugins)) {
317 throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
318 }
42f2c59e 319 $class = 'cachestore_'.$plugin;
8139ad13
SH
320 $file = $plugins[$plugin];
321 if (!class_exists($class)) {
322 if (file_exists($file)) {
323 require_once($file);
324 }
325 if (!class_exists($class)) {
42f2c59e 326 throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.'.$class);
8139ad13
SH
327 }
328 }
329 $this->configstores[$name] = array(
330 'name' => $name,
331 'plugin' => $plugin,
332 'configuration' => $configuration,
333 'features' => $class::get_supported_features($configuration),
334 'modes' => $class::get_supported_modes($configuration),
42f2c59e
SH
335 'mappingsonly' => !empty($configuration['mappingsonly']),
336 'class' => $class,
337 'default' => $this->configstores[$name]['default'] // Can't change the default.
8139ad13 338 );
167ad91e
SH
339 if (array_key_exists('lock', $configuration)) {
340 $this->configstores[$name]['lock'] = $configuration['lock'];
341 unset($this->configstores[$name]['configuration']['lock']);
342 }
8139ad13
SH
343 $this->config_save();
344 return true;
345 }
346
347 /**
348 * Deletes a store instance.
349 *
350 * This function also calls save so you should redirect immediately, or at least very shortly after
351 * calling this method.
352 *
353 * @param string $name The name of the instance to delete.
354 * @return bool
355 * @throws cache_exception
356 */
26ce56fd 357 public function delete_store_instance($name) {
8139ad13
SH
358 if (!array_key_exists($name, $this->configstores)) {
359 throw new cache_exception('The requested store does not exist.');
360 }
361 if ($this->configstores[$name]['default']) {
362 throw new cache_exception('The can not delete the default stores.');
363 }
364 foreach ($this->configmodemappings as $mapping) {
365 if ($mapping['store'] === $name) {
366 throw new cache_exception('You cannot delete a cache store that has mode mappings.');
367 }
368 }
369 foreach ($this->configdefinitionmappings as $mapping) {
370 if ($mapping['store'] === $name) {
371 throw new cache_exception('You cannot delete a cache store that has definition mappings.');
372 }
373 }
a037c943 374
730cf5ac
MS
375 // Call instance_deleted()
376 $class = 'cachestore_'.$this->configstores[$name]['plugin'];
377 $store = new $class($name, $this->configstores[$name]['configuration']);
378 $store->instance_deleted();
379
8139ad13
SH
380 unset($this->configstores[$name]);
381 $this->config_save();
382 return true;
383 }
384
385 /**
386 * Creates the default configuration and saves it.
387 *
388 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
389 * be called when there is no configuration file already.
7383a7e2
SH
390 *
391 * @return true|array Returns true if the default configuration was successfully created.
392 * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
8139ad13
SH
393 */
394 public static function create_default_configuration() {
395 global $CFG;
396
397 // HACK ALERT.
398 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
399 // default store plugins are protected from deletion.
400 require_once($CFG->dirroot.'/cache/stores/file/lib.php');
401 require_once($CFG->dirroot.'/cache/stores/session/lib.php');
402 require_once($CFG->dirroot.'/cache/stores/static/lib.php');
403
404 $writer = new self;
fbf76dcd 405 $writer->configstores = self::get_default_stores();
8139ad13
SH
406 $writer->configdefinitions = self::locate_definitions();
407 $writer->configmodemappings = array(
408 array(
409 'mode' => cache_store::MODE_APPLICATION,
410 'store' => 'default_application',
411 'sort' => -1
412 ),
413 array(
414 'mode' => cache_store::MODE_SESSION,
415 'store' => 'default_session',
416 'sort' => -1
417 ),
418 array(
419 'mode' => cache_store::MODE_REQUEST,
420 'store' => 'default_request',
421 'sort' => -1
422 )
423 );
34c84c72
SH
424 $writer->configlocks = array(
425 'default_file_lock' => array(
167ad91e 426 'name' => 'cachelock_file_default',
34c84c72 427 'type' => 'cachelock_file',
167ad91e
SH
428 'dir' => 'filelocks',
429 'default' => true
34c84c72
SH
430 )
431 );
7383a7e2
SH
432
433 $factory = cache_factory::instance();
434 // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
435 // we are now in a loop.
436 if ($factory->get_state() !== cache_factory::STATE_INITIALISING) {
437 return $writer->generate_configuration_array();
438 }
439 $factory->set_state(cache_factory::STATE_SAVING);
8139ad13 440 $writer->config_save();
7383a7e2 441 return true;
8139ad13
SH
442 }
443
fbf76dcd
SH
444 /**
445 * Returns an array of default stores for use.
446 *
447 * @return array
448 */
449 protected static function get_default_stores() {
450 return array(
451 'default_application' => array(
452 'name' => 'default_application',
453 'plugin' => 'file',
454 'configuration' => array(),
455 'features' => cachestore_file::get_supported_features(),
456 'modes' => cachestore_file::get_supported_modes(),
457 'default' => true,
458 ),
459 'default_session' => array(
460 'name' => 'default_session',
461 'plugin' => 'session',
462 'configuration' => array(),
463 'features' => cachestore_session::get_supported_features(),
464 'modes' => cachestore_session::get_supported_modes(),
465 'default' => true,
466 ),
467 'default_request' => array(
468 'name' => 'default_request',
469 'plugin' => 'static',
470 'configuration' => array(),
471 'features' => cachestore_static::get_supported_features(),
472 'modes' => cachestore_static::get_supported_modes(),
473 'default' => true,
474 )
475 );
476 }
477
478 /**
479 * Updates the default stores within the MUC config file.
480 */
481 public static function update_default_config_stores() {
482 $factory = cache_factory::instance();
483 $factory->updating_started();
484 $config = $factory->create_config_instance(true);
485 $config->configstores = array_merge($config->configstores, self::get_default_stores());
486 $config->config_save();
487 $factory->updating_finished();
488 }
489
8139ad13
SH
490 /**
491 * Updates the definition in the configuration from those found in the cache files.
492 *
493 * Calls config_save further down, you should redirect immediately or asap after calling this method.
75af47ee
SH
494 *
495 * @param bool $coreonly If set to true only core definitions will be updated.
8139ad13 496 */
75af47ee 497 public static function update_definitions($coreonly = false) {
9890ecfc
SH
498 $factory = cache_factory::instance();
499 $factory->updating_started();
500 $config = $factory->create_config_instance(true);
75af47ee 501 $config->write_definitions_to_cache(self::locate_definitions($coreonly));
9890ecfc 502 $factory->updating_finished();
8139ad13
SH
503 }
504
505 /**
506 * Locates all of the definition files.
507 *
75af47ee 508 * @param bool $coreonly If set to true only core definitions will be updated.
8139ad13
SH
509 * @return array
510 */
75af47ee 511 protected static function locate_definitions($coreonly = false) {
8139ad13
SH
512 global $CFG;
513
514 $files = array();
515 if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
516 $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
517 }
518
75af47ee
SH
519 if (!$coreonly) {
520 $plugintypes = get_plugin_types();
521 foreach ($plugintypes as $type => $location) {
522 $plugins = get_plugin_list_with_file($type, 'db/caches.php');
523 foreach ($plugins as $plugin => $filepath) {
524 $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
525 $files[$component] = $filepath;
526 }
8139ad13
SH
527 }
528 }
529
530 $definitions = array();
531 foreach ($files as $component => $file) {
532 $filedefs = self::load_caches_file($file);
533 foreach ($filedefs as $area => $definition) {
534 $area = clean_param($area, PARAM_AREA);
535 $id = $component.'/'.$area;
536 $definition['component'] = $component;
537 $definition['area'] = $area;
538 if (array_key_exists($id, $definitions)) {
d4797177 539 debugging('Error: duplicate cache definition found with id: '.$id, DEBUG_DEVELOPER);
8139ad13
SH
540 continue;
541 }
542 $definitions[$id] = $definition;
543 }
544 }
545
546 return $definitions;
547 }
548
549 /**
550 * Writes the updated definitions for the config file.
551 * @param array $definitions
552 */
553 private function write_definitions_to_cache(array $definitions) {
554 $this->configdefinitions = $definitions;
555 foreach ($this->configdefinitionmappings as $key => $mapping) {
556 if (!array_key_exists($mapping['definition'], $definitions)) {
557 unset($this->configdefinitionmappings[$key]);
558 }
559 }
560 $this->config_save();
561 }
562
563 /**
564 * Loads the caches file if it exists.
565 * @param string $file Absolute path to the file.
566 * @return array
567 */
568 private static function load_caches_file($file) {
569 if (!file_exists($file)) {
570 return array();
571 }
572 $definitions = array();
170f821b 573 include($file);
8139ad13
SH
574 return $definitions;
575 }
576
577 /**
578 * Sets the mappings for a given definition.
579 *
580 * @param string $definition
581 * @param array $mappings
582 * @throws coding_exception
583 */
584 public function set_definition_mappings($definition, $mappings) {
585 if (!array_key_exists($definition, $this->configdefinitions)) {
586 throw new coding_exception('Invalid definition name passed when updating mappings.');
587 }
588 foreach ($mappings as $store) {
589 if (!array_key_exists($store, $this->configstores)) {
590 throw new coding_exception('Invalid store name passed when updating definition mappings.');
591 }
592 }
593 foreach ($this->configdefinitionmappings as $key => $mapping) {
594 if ($mapping['definition'] == $definition) {
595 unset($this->configdefinitionmappings[$key]);
596 }
597 }
598 $sort = count($mappings);
599 foreach ($mappings as $store) {
600 $this->configdefinitionmappings[] = array(
601 'store' => $store,
602 'definition' => $definition,
603 'sort' => $sort
604 );
605 $sort--;
606 }
607
608 $this->config_save();
609 }
610
e0d9b7c0
SH
611 /**
612 * Update the site identifier stored by the cache API.
613 *
614 * @param string $siteidentifier
fe86ebfa 615 * @return string The new site identifier.
e0d9b7c0
SH
616 */
617 public function update_site_identifier($siteidentifier) {
618 $this->siteidentifier = md5((string)$siteidentifier);
619 $this->config_save();
fe86ebfa 620 return $this->siteidentifier;
e0d9b7c0 621 }
8139ad13
SH
622}
623
624/**
625 * A cache helper for administration tasks
626 *
627 * @package core
628 * @category cache
629 * @copyright 2012 Sam Hemelryk
630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
631 */
632abstract class cache_administration_helper extends cache_helper {
633
634 /**
635 * Returns an array containing all of the information about stores a renderer needs.
636 * @return array
637 */
26ce56fd 638 public static function get_store_instance_summaries() {
8139ad13
SH
639 $return = array();
640 $default = array();
641 $instance = cache_config::instance();
642 $stores = $instance->get_all_stores();
acf49f4b 643 $locks = $instance->get_locks();
8139ad13
SH
644 foreach ($stores as $name => $details) {
645 $class = $details['class'];
646 $store = new $class($details['name'], $details['configuration']);
acf49f4b 647 $lock = (isset($details['lock'])) ? $locks[$details['lock']] : $instance->get_default_lock();
8139ad13
SH
648 $record = array(
649 'name' => $name,
650 'plugin' => $details['plugin'],
651 'default' => $details['default'],
652 'isready' => $store->is_ready(),
653 'requirementsmet' => $store->are_requirements_met(),
654 'mappings' => 0,
acf49f4b 655 'lock' => $lock,
8139ad13
SH
656 'modes' => array(
657 cache_store::MODE_APPLICATION =>
658 ($store->get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
659 cache_store::MODE_SESSION =>
660 ($store->get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
661 cache_store::MODE_REQUEST =>
662 ($store->get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
663 ),
664 'supports' => array(
758dbdf8 665 'multipleidentifiers' => $store->supports_multiple_identifiers(),
8139ad13
SH
666 'dataguarantee' => $store->supports_data_guarantee(),
667 'nativettl' => $store->supports_native_ttl(),
668 'nativelocking' => ($store instanceof cache_is_lockable),
669 'keyawareness' => ($store instanceof cache_is_key_aware),
dbd2ea4e 670 'searchable' => ($store instanceof cache_is_searchable)
8139ad13
SH
671 )
672 );
673 if (empty($details['default'])) {
674 $return[$name] = $record;
675 } else {
676 $default[$name] = $record;
677 }
678 }
679
680 ksort($return);
681 ksort($default);
682 $return = $return + $default;
683
8139ad13
SH
684 foreach ($instance->get_definition_mappings() as $mapping) {
685 if (!array_key_exists($mapping['store'], $return)) {
686 continue;
687 }
688 $return[$mapping['store']]['mappings']++;
689 }
690
691 return $return;
692 }
693
694 /**
695 * Returns an array of information about plugins, everything a renderer needs.
696 * @return array
697 */
26ce56fd 698 public static function get_store_plugin_summaries() {
8139ad13 699 $return = array();
6fec1820 700 $plugins = get_plugin_list_with_file('cachestore', 'lib.php', true);
8139ad13 701 foreach ($plugins as $plugin => $path) {
6fec1820 702 $class = 'cachestore_'.$plugin;
8139ad13 703 $return[$plugin] = array(
6fec1820 704 'name' => get_string('pluginname', 'cachestore_'.$plugin),
8139ad13
SH
705 'requirementsmet' => $class::are_requirements_met(),
706 'instances' => 0,
707 'modes' => array(
708 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
709 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
710 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
711 ),
712 'supports' => array(
713 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
714 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
715 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
716 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
717 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
718 ),
7e7e108f 719 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
8139ad13
SH
720 );
721 }
722
723 $instance = cache_config::instance();
724 $stores = $instance->get_all_stores();
725 foreach ($stores as $store) {
726 $plugin = $store['plugin'];
727 if (array_key_exists($plugin, $return)) {
728 $return[$plugin]['instances']++;
729 }
730 }
731
732 return $return;
733 }
734
735 /**
736 * Returns an array about the definitions. All the information a renderer needs.
737 * @return array
738 */
739 public static function get_definition_summaries() {
740 $instance = cache_config::instance();
741 $definitions = $instance->get_definitions();
742
743 $storenames = array();
744 foreach ($instance->get_all_stores() as $key => $store) {
745 if (!empty($store['default'])) {
746 $storenames[$key] = new lang_string('store_'.$key, 'cache');
747 }
748 }
749
750 $modemappings = array();
751 foreach ($instance->get_mode_mappings() as $mapping) {
752 $mode = $mapping['mode'];
753 if (!array_key_exists($mode, $modemappings)) {
754 $modemappings[$mode] = array();
755 }
756 if (array_key_exists($mapping['store'], $storenames)) {
757 $modemappings[$mode][] = $storenames[$mapping['store']];
758 } else {
759 $modemappings[$mode][] = $mapping['store'];
760 }
761 }
762
763 $definitionmappings = array();
764 foreach ($instance->get_definition_mappings() as $mapping) {
765 $definition = $mapping['definition'];
766 if (!array_key_exists($definition, $definitionmappings)) {
767 $definitionmappings[$definition] = array();
768 }
769 if (array_key_exists($mapping['store'], $storenames)) {
770 $definitionmappings[$definition][] = $storenames[$mapping['store']];
771 } else {
772 $definitionmappings[$definition][] = $mapping['store'];
773 }
774 }
775
776 $return = array();
777
778 foreach ($definitions as $id => $definition) {
779
780 $mappings = array();
781 if (array_key_exists($id, $definitionmappings)) {
782 $mappings = $definitionmappings[$id];
783 } else if (empty($definition['mappingsonly'])) {
784 $mappings = $modemappings[$definition['mode']];
785 }
786
787 $return[$id] = array(
788 'id' => $id,
789 'name' => cache_helper::get_definition_name($definition),
790 'mode' => $definition['mode'],
791 'component' => $definition['component'],
792 'area' => $definition['area'],
793 'mappings' => $mappings
794 );
795 }
796 return $return;
797 }
798
799 /**
800 * Returns all of the actions that can be performed on a definition.
801 * @param context $context
802 * @return array
803 */
804 public static function get_definition_actions(context $context) {
805 if (has_capability('moodle/site:config', $context)) {
806 return array(
807 array(
808 'text' => get_string('editmappings', 'cache'),
809 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
50523565
SH
810 ),
811 array(
812 'text' => get_string('purge', 'cache'),
813 'url' => new moodle_url('/cache/admin.php', array('action' => 'purgedefinition', 'sesskey' => sesskey()))
8139ad13
SH
814 )
815 );
816 }
817 return array();
818 }
819
820 /**
821 * Returns all of the actions that can be performed on a store.
822 *
823 * @param string $name The name of the store
824 * @param array $storedetails
825 * @return array
826 */
26ce56fd 827 public static function get_store_instance_actions($name, array $storedetails) {
8139ad13
SH
828 $actions = array();
829 if (has_capability('moodle/site:config', get_system_context())) {
830 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
831 if (empty($storedetails['default'])) {
832 $actions[] = array(
833 'text' => get_string('editstore', 'cache'),
834 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
835 );
836 $actions[] = array(
837 'text' => get_string('deletestore', 'cache'),
838 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
839 );
840 }
841 $actions[] = array(
842 'text' => get_string('purge', 'cache'),
50523565 843 'url' => new moodle_url($baseurl, array('action' => 'purgestore'))
8139ad13
SH
844 );
845 }
846 return $actions;
847 }
848
849
850 /**
851 * Returns all of the actions that can be performed on a plugin.
852 *
853 * @param string $name The name of the plugin
854 * @param array $plugindetails
855 * @return array
856 */
26ce56fd 857 public static function get_store_plugin_actions($name, array $plugindetails) {
8139ad13 858 $actions = array();
7e7e108f 859 if (has_capability('moodle/site:config', context_system::instance())) {
8139ad13
SH
860 if (!empty($plugindetails['canaddinstance'])) {
861 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
862 $actions[] = array(
863 'text' => get_string('addinstance', 'cache'),
864 'url' => $url
865 );
866 }
867 }
868 return $actions;
869 }
870
871 /**
872 * Returns a form that can be used to add a store instance.
873 *
874 * @param string $plugin The plugin to add an instance of
6fec1820 875 * @return cachestore_addinstance_form
8139ad13
SH
876 * @throws coding_exception
877 */
878 public static function get_add_store_form($plugin) {
170f821b 879 global $CFG; // Needed for includes.
42f2c59e
SH
880 $plugins = get_plugin_list('cachestore');
881 if (!array_key_exists($plugin, $plugins)) {
882 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
883 }
884 $plugindir = $plugins[$plugin];
6fec1820 885 $class = 'cachestore_addinstance_form';
8139ad13
SH
886 if (file_exists($plugindir.'/addinstanceform.php')) {
887 require_once($plugindir.'/addinstanceform.php');
6fec1820
SH
888 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
889 $class = 'cachestore_'.$plugin.'_addinstance_form';
890 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
891 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
8139ad13
SH
892 }
893 }
894 }
895
26ce56fd 896 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
167ad91e 897
8139ad13 898 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
167ad91e 899 return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
8139ad13
SH
900 }
901
902 /**
903 * Returns a form that can be used to edit a store instance.
904 *
905 * @param string $plugin
906 * @param string $store
6fec1820 907 * @return cachestore_addinstance_form
8139ad13
SH
908 * @throws coding_exception
909 */
910 public static function get_edit_store_form($plugin, $store) {
170f821b 911 global $CFG; // Needed for includes.
42f2c59e
SH
912 $plugins = get_plugin_list('cachestore');
913 if (!array_key_exists($plugin, $plugins)) {
914 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
915 }
916 $factory = cache_factory::instance();
917 $config = $factory->create_config_instance();
918 $stores = $config->get_all_stores();
919 if (!array_key_exists($store, $stores)) {
920 throw new coding_exception('Invalid store name given when trying to create an edit form.');
921 }
922 $plugindir = $plugins[$plugin];
6fec1820 923 $class = 'cachestore_addinstance_form';
8139ad13
SH
924 if (file_exists($plugindir.'/addinstanceform.php')) {
925 require_once($plugindir.'/addinstanceform.php');
6fec1820
SH
926 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
927 $class = 'cachestore_'.$plugin.'_addinstance_form';
928 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
929 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
8139ad13
SH
930 }
931 }
932 }
933
26ce56fd 934 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
42f2c59e 935
81ede547
SH
936 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
937 $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
acf49f4b 938 if (isset($stores[$store]['lock'])) {
25927c42 939 $editform->set_data(array('lock' => $stores[$store]['lock']));
acf49f4b 940 }
81ede547
SH
941 // See if the cachestore is going to want to load data for the form.
942 // If it has a customised add instance form then it is going to want to.
943 $storeclass = 'cachestore_'.$plugin;
944 $storedata = $stores[$store];
2b274ad0 945 if (array_key_exists('configuration', $storedata) && array_key_exists('cache_is_configurable', class_implements($storeclass))) {
81ede547
SH
946 $storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
947 }
948 return $editform;
42f2c59e
SH
949 }
950
951 /**
952 * Returns an array of suitable lock instances for use with this plugin, or false if the plugin handles locking itself.
953 *
954 * @param string $plugindir
955 * @param string $plugin
956 * @return array|false
957 */
26ce56fd 958 protected static function get_possible_locks_for_stores($plugindir, $plugin) {
42f2c59e
SH
959 global $CFG; // Needed for includes.
960 $supportsnativelocking = false;
961 if (file_exists($plugindir.'/lib.php')) {
962 require_once($plugindir.'/lib.php');
963 $pluginclass = 'cachestore_'.$plugin;
964 if (class_exists($pluginclass)) {
965 $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
966 }
967 }
968
969 if (!$supportsnativelocking) {
970 $config = cache_config::instance();
971 $locks = array();
972 foreach ($config->get_locks() as $lock => $conf) {
973 if (!empty($conf['default'])) {
974 $name = get_string($lock, 'cache');
975 } else {
976 $name = $lock;
977 }
978 $locks[$lock] = $name;
979 }
980 } else {
981 $locks = false;
982 }
983
984 return $locks;
8139ad13
SH
985 }
986
987 /**
988 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
989 * store in configuration.
990 *
991 * @param stdClass $data The mform data.
992 * @return array
993 * @throws coding_exception
994 */
995 public static function get_store_configuration_from_data(stdClass $data) {
996 global $CFG;
997 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
998 if (!file_exists($file)) {
999 throw new coding_exception('Invalid cache plugin provided. '.$file);
1000 }
1001 require_once($file);
6fec1820 1002 $class = 'cachestore_'.$data->plugin;
8139ad13
SH
1003 if (!class_exists($class)) {
1004 throw new coding_exception('Invalid cache plugin provided.');
1005 }
2b274ad0
SH
1006 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1007 return $class::config_get_configuration_array($data);
8139ad13
SH
1008 }
1009 return array();
1010 }
1011
1012 /**
1013 * Get an array of stores that are suitable to be used for a given definition.
1014 *
1015 * @param string $component
1016 * @param string $area
1017 * @return array Array containing 3 elements
1018 * 1. An array of currently used stores
1019 * 2. An array of suitable stores
1020 * 3. An array of default stores
1021 */
1022 public static function get_definition_store_options($component, $area) {
1023 $factory = cache_factory::instance();
1024 $definition = $factory->create_definition($component, $area);
1025 $config = cache_config::instance();
1026 $currentstores = $config->get_stores_for_definition($definition);
1027 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
1028
1029 $defaults = array();
1030 foreach ($currentstores as $key => $store) {
1031 if (!empty($store['default'])) {
1032 $defaults[] = $key;
1033 unset($currentstores[$key]);
1034 }
1035 }
1036 foreach ($possiblestores as $key => $store) {
167ad91e 1037 if ($store['default']) {
8139ad13
SH
1038 unset($possiblestores[$key]);
1039 $possiblestores[$key] = $store;
1040 }
1041 }
1042 return array($currentstores, $possiblestores, $defaults);
1043 }
1044
1045 /**
1046 * Get the default stores for all modes.
1047 *
1048 * @return array An array containing sub-arrays, one for each mode.
1049 */
1050 public static function get_default_mode_stores() {
1051 $instance = cache_config::instance();
1052 $storenames = array();
1053 foreach ($instance->get_all_stores() as $key => $store) {
1054 if (!empty($store['default'])) {
1055 $storenames[$key] = new lang_string('store_'.$key, 'cache');
1056 }
1057 }
1058 $modemappings = array(
1059 cache_store::MODE_APPLICATION => array(),
1060 cache_store::MODE_SESSION => array(),
1061 cache_store::MODE_REQUEST => array(),
1062 );
1063 foreach ($instance->get_mode_mappings() as $mapping) {
1064 $mode = $mapping['mode'];
1065 if (!array_key_exists($mode, $modemappings)) {
1066 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
1067 continue;
1068 }
1069 if (array_key_exists($mapping['store'], $storenames)) {
1070 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
1071 } else {
1072 $modemappings[$mode][$mapping['store']] = $mapping['store'];
1073 }
1074 }
1075 return $modemappings;
1076 }
167ad91e
SH
1077
1078 /**
1079 * Returns an array summarising the locks available in the system
1080 */
1081 public static function get_lock_summaries() {
1082 $locks = array();
1083 $instance = cache_config::instance();
1084 $stores = $instance->get_all_stores();
1085 foreach ($instance->get_locks() as $lock) {
1086 $default = !empty($lock['default']);
1087 if ($default) {
1088 $name = new lang_string($lock['name'], 'cache');
1089 } else {
1090 $name = $lock['name'];
1091 }
1092 $uses = 0;
1093 foreach ($stores as $store) {
1094 if (!empty($store['lock']) && $store['lock'] === $lock['name']) {
1095 $uses++;
1096 }
1097 }
1098 $lockdata = array(
1099 'name' => $name,
1100 'default' => $default,
acf49f4b
SH
1101 'uses' => $uses,
1102 'type' => get_string('pluginname', $lock['type'])
167ad91e 1103 );
acf49f4b 1104 $locks[$lock['name']] = $lockdata;
167ad91e
SH
1105 }
1106 return $locks;
1107 }
acf49f4b
SH
1108
1109 /**
1110 * Returns an array of lock plugins for which we can add an instance.
1111 *
1112 * Suitable for use within an mform select element.
1113 *
1114 * @return array
1115 */
1116 public static function get_addable_lock_options() {
1117 $plugins = get_plugin_list_with_class('cachelock', '', 'lib.php');
1118 $options = array();
1119 $len = strlen('cachelock_');
1120 foreach ($plugins as $plugin => $class) {
1121 $method = "$class::can_add_instance";
1122 if (is_callable($method) && !call_user_func($method)) {
1123 // Can't add an instance of this plugin.
1124 continue;
1125 }
1126 $options[substr($plugin, $len)] = get_string('pluginname', $plugin);
1127 }
1128 return $options;
1129 }
1130
1131 /**
1132 * Gets the form to use when adding a lock instance.
1133 *
1134 * @param string $plugin
1135 * @param array $lockplugin
1136 * @return cache_lock_form
1137 * @throws coding_exception
1138 */
1139 public static function get_add_lock_form($plugin, array $lockplugin = null) {
1140 global $CFG; // Needed for includes.
1141 $plugins = get_plugin_list('cachelock');
1142 if (!array_key_exists($plugin, $plugins)) {
1143 throw new coding_exception('Invalid cache lock plugin requested when trying to create a form.');
1144 }
1145 $plugindir = $plugins[$plugin];
1146 $class = 'cache_lock_form';
1147 if (file_exists($plugindir.'/addinstanceform.php') && in_array('cache_is_configurable', class_implements($class))) {
1148 require_once($plugindir.'/addinstanceform.php');
1149 if (class_exists('cachelock_'.$plugin.'_addinstance_form')) {
1150 $class = 'cachelock_'.$plugin.'_addinstance_form';
1151 if (!array_key_exists('cache_lock_form', class_parents($class))) {
1152 throw new coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
1153 }
1154 }
1155 }
1156 return new $class(null, array('lock' => $plugin));
1157 }
1158
1159 /**
1160 * Gets configuration data from a new lock instance form.
1161 *
1162 * @param string $plugin
1163 * @param stdClass $data
1164 * @return array
1165 * @throws coding_exception
1166 */
1167 public static function get_lock_configuration_from_data($plugin, $data) {
1168 global $CFG;
1169 $file = $CFG->dirroot.'/cache/locks/'.$plugin.'/lib.php';
1170 if (!file_exists($file)) {
1171 throw new coding_exception('Invalid cache plugin provided. '.$file);
1172 }
1173 require_once($file);
1174 $class = 'cachelock_'.$plugin;
1175 if (!class_exists($class)) {
1176 throw new coding_exception('Invalid cache plugin provided.');
1177 }
1178 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1179 return $class::config_get_configuration_array($data);
1180 }
1181 return array();
1182 }
7866b094 1183}