MDL-40947: Fix segmentation fault issue in get_fast_modinfo.
[moodle.git] / cache / classes / factory.php
blobe57d6ef077eeed13423f0358c4b9be15a044ae96
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.
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/>.
17 /**
18 * This file contains the cache factory class.
20 * This file is part of Moodle's cache API, affectionately called MUC.
21 * It contains the components that are requried in order to use caching.
23 * @package core
24 * @category cache
25 * @copyright 2012 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * The cache factory class.
34 * This factory class is important because it stores instances of objects used by the cache API and returns them upon requests.
35 * This allows us to both reuse objects saving on overhead, and gives us an easy place to "reset" the cache API in situations that
36 * we need such as unit testing.
38 * @copyright 2012 Sam Hemelryk
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 class cache_factory {
43 /** The cache has not been initialised yet. */
44 const STATE_UNINITIALISED = 0;
45 /** The cache is in the process of initialising itself. */
46 const STATE_INITIALISING = 1;
47 /** The cache is in the process of saving its configuration file. */
48 const STATE_SAVING = 2;
49 /** The cache is ready to use. */
50 const STATE_READY = 3;
51 /** The cache is currently updating itself */
52 const STATE_UPDATING = 4;
53 /** The cache encountered an error while initialising. */
54 const STATE_ERROR_INITIALISING = 9;
55 /** The cache has been disabled. */
56 const STATE_DISABLED = 10;
57 /** The cache stores have been disabled */
58 const STATE_STORES_DISABLED = 11;
60 /**
61 * An instance of the cache_factory class created upon the first request.
62 * @var cache_factory
64 protected static $instance;
66 /**
67 * An array containing caches created for definitions
68 * @var array
70 protected $cachesfromdefinitions = array();
72 /**
73 * Array of caches created by parameters, ad-hoc definitions will have been used.
74 * @var array
76 protected $cachesfromparams = array();
78 /**
79 * An array of stores organised by definitions.
80 * @var array
82 protected $definitionstores = array();
84 /**
85 * An array of instantiated stores.
86 * @var array
88 protected $stores = array();
90 /**
91 * An array of configuration instances
92 * @var array
94 protected $configs = array();
96 /**
97 * An array of initialised definitions
98 * @var array
100 protected $definitions = array();
103 * An array of lock plugins.
104 * @var array
106 protected $lockplugins = array();
109 * The current state of the cache API.
110 * @var int
112 protected $state = 0;
115 * Returns an instance of the cache_factor method.
117 * @param bool $forcereload If set to true a new cache_factory instance will be created and used.
118 * @return cache_factory
120 public static function instance($forcereload = false) {
121 global $CFG;
122 if ($forcereload || self::$instance === null) {
123 // Initialise a new factory to facilitate our needs.
124 if (defined('CACHE_DISABLE_ALL') && CACHE_DISABLE_ALL !== false) {
125 // The cache has been disabled. Load disabledlib and start using the factory designed to handle this
126 // situation. It will use disabled alternatives where available.
127 require_once($CFG->dirroot.'/cache/disabledlib.php');
128 self::$instance = new cache_factory_disabled();
129 } else {
130 // We're using the regular factory.
131 self::$instance = new cache_factory();
132 if (defined('CACHE_DISABLE_STORES') && CACHE_DISABLE_STORES !== false) {
133 // The cache stores have been disabled.
134 self::$instance->set_state(self::STATE_STORES_DISABLED);
138 return self::$instance;
142 * Protected constructor, please use the static instance method.
144 protected function __construct() {
145 // Nothing to do here.
149 * Resets the arrays containing instantiated caches, stores, and config instances.
151 public static function reset() {
152 $factory = self::instance();
153 $factory->cachesfromdefinitions = array();
154 $factory->cachesfromparams = array();
155 $factory->stores = array();
156 $factory->configs = array();
157 $factory->definitions = array();
158 $factory->lockplugins = array(); // MUST be null in order to force its regeneration.
159 // Reset the state to uninitialised.
160 $factory->state = self::STATE_UNINITIALISED;
164 * Creates a cache object given the parameters for a definition.
166 * If a cache has already been created for the given definition then that cache instance will be returned.
168 * @param string $component
169 * @param string $area
170 * @param array $identifiers
171 * @param string $aggregate
172 * @return cache_application|cache_session|cache_request
174 public function create_cache_from_definition($component, $area, array $identifiers = array(), $aggregate = null) {
175 $definitionname = $component.'/'.$area;
176 if (array_key_exists($definitionname, $this->cachesfromdefinitions)) {
177 $cache = $this->cachesfromdefinitions[$definitionname];
178 $cache->set_identifiers($identifiers);
179 return $cache;
181 $definition = $this->create_definition($component, $area, $aggregate);
182 $definition->set_identifiers($identifiers);
183 $cache = $this->create_cache($definition, $identifiers);
184 if ($definition->should_be_persistent()) {
185 $this->cachesfromdefinitions[$definitionname] = $cache;
187 return $cache;
191 * Creates an ad-hoc cache from the given param.
193 * If a cache has already been created using the same params then that cache instance will be returned.
195 * @param int $mode
196 * @param string $component
197 * @param string $area
198 * @param array $identifiers
199 * @param array $options An array of options, available options are:
200 * - simplekeys : Set to true if the keys you will use are a-zA-Z0-9_
201 * - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
202 * - persistent : If set to true the cache will persist construction requests.
203 * @return cache_application|cache_session|cache_request
205 public function create_cache_from_params($mode, $component, $area, array $identifiers = array(), array $options = array()) {
206 $key = "{$mode}_{$component}_{$area}";
207 if (array_key_exists($key, $this->cachesfromparams)) {
208 return $this->cachesfromparams[$key];
210 $definition = cache_definition::load_adhoc($mode, $component, $area, $options);
211 $definition->set_identifiers($identifiers);
212 $cache = $this->create_cache($definition, $identifiers);
213 if ($definition->should_be_persistent()) {
214 $this->cachesfromparams[$key] = $cache;
216 return $cache;
220 * Common public method to create a cache instance given a definition.
222 * This is used by the static make methods.
224 * @param cache_definition $definition
225 * @return cache_application|cache_session|cache_store
226 * @throws coding_exception
228 public function create_cache(cache_definition $definition) {
229 $class = $definition->get_cache_class();
230 if ($this->is_initialising()) {
231 // Do nothing we just want the dummy store.
232 $stores = array();
233 } else {
234 $stores = cache_helper::get_cache_stores($definition);
236 if (count($stores) === 0) {
237 // Hmm no stores, better provide a dummy store to mimick functionality. The dev will be none the wiser.
238 $stores[] = $this->create_dummy_store($definition);
240 $loader = null;
241 if ($definition->has_data_source()) {
242 $loader = $definition->get_data_source();
244 while (($store = array_pop($stores)) !== null) {
245 $loader = new $class($definition, $store, $loader);
247 return $loader;
251 * Creates a store instance given its name and configuration.
253 * If the store has already been instantiated then the original objetc will be returned. (reused)
255 * @param string $name The name of the store (must be unique remember)
256 * @param array $details
257 * @param cache_definition $definition The definition to instantiate it for.
258 * @return boolean|cache_store
260 public function create_store_from_config($name, array $details, cache_definition $definition) {
261 if (!array_key_exists($name, $this->stores)) {
262 // Properties: name, plugin, configuration, class.
263 $class = $details['class'];
264 $store = new $class($details['name'], $details['configuration']);
265 $this->stores[$name] = $store;
267 $store = $this->stores[$name];
268 if (!$store->is_ready() || !$store->is_supported_mode($definition->get_mode())) {
269 return false;
271 // We always create a clone of the original store.
272 // If we were to clone a store that had already been initialised with a definition then
273 // we'd run into a myriad of issues.
274 // We use a method of the store to create a clone rather than just creating it ourselves
275 // so that if any store out there doesn't handle cloning they can override this method in
276 // order to address the issues.
277 $store = $this->stores[$name]->create_clone($details);
278 $store->initialise($definition);
279 $definitionid = $definition->get_id();
280 if (!isset($this->definitionstores[$definitionid])) {
281 $this->definitionstores[$definitionid] = array();
283 $this->definitionstores[$definitionid][] = $store;
284 return $store;
288 * Returns an array of cache stores that have been initialised for use in definitions.
289 * @param cache_definition $definition
290 * @return array
292 public function get_store_instances_in_use(cache_definition $definition) {
293 $id = $definition->get_id();
294 if (!isset($this->definitionstores[$id])) {
295 return array();
297 return $this->definitionstores[$id];
301 * Creates a cache config instance with the ability to write if required.
303 * @param bool $writer If set to true an instance that can update the configuration will be returned.
304 * @return cache_config|cache_config_writer
306 public function create_config_instance($writer = false) {
307 global $CFG;
309 // Check if we need to create a config file with defaults.
310 $needtocreate = !cache_config::config_file_exists();
312 // The class to use.
313 $class = 'cache_config';
314 if ($writer || $needtocreate) {
315 require_once($CFG->dirroot.'/cache/locallib.php');
316 $class .= '_writer';
319 // Check if this is a PHPUnit test and redirect to the phpunit config classes if it is.
320 if (defined('PHPUNIT_TEST') && PHPUNIT_TEST) {
321 require_once($CFG->dirroot.'/cache/locallib.php');
322 require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
323 // We have just a single class for PHP unit tests. We don't care enough about its
324 // performance to do otherwise and having a single method allows us to inject things into it
325 // while testing.
326 $class = 'cache_config_phpunittest';
329 $error = false;
330 if ($needtocreate) {
331 // Create the default configuration.
332 // Update the state, we are now initialising the cache.
333 self::set_state(self::STATE_INITIALISING);
334 $configuration = $class::create_default_configuration();
335 if ($configuration !== true) {
336 // Failed to create the default configuration. Disable the cache stores and update the state.
337 self::set_state(self::STATE_ERROR_INITIALISING);
338 $this->configs[$class] = new $class;
339 $this->configs[$class]->load($configuration);
340 $error = true;
344 if (!array_key_exists($class, $this->configs)) {
345 // Create a new instance and call it to load it.
346 $this->configs[$class] = new $class;
347 $this->configs[$class]->load();
350 if (!$error) {
351 // The cache is now ready to use. Update the state.
352 self::set_state(self::STATE_READY);
355 // Return the instance.
356 return $this->configs[$class];
360 * Creates a definition instance or returns the existing one if it has already been created.
361 * @param string $component
362 * @param string $area
363 * @param string $aggregate
364 * @return cache_definition
366 public function create_definition($component, $area, $aggregate = null) {
367 $id = $component.'/'.$area;
368 if ($aggregate) {
369 $id .= '::'.$aggregate;
371 if (!array_key_exists($id, $this->definitions)) {
372 // This is the first time this definition has been requested.
373 if ($this->is_initialising()) {
374 // We're initialising the cache right now. Don't try to create another config instance.
375 // We'll just use an ad-hoc cache for the time being.
376 $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
377 } else {
378 // Load all the known definitions and find the desired one.
379 $instance = $this->create_config_instance();
380 $definition = $instance->get_definition_by_id($id);
381 if (!$definition) {
382 // Oh-oh the definition doesn't exist.
383 // There are several things that could be going on here.
384 // We may be installing/upgrading a site and have hit a definition that hasn't been used before.
385 // Of the developer may be trying to use a newly created definition.
386 if ($this->is_updating()) {
387 // The cache is presently initialising and the requested cache definition has not been found.
388 // This means that the cache initialisation has requested something from a cache (I had recursive nightmares about this).
389 // To serve this purpose and avoid errors we are going to make use of an ad-hoc cache rather than
390 // search for the definition which would possibly cause an infitite loop trying to initialise the cache.
391 $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
392 if ($aggregate !== null) {
393 // If you get here you deserve a warning. We have to use an ad-hoc cache here, so we can't find the definition and therefor
394 // can't find any information about the datasource or any of its aggregated.
395 // Best of luck.
396 debugging('An unknown cache was requested during development with an aggregate that could not be loaded. Ad-hoc cache used instead.', DEBUG_DEVELOPER);
397 $aggregate = null;
399 } else {
400 // Either a typo of the developer has just created the definition and is using it for the first time.
401 $this->reset();
402 $instance = $this->create_config_instance(true);
403 $instance->update_definitions();
404 $definition = $instance->get_definition_by_id($id);
405 if (!$definition) {
406 throw new coding_exception('The requested cache definition does not exist.'. $id, $id);
407 } else if (!$this->is_disabled()) {
408 debugging('Cache definitions reparsed causing cache reset in order to locate definition.
409 You should bump the version number to ensure definitions are reprocessed.', DEBUG_DEVELOPER);
411 $definition = cache_definition::load($id, $definition, $aggregate);
413 } else {
414 $definition = cache_definition::load($id, $definition, $aggregate);
417 $this->definitions[$id] = $definition;
419 return $this->definitions[$id];
423 * Creates a dummy store object for use when a loader has no potential stores to use.
425 * @param cache_definition $definition
426 * @return cachestore_dummy
428 protected function create_dummy_store(cache_definition $definition) {
429 global $CFG;
430 require_once($CFG->dirroot.'/cache/classes/dummystore.php');
431 $store = new cachestore_dummy();
432 $store->initialise($definition);
433 return $store;
437 * Returns a lock instance ready for use.
439 * @param array $config
440 * @return cache_lock_interface
442 public function create_lock_instance(array $config) {
443 global $CFG;
444 if (!array_key_exists('name', $config) || !array_key_exists('type', $config)) {
445 throw new coding_exception('Invalid cache lock instance provided');
447 $name = $config['name'];
448 $type = $config['type'];
449 unset($config['name']);
450 unset($config['type']);
452 if (!isset($this->lockplugins[$type])) {
453 $pluginname = substr($type, 10);
454 $file = $CFG->dirroot."/cache/locks/{$pluginname}/lib.php";
455 if (file_exists($file) && is_readable($file)) {
456 require_once($file);
458 if (!class_exists($type)) {
459 throw new coding_exception('Invalid lock plugin requested.');
461 $this->lockplugins[$type] = $type;
463 if (!array_key_exists($type, $this->lockplugins)) {
464 throw new coding_exception('Invalid cache lock type.');
466 $class = $this->lockplugins[$type];
467 return new $class($name, $config);
471 * Returns the current state of the cache API.
473 * @return int
475 public function get_state() {
476 return $this->state;
480 * Updates the state fo the cache API.
482 * @param int $state
483 * @return bool
485 public function set_state($state) {
486 if ($state <= $this->state) {
487 return false;
489 $this->state = $state;
490 return true;
494 * Informs the factory that the cache is currently updating itself.
496 * This forces the state to upgrading and can only be called once the cache is ready to use.
497 * Calling it ensure we don't try to reinstantite things when requesting cache definitions that don't exist yet.
499 public function updating_started() {
500 if ($this->state !== self::STATE_READY) {
501 return false;
503 $this->state = self::STATE_UPDATING;
504 return true;
508 * Informs the factory that the upgrading has finished.
510 * This forces the state back to ready.
512 public function updating_finished() {
513 $this->state = self::STATE_READY;
517 * Returns true if the cache API has been disabled.
519 * @return bool
521 public function is_disabled() {
522 return $this->state === self::STATE_DISABLED;
526 * Returns true if the cache is currently initialising itself.
528 * This includes both initialisation and saving the cache config file as part of that initialisation.
530 * @return bool
532 public function is_initialising() {
533 return $this->state === self::STATE_INITIALISING || $this->state === self::STATE_SAVING;
537 * Returns true if the cache is currently updating itself.
539 * @return bool
541 public function is_updating() {
542 return $this->state === self::STATE_UPDATING;
546 * Disables as much of the cache API as possible.
548 * All of the magic associated with the disabled cache is wrapped into this function.
549 * In switching out the factory for the disabled factory it gains full control over the initialisation of objects
550 * and can use all of the disabled alternatives.
551 * Simple!
553 * This function has been marked as protected so that it cannot be abused through the public API presently.
554 * Perhaps in the future we will allow this, however as per the build up to the first release containing
555 * MUC it was decided that this was just to risky and abusable.
557 protected static function disable() {
558 global $CFG;
559 require_once($CFG->dirroot.'/cache/disabledlib.php');
560 self::$instance = new cache_factory_disabled();
564 * Returns true if the cache stores have been disabled.
566 * @return bool
568 public function stores_disabled() {
569 return $this->state === self::STATE_STORES_DISABLED || $this->is_disabled();
573 * Disables cache stores.
575 * The cache API will continue to function however none of the actual stores will be used.
576 * Instead the dummy store will be provided for all cache requests.
577 * This is useful in situations where you cannot be sure any stores are working.
579 * In order to re-enable the cache you must call the cache factories static reset method:
580 * <code>
581 * // Disable the cache factory.
582 * cache_factory::disable_stores();
583 * // Re-enable the cache factory by resetting it.
584 * cache_factory::reset();
585 * </code>
587 public static function disable_stores() {
588 $factory = self::instance();
589 $factory->set_state(self::STATE_STORES_DISABLED);