Projet

Général

Profil

Paste
Télécharger (20 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / cache.inc @ db2d93dd

1
<?php
2

    
3
/**
4
 * @file
5
 * Functions and interfaces for cache handling.
6
 */
7

    
8
/**
9
 * Gets the cache object for a cache bin.
10
 *
11
 * By default, this returns an instance of the DrupalDatabaseCache class.
12
 * Classes implementing DrupalCacheInterface can register themselves both as a
13
 * default implementation and for specific bins.
14
 *
15
 * @param $bin
16
 *   The cache bin for which the cache object should be returned.
17
 * @return DrupalCacheInterface
18
 *   The cache object associated with the specified bin.
19
 *
20
 * @see DrupalCacheInterface
21
 */
22
function _cache_get_object($bin) {
23
  // We do not use drupal_static() here because we do not want to change the
24
  // storage of a cache bin mid-request.
25
  static $cache_objects;
26
  if (!isset($cache_objects[$bin])) {
27
    $class = variable_get('cache_class_' . $bin);
28
    if (!isset($class)) {
29
      $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
30
    }
31
    $cache_objects[$bin] = new $class($bin);
32
  }
33
  return $cache_objects[$bin];
34
}
35

    
36
/**
37
 * Returns data from the persistent cache.
38
 *
39
 * Data may be stored as either plain text or as serialized data. cache_get
40
 * will automatically return unserialized objects and arrays.
41
 *
42
 * @param $cid
43
 *   The cache ID of the data to retrieve.
44
 * @param $bin
45
 *   The cache bin to store the data in. Valid core values are 'cache_block',
46
 *   'cache_bootstrap', 'cache_field', 'cache_filter', 'cache_form',
47
 *   'cache_menu', 'cache_page', 'cache_path', 'cache_update' or 'cache' for
48
 *   the default cache.
49
 *
50
 * @return
51
 *   The cache or FALSE on failure.
52
 *
53
 * @see cache_set()
54
 */
55
function cache_get($cid, $bin = 'cache') {
56
  return _cache_get_object($bin)->get($cid);
57
}
58

    
59
/**
60
 * Returns data from the persistent cache when given an array of cache IDs.
61
 *
62
 * @param $cids
63
 *   An array of cache IDs for the data to retrieve. This is passed by
64
 *   reference, and will have the IDs successfully returned from cache removed.
65
 * @param $bin
66
 *   The cache bin where the data is stored.
67
 *
68
 * @return
69
 *   An array of the items successfully returned from cache indexed by cid.
70
 */
71
function cache_get_multiple(array &$cids, $bin = 'cache') {
72
  return _cache_get_object($bin)->getMultiple($cids);
73
}
74

    
75
/**
76
 * Stores data in the persistent cache.
77
 *
78
 * The persistent cache is split up into several cache bins. In the default
79
 * cache implementation, each cache bin corresponds to a database table by the
80
 * same name. Other implementations might want to store several bins in data
81
 * structures that get flushed together. While it is not a problem for most
82
 * cache bins if the entries in them are flushed before their expire time, some
83
 * might break functionality or are extremely expensive to recalculate. The
84
 * other bins are expired automatically by core. Contributed modules can add
85
 * additional bins and get them expired automatically by implementing
86
 * hook_flush_caches().
87
 *
88
 * The reasons for having several bins are as follows:
89
 * - Smaller bins mean smaller database tables and allow for faster selects and
90
 *   inserts.
91
 * - We try to put fast changing cache items and rather static ones into
92
 *   different bins. The effect is that only the fast changing bins will need a
93
 *   lot of writes to disk. The more static bins will also be better cacheable
94
 *   with MySQL's query cache.
95
 *
96
 * @param $cid
97
 *   The cache ID of the data to store.
98
 * @param $data
99
 *   The data to store in the cache. Complex data types will be automatically
100
 *   serialized before insertion. Strings will be stored as plain text and are
101
 *   not serialized. Some storage engines only allow objects up to a maximum of
102
 *   1MB in size to be stored by default. When caching large arrays or similar,
103
 *   take care to ensure $data does not exceed this size.
104
 * @param $bin
105
 *   (optional) The cache bin to store the data in. Valid core values are:
106
 *   - cache: (default) Generic cache storage bin (used for theme registry,
107
 *     locale date, list of simpletest tests, etc.).
108
 *   - cache_block: Stores the content of various blocks.
109
 *   - cache_bootstrap: Stores the class registry, the system list of modules,
110
 *     the list of which modules implement which hooks, and the Drupal variable
111
 *     list.
112
 *   - cache_field: Stores the field data belonging to a given object.
113
 *   - cache_filter: Stores filtered pieces of content.
114
 *   - cache_form: Stores multistep forms. Flushing this bin means that some
115
 *     forms displayed to users lose their state and the data already submitted
116
 *     to them. This bin should not be flushed before its expired time.
117
 *   - cache_menu: Stores the structure of visible navigation menus per page.
118
 *   - cache_page: Stores generated pages for anonymous users. It is flushed
119
 *     very often, whenever a page changes, at least for every node and comment
120
 *     submission. This is the only bin affected by the page cache setting on
121
 *     the administrator panel.
122
 *   - cache_path: Stores the system paths that have an alias.
123
 * @param $expire
124
 *   (optional) One of the following values:
125
 *   - CACHE_PERMANENT: Indicates that the item should never be removed unless
126
 *     explicitly told to using cache_clear_all() with a cache ID.
127
 *   - CACHE_TEMPORARY: Indicates that the item should be removed at the next
128
 *     general cache wipe.
129
 *   - A Unix timestamp: Indicates that the item should be kept at least until
130
 *     the given time, after which it behaves like CACHE_TEMPORARY.
131
 *
132
 * @see _update_cache_set()
133
 * @see cache_get()
134
 */
135
function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
136
  return _cache_get_object($bin)->set($cid, $data, $expire);
137
}
138

    
139
/**
140
 * Expires data from the cache.
141
 *
142
 * If called with the arguments $cid and $bin set to NULL or omitted, then
143
 * expirable entries will be cleared from the cache_page and cache_block bins,
144
 * and the $wildcard argument is ignored.
145
 *
146
 * @param $cid
147
 *   If set, the cache ID or an array of cache IDs. Otherwise, all cache entries
148
 *   that can expire are deleted. The $wildcard argument will be ignored if set
149
 *   to NULL.
150
 * @param $bin
151
 *   If set, the cache bin to delete from. Mandatory argument if $cid is set.
152
 * @param $wildcard
153
 *   If TRUE, the $cid argument must contain a string value and cache IDs
154
 *   starting with $cid are deleted in addition to the exact cache ID specified
155
 *   by $cid. If $wildcard is TRUE and $cid is '*', the entire cache is emptied.
156
 */
