cache.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. *
  16. * @return DrupalCacheInterface
  17. * The cache object associated with the specified bin.
  18. *
  19. * @see DrupalCacheInterface
  20. */
  21. function _cache_get_object($bin) {
  22. // We do not use drupal_static() here because we do not want to change the
  23. // storage of a cache bin mid-request.
  24. static $cache_objects;
  25. if (!isset($cache_objects[$bin])) {
  26. $class = variable_get('cache_class_' . $bin);
  27. if (!isset($class)) {
  28. $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
  29. }
  30. $cache_objects[$bin] = new $class($bin);
  31. }
  32. return $cache_objects[$bin];
  33. }
  34. /**
  35. * Returns data from the persistent cache.
  36. *
  37. * Data may be stored as either plain text or as serialized data. cache_get
  38. * will automatically return unserialized objects and arrays.
  39. *
  40. * @param $cid
  41. * The cache ID of the data to retrieve.
  42. * @param $bin
  43. * The cache bin to store the data in. Valid core values are 'cache_block',
  44. * 'cache_bootstrap', 'cache_field', 'cache_filter', 'cache_form',
  45. * 'cache_menu', 'cache_page', 'cache_path', 'cache_update' or 'cache' for
  46. * the default cache.
  47. *
  48. * @return
  49. * The cache or FALSE on failure.
  50. *
  51. * @see cache_set()
  52. */
  53. function cache_get($cid, $bin = 'cache') {
  54. return _cache_get_object($bin)->get($cid);
  55. }
  56. /**
  57. * Returns data from the persistent cache when given an array of cache IDs.
  58. *
  59. * @param $cids
  60. * An array of cache IDs for the data to retrieve. This is passed by
  61. * reference, and will have the IDs successfully returned from cache removed.
  62. * @param $bin
  63. * The cache bin where the data is stored.
  64. *
  65. * @return
  66. * An array of the items successfully returned from cache indexed by cid.
  67. */
  68. function cache_get_multiple(array &$cids, $bin = 'cache') {
  69. return _cache_get_object($bin)->getMultiple($cids);
  70. }
  71. /**
  72. * Stores data in the persistent cache.
  73. *
  74. * The persistent cache is split up into several cache bins. In the default
  75. * cache implementation, each cache bin corresponds to a database table by the
  76. * same name. Other implementations might want to store several bins in data
  77. * structures that get flushed together. While it is not a problem for most
  78. * cache bins if the entries in them are flushed before their expire time, some
  79. * might break functionality or are extremely expensive to recalculate. The
  80. * other bins are expired automatically by core. Contributed modules can add
  81. * additional bins and get them expired automatically by implementing
  82. * hook_flush_caches().
  83. *
  84. * The reasons for having several bins are as follows:
  85. * - Smaller bins mean smaller database tables and allow for faster selects and
  86. * inserts.
  87. * - We try to put fast changing cache items and rather static ones into
  88. * different bins. The effect is that only the fast changing bins will need a
  89. * lot of writes to disk. The more static bins will also be better cacheable
  90. * with MySQL's query cache.
  91. *
  92. * @param $cid
  93. * The cache ID of the data to store.
  94. * @param $data
  95. * The data to store in the cache. Complex data types will be automatically
  96. * serialized before insertion. Strings will be stored as plain text and are
  97. * not serialized. Some storage engines only allow objects up to a maximum of
  98. * 1MB in size to be stored by default. When caching large arrays or similar,
  99. * take care to ensure $data does not exceed this size.
  100. * @param $bin
  101. * (optional) The cache bin to store the data in. Valid core values are:
  102. * - cache: (default) Generic cache storage bin (used for theme registry,
  103. * locale date, list of simpletest tests, etc.).
  104. * - cache_block: Stores the content of various blocks.
  105. * - cache_bootstrap: Stores the class registry, the system list of modules,
  106. * the list of which modules implement which hooks, and the Drupal variable
  107. * list.
  108. * - cache_field: Stores the field data belonging to a given object.
  109. * - cache_filter: Stores filtered pieces of content.
  110. * - cache_form: Stores multistep forms. Flushing this bin means that some
  111. * forms displayed to users lose their state and the data already submitted
  112. * to them. This bin should not be flushed before its expired time.
  113. * - cache_menu: Stores the structure of visible navigation menus per page.
  114. * - cache_page: Stores generated pages for anonymous users. It is flushed
  115. * very often, whenever a page changes, at least for every node and comment
  116. * submission. This is the only bin affected by the page cache setting on
  117. * the administrator panel.
  118. * - cache_path: Stores the system paths that have an alias.
  119. * @param $expire
  120. * (optional) Controls the maximum lifetime of this cache entry. Note that
  121. * caches might be subject to clearing at any time, so this setting does not
  122. * guarantee a minimum lifetime. With this in mind, the cache should not be
  123. * used for data that must be kept during a cache clear, like sessions.
  124. *
  125. * Use 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. * 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. * Checks if a cache bin is empty.
  171. *
  172. * A cache bin is considered empty if it does not contain any valid data for any
  173. * cache ID.
  174. *
  175. * @param $bin
  176. * The cache bin to check.
  177. *
  178. * @return
  179. * TRUE if the cache bin specified is empty.
  180. */
  181. function cache_is_empty($bin) {
  182. return _cache_get_object($bin)->isEmpty();
  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. * Returns data from the persistent cache.
  224. *
  225. * Data may be stored as either plain text or as serialized data. cache_get()
  226. * will automatically return unserialized objects and arrays.
  227. *
  228. * @param $cid
  229. * The cache ID of the data to retrieve.
  230. *
  231. * @return
  232. * The cache or FALSE on failure.
  233. */
  234. function get($cid);
  235. /**
  236. * Returns data from the persistent cache when given an array of cache IDs.
  237. *
  238. * @param $cids
  239. * An array of cache IDs for the data to retrieve. This is passed by
  240. * reference, and will have the IDs successfully returned from cache
  241. * removed.
  242. *
  243. * @return
  244. * An array of the items successfully returned from cache indexed by cid.
  245. */
  246. function getMultiple(&$cids);
  247. /**
  248. * Stores data in the persistent cache.
  249. *
  250. * @param $cid
  251. * The cache ID of the data to store.
  252. * @param $data
  253. * The data to store in the cache. Complex data types will be automatically
  254. * serialized before insertion. Strings will be stored as plain text and not
  255. * serialized. Some storage engines only allow objects up to a maximum of
  256. * 1MB in size to be stored by default. When caching large arrays or
  257. * similar, take care to ensure $data does not exceed this size.
  258. * @param $expire
  259. * (optional) Controls the maximum lifetime of this cache entry. Note that
  260. * caches might be subject to clearing at any time, so this setting does not
  261. * guarantee a minimum lifetime. With this in mind, the cache should not be
  262. * used for data that must be kept during a cache clear, like sessions.
  263. *
  264. * Use 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. * Expires data from the cache.
  275. *
  276. * If called without arguments, expirable entries will be cleared from the
  277. * cache_page and cache_block bins.
  278. *
  279. * @param $cid
  280. * If set, the cache ID or an array of cache IDs. Otherwise, all cache
  281. * entries that can expire are deleted. The $wildcard argument will be
  282. * ignored if set to NULL.
  283. * @param $wildcard
  284. * If TRUE, the $cid argument must contain a string value and cache IDs
  285. * starting with $cid are deleted in addition to the exact cache ID
  286. * specified by $cid. If $wildcard is TRUE and $cid is '*', the entire
  287. * cache is emptied.
  288. */
  289. function clear($cid = NULL, $wildcard = FALSE);
  290. /**
  291. * Checks if a cache bin is empty.
  292. *
  293. * A cache bin is considered empty if it does not contain any valid data for
  294. * any cache ID.
  295. *
  296. * @return
  297. * TRUE if the cache bin specified is empty.
  298. */
  299. function isEmpty();
  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. * Constructs a DrupalDatabaseCache object.
  311. *
  312. * @param $bin
  313. * The cache bin for which the object is created.
  314. */
  315. function __construct($bin) {
  316. $this->bin = $bin;
  317. }
  318. /**
  319. * Implements DrupalCacheInterface::get().
  320. */
  321. function get($cid) {
  322. $cids = array($cid);
  323. $cache = $this->getMultiple($cids);
  324. return reset($cache);
  325. }
  326. /**
  327. * Implements DrupalCacheInterface::getMultiple().
  328. */
  329. function getMultiple(&$cids) {
  330. try {
  331. // Garbage collection necessary when enforcing a minimum cache lifetime.
  332. $this->garbageCollection($this->bin);
  333. // When serving cached pages, the overhead of using db_select() was found
  334. // to add around 30% overhead to the request. Since $this->bin is a
  335. // variable, this means the call to db_query() here uses a concatenated
  336. // string. This is highly discouraged under any other circumstances, and
  337. // is used here only due to the performance overhead we would incur
  338. // otherwise. When serving an uncached page, the overhead of using
  339. // db_select() is a much smaller proportion of the request.
  340. $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
  341. $cache = array();
  342. foreach ($result as $item) {
  343. $item = $this->prepareItem($item);
  344. if ($item) {
  345. $cache[$item->cid] = $item;
  346. }
  347. }
  348. $cids = array_diff($cids, array_keys($cache));
  349. return $cache;
  350. }
  351. catch (Exception $e) {
  352. // If the database is never going to be available, cache requests should
  353. // return FALSE in order to allow exception handling to occur.
  354. return array();
  355. }
  356. }
  357. /**
  358. * Garbage collection for get() and getMultiple().
  359. *
  360. * @param $bin
  361. * The bin being requested.
  362. */
  363. protected function garbageCollection() {
  364. $cache_lifetime = variable_get('cache_lifetime', 0);
  365. // Clean-up the per-user cache expiration session data, so that the session
  366. // handler can properly clean-up the session data for anonymous users.
  367. if (isset($_SESSION['cache_expiration'])) {
  368. $expire = REQUEST_TIME - $cache_lifetime;
  369. foreach ($_SESSION['cache_expiration'] as $bin => $timestamp) {
  370. if ($timestamp < $expire) {
  371. unset($_SESSION['cache_expiration'][$bin]);
  372. }
  373. }
  374. if (!$_SESSION['cache_expiration']) {
  375. unset($_SESSION['cache_expiration']);
  376. }
  377. }
  378. // Garbage collection of temporary items is only necessary when enforcing
  379. // a minimum cache lifetime.
  380. if (!$cache_lifetime) {
  381. return;
  382. }
  383. // When cache lifetime is in force, avoid running garbage collection too
  384. // often since this will remove temporary cache items indiscriminately.
  385. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  386. if ($cache_flush && ($cache_flush + $cache_lifetime <= REQUEST_TIME)) {
  387. // Reset the variable immediately to prevent a meltdown in heavy load situations.
  388. variable_set('cache_flush_' . $this->bin, 0);
  389. // Time to flush old cache data
  390. db_delete($this->bin)
  391. ->condition('expire', CACHE_PERMANENT, '<>')
  392. ->condition('expire', $cache_flush, '<=')
  393. ->execute();
  394. }
  395. }
  396. /**
  397. * Prepares a cached item.
  398. *
  399. * Checks that items are either permanent or did not expire, and unserializes
  400. * data as appropriate.
  401. *
  402. * @param $cache
  403. * An item loaded from cache_get() or cache_get_multiple().
  404. *
  405. * @return
  406. * The item with data unserialized as appropriate or FALSE if there is no
  407. * valid item to load.
  408. */
  409. protected function prepareItem($cache) {
  410. global $user;
  411. if (!isset($cache->data)) {
  412. return FALSE;
  413. }
  414. // If the cached data is temporary and subject to a per-user minimum
  415. // lifetime, compare the cache entry timestamp with the user session
  416. // cache_expiration timestamp. If the cache entry is too old, ignore it.
  417. if ($cache->expire != CACHE_PERMANENT && variable_get('cache_lifetime', 0) && isset($_SESSION['cache_expiration'][$this->bin]) && $_SESSION['cache_expiration'][$this->bin] > $cache->created) {
  418. // Ignore cache data that is too old and thus not valid for this user.
  419. return FALSE;
  420. }
  421. // If the data is permanent or not subject to a minimum cache lifetime,
  422. // unserialize and return the cached data.
  423. if ($cache->serialized) {
  424. $cache->data = unserialize($cache->data);
  425. }
  426. return $cache;
  427. }
  428. /**
  429. * Implements DrupalCacheInterface::set().
  430. */
  431. function set($cid, $data, $expire = CACHE_PERMANENT) {
  432. $fields = array(
  433. 'serialized' => 0,
  434. 'created' => REQUEST_TIME,
  435. 'expire' => $expire,
  436. );
  437. if (!is_string($data)) {
  438. $fields['data'] = serialize($data);
  439. $fields['serialized'] = 1;
  440. }
  441. else {
  442. $fields['data'] = $data;
  443. $fields['serialized'] = 0;
  444. }
  445. try {
  446. db_merge($this->bin)
  447. ->key(array('cid' => $cid))
  448. ->fields($fields)
  449. ->execute();
  450. }
  451. catch (Exception $e) {
  452. // The database may not be available, so we'll ignore cache_set requests.
  453. }
  454. }
  455. /**
  456. * Implements DrupalCacheInterface::clear().
  457. */
  458. function clear($cid = NULL, $wildcard = FALSE) {
  459. global $user;
  460. if (empty($cid)) {
  461. if (variable_get('cache_lifetime', 0)) {
  462. // We store the time in the current user's session. We then simulate
  463. // that the cache was flushed for this user by not returning cached
  464. // data that was cached before the timestamp.
  465. $_SESSION['cache_expiration'][$this->bin] = REQUEST_TIME;
  466. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  467. if ($cache_flush == 0) {
  468. // This is the first request to clear the cache, start a timer.
  469. variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  470. }
  471. elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
  472. // Clear the cache for everyone, cache_lifetime seconds have
  473. // passed since the first request to clear the cache.
  474. db_delete($this->bin)
  475. ->condition('expire', CACHE_PERMANENT, '<>')
  476. ->condition('expire', REQUEST_TIME, '<')
  477. ->execute();
  478. variable_set('cache_flush_' . $this->bin, 0);
  479. }
  480. }
  481. else {
  482. // No minimum cache lifetime, flush all temporary cache entries now.
  483. db_delete($this->bin)
  484. ->condition('expire', CACHE_PERMANENT, '<>')
  485. ->condition('expire', REQUEST_TIME, '<')
  486. ->execute();
  487. }
  488. }
  489. else {
  490. if ($wildcard) {
  491. if ($cid == '*') {
  492. // Check if $this->bin is a cache table before truncating. Other
  493. // cache_clear_all() operations throw a PDO error in this situation,
  494. // so we don't need to verify them first. This ensures that non-cache
  495. // tables cannot be truncated accidentally.
  496. if ($this->isValidBin()) {
  497. db_truncate($this->bin)->execute();
  498. }
  499. else {
  500. throw new Exception(t('Invalid or missing cache bin specified: %bin', array('%bin' => $this->bin)));
  501. }
  502. }
  503. else {
  504. db_delete($this->bin)
  505. ->condition('cid', db_like($cid) . '%', 'LIKE')
  506. ->execute();
  507. }
  508. }
  509. elseif (is_array($cid)) {
  510. // Delete in chunks when a large array is passed.
  511. do {
  512. db_delete($this->bin)
  513. ->condition('cid', array_splice($cid, 0, 1000), 'IN')
  514. ->execute();
  515. }
  516. while (count($cid));
  517. }
  518. else {
  519. db_delete($this->bin)
  520. ->condition('cid', $cid)
  521. ->execute();
  522. }
  523. }
  524. }
  525. /**
  526. * Implements DrupalCacheInterface::isEmpty().
  527. */
  528. function isEmpty() {
  529. $this->garbageCollection();
  530. $query = db_select($this->bin);
  531. $query->addExpression('1');
  532. $result = $query->range(0, 1)
  533. ->execute()
  534. ->fetchField();
  535. return empty($result);
  536. }
  537. /**
  538. * Checks if $this->bin represents a valid cache table.
  539. *
  540. * This check is required to ensure that non-cache tables are not truncated
  541. * accidentally when calling cache_clear_all().
  542. *
  543. * @return boolean
  544. */
  545. function isValidBin() {
  546. if ($this->bin == 'cache' || substr($this->bin, 0, 6) == 'cache_') {
  547. // Skip schema check for bins with standard table names.
  548. return TRUE;
  549. }
  550. // These fields are required for any cache table.
  551. $fields = array('cid', 'data', 'expire', 'created', 'serialized');
  552. // Load the table schema.
  553. $schema = drupal_get_schema($this->bin);
  554. // Confirm that all fields are present.
  555. return isset($schema['fields']) && !array_diff($fields, array_keys($schema['fields']));
  556. }
  557. }