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