annotate core/lib/Drupal/Core/Cache/DatabaseBackend.php @ 13:5fb285c0d0e3

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