MDL-39554 cache: forced sharing options for static + request
[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) {
46e17f04
SH
554
555 // Preserve the selected sharing option when updating the definitions.
556 // This is set by the user and should never come from caches.php.
557 foreach ($definitions as $key => $definition) {
558 unset($definitions[$key]['selectedsharingoption']);
559 unset($definitions[$key]['userinputsharingkey']);
560 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['selectedsharingoption'])) {
561 $definitions[$key]['selectedsharingoption'] = $this->configdefinitions[$key]['selectedsharingoption'];
562 }
563 if (isset($this->configdefinitions[$key]) && isset($this->configdefinitions[$key]['userinputsharingkey'])) {
564 $definitions[$key]['userinputsharingkey'] = $this->configdefinitions[$key]['userinputsharingkey'];
565 }
566 }
567
8139ad13
SH
568 $this->configdefinitions = $definitions;
569 foreach ($this->configdefinitionmappings as $key => $mapping) {
570 if (!array_key_exists($mapping['definition'], $definitions)) {
571 unset($this->configdefinitionmappings[$key]);
572 }
573 }
574 $this->config_save();
575 }
576
577 /**
578 * Loads the caches file if it exists.
579 * @param string $file Absolute path to the file.
580 * @return array
581 */
582 private static function load_caches_file($file) {
583 if (!file_exists($file)) {
584 return array();
585 }
586 $definitions = array();
170f821b 587 include($file);
8139ad13
SH
588 return $definitions;
589 }
590
591 /**
592 * Sets the mappings for a given definition.
593 *
594 * @param string $definition
595 * @param array $mappings
596 * @throws coding_exception
597 */
598 public function set_definition_mappings($definition, $mappings) {
599 if (!array_key_exists($definition, $this->configdefinitions)) {
600 throw new coding_exception('Invalid definition name passed when updating mappings.');
601 }
602 foreach ($mappings as $store) {
603 if (!array_key_exists($store, $this->configstores)) {
604 throw new coding_exception('Invalid store name passed when updating definition mappings.');
605 }
606 }
607 foreach ($this->configdefinitionmappings as $key => $mapping) {
608 if ($mapping['definition'] == $definition) {
609 unset($this->configdefinitionmappings[$key]);
610 }
611 }
612 $sort = count($mappings);
613 foreach ($mappings as $store) {
614 $this->configdefinitionmappings[] = array(
615 'store' => $store,
616 'definition' => $definition,
617 'sort' => $sort
618 );
619 $sort--;
620 }
621
622 $this->config_save();
623 }
624
e0d9b7c0
SH
625 /**
626 * Update the site identifier stored by the cache API.
627 *
628 * @param string $siteidentifier
fe86ebfa 629 * @return string The new site identifier.
e0d9b7c0
SH
630 */
631 public function update_site_identifier($siteidentifier) {
632 $this->siteidentifier = md5((string)$siteidentifier);
633 $this->config_save();
fe86ebfa 634 return $this->siteidentifier;
e0d9b7c0 635 }
46e17f04
SH
636
637 /**
638 * Sets the selected sharing options and key for a definition.
639 *
640 * @param string $definition The name of the definition to set for.
641 * @param int $sharingoption The sharing option to set.
642 * @param string|null $userinputsharingkey The user input key or null.
643 * @throws coding_exception
644 */
645 public function set_definition_sharing($definition, $sharingoption, $userinputsharingkey = null) {
646 if (!array_key_exists($definition, $this->configdefinitions)) {
647 throw new coding_exception('Invalid definition name passed when updating sharing options.');
648 }
649 if (!($this->configdefinitions[$definition]['sharingoptions'] & $sharingoption)) {
650 throw new coding_exception('Invalid sharing option passed when updating definition.');
651 }
652 $this->configdefinitions[$definition]['selectedsharingoption'] = (int)$sharingoption;
653 if (!empty($userinputsharingkey)) {
654 $this->configdefinitions[$definition]['userinputsharingkey'] = (string)$userinputsharingkey;
655 }
656 $this->config_save();
657 }
658
8139ad13
SH
659}
660
661/**
662 * A cache helper for administration tasks
663 *
664 * @package core
665 * @category cache
666 * @copyright 2012 Sam Hemelryk
667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
668 */
669abstract class cache_administration_helper extends cache_helper {
670
671 /**
672 * Returns an array containing all of the information about stores a renderer needs.
673 * @return array
674 */
26ce56fd 675 public static function get_store_instance_summaries() {
8139ad13
SH
676 $return = array();
677 $default = array();
678 $instance = cache_config::instance();
679 $stores = $instance->get_all_stores();
acf49f4b 680 $locks = $instance->get_locks();
8139ad13
SH
681 foreach ($stores as $name => $details) {
682 $class = $details['class'];
683 $store = new $class($details['name'], $details['configuration']);
acf49f4b 684 $lock = (isset($details['lock'])) ? $locks[$details['lock']] : $instance->get_default_lock();
8139ad13
SH
685 $record = array(
686 'name' => $name,
687 'plugin' => $details['plugin'],
688 'default' => $details['default'],
689 'isready' => $store->is_ready(),
690 'requirementsmet' => $store->are_requirements_met(),
691 'mappings' => 0,
acf49f4b 692 'lock' => $lock,
8139ad13
SH
693 'modes' => array(
694 cache_store::MODE_APPLICATION =>
695 ($store->get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
696 cache_store::MODE_SESSION =>
697 ($store->get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
698 cache_store::MODE_REQUEST =>
699 ($store->get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
700 ),
701 'supports' => array(
758dbdf8 702 'multipleidentifiers' => $store->supports_multiple_identifiers(),
8139ad13
SH
703 'dataguarantee' => $store->supports_data_guarantee(),
704 'nativettl' => $store->supports_native_ttl(),
705 'nativelocking' => ($store instanceof cache_is_lockable),
706 'keyawareness' => ($store instanceof cache_is_key_aware),
dbd2ea4e 707 'searchable' => ($store instanceof cache_is_searchable)
8139ad13
SH
708 )
709 );
710 if (empty($details['default'])) {
711 $return[$name] = $record;
712 } else {
713 $default[$name] = $record;
714 }
715 }
716
717 ksort($return);
718 ksort($default);
719 $return = $return + $default;
720
8139ad13
SH
721 foreach ($instance->get_definition_mappings() as $mapping) {
722 if (!array_key_exists($mapping['store'], $return)) {
723 continue;
724 }
725 $return[$mapping['store']]['mappings']++;
726 }
727
728 return $return;
729 }
730
731 /**
732 * Returns an array of information about plugins, everything a renderer needs.
733 * @return array
734 */
26ce56fd 735 public static function get_store_plugin_summaries() {
8139ad13 736 $return = array();
6fec1820 737 $plugins = get_plugin_list_with_file('cachestore', 'lib.php', true);
8139ad13 738 foreach ($plugins as $plugin => $path) {
6fec1820 739 $class = 'cachestore_'.$plugin;
8139ad13 740 $return[$plugin] = array(
6fec1820 741 'name' => get_string('pluginname', 'cachestore_'.$plugin),
8139ad13
SH
742 'requirementsmet' => $class::are_requirements_met(),
743 'instances' => 0,
744 'modes' => array(
745 cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
746 cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
747 cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
748 ),
749 'supports' => array(
750 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
751 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
752 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
753 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
754 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
755 ),
7e7e108f 756 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
8139ad13
SH
757 );
758 }
759
760 $instance = cache_config::instance();
761 $stores = $instance->get_all_stores();
762 foreach ($stores as $store) {
763 $plugin = $store['plugin'];
764 if (array_key_exists($plugin, $return)) {
765 $return[$plugin]['instances']++;
766 }
767 }
768
769 return $return;
770 }
771
772 /**
773 * Returns an array about the definitions. All the information a renderer needs.
774 * @return array
775 */
776 public static function get_definition_summaries() {
777 $instance = cache_config::instance();
778 $definitions = $instance->get_definitions();
779
780 $storenames = array();
781 foreach ($instance->get_all_stores() as $key => $store) {
782 if (!empty($store['default'])) {
783 $storenames[$key] = new lang_string('store_'.$key, 'cache');
784 }
785 }
786
787 $modemappings = array();
788 foreach ($instance->get_mode_mappings() as $mapping) {
789 $mode = $mapping['mode'];
790 if (!array_key_exists($mode, $modemappings)) {
791 $modemappings[$mode] = array();
792 }
793 if (array_key_exists($mapping['store'], $storenames)) {
794 $modemappings[$mode][] = $storenames[$mapping['store']];
795 } else {
796 $modemappings[$mode][] = $mapping['store'];
797 }
798 }
799
800 $definitionmappings = array();
801 foreach ($instance->get_definition_mappings() as $mapping) {
802 $definition = $mapping['definition'];
803 if (!array_key_exists($definition, $definitionmappings)) {
804 $definitionmappings[$definition] = array();
805 }
806 if (array_key_exists($mapping['store'], $storenames)) {
807 $definitionmappings[$definition][] = $storenames[$mapping['store']];
808 } else {
809 $definitionmappings[$definition][] = $mapping['store'];
810 }
811 }
812
813 $return = array();
814
815 foreach ($definitions as $id => $definition) {
816
817 $mappings = array();
818 if (array_key_exists($id, $definitionmappings)) {
819 $mappings = $definitionmappings[$id];
820 } else if (empty($definition['mappingsonly'])) {
821 $mappings = $modemappings[$definition['mode']];
822 }
823
824 $return[$id] = array(
825 'id' => $id,
826 'name' => cache_helper::get_definition_name($definition),
827 'mode' => $definition['mode'],
828 'component' => $definition['component'],
829 'area' => $definition['area'],
46e17f04
SH
830 'mappings' => $mappings,
831 'sharingoptions' => self::get_definition_sharing_options($definition['sharingoptions'], false),
832 'selectedsharingoption' => self::get_definition_sharing_options($definition['selectedsharingoption'], true),
833 'userinputsharingkey' => $definition['userinputsharingkey']
8139ad13
SH
834 );
835 }
836 return $return;
837 }
838
46e17f04
SH
839 /**
840 * Given a sharing option hash this function returns an array of strings that can be used to describe it.
841 *
842 * @param int $sharingoption The sharing option hash to get strings for.
843 * @param bool $isselectedoptions Set to true if the strings will be used to view the selected options.
844 * @return array An array of lang_string's.
845 */
846 public static function get_definition_sharing_options($sharingoption, $isselectedoptions = true) {
847 $options = array();
848 $prefix = ($isselectedoptions) ? 'sharingselected' : 'sharing';
849 if ($sharingoption & cache_definition::SHARING_ALL) {
850 $options[cache_definition::SHARING_ALL] = new lang_string($prefix.'_all', 'cache');
851 }
852 if ($sharingoption & cache_definition::SHARING_SITEID) {
853 $options[cache_definition::SHARING_SITEID] = new lang_string($prefix.'_siteid', 'cache');
854 }
855 if ($sharingoption & cache_definition::SHARING_VERSION) {
856 $options[cache_definition::SHARING_VERSION] = new lang_string($prefix.'_version', 'cache');
857 }
858 if ($sharingoption & cache_definition::SHARING_INPUT) {
859 $options[cache_definition::SHARING_INPUT] = new lang_string($prefix.'_input', 'cache');
860 }
861 return $options;
862 }
863
8139ad13
SH
864 /**
865 * Returns all of the actions that can be performed on a definition.
866 * @param context $context
867 * @return array
868 */
869 public static function get_definition_actions(context $context) {
870 if (has_capability('moodle/site:config', $context)) {
871 return array(
46e17f04 872 // Edit mappings.
8139ad13
SH
873 array(
874 'text' => get_string('editmappings', 'cache'),
875 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping', 'sesskey' => sesskey()))
50523565 876 ),
46e17f04
SH
877 // Edit sharing.
878 array(
879 'text' => get_string('editsharing', 'cache'),
880 'url' => new moodle_url('/cache/admin.php', array('action' => 'editdefinitionsharing', 'sesskey' => sesskey()))
881 ),
882 // Purge.
50523565
SH
883 array(
884 'text' => get_string('purge', 'cache'),
885 'url' => new moodle_url('/cache/admin.php', array('action' => 'purgedefinition', 'sesskey' => sesskey()))
8139ad13
SH
886 )
887 );
888 }
889 return array();
890 }
891
892 /**
893 * Returns all of the actions that can be performed on a store.
894 *
895 * @param string $name The name of the store
896 * @param array $storedetails
897 * @return array
898 */
26ce56fd 899 public static function get_store_instance_actions($name, array $storedetails) {
8139ad13
SH
900 $actions = array();
901 if (has_capability('moodle/site:config', get_system_context())) {
902 $baseurl = new moodle_url('/cache/admin.php', array('store' => $name, 'sesskey' => sesskey()));
903 if (empty($storedetails['default'])) {
904 $actions[] = array(
905 'text' => get_string('editstore', 'cache'),
906 'url' => new moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin']))
907 );
908 $actions[] = array(
909 'text' => get_string('deletestore', 'cache'),
910 'url' => new moodle_url($baseurl, array('action' => 'deletestore'))
911 );
912 }
913 $actions[] = array(
914 'text' => get_string('purge', 'cache'),
50523565 915 'url' => new moodle_url($baseurl, array('action' => 'purgestore'))
8139ad13
SH
916 );
917 }
918 return $actions;
919 }
920
921
922 /**
923 * Returns all of the actions that can be performed on a plugin.
924 *
925 * @param string $name The name of the plugin
926 * @param array $plugindetails
927 * @return array
928 */
26ce56fd 929 public static function get_store_plugin_actions($name, array $plugindetails) {
8139ad13 930 $actions = array();
7e7e108f 931 if (has_capability('moodle/site:config', context_system::instance())) {
8139ad13
SH
932 if (!empty($plugindetails['canaddinstance'])) {
933 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore', 'plugin' => $name, 'sesskey' => sesskey()));
934 $actions[] = array(
935 'text' => get_string('addinstance', 'cache'),
936 'url' => $url
937 );
938 }
939 }
940 return $actions;
941 }
942
943 /**
944 * Returns a form that can be used to add a store instance.
945 *
946 * @param string $plugin The plugin to add an instance of
6fec1820 947 * @return cachestore_addinstance_form
8139ad13
SH
948 * @throws coding_exception
949 */
950 public static function get_add_store_form($plugin) {
170f821b 951 global $CFG; // Needed for includes.
42f2c59e
SH
952 $plugins = get_plugin_list('cachestore');
953 if (!array_key_exists($plugin, $plugins)) {
954 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
955 }
956 $plugindir = $plugins[$plugin];
6fec1820 957 $class = 'cachestore_addinstance_form';
8139ad13
SH
958 if (file_exists($plugindir.'/addinstanceform.php')) {
959 require_once($plugindir.'/addinstanceform.php');
6fec1820
SH
960 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
961 $class = 'cachestore_'.$plugin.'_addinstance_form';
962 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
963 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
8139ad13
SH
964 }
965 }
966 }
967
26ce56fd 968 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
167ad91e 969
8139ad13 970 $url = new moodle_url('/cache/admin.php', array('action' => 'addstore'));
167ad91e 971 return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
8139ad13
SH
972 }
973
974 /**
975 * Returns a form that can be used to edit a store instance.
976 *
977 * @param string $plugin
978 * @param string $store
6fec1820 979 * @return cachestore_addinstance_form
8139ad13
SH
980 * @throws coding_exception
981 */
982 public static function get_edit_store_form($plugin, $store) {
170f821b 983 global $CFG; // Needed for includes.
42f2c59e
SH
984 $plugins = get_plugin_list('cachestore');
985 if (!array_key_exists($plugin, $plugins)) {
986 throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
987 }
988 $factory = cache_factory::instance();
989 $config = $factory->create_config_instance();
990 $stores = $config->get_all_stores();
991 if (!array_key_exists($store, $stores)) {
992 throw new coding_exception('Invalid store name given when trying to create an edit form.');
993 }
994 $plugindir = $plugins[$plugin];
6fec1820 995 $class = 'cachestore_addinstance_form';
8139ad13
SH
996 if (file_exists($plugindir.'/addinstanceform.php')) {
997 require_once($plugindir.'/addinstanceform.php');
6fec1820
SH
998 if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
999 $class = 'cachestore_'.$plugin.'_addinstance_form';
1000 if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
1001 throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
8139ad13
SH
1002 }
1003 }
1004 }
1005
26ce56fd 1006 $locks = self::get_possible_locks_for_stores($plugindir, $plugin);
42f2c59e 1007
81ede547
SH
1008 $url = new moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
1009 $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
acf49f4b 1010 if (isset($stores[$store]['lock'])) {
25927c42 1011 $editform->set_data(array('lock' => $stores[$store]['lock']));
acf49f4b 1012 }
81ede547
SH
1013 // See if the cachestore is going to want to load data for the form.
1014 // If it has a customised add instance form then it is going to want to.
1015 $storeclass = 'cachestore_'.$plugin;
1016 $storedata = $stores[$store];
2b274ad0 1017 if (array_key_exists('configuration', $storedata) && array_key_exists('cache_is_configurable', class_implements($storeclass))) {
81ede547
SH
1018 $storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
1019 }
1020 return $editform;
42f2c59e
SH
1021 }
1022
1023 /**
1024 * Returns an array of suitable lock instances for use with this plugin, or false if the plugin handles locking itself.
1025 *
1026 * @param string $plugindir
1027 * @param string $plugin
1028 * @return array|false
1029 */
26ce56fd 1030 protected static function get_possible_locks_for_stores($plugindir, $plugin) {
42f2c59e
SH
1031 global $CFG; // Needed for includes.
1032 $supportsnativelocking = false;
1033 if (file_exists($plugindir.'/lib.php')) {
1034 require_once($plugindir.'/lib.php');
1035 $pluginclass = 'cachestore_'.$plugin;
1036 if (class_exists($pluginclass)) {
1037 $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
1038 }
1039 }
1040
1041 if (!$supportsnativelocking) {
1042 $config = cache_config::instance();
1043 $locks = array();
1044 foreach ($config->get_locks() as $lock => $conf) {
1045 if (!empty($conf['default'])) {
1046 $name = get_string($lock, 'cache');
1047 } else {
1048 $name = $lock;
1049 }
1050 $locks[$lock] = $name;
1051 }
1052 } else {
1053 $locks = false;
1054 }
1055
1056 return $locks;
8139ad13
SH
1057 }
1058
1059 /**
1060 * Processes the results of the add/edit instance form data for a plugin returning an array of config information suitable to
1061 * store in configuration.
1062 *
1063 * @param stdClass $data The mform data.
1064 * @return array
1065 * @throws coding_exception
1066 */
1067 public static function get_store_configuration_from_data(stdClass $data) {
1068 global $CFG;
1069 $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
1070 if (!file_exists($file)) {
1071 throw new coding_exception('Invalid cache plugin provided. '.$file);
1072 }
1073 require_once($file);
6fec1820 1074 $class = 'cachestore_'.$data->plugin;
8139ad13
SH
1075 if (!class_exists($class)) {
1076 throw new coding_exception('Invalid cache plugin provided.');
1077 }
2b274ad0
SH
1078 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1079 return $class::config_get_configuration_array($data);
8139ad13
SH
1080 }
1081 return array();
1082 }
1083
1084 /**
1085 * Get an array of stores that are suitable to be used for a given definition.
1086 *
1087 * @param string $component
1088 * @param string $area
1089 * @return array Array containing 3 elements
1090 * 1. An array of currently used stores
1091 * 2. An array of suitable stores
1092 * 3. An array of default stores
1093 */
1094 public static function get_definition_store_options($component, $area) {
1095 $factory = cache_factory::instance();
1096 $definition = $factory->create_definition($component, $area);
1097 $config = cache_config::instance();
1098 $currentstores = $config->get_stores_for_definition($definition);
1099 $possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
1100
1101 $defaults = array();
1102 foreach ($currentstores as $key => $store) {
1103 if (!empty($store['default'])) {
1104 $defaults[] = $key;
1105 unset($currentstores[$key]);
1106 }
1107 }
1108 foreach ($possiblestores as $key => $store) {
167ad91e 1109 if ($store['default']) {
8139ad13
SH
1110 unset($possiblestores[$key]);
1111 $possiblestores[$key] = $store;
1112 }
1113 }
1114 return array($currentstores, $possiblestores, $defaults);
1115 }
1116
1117 /**
1118 * Get the default stores for all modes.
1119 *
1120 * @return array An array containing sub-arrays, one for each mode.
1121 */
1122 public static function get_default_mode_stores() {
1123 $instance = cache_config::instance();
1124 $storenames = array();
1125 foreach ($instance->get_all_stores() as $key => $store) {
1126 if (!empty($store['default'])) {
1127 $storenames[$key] = new lang_string('store_'.$key, 'cache');
1128 }
1129 }
1130 $modemappings = array(
1131 cache_store::MODE_APPLICATION => array(),
1132 cache_store::MODE_SESSION => array(),
1133 cache_store::MODE_REQUEST => array(),
1134 );
1135 foreach ($instance->get_mode_mappings() as $mapping) {
1136 $mode = $mapping['mode'];
1137 if (!array_key_exists($mode, $modemappings)) {
1138 debugging('Unknown mode in cache store mode mappings', DEBUG_DEVELOPER);
1139 continue;
1140 }
1141 if (array_key_exists($mapping['store'], $storenames)) {
1142 $modemappings[$mode][$mapping['store']] = $storenames[$mapping['store']];
1143 } else {
1144 $modemappings[$mode][$mapping['store']] = $mapping['store'];
1145 }
1146 }
1147 return $modemappings;
1148 }
167ad91e
SH
1149
1150 /**
1151 * Returns an array summarising the locks available in the system
1152 */
1153 public static function get_lock_summaries() {
1154 $locks = array();
1155 $instance = cache_config::instance();
1156 $stores = $instance->get_all_stores();
1157 foreach ($instance->get_locks() as $lock) {
1158 $default = !empty($lock['default']);
1159 if ($default) {
1160 $name = new lang_string($lock['name'], 'cache');
1161 } else {
1162 $name = $lock['name'];
1163 }
1164 $uses = 0;
1165 foreach ($stores as $store) {
1166 if (!empty($store['lock']) && $store['lock'] === $lock['name']) {
1167 $uses++;
1168 }
1169 }
1170 $lockdata = array(
1171 'name' => $name,
1172 'default' => $default,
acf49f4b
SH
1173 'uses' => $uses,
1174 'type' => get_string('pluginname', $lock['type'])
167ad91e 1175 );
acf49f4b 1176 $locks[$lock['name']] = $lockdata;
167ad91e
SH
1177 }
1178 return $locks;
1179 }
acf49f4b
SH
1180
1181 /**
1182 * Returns an array of lock plugins for which we can add an instance.
1183 *
1184 * Suitable for use within an mform select element.
1185 *
1186 * @return array
1187 */
1188 public static function get_addable_lock_options() {
1189 $plugins = get_plugin_list_with_class('cachelock', '', 'lib.php');
1190 $options = array();
1191 $len = strlen('cachelock_');
1192 foreach ($plugins as $plugin => $class) {
1193 $method = "$class::can_add_instance";
1194 if (is_callable($method) && !call_user_func($method)) {
1195 // Can't add an instance of this plugin.
1196 continue;
1197 }
1198 $options[substr($plugin, $len)] = get_string('pluginname', $plugin);
1199 }
1200 return $options;
1201 }
1202
1203 /**
1204 * Gets the form to use when adding a lock instance.
1205 *
1206 * @param string $plugin
1207 * @param array $lockplugin
1208 * @return cache_lock_form
1209 * @throws coding_exception
1210 */
1211 public static function get_add_lock_form($plugin, array $lockplugin = null) {
1212 global $CFG; // Needed for includes.
1213 $plugins = get_plugin_list('cachelock');
1214 if (!array_key_exists($plugin, $plugins)) {
1215 throw new coding_exception('Invalid cache lock plugin requested when trying to create a form.');
1216 }
1217 $plugindir = $plugins[$plugin];
1218 $class = 'cache_lock_form';
1219 if (file_exists($plugindir.'/addinstanceform.php') && in_array('cache_is_configurable', class_implements($class))) {
1220 require_once($plugindir.'/addinstanceform.php');
1221 if (class_exists('cachelock_'.$plugin.'_addinstance_form')) {
1222 $class = 'cachelock_'.$plugin.'_addinstance_form';
1223 if (!array_key_exists('cache_lock_form', class_parents($class))) {
1224 throw new coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
1225 }
1226 }
1227 }
1228 return new $class(null, array('lock' => $plugin));
1229 }
1230
1231 /**
1232 * Gets configuration data from a new lock instance form.
1233 *
1234 * @param string $plugin
1235 * @param stdClass $data
1236 * @return array
1237 * @throws coding_exception
1238 */
1239 public static function get_lock_configuration_from_data($plugin, $data) {
1240 global $CFG;
1241 $file = $CFG->dirroot.'/cache/locks/'.$plugin.'/lib.php';
1242 if (!file_exists($file)) {
1243 throw new coding_exception('Invalid cache plugin provided. '.$file);
1244 }
1245 require_once($file);
1246 $class = 'cachelock_'.$plugin;
1247 if (!class_exists($class)) {
1248 throw new coding_exception('Invalid cache plugin provided.');
1249 }
1250 if (array_key_exists('cache_is_configurable', class_implements($class))) {
1251 return $class::config_get_configuration_array($data);
1252 }
1253 return array();
1254 }
7866b094 1255}