Projet

Général

Profil

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

root / drupal7 / includes / cache.inc @ 582db59d

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
 *
18
 * @return DrupalCacheInterface
19
 *   The cache object associated with the specified bin.
20
 *
21
 * @see DrupalCacheInterface
22
 */
23
function _cache_get_object($bin) {
24
  // We do not use drupal_static() here because we do not want to change the
25
  // storage of a cache bin mid-request.
26
  static $cache_objects;
27
  if (!isset($cache_objects[$bin])) {
28
    $class = variable_get('cache_class_' . $bin);
29
    if (!isset($class)) {
30
      $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
31
    }
32
    $cache_objects[$bin] = new $class($bin);
33
  }
34
  return $cache_objects[$bin];
35
}
36

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

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

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

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

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

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

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

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

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

    
275

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

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

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

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

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

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

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

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

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

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

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

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

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

    
442
    return $cache;
443
  }
444

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

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

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

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

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

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

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