157
function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
158
  if (!isset($cid) && !isset($bin)) {
159
    // Clear the block cache first, so stale data will
160
    // not end up in the page cache.
161
    if (module_exists('block')) {
162
      cache_clear_all(NULL, 'cache_block');
163
    }
164
    cache_clear_all(NULL, 'cache_page');
165
    return;
166
  }
167
  return _cache_get_object($bin)->clear($cid, $wildcard);
168
}
169

    
170
/**
171
 * Checks if a cache bin is empty.
172
 *
173
 * A cache bin is considered empty if it does not contain any valid data for any
174
 * cache ID.
175
 *
176
 * @param $bin
177
 *   The cache bin to check.
178
 *
179
 * @return
180
 *   TRUE if the cache bin specified is empty.
181
 */
182
function cache_is_empty($bin) {
183
  return _cache_get_object($bin)->isEmpty();
184
}
185

    
186
/**
187
 * Defines an interface for cache implementations.
188
 *
189
 * All cache implementations have to implement this interface.
190
 * DrupalDatabaseCache provides the default implementation, which can be
191
 * consulted as an example.
192
 *
193
 * To make Drupal use your implementation for a certain cache bin, you have to
194
 * set a variable with the name of the cache bin as its key and the name of
195
 * your class as its value. For example, if your implementation of
196
 * DrupalCacheInterface was called MyCustomCache, the following line would make
197
 * Drupal use it for the 'cache_page' bin:
198
 * @code
199
 *  variable_set('cache_class_cache_page', 'MyCustomCache');
200
 * @endcode
201
 *
202
 * Additionally, you can register your cache implementation to be used by
203
 * default for all cache bins by setting the variable 'cache_default_class' to
204
 * the name of your implementation of the DrupalCacheInterface, e.g.
205
 * @code
206
 *  variable_set('cache_default_class', 'MyCustomCache');
207
 * @endcode
208
 *
209
 * To implement a completely custom cache bin, use the same variable format:
210
 * @code
211
 *  variable_set('cache_class_custom_bin', 'MyCustomCache');
212
 * @endcode
213
 * To access your custom cache bin, specify the name of the bin when storing
214
 * or retrieving cached data:
215
 * @code
216
 *  cache_set($cid, $data, 'custom_bin', $expire);
217
 *  cache_get($cid, 'custom_bin');
218
 * @endcode
219
 *
220
 * @see _cache_get_object()
221
 * @see DrupalDatabaseCache
222
 */
