2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * The library file for the MongoDB store plugin.
20 * This file is part of the MongoDB store plugin, it contains the API for interacting with an instance of the store.
22 * @package cachestore_mongodb
23 * @copyright 2012 Sam Hemelryk
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 * The MongoDB Cache store.
32 * This cache store uses the MongoDB Native Driver.
33 * For installation instructions have a look at the following two links:
34 * - {@link http://www.php.net/manual/en/mongo.installation.php}
35 * - {@link http://www.mongodb.org/display/DOCS/PHP+Language+Center}
37 * @copyright 2012 Sam Hemelryk
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class cachestore_mongodb extends cache_store implements cache_is_configurable {
43 * The name of the store
49 * The server connection string. Comma separated values.
52 protected $server = 'mongodb://127.0.0.1:27017';
55 * The database connection options
58 protected $options = array();
61 * The name of the database to use.
64 protected $databasename = 'mcache';
67 * The Connection object
70 protected $connection = false;
79 * The Collection object
80 * @var MongoCollection
82 protected $collection;
85 * Determines if and what safe setting is to be used.
88 protected $usesafe = false;
91 * If set to true then multiple identifiers will be requested and used.
94 protected $extendedmode = false;
97 * The definition has which is used in the construction of the collection.
100 protected $definitionhash = null;
103 * Set to true once this store is ready to be initialised and used.
106 protected $isready = false;
109 * Constructs a new instance of the Mongo store.
111 * Noting that this function is not an initialisation. It is used to prepare the store for use.
112 * The store will be initialised when required and will be provided with a cache_definition at that time.
114 * @param string $name
115 * @param array $configuration
117 public function __construct($name, array $configuration = array()) {
120 if (array_key_exists('server', $configuration)) {
121 $this->server = $configuration['server'];
124 if (array_key_exists('replicaset', $configuration)) {
125 $this->options['replicaSet'] = (string)$configuration['replicaset'];
127 if (array_key_exists('username', $configuration) && !empty($configuration['username'])) {
128 $this->options['username'] = (string)$configuration['username'];
130 if (array_key_exists('password', $configuration) && !empty($configuration['password'])) {
131 $this->options['password'] = (string)$configuration['password'];
133 if (array_key_exists('database', $configuration)) {
134 $this->databasename = (string)$configuration['database'];
136 if (array_key_exists('usesafe', $configuration)) {
137 $this->usesafe = $configuration['usesafe'];
139 if (array_key_exists('extendedmode', $configuration)) {
140 $this->extendedmode = $configuration['extendedmode'];
144 $this->connection = new Mongo($this->server, $this->options);
145 $this->isready = true;
146 } catch (MongoConnectionException $e) {
147 // We only want to catch MongoConnectionExceptions here.
152 * Returns true if the requirements of this store have been met.
155 public static function are_requirements_met() {
156 return class_exists('Mongo');
160 * Returns the supported features.
161 * @param array $configuration
164 public static function get_supported_features(array $configuration = array()) {
165 $supports = self::SUPPORTS_DATA_GUARANTEE;
166 if (array_key_exists('extendedmode', $configuration) && $configuration['extendedmode']) {
167 $supports += self::SUPPORTS_MULTIPLE_IDENTIFIERS;
173 * Returns an int describing the supported modes.
174 * @param array $configuration
177 public static function get_supported_modes(array $configuration = array()) {
178 return self::MODE_APPLICATION + self::MODE_SESSION;
182 * Initialises the store instance for use.
184 * Once this has been done the cache is all set to be used.
186 * @param cache_definition $definition
187 * @throws coding_exception
189 public function initialise(cache_definition $definition) {
190 if ($this->is_initialised()) {
191 throw new coding_exception('This mongodb instance has already been initialised.');
193 $this->database = $this->connection->selectDB($this->databasename);
194 $this->definitionhash = $definition->generate_definition_hash();
195 $this->collection = $this->database->selectCollection($this->definitionhash);
196 $this->collection->ensureIndex(array('key' => 1), array(
197 'safe' => $this->usesafe,
203 * Returns true if this store instance has been initialised.
206 public function is_initialised() {
207 return ($this->database instanceof MongoDB);
211 * Returns true if this store instance is ready to use.
214 public function is_ready() {
215 return $this->isready;
219 * Returns true if the given mode is supported by this store.
223 public static function is_supported_mode($mode) {
224 return ($mode == self::MODE_APPLICATION || $mode == self::MODE_SESSION);
228 * Returns true if this store is making use of multiple identifiers.
231 public function supports_multiple_identifiers() {
232 return $this->extendedmode;
236 * Retrieves an item from the cache store given its key.
238 * @param string $key The key to retrieve
239 * @return mixed The data that was associated with the key, or false if the key did not exist.
241 public function get($key) {
242 if (!is_array($key)) {
243 $key = array('key' => $key);
246 $result = $this->collection->findOne($key);
247 if ($result === null || !array_key_exists('data', $result)) {
250 $data = @unserialize($result['data']);
255 * Retrieves several items from the cache store in a single transaction.
257 * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
259 * @param array $keys The array of keys to retrieve
260 * @return array An array of items from the cache.
262 public function get_many($keys) {
263 if ($this->extendedmode) {
264 $query = $this->get_many_extendedmode_query($keys);
266 foreach ($keys as $key) {
267 $keyarray[] = $key['key'];
270 $query = array('key' => array('$in' => $keys));
272 $query = array('key' => array('$in' => $keys));
274 $cursor = $this->collection->find($query);
276 foreach ($cursor as $result) {
277 $id = (string)$result['key'];
278 $results[$id] = unserialize($result['data']);
280 foreach ($keys as $key) {
281 if (!array_key_exists($key, $results)) {
282 $results[$key] = false;
289 * Sets an item in the cache given its key and data value.
291 * @param string $key The key to use.
292 * @param mixed $data The data to set.
293 * @return bool True if the operation was a success false otherwise.
295 public function set($key, $data) {
296 if (!is_array($key)) {
303 $record['data'] = serialize($data);
306 'safe' => $this->usesafe,
307 'w' => $this->usesafe ? 1 : 0
310 $result = $this->collection->insert($record, $options);
311 if ($result === true) {
314 } else if (is_array($result)) {
315 if (empty($result['ok']) || isset($result['err'])) {
325 * Sets many items in the cache in a single transaction.
327 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
328 * keys, 'key' and 'value'.
329 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
330 * sent ... if they care that is.
332 public function set_many(array $keyvaluearray) {
334 foreach ($keyvaluearray as $pair) {
335 $result = $this->set($pair['key'], $pair['value']);
336 if ($result === true) {
344 * Deletes an item from the cache store.
346 * @param string $key The key to delete.
347 * @return bool Returns true if the operation was a success, false otherwise.
349 public function delete($key) {
350 if (!is_array($key)) {
359 'safe' => $this->usesafe,
360 'w' => $this->usesafe ? 1 : 0
362 $result = $this->collection->remove($criteria, $options);
364 if ($result === true) {
367 } else if (is_array($result)) {
368 if (empty($result['ok']) || isset($result['err'])) {
370 } else if (empty($result['n'])) {
371 // Nothing was removed.
381 * Deletes several keys from the cache in a single action.
383 * @param array $keys The keys to delete
384 * @return int The number of items successfully deleted.
386 public function delete_many(array $keys) {
388 foreach ($keys as $key) {
389 if ($this->delete($key)) {
397 * Purges the cache deleting all items within it.
399 * @return boolean True on success. False otherwise.
401 public function purge() {
402 if ($this->isready) {
403 $this->collection->drop();
404 $this->collection = $this->database->selectCollection($this->definitionhash);
411 * Takes the object from the add instance store and creates a configuration array that can be used to initialise an instance.
413 * @param stdClass $data
416 public static function config_get_configuration_array($data) {
418 'server' => $data->server,
419 'database' => $data->database,
420 'extendedmode' => (!empty($data->extendedmode))
422 if (!empty($data->username)) {
423 $return['username'] = $data->username;
425 if (!empty($data->password)) {
426 $return['password'] = $data->password;
428 if (!empty($data->replicaset)) {
429 $return['replicaset'] = $data->replicaset;
431 if (!empty($data->usesafe)) {
432 $return['usesafe'] = true;
433 if (!empty($data->usesafevalue)) {
434 $return['usesafe'] = (int)$data->usesafevalue;
435 $return['usesafevalue'] = $return['usesafe'];
442 * Allows the cache store to set its data against the edit form before it is shown to the user.
444 * @param moodleform $editform
445 * @param array $config
447 public static function config_set_edit_form_data(moodleform $editform, array $config) {
449 if (!empty($config['server'])) {
450 $data['server'] = $config['server'];
452 if (!empty($config['database'])) {
453 $data['database'] = $config['database'];
455 if (isset($config['extendedmode'])) {
456 $data['extendedmode'] = (bool)$config['extendedmode'];
458 if (!empty($config['username'])) {
459 $data['username'] = $config['username'];
461 if (!empty($config['password'])) {
462 $data['password'] = $config['password'];
464 if (!empty($config['replicaset'])) {
465 $data['replicaset'] = $config['replicaset'];
467 if (isset($config['usesafevalue'])) {
468 $data['usesafe'] = true;
469 $data['usesafevalue'] = (int)$data['usesafe'];
470 } else if (isset($config['usesafe'])) {
471 $data['usesafe'] = (bool)$config['usesafe'];
473 $editform->set_data($data);
477 * Performs any necessary clean up when the store instance is being deleted.
479 public function instance_deleted() {
480 // We can't use purge here that acts upon a collection.
481 // Instead we must drop the named database.
482 if ($this->connection) {
483 $connection = $this->connection;
486 $connection = new Mongo($this->server, $this->options);
487 } catch (MongoConnectionException $e) {
488 // We only want to catch MongoConnectionExceptions here.
489 // If the server cannot be connected to we cannot clean it.
493 $database = $connection->selectDB($this->databasename);
497 // Explicitly unset things to cause a close.
498 $this->collection = null;
499 $this->database = null;
500 $this->connection = null;
504 * Generates an instance of the cache store that can be used for testing.
506 * @param cache_definition $definition
509 public static function initialise_test_instance(cache_definition $definition) {
510 if (!self::are_requirements_met()) {
514 $config = get_config('cachestore_mongodb');
515 if (empty($config->testserver)) {
518 $configuration = array();
519 $configuration['server'] = $config->testserver;
520 if (!empty($config->testreplicaset)) {
521 $configuration['replicaset'] = $config->testreplicaset;
523 if (!empty($config->testusername)) {
524 $configuration['username'] = $config->testusername;
526 if (!empty($config->testpassword)) {
527 $configuration['password'] = $config->testpassword;
529 if (!empty($config->testdatabase)) {
530 $configuration['database'] = $config->testdatabase;
532 $configuration['usesafe'] = 1;
533 if (!empty($config->testextendedmode)) {
534 $configuration['extendedmode'] = (bool)$config->testextendedmode;
537 $store = new cachestore_mongodb('Test mongodb', $configuration);
538 $store->initialise($definition);
544 * Returns the name of this instance.
547 public function my_name() {