cache.inc

Functions and interfaces for cache handling.

File

drupal/includes/cache.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions and interfaces for cache handling.
  5. */
  6. /**
  7. * Gets the cache object for a cache bin.
  8. *
  9. * By default, this returns an instance of the DrupalDatabaseCache class.
  10. * Classes implementing DrupalCacheInterface can register themselves both as a
  11. * default implementation and for specific bins.
  12. *
  13. * @param $bin
  14. * The cache bin for which the cache object should be returned.
  15. * @return DrupalCacheInterface
  16. * The cache object associated with the specified bin.
  17. *
  18. * @see DrupalCacheInterface
  19. */
  20. function _cache_get_object($bin) {
  21. // We do not use drupal_static() here because we do not want to change the
  22. // storage of a cache bin mid-request.
  23. static $cache_objects;
  24. if (!isset($cache_objects[$bin])) {
  25. $class = variable_get('cache_class_' . $bin);
  26. if (!isset($class)) {
  27. $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
  28. }
  29. $cache_objects[$bin] = new $class($bin);
  30. }
  31. return $cache_objects[$bin];
  32. }
  33. /**
  34. * Returns data from the persistent cache.
  35. *
  36. * Data may be stored as either plain text or as serialized data. cache_get
  37. * will automatically return unserialized objects and arrays.
  38. *
  39. * @param $cid
  40. * The cache ID of the data to retrieve.
  41. * @param $bin
  42. * The cache bin to store the data in. Valid core values are 'cache_block',
  43. * 'cache_bootstrap', 'cache_field', 'cache_filter', 'cache_form',
  44. * 'cache_menu', 'cache_page', 'cache_path', 'cache_update' or 'cache' for
  45. * the default cache.
  46. *
  47. * @return
  48. * The cache or FALSE on failure.
  49. *
  50. * @see cache_set()
  51. */
  52. function cache_get($cid, $bin = 'cache') {
  53. return _cache_get_object($bin)->get($cid);
  54. }
  55. /**
  56. * Returns data from the persistent cache when given an array of cache IDs.
  57. *
  58. * @param $cids
  59. * An array of cache IDs for the data to retrieve. This is passed by
  60. * reference, and will have the IDs successfully returned from cache removed.
  61. * @param $bin
  62. * The cache bin where the data is stored.
  63. *
  64. * @return
  65. * An array of the items successfully returned from cache indexed by cid.
  66. */
  67. function cache_get_multiple(array &$cids, $bin = 'cache') {
  68. return _cache_get_object($bin)->getMultiple($cids);
  69. }
  70. /**
  71. * Stores data in the persistent cache.
  72. *
  73. * The persistent cache is split up into several cache bins. In the default
  74. * cache implementation, each cache bin corresponds to a database table by the
  75. * same name. Other implementations might want to store several bins in data
  76. * structures that get flushed together. While it is not a problem for most
  77. * cache bins if the entries in them are flushed before their expire time, some
  78. * might break functionality or are extremely expensive to recalculate. The
  79. * other bins are expired automatically by core. Contributed modules can add
  80. * additional bins and get them expired automatically by implementing
  81. * hook_flush_caches().
  82. *
  83. * The reasons for having several bins are as follows:
  84. * - Smaller bins mean smaller database tables and allow for faster selects and
  85. * inserts.
  86. * - We try to put fast changing cache items and rather static ones into
  87. * different bins. The effect is that only the fast changing bins will need a
  88. * lot of writes to disk. The more static bins will also be better cacheable
  89. * with MySQL's query cache.
  90. *
  91. * @param $cid
  92. * The cache ID of the data to store.
  93. * @param $data
  94. * The data to store in the cache. Complex data types will be automatically
  95. * serialized before insertion. Strings will be stored as plain text and are
  96. * not serialized.
  97. * @param $bin
  98. * The cache bin to store the data in. Valid core values are:
  99. * - cache: (default) Generic cache storage bin (used for theme registry,
  100. * locale date, list of simpletest tests, etc.).
  101. * - cache_block: Stores the content of various blocks.
  102. * - cache_bootstrap: Stores the class registry, the system list of modules,
  103. * the list of which modules implement which hooks, and the Drupal variable
  104. * list.
  105. * - cache_field: Stores the field data belonging to a given object.
  106. * - cache_filter: Stores filtered pieces of content.
  107. * - cache_form: Stores multistep forms. Flushing this bin means that some
  108. * forms displayed to users lose their state and the data already submitted
  109. * to them. This bin should not be flushed before its expired time.
  110. * - cache_menu: Stores the structure of visible navigation menus per page.
  111. * - cache_page: Stores generated pages for anonymous users. It is flushed
  112. * very often, whenever a page changes, at least for every node and comment
  113. * submission. This is the only bin affected by the page cache setting on
  114. * the administrator panel.
  115. * - cache_path: Stores the system paths that have an alias.
  116. * @param $expire
  117. * One of the following values:
  118. * - CACHE_PERMANENT: Indicates that the item should never be removed unless
  119. * explicitly told to using cache_clear_all() with a cache ID.
  120. * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
  121. * general cache wipe.
  122. * - A Unix timestamp: Indicates that the item should be kept at least until
  123. * the given time, after which it behaves like CACHE_TEMPORARY.
  124. *
  125. * @see _update_cache_set()
  126. * @see cache_get()
  127. */
  128. function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  129. return _cache_get_object($bin)->set($cid, $data, $expire);
  130. }
  131. /**
  132. * Expires data from the cache.
  133. *
  134. * If called without arguments, expirable entries will be cleared from the
  135. * cache_page and cache_block bins.
  136. *
  137. * @param $cid
  138. * If set, the cache ID to delete. Otherwise, all cache entries that can
  139. * expire are deleted.
  140. * @param $bin
  141. * If set, the cache bin to delete from. Mandatory argument if $cid is set.
  142. * @param $wildcard
  143. * If TRUE, cache IDs starting with $cid are deleted in addition to the
  144. * exact cache ID specified by $cid. If $wildcard is TRUE and $cid is '*',
  145. * the entire cache bin is emptied.
  146. */
  147. function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
  148. if (!isset($cid) && !isset($bin)) {
  149. // Clear the block cache first, so stale data will
  150. // not end up in the page cache.
  151. if (module_exists('block')) {
  152. cache_clear_all(NULL, 'cache_block');
  153. }
  154. cache_clear_all(NULL, 'cache_page');
  155. return;
  156. }
  157. return _cache_get_object($bin)->clear($cid, $wildcard);
  158. }
  159. /**
  160. * Checks if a cache bin is empty.
  161. *
  162. * A cache bin is considered empty if it does not contain any valid data for any
  163. * cache ID.
  164. *
  165. * @param $bin
  166. * The cache bin to check.
  167. *
  168. * @return
  169. * TRUE if the cache bin specified is empty.
  170. */
  171. function cache_is_empty($bin) {
  172. return _cache_get_object($bin)->isEmpty();
  173. }
  174. /**
  175. * Defines an interface for cache implementations.
  176. *
  177. * All cache implementations have to implement this interface.
  178. * DrupalDatabaseCache provides the default implementation, which can be
  179. * consulted as an example.
  180. *
  181. * To make Drupal use your implementation for a certain cache bin, you have to
  182. * set a variable with the name of the cache bin as its key and the name of
  183. * your class as its value. For example, if your implementation of
  184. * DrupalCacheInterface was called MyCustomCache, the following line would make
  185. * Drupal use it for the 'cache_page' bin:
  186. * @code
  187. * variable_set('cache_class_cache_page', 'MyCustomCache');
  188. * @endcode
  189. *
  190. * Additionally, you can register your cache implementation to be used by
  191. * default for all cache bins by setting the variable 'cache_default_class' to
  192. * the name of your implementation of the DrupalCacheInterface, e.g.
  193. * @code
  194. * variable_set('cache_default_class', 'MyCustomCache');
  195. * @endcode
  196. *
  197. * To implement a completely custom cache bin, use the same variable format:
  198. * @code
  199. * variable_set('cache_class_custom_bin', 'MyCustomCache');
  200. * @endcode
  201. * To access your custom cache bin, specify the name of the bin when storing
  202. * or retrieving cached data:
  203. * @code
  204. * cache_set($cid, $data, 'custom_bin', $expire);
  205. * cache_get($cid, 'custom_bin');
  206. * @endcode
  207. *
  208. * @see _cache_get_object()
  209. * @see DrupalDatabaseCache
  210. */
  211. interface DrupalCacheInterface {
  212. /**
  213. * Constructs a new cache interface.
  214. *
  215. * @param $bin
  216. * The cache bin for which the object is created.
  217. */
  218. function __construct($bin);
  219. /**
  220. * Returns data from the persistent cache.
  221. *
  222. * Data may be stored as either plain text or as serialized data. cache_get()
  223. * will automatically return unserialized objects and arrays.
  224. *
  225. * @param $cid
  226. * The cache ID of the data to retrieve.
  227. *
  228. * @return
  229. * The cache or FALSE on failure.
  230. */
  231. function get($cid);
  232. /**
  233. * Returns data from the persistent cache when given an array of cache IDs.
  234. *
  235. * @param $cids
  236. * An array of cache IDs for the data to retrieve. This is passed by
  237. * reference, and will have the IDs successfully returned from cache
  238. * removed.
  239. *
  240. * @return
  241. * An array of the items successfully returned from cache indexed by cid.
  242. */
  243. function getMultiple(&$cids);
  244. /**
  245. * Stores data in the persistent cache.
  246. *
  247. * @param $cid
  248. * The cache ID of the data to store.
  249. * @param $data
  250. * The data to store in the cache. Complex data types will be automatically
  251. * serialized before insertion.
  252. * Strings will be stored as plain text and not serialized.
  253. * @param $expire
  254. * One of the following values:
  255. * - CACHE_PERMANENT: Indicates that the item should never be removed unless
  256. * explicitly told to using cache_clear_all() with a cache ID.
  257. * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
  258. * general cache wipe.
  259. * - A Unix timestamp: Indicates that the item should be kept at least until
  260. * the given time, after which it behaves like CACHE_TEMPORARY.
  261. */
  262. function set($cid, $data, $expire = CACHE_PERMANENT);
  263. /**
  264. * Expires data from the cache.
  265. *
  266. * If called without arguments, expirable entries will be cleared from the
  267. * cache_page and cache_block bins.
  268. *
  269. * @param $cid
  270. * If set, the cache ID to delete. Otherwise, all cache entries that can
  271. * expire are deleted.
  272. * @param $wildcard
  273. * If set to TRUE, the $cid is treated as a substring
  274. * to match rather than a complete ID. The match is a right hand
  275. * match. If '*' is given as $cid, the bin $bin will be emptied.
  276. */
  277. function clear($cid = NULL, $wildcard = FALSE);
  278. /**
  279. * Checks if a cache bin is empty.
  280. *
  281. * A cache bin is considered empty if it does not contain any valid data for
  282. * any cache ID.
  283. *
  284. * @return
  285. * TRUE if the cache bin specified is empty.
  286. */
  287. function isEmpty();
  288. }
  289. /**
  290. * Defines a default cache implementation.
  291. *
  292. * This is Drupal's default cache implementation. It uses the database to store
  293. * cached data. Each cache bin corresponds to a database table by the same name.
  294. */
  295. class DrupalDatabaseCache implements DrupalCacheInterface {
  296. protected $bin;
  297. /**
  298. * Constructs a new DrupalDatabaseCache object.
  299. */
  300. function __construct($bin) {
  301. $this->bin = $bin;
  302. }
  303. /**
  304. * Implements DrupalCacheInterface::get().
  305. */
  306. function get($cid) {
  307. $cids = array($cid);
  308. $cache = $this->getMultiple($cids);
  309. return reset($cache);
  310. }
  311. /**
  312. * Implements DrupalCacheInterface::getMultiple().
  313. */
  314. function getMultiple(&$cids) {
  315. try {
  316. // Garbage collection necessary when enforcing a minimum cache lifetime.
  317. $this->garbageCollection($this->bin);
  318. // When serving cached pages, the overhead of using db_select() was found
  319. // to add around 30% overhead to the request. Since $this->bin is a
  320. // variable, this means the call to db_query() here uses a concatenated
  321. // string. This is highly discouraged under any other circumstances, and
  322. // is used here only due to the performance overhead we would incur
  323. // otherwise. When serving an uncached page, the overhead of using
  324. // db_select() is a much smaller proportion of the request.
  325. $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
  326. $cache = array();
  327. foreach ($result as $item) {
  328. $item = $this->prepareItem($item);
  329. if ($item) {
  330. $cache[$item->cid] = $item;
  331. }
  332. }
  333. $cids = array_diff($cids, array_keys($cache));
  334. return $cache;
  335. }
  336. catch (Exception $e) {
  337. // If the database is never going to be available, cache requests should
  338. // return FALSE in order to allow exception handling to occur.
  339. return array();
  340. }
  341. }
  342. /**
  343. * Garbage collection for get() and getMultiple().
  344. *
  345. * @param $bin
  346. * The bin being requested.
  347. */
  348. protected function garbageCollection() {
  349. $cache_lifetime = variable_get('cache_lifetime', 0);
  350. // Clean-up the per-user cache expiration session data, so that the session
  351. // handler can properly clean-up the session data for anonymous users.
  352. if (isset($_SESSION['cache_expiration'])) {
  353. $expire = REQUEST_TIME - $cache_lifetime;
  354. foreach ($_SESSION['cache_expiration'] as $bin => $timestamp) {
  355. if ($timestamp < $expire) {
  356. unset($_SESSION['cache_expiration'][$bin]);
  357. }
  358. }
  359. if (!$_SESSION['cache_expiration']) {
  360. unset($_SESSION['cache_expiration']);
  361. }
  362. }
  363. // Garbage collection of temporary items is only necessary when enforcing
  364. // a minimum cache lifetime.
  365. if (!$cache_lifetime) {
  366. return;
  367. }
  368. // When cache lifetime is in force, avoid running garbage collection too
  369. // often since this will remove temporary cache items indiscriminately.
  370. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  371. if ($cache_flush && ($cache_flush + $cache_lifetime <= REQUEST_TIME)) {
  372. // Reset the variable immediately to prevent a meltdown in heavy load situations.
  373. variable_set('cache_flush_' . $this->bin, 0);
  374. // Time to flush old cache data
  375. db_delete($this->bin)
  376. ->condition('expire', CACHE_PERMANENT, '<>')
  377. ->condition('expire', $cache_flush, '<=')
  378. ->execute();
  379. }
  380. }
  381. /**
  382. * Prepares a cached item.
  383. *
  384. * Checks that items are either permanent or did not expire, and unserializes
  385. * data as appropriate.
  386. *
  387. * @param $cache
  388. * An item loaded from cache_get() or cache_get_multiple().
  389. *
  390. * @return
  391. * The item with data unserialized as appropriate or FALSE if there is no
  392. * valid item to load.
  393. */
  394. protected function prepareItem($cache) {
  395. global $user;
  396. if (!isset($cache->data)) {
  397. return FALSE;
  398. }
  399. // If the cached data is temporary and subject to a per-user minimum
  400. // lifetime, compare the cache entry timestamp with the user session
  401. // cache_expiration timestamp. If the cache entry is too old, ignore it.
  402. if ($cache->expire != CACHE_PERMANENT && variable_get('cache_lifetime', 0) && isset($_SESSION['cache_expiration'][$this->bin]) && $_SESSION['cache_expiration'][$this->bin] > $cache->created) {
  403. // Ignore cache data that is too old and thus not valid for this user.
  404. return FALSE;
  405. }
  406. // If the data is permanent or not subject to a minimum cache lifetime,
  407. // unserialize and return the cached data.
  408. if ($cache->serialized) {
  409. $cache->data = unserialize($cache->data);
  410. }
  411. return $cache;
  412. }
  413. /**
  414. * Implements DrupalCacheInterface::set().
  415. */
  416. function set($cid, $data, $expire = CACHE_PERMANENT) {
  417. $fields = array(
  418. 'serialized' => 0,
  419. 'created' => REQUEST_TIME,
  420. 'expire' => $expire,
  421. );
  422. if (!is_string($data)) {
  423. $fields['data'] = serialize($data);
  424. $fields['serialized'] = 1;
  425. }
  426. else {
  427. $fields['data'] = $data;
  428. $fields['serialized'] = 0;
  429. }
  430. try {
  431. db_merge($this->bin)
  432. ->key(array('cid' => $cid))
  433. ->fields($fields)
  434. ->execute();
  435. }
  436. catch (Exception $e) {
  437. // The database may not be available, so we'll ignore cache_set requests.
  438. }
  439. }
  440. /**
  441. * Implements DrupalCacheInterface::clear().
  442. */
  443. function clear($cid = NULL, $wildcard = FALSE) {
  444. global $user;
  445. if (empty($cid)) {
  446. if (variable_get('cache_lifetime', 0)) {
  447. // We store the time in the current user's session. We then simulate
  448. // that the cache was flushed for this user by not returning cached
  449. // data that was cached before the timestamp.
  450. $_SESSION['cache_expiration'][$this->bin] = REQUEST_TIME;
  451. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  452. if ($cache_flush == 0) {
  453. // This is the first request to clear the cache, start a timer.
  454. variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  455. }
  456. elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
  457. // Clear the cache for everyone, cache_lifetime seconds have
  458. // passed since the first request to clear the cache.
  459. db_delete($this->bin)
  460. ->condition('expire', CACHE_PERMANENT, '<>')
  461. ->condition('expire', REQUEST_TIME, '<')
  462. ->execute();
  463. variable_set('cache_flush_' . $this->bin, 0);
  464. }
  465. }
  466. else {
  467. // No minimum cache lifetime, flush all temporary cache entries now.
  468. db_delete($this->bin)
  469. ->condition('expire', CACHE_PERMANENT, '<>')
  470. ->condition('expire', REQUEST_TIME, '<')
  471. ->execute();
  472. }
  473. }
  474. else {
  475. if ($wildcard) {
  476. if ($cid == '*') {
  477. db_truncate($this->bin)->execute();
  478. }
  479. else {
  480. db_delete($this->bin)
  481. ->condition('cid', db_like($cid) . '%', 'LIKE')
  482. ->execute();
  483. }
  484. }
  485. elseif (is_array($cid)) {
  486. // Delete in chunks when a large array is passed.
  487. do {
  488. db_delete($this->bin)
  489. ->condition('cid', array_splice($cid, 0, 1000), 'IN')
  490. ->execute();
  491. }
  492. while (count($cid));
  493. }
  494. else {
  495. db_delete($this->bin)
  496. ->condition('cid', $cid)
  497. ->execute();
  498. }
  499. }
  500. }
  501. /**
  502. * Implements DrupalCacheInterface::isEmpty().
  503. */
  504. function isEmpty() {
  505. $this->garbageCollection();
  506. $query = db_select($this->bin);
  507. $query->addExpression('1');
  508. $result = $query->range(0, 1)
  509. ->execute()
  510. ->fetchField();
  511. return empty($result);
  512. }
  513. }

Functions

Namesort descending Description
cache_clear_all Expires data from the cache.
cache_get Returns data from the persistent cache.
cache_get_multiple Returns data from the persistent cache when given an array of cache IDs.
cache_is_empty Checks if a cache bin is empty.
cache_set Stores data in the persistent cache.
_cache_get_object Gets the cache object for a cache bin.

Classes

Namesort descending Description
DrupalDatabaseCache Defines a default cache implementation.

Interfaces

Namesort descending Description
DrupalCacheInterface Defines an interface for cache implementations.