223
interface DrupalCacheInterface {
224

    
225
  /**
226
   * Returns data from the persistent cache.
227
   *
228
   * Data may be stored as either plain text or as serialized data. cache_get()
229
   * will automatically return unserialized objects and arrays.
230
   *
231
   * @param $cid
232
   *   The cache ID of the data to retrieve.
233
   *
234
   * @return
235
   *   The cache or FALSE on failure.
236
   */
237
  function get($cid);
238

    
239
  /**
240
   * Returns data from the persistent cache when given an array of cache IDs.
241
   *
242
   * @param $cids
243
   *   An array of cache IDs for the data to retrieve. This is passed by
244
   *   reference, and will have the IDs successfully returned from cache
245
   *   removed.
246
   *
247
   * @return
248
   *   An array of the items successfully returned from cache indexed by cid.
249
   */
250
   function getMultiple(&$cids);
251

    
252
  /**
253
   * Stores data in the persistent cache.
254
   *
255
   * @param $cid
256
   *   The cache ID of the data to store.
257
   * @param $data
258
   *   The data to store in the cache. Complex data types will be automatically
259
   *   serialized before insertion. Strings will be stored as plain text and not
260
   *   serialized. Some storage engines only allow objects up to a maximum of
261
   *   1MB in size to be stored by default. When caching large arrays or
262
   *   similar, take care to ensure $data does not exceed this size.
263
   * @param $expire
264
   *   (optional) One of the following values:
265
   *   - CACHE_PERMANENT: Indicates that the item should never be removed unless
266
   *     explicitly told to using cache_clear_all() with a cache ID.
267
   *   - CACHE_TEMPORARY: Indicates that the item should be removed at the next
268
   *     general cache wipe.
269
   *   - A Unix timestamp: Indicates that the item should be kept at least until
270
   *     the given time, after which it behaves like CACHE_TEMPORARY.
271
   */
272
  function set($cid, $data, $expire = CACHE_PERMANENT);
273

    
274

    
275
  /**
276
   * Expires data from the cache.
277
   *
278
   * If called without arguments, expirable entries will be cleared from the
279
   * cache_page and cache_block bins.
280
   *
281
   * @param $cid
282
   *   If set, the cache ID or an array of cache IDs. Otherwise, all cache
283
   *   entries that can expire are deleted. The $wildcard argument will be
284
   *   ignored if set to NULL.
285
   * @param $wildcard
286
   *   If TRUE, the $cid argument must contain a string value and cache IDs
287
   *   starting with $cid are deleted in addition to the exact cache ID
288
   *   specified by $cid. If $wildcard is TRUE and $cid is '*', the entire
289
   *   cache is emptied.
290
   */
291
  function clear($cid = NULL, $wildcard = FALSE);
292

    
293
  /**
294
   * Checks if a cache bin is empty.
295
   *
296
   * A cache bin is considered empty if it does not contain any valid data for
297
   * any cache ID.
298
   *
299
   * @return
300
   *   TRUE if the cache bin specified is empty.
301
   */
302
  function isEmpty();
303
}
304

    
305
/**
306
 * Defines a default cache implementation.
307
 *
308
 * This is Drupal's default cache implementation. It uses the database to store
309
 * cached data. Each cache bin corresponds to a database table by the same name.
310
 */
311
class DrupalDatabaseCache implements DrupalCacheInterface {
312
  protected $bin;
313

    
314
  /**
315
   * Constructs a DrupalDatabaseCache object.
316
   *
317
   * @param $bin
318
   *   The cache bin for which the object is created.
319
   */
320
  function __construct($bin) {
321
    $this->bin = $bin;
322
  }
323

    
324
  /**
325
   * Implements DrupalCacheInterface::get().
326
   */
327
  function get($cid) {
328
    $cids = array($cid);
329
    $cache = $this->getMultiple($cids);
330
    return reset($cache);
331
  }
332

    
333
  /**
334
   * Implements DrupalCacheInterface::getMultiple().
335
   */
336
  function getMultiple(&$cids) {
337
    try {
338
      // Garbage collection necessary when enforcing a minimum cache lifetime.
339
      $this->garbageCollection($this->bin);
340

    
341
      // When serving cached pages, the overhead of using db_select() was found
342
      // to add around 30% overhead to the request. Since $this->bin is a
343
      // variable, this means the call to db_query() here uses a concatenated
344
      // string. This is highly discouraged under any other circumstances, and
345
      // is used here only due to the performance overhead we would incur
346
      // otherwise. When serving an uncached page, the overhead of using
347
      // db_select() is a much smaller proportion of the request.
348
      $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
349
      $cache = array();
350
      foreach ($result as $item) {
351
        $item = $this->prepareItem($item);
352
        if ($item) {
353
          $cache[$item->cid] = $item;
354
        }
355
      }
356
      $cids = array_diff($cids, array_keys($cache));
357
      return $cache;
358
    }
359
    catch (Exception $e) {
360
      // If the database is never going to be available, cache requests should
361
      // return FALSE in order to allow exception handling to occur.
362
      return array();
363
    }
364
  }
365

    
366
  /**
367
   * Garbage collection for get() and getMultiple().
368
   *
369
   * @param $bin
370
   *   The bin being requested.
371
   */
372
  protected function garbageCollection() {
373
    $cache_lifetime = variable_get('cache_lifetime', 0);
374

    
375
    // Clean-up the per-user cache expiration session data, so that the session
376
    // handler can properly clean-up the session data for anonymous users.
377
    if (isset($_SESSION['cache_expiration'])) {
378
      $expire = REQUEST_TIME - $cache_lifetime;
379
      foreach ($_SESSION['cache_expiration'] as $bin => $timestamp) {
380
        if ($timestamp < $expire) {
381
          unset($_SESSION['cache_expiration'][$bin]);
382
        }
383
      }
384
      if (!$_SESSION['cache_expiration']) {
385
        unset($_SESSION['cache_expiration']);
386
      }
387
    }
388

    
389
    // Garbage collection of temporary items is only necessary when enforcing
390
    // a minimum cache lifetime.
391
    if (!$cache_lifetime) {
392
      return;
393
    }
394
    // When cache lifetime is in force, avoid running garbage collection too
395
    // often since this will remove temporary cache items indiscriminately.
396
    $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
397
    if ($cache_flush && ($cache_flush + $cache_lifetime <= REQUEST_TIME)) {
398
      // Reset the variable immediately to prevent a meltdown in heavy load situations.
399
      variable_set('cache_flush_' . $this->bin, 0);
400
      // Time to flush old cache data
401
      db_delete($this->bin)
402
        ->condition('expire', CACHE_PERMANENT, '<>')
403
        ->condition('expire', $cache_flush, '<=')
404
        ->execute();
405
    }
406
  }
407

    
408
  /**
409
   * Prepares a cached item.
410
   *
411
   * Checks that items are either permanent or did not expire, and unserializes
412
   * data as appropriate.
413
   *
414
   * @param $cache
415
   *   An item loaded from cache_get() or cache_get_multiple().
416
   *
417
   * @return
418
   *   The item with data unserialized as appropriate or FALSE if there is no
419
   *   valid item to load.
420
   */
421
  protected function prepareItem($cache) {
422
    global $user;
423

    
424
    if (!isset($cache->data)) {
425
      return FALSE;
426
    }
427
    // If the cached data is temporary and subject to a per-user minimum
428
    // lifetime, compare the cache entry timestamp with the user session
429
    // cache_expiration timestamp. If the cache entry is too old, ignore it.
430
    if ($cache->expire != CACHE_PERMANENT && variable_get('cache_lifetime', 0) && isset($_SESSION['cache_expiration'][$this->bin]) && $_SESSION['cache_expiration'][$this->bin] > $cache->created) {
431
      // Ignore cache data that is too old and thus not valid for this user.
432
      return FALSE;
433
    }
434

    
435
    // If the data is permanent or not subject to a minimum cache lifetime,
436
    // unserialize and return the cached data.
437
    if ($cache->serialized) {
438
      $cache->data = unserialize($cache->data);
439
    }
440

    
441
    return $cache;
442
  }
443

    
444
  /**
445
   * Implements DrupalCacheInterface::set().
446
   */
447
  function set($cid, $data, $expire = CACHE_PERMANENT) {
448
    $fields = array(
449
      'serialized' => 0,
450
      'created' => REQUEST_TIME,
451
      'expire' => $expire,
452
    );
453
    if (!is_string($data)) {
454
      $fields['data'] = serialize($data);
455
      $fields['serialized'] = 1;
456
    }
457
    else {
458
      $fields['data'] = $data;
459
      $fields['serialized'] = 0;
460
    }
461

    
462
    try {
463
      db_merge($this->bin)
464
        ->key(array('cid' => $cid))
465
        ->fields($fields)
466
        ->execute();
467
    }
468
    catch (Exception $e) {
469
      // The database may not be available, so we'll ignore cache_set requests.
470
    }
471
  }
472

    
473
  /**
474
   * Implements DrupalCacheInterface::clear().
475
   */
476
  function clear($cid = NULL, $wildcard = FALSE) {
477
    global $user;
478

    
479
    if (empty($cid)) {
480
      if (variable_get('cache_lifetime', 0)) {
481
        // We store the time in the current user's session. We then simulate
482
        // that the cache was flushed for this user by not returning cached
483
        // data that was cached before the timestamp.
484
        $_SESSION['cache_expiration'][$this->bin] = REQUEST_TIME;
485

    
486
        $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
487
        if ($cache_flush == 0) {
488
          // This is the first request to clear the cache, start a timer.
489
          variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
490
        }
491
        elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
492
          // Clear the cache for everyone, cache_lifetime seconds have
493
          // passed since the first request to clear the cache.
494
          db_delete($this->bin)
495
            ->condition('expire', CACHE_PERMANENT, '<>')
496
            ->condition('expire', REQUEST_TIME, '<')
497
            ->execute();
498
          variable_set('cache_flush_' . $this->bin, 0);
499
        }
500
      }
501
      else {
502
        // No minimum cache lifetime, flush all temporary cache entries now.
503
        db_delete($this->bin)
504
          ->condition('expire', CACHE_PERMANENT, '<>')
505
          ->condition('expire', REQUEST_TIME, '<')
506
          ->execute();
507
      }
508
    }
509
    else {
510
      if ($wildcard) {
511
        if ($cid == '*') {
512
          // Check if $this->bin is a cache table before truncating. Other
513
          // cache_clear_all() operations throw a PDO error in this situation,
514
          // so we don't need to verify them first. This ensures that non-cache
515
          // tables cannot be truncated accidentally.
516
          if ($this->isValidBin()) {
517
            db_truncate($this->bin)->execute();
518
          }
519
          else {
520
            throw new Exception(t('Invalid or missing cache bin specified: %bin', array('%bin' => $this->bin)));
521
          }
522
        }
523
        else {
524
          db_delete($this->bin)
525
            ->condition('cid', db_like($cid) . '%', 'LIKE')
526
            ->execute();
527
        }
528
      }
529
      elseif (is_array($cid)) {
530
        // Delete in chunks when a large array is passed.
531
        do {
532
          db_delete($this->bin)
533
            ->condition('cid', array_splice($cid, 0, 1000), 'IN')
534
            ->execute();
535
        }
536
        while (count($cid));
537
      }
538
      else {
539
        db_delete($this->bin)
540
          ->condition('cid', $cid)
541
          ->execute();
542
      }
543
    }
544
  }
545

    
546
  /**
547
   * Implements DrupalCacheInterface::isEmpty().
548
   */
549
  function isEmpty() {
550
    $this->garbageCollection();
551
    $query = db_select($this->bin);
552
    $query->addExpression('1');
553
    $result = $query->range(0, 1)
554
      ->execute()
555
      ->fetchField();
556
    return empty($result);
557
  }
558

    
559
  /**
560
   * Checks if $this->bin represents a valid cache table.
561
   *
562
   * This check is required to ensure that non-cache tables are not truncated
563
   * accidentally when calling cache_clear_all().
564
   *
565
   * @return boolean
566
   */
567
  function isValidBin() {
568
    if ($this->bin == 'cache' || substr($this->bin, 0, 6) == 'cache_') {
569
      // Skip schema check for bins with standard table names.
570
      return TRUE;
571
    }
572
    // These fields are required for any cache table.
573
    $fields = array('cid', 'data', 'expire', 'created', 'serialized');
574
    // Load the table schema.
575
    $schema = drupal_get_schema($this->bin);
576
    // Confirm that all fields are present.
577
    return isset($schema['fields']) && !array_diff($fields, array_keys($schema['fields']));
578
  }
579
}