Projet

Général

Profil

Paste
Télécharger (19,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / cache.inc @ b230fec6

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.
102
 * @param $bin
103
 *   The cache bin to store the data in. Valid core values are:
104
 *   - cache: (default) Generic cache storage bin (used for theme registry,
105
 *     locale date, list of simpletest tests, etc.).
106
 *   - cache_block: Stores the content of various blocks.
107
 *   - cache_bootstrap: Stores the class registry, the system list of modules,
108
 *     the list of which modules implement which hooks, and the Drupal variable
109
 *     list.
110
 *   - cache_field: Stores the field data belonging to a given object.
111
 *   - cache_filter: Stores filtered pieces of content.
112
 *   - cache_form: Stores multistep forms. Flushing this bin means that some
113
 *     forms displayed to users lose their state and the data already submitted
114
 *     to them. This bin should not be flushed before its expired time.
115
 *   - cache_menu: Stores the structure of visible navigation menus per page.
116
 *   - cache_page: Stores generated pages for anonymous users. It is flushed
117
 *     very often, whenever a page changes, at least for every node and comment
118
 *     submission. This is the only bin affected by the page cache setting on
119
 *     the administrator panel.
120
 *   - cache_path: Stores the system paths that have an alias.
121
 * @param $expire
122
 *   One of the following values:
123
 *   - CACHE_PERMANENT: Indicates that the item should never be removed unless
124
 *     explicitly told to using cache_clear_all() with a cache ID.
125
 *   - CACHE_TEMPORARY: Indicates that the item should be removed at the next
126
 *     general cache wipe.
127
 *   - A Unix timestamp: Indicates that the item should be kept at least until
128
 *     the given time, after which it behaves like CACHE_TEMPORARY.
129
 *
130
 * @see _update_cache_set()
131
 * @see cache_get()
132
 */
133
function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
134
  return _cache_get_object($bin)->set($cid, $data, $expire);
135
}
136

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

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

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

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

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

    
250
  /**
251
   * Stores data in the persistent cache.
252
   *
253
   * @param $cid
254
   *   The cache ID of the data to store.
255
   * @param $data
256
   *   The data to store in the cache. Complex data types will be automatically
257
   *   serialized before insertion.
258
   *   Strings will be stored as plain text and not serialized.
259
   * @param $expire
260
   *   One of the following values:
261
   *   - CACHE_PERMANENT: Indicates that the item should never be removed unless
262
   *     explicitly told to using cache_clear_all() with a cache ID.
263
   *   - CACHE_TEMPORARY: Indicates that the item should be removed at the next
264
   *     general cache wipe.
265
   *   - A Unix timestamp: Indicates that the item should be kept at least until
266
   *     the given time, after which it behaves like CACHE_TEMPORARY.
267
   */
268
  function set($cid, $data, $expire = CACHE_PERMANENT);
269

    
270

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

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

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

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

    
320
  /**
321
   * Implements DrupalCacheInterface::get().
322
   */
323
  function get($cid) {
324
    $cids = array($cid);
325
    $cache = $this->getMultiple($cids);
326
    return reset($cache);
327
  }
328

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

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

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

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

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

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

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

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

    
437
    return $cache;
438
  }
439

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

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

    
469
  /**
470
   * Implements DrupalCacheInterface::clear().
471
   */
472
  function clear($cid = NULL, $wildcard = FALSE) {
473
    global $user;
474

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

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

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

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