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