Upgraded drupal core with security updates
[yaffs-website] / web / core / lib / Drupal / Core / Cache / DatabaseBackend.php
1 <?php
2
3 namespace Drupal\Core\Cache;
4
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Core\Database\Connection;
7 use Drupal\Core\Database\SchemaObjectExistsException;
8
9 /**
10  * Defines a default cache implementation.
11  *
12  * This is Drupal's default cache implementation. It uses the database to store
13  * cached data. Each cache bin corresponds to a database table by the same name.
14  *
15  * @ingroup cache
16  */
17 class DatabaseBackend implements CacheBackendInterface {
18
19   /**
20    * @var string
21    */
22   protected $bin;
23
24
25   /**
26    * The database connection.
27    *
28    * @var \Drupal\Core\Database\Connection
29    */
30   protected $connection;
31
32   /**
33    * The cache tags checksum provider.
34    *
35    * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
36    */
37   protected $checksumProvider;
38
39   /**
40    * Constructs a DatabaseBackend object.
41    *
42    * @param \Drupal\Core\Database\Connection $connection
43    *   The database connection.
44    * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
45    *   The cache tags checksum provider.
46    * @param string $bin
47    *   The cache bin for which the object is created.
48    */
49   public function __construct(Connection $connection, CacheTagsChecksumInterface $checksum_provider, $bin) {
50     // All cache tables should be prefixed with 'cache_'.
51     $bin = 'cache_' . $bin;
52
53     $this->bin = $bin;
54     $this->connection = $connection;
55     $this->checksumProvider = $checksum_provider;
56   }
57
58   /**
59    * {@inheritdoc}
60    */
61   public function get($cid, $allow_invalid = FALSE) {
62     $cids = [$cid];
63     $cache = $this->getMultiple($cids, $allow_invalid);
64     return reset($cache);
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public function getMultiple(&$cids, $allow_invalid = FALSE) {
71     $cid_mapping = [];
72     foreach ($cids as $cid) {
73       $cid_mapping[$this->normalizeCid($cid)] = $cid;
74     }
75     // When serving cached pages, the overhead of using ::select() was found
76     // to add around 30% overhead to the request. Since $this->bin is a
77     // variable, this means the call to ::query() here uses a concatenated
78     // string. This is highly discouraged under any other circumstances, and
79     // is used here only due to the performance overhead we would incur
80     // otherwise. When serving an uncached page, the overhead of using
81     // ::select() is a much smaller proportion of the request.
82     $result = [];
83     try {
84       $result = $this->connection->query('SELECT cid, data, created, expire, serialized, tags, checksum FROM {' . $this->connection->escapeTable($this->bin) . '} WHERE cid IN ( :cids[] ) ORDER BY cid', [':cids[]' => array_keys($cid_mapping)]);
85     }
86     catch (\Exception $e) {
87       // Nothing to do.
88     }
89     $cache = [];
90     foreach ($result as $item) {
91       // Map the cache ID back to the original.
92       $item->cid = $cid_mapping[$item->cid];
93       $item = $this->prepareItem($item, $allow_invalid);
94       if ($item) {
95         $cache[$item->cid] = $item;
96       }
97     }
98     $cids = array_diff($cids, array_keys($cache));
99     return $cache;
100   }
101
102   /**
103    * Prepares a cached item.
104    *
105    * Checks that items are either permanent or did not expire, and unserializes
106    * data as appropriate.
107    *
108    * @param object $cache
109    *   An item loaded from cache_get() or cache_get_multiple().
110    * @param bool $allow_invalid
111    *   If FALSE, the method returns FALSE if the cache item is not valid.
112    *
113    * @return mixed|false
114    *   The item with data unserialized as appropriate and a property indicating
115    *   whether the item is valid, or FALSE if there is no valid item to load.
116    */
117   protected function prepareItem($cache, $allow_invalid) {
118     if (!isset($cache->data)) {
119       return FALSE;
120     }
121
122     $cache->tags = $cache->tags ? explode(' ', $cache->tags) : [];
123
124     // Check expire time.
125     $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
126
127     // Check if invalidateTags() has been called with any of the items's tags.
128     if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
129       $cache->valid = FALSE;
130     }
131
132     if (!$allow_invalid && !$cache->valid) {
133       return FALSE;
134     }
135
136     // Unserialize and return the cached data.
137     if ($cache->serialized) {
138       $cache->data = unserialize($cache->data);
139     }
140
141     return $cache;
142   }
143
144   /**
145    * {@inheritdoc}
146    */
147   public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
148     $this->setMultiple([
149       $cid => [
150         'data' => $data,
151         'expire' => $expire,
152         'tags' => $tags,
153       ],
154     ]);
155   }
156
157   /**
158    * {@inheritdoc}
159    */
160   public function setMultiple(array $items) {
161     $try_again = FALSE;
162     try {
163       // The bin might not yet exist.
164       $this->doSetMultiple($items);
165     }
166     catch (\Exception $e) {
167       // If there was an exception, try to create the bins.
168       if (!$try_again = $this->ensureBinExists()) {
169         // If the exception happened for other reason than the missing bin
170         // table, propagate the exception.
171         throw $e;
172       }
173     }
174     // Now that the bin has been created, try again if necessary.
175     if ($try_again) {
176       $this->doSetMultiple($items);
177     }
178   }
179
180   /**
181    * Stores multiple items in the persistent cache.
182    *
183    * @param array $items
184    *   An array of cache items, keyed by cid.
185    *
186    * @see \Drupal\Core\Cache\CacheBackendInterface::setMultiple()
187    */
188   protected function doSetMultiple(array $items) {
189     $values = [];
190
191     foreach ($items as $cid => $item) {
192       $item += [
193         'expire' => CacheBackendInterface::CACHE_PERMANENT,
194         'tags' => [],
195       ];
196
197       assert('\Drupal\Component\Assertion\Inspector::assertAllStrings($item[\'tags\'])', 'Cache Tags must be strings.');
198       $item['tags'] = array_unique($item['tags']);
199       // Sort the cache tags so that they are stored consistently in the DB.
200       sort($item['tags']);
201
202       $fields = [
203         'cid' => $this->normalizeCid($cid),
204         'expire' => $item['expire'],
205         'created' => round(microtime(TRUE), 3),
206         'tags' => implode(' ', $item['tags']),
207         'checksum' => $this->checksumProvider->getCurrentChecksum($item['tags']),
208       ];
209
210       if (!is_string($item['data'])) {
211         $fields['data'] = serialize($item['data']);
212         $fields['serialized'] = 1;
213       }
214       else {
215         $fields['data'] = $item['data'];
216         $fields['serialized'] = 0;
217       }
218       $values[] = $fields;
219     }
220
221     // Use an upsert query which is atomic and optimized for multiple-row
222     // merges.
223     $query = $this->connection
224       ->upsert($this->bin)
225       ->key('cid')
226       ->fields(['cid', 'expire', 'created', 'tags', 'checksum', 'data', 'serialized']);
227     foreach ($values as $fields) {
228       // Only pass the values since the order of $fields matches the order of
229       // the insert fields. This is a performance optimization to avoid
230       // unnecessary loops within the method.
231       $query->values(array_values($fields));
232     }
233
234     $query->execute();
235   }
236
237   /**
238    * {@inheritdoc}
239    */
240   public function delete($cid) {
241     $this->deleteMultiple([$cid]);
242   }
243
244   /**
245    * {@inheritdoc}
246    */
247   public function deleteMultiple(array $cids) {
248     $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
249     try {
250       // Delete in chunks when a large array is passed.
251       foreach (array_chunk($cids, 1000) as $cids_chunk) {
252         $this->connection->delete($this->bin)
253           ->condition('cid', $cids_chunk, 'IN')
254           ->execute();
255       }
256     }
257     catch (\Exception $e) {
258       // Create the cache table, which will be empty. This fixes cases during
259       // core install where a cache table is cleared before it is set
260       // with {cache_render} and {cache_data}.
261       if (!$this->ensureBinExists()) {
262         $this->catchException($e);
263       }
264     }
265   }
266
267   /**
268    * {@inheritdoc}
269    */
270   public function deleteAll() {
271     try {
272       $this->connection->truncate($this->bin)->execute();
273     }
274     catch (\Exception $e) {
275       // Create the cache table, which will be empty. This fixes cases during
276       // core install where a cache table is cleared before it is set
277       // with {cache_render} and {cache_data}.
278       if (!$this->ensureBinExists()) {
279         $this->catchException($e);
280       }
281     }
282   }
283
284   /**
285    * {@inheritdoc}
286    */
287   public function invalidate($cid) {
288     $this->invalidateMultiple([$cid]);
289   }
290
291   /**
292    * {@inheritdoc}
293    */
294   public function invalidateMultiple(array $cids) {
295     $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
296     try {
297       // Update in chunks when a large array is passed.
298       foreach (array_chunk($cids, 1000) as $cids_chunk) {
299         $this->connection->update($this->bin)
300           ->fields(['expire' => REQUEST_TIME - 1])
301           ->condition('cid', $cids_chunk, 'IN')
302           ->execute();
303       }
304     }
305     catch (\Exception $e) {
306       $this->catchException($e);
307     }
308   }
309
310   /**
311    * {@inheritdoc}
312    */
313   public function invalidateAll() {
314     try {
315       $this->connection->update($this->bin)
316         ->fields(['expire' => REQUEST_TIME - 1])
317         ->execute();
318     }
319     catch (\Exception $e) {
320       $this->catchException($e);
321     }
322   }
323
324   /**
325    * {@inheritdoc}
326    */
327   public function garbageCollection() {
328     try {
329       $this->connection->delete($this->bin)
330         ->condition('expire', Cache::PERMANENT, '<>')
331         ->condition('expire', REQUEST_TIME, '<')
332         ->execute();
333     }
334     catch (\Exception $e) {
335       // If the table does not exist, it surely does not have garbage in it.
336       // If the table exists, the next garbage collection will clean up.
337       // There is nothing to do.
338     }
339   }
340
341   /**
342    * {@inheritdoc}
343    */
344   public function removeBin() {
345     try {
346       $this->connection->schema()->dropTable($this->bin);
347     }
348     catch (\Exception $e) {
349       $this->catchException($e);
350     }
351   }
352
353   /**
354    * Check if the cache bin exists and create it if not.
355    */
356   protected function ensureBinExists() {
357     try {
358       $database_schema = $this->connection->schema();
359       if (!$database_schema->tableExists($this->bin)) {
360         $schema_definition = $this->schemaDefinition();
361         $database_schema->createTable($this->bin, $schema_definition);
362         return TRUE;
363       }
364     }
365     // If another process has already created the cache table, attempting to
366     // recreate it will throw an exception. In this case just catch the
367     // exception and do nothing.
368     catch (SchemaObjectExistsException $e) {
369       return TRUE;
370     }
371     return FALSE;
372   }
373
374   /**
375    * Act on an exception when cache might be stale.
376    *
377    * If the table does not yet exist, that's fine, but if the table exists and
378    * yet the query failed, then the cache is stale and the exception needs to
379    * propagate.
380    *
381    * @param $e
382    *   The exception.
383    * @param string|null $table_name
384    *   The table name. Defaults to $this->bin.
385    *
386    * @throws \Exception
387    */
388   protected function catchException(\Exception $e, $table_name = NULL) {
389     if ($this->connection->schema()->tableExists($table_name ?: $this->bin)) {
390       throw $e;
391     }
392   }
393
394   /**
395    * Normalizes a cache ID in order to comply with database limitations.
396    *
397    * @param string $cid
398    *   The passed in cache ID.
399    *
400    * @return string
401    *   An ASCII-encoded cache ID that is at most 255 characters long.
402    */
403   protected function normalizeCid($cid) {
404     // Nothing to do if the ID is a US ASCII string of 255 characters or less.
405     $cid_is_ascii = mb_check_encoding($cid, 'ASCII');
406     if (strlen($cid) <= 255 && $cid_is_ascii) {
407       return $cid;
408     }
409     // Return a string that uses as much as possible of the original cache ID
410     // with the hash appended.
411     $hash = Crypt::hashBase64($cid);
412     if (!$cid_is_ascii) {
413       return $hash;
414     }
415     return substr($cid, 0, 255 - strlen($hash)) . $hash;
416   }
417
418   /**
419    * Defines the schema for the {cache_*} bin tables.
420    */
421   public function schemaDefinition() {
422     $schema = [
423       'description' => 'Storage for the cache API.',
424       'fields' => [
425         'cid' => [
426           'description' => 'Primary Key: Unique cache ID.',
427           'type' => 'varchar_ascii',
428           'length' => 255,
429           'not null' => TRUE,
430           'default' => '',
431           'binary' => TRUE,
432         ],
433         'data' => [
434           'description' => 'A collection of data to cache.',
435           'type' => 'blob',
436           'not null' => FALSE,
437           'size' => 'big',
438         ],
439         'expire' => [
440           'description' => 'A Unix timestamp indicating when the cache entry should expire, or ' . Cache::PERMANENT . ' for never.',
441           'type' => 'int',
442           'not null' => TRUE,
443           'default' => 0,
444         ],
445         'created' => [
446           'description' => 'A timestamp with millisecond precision indicating when the cache entry was created.',
447           'type' => 'numeric',
448           'precision' => 14,
449           'scale' => 3,
450           'not null' => TRUE,
451           'default' => 0,
452         ],
453         'serialized' => [
454           'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
455           'type' => 'int',
456           'size' => 'small',
457           'not null' => TRUE,
458           'default' => 0,
459         ],
460         'tags' => [
461           'description' => 'Space-separated list of cache tags for this entry.',
462           'type' => 'text',
463           'size' => 'big',
464           'not null' => FALSE,
465         ],
466         'checksum' => [
467           'description' => 'The tag invalidation checksum when this entry was saved.',
468           'type' => 'varchar_ascii',
469           'length' => 255,
470           'not null' => TRUE,
471         ],
472       ],
473       'indexes' => [
474         'expire' => ['expire'],
475       ],
476       'primary key' => ['cid'],
477     ];
478     return $schema;
479   }
480
481 }