cache.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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) One of the following values:
  121. * - CACHE_PERMANENT: Indicates that the item should never be removed unless
  122. * explicitly told to using cache_clear_all() with a cache ID.
  123. * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
  124. * general cache wipe.
  125. * - A Unix timestamp: Indicates that the item should be kept at least until
  126. * the given time, after which it behaves like CACHE_TEMPORARY.
  127. *
  128. * @see _update_cache_set()
  129. * @see cache_get()
  130. */
  131. function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  132. return _cache_get_object($bin)->set($cid, $data, $expire);
  133. }
  134. /**
  135. * Expires data from the cache.
  136. *
  137. * If called with the arguments $cid and $bin set to NULL or omitted, then
  138. * expirable entries will be cleared from the cache_page and cache_block bins,
  139. * and the $wildcard argument is ignored.
  140. *
  141. * @param $cid
  142. * If set, the cache ID or an array of cache IDs. Otherwise, all cache entries
  143. * that can expire are deleted. The $wildcard argument will be ignored if set
  144. * to NULL.
  145. * @param $bin
  146. * If set, the cache bin to delete from. Mandatory argument if $cid is set.
  147. * @param $wildcard
  148. * If TRUE, the $cid argument must contain a string value and cache IDs
  149. * starting with $cid are deleted in addition to the exact cache ID specified
  150. * by $cid. If $wildcard is TRUE and $cid is '*', the entire cache is emptied.
  151. */
  152. function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
  153. if (!isset($cid) && !isset($bin)) {
  154. // Clear the block cache first, so stale data will
  155. // not end up in the page cache.
  156. if (module_exists('block')) {
  157. cache_clear_all(NULL, 'cache_block');
  158. }
  159. cache_clear_all(NULL, 'cache_page');
  160. return;
  161. }
  162. return _cache_get_object($bin)->clear($cid, $wildcard);
  163. }
  164. /**
  165. * Checks if a cache bin is empty.
  166. *
  167. * A cache bin is considered empty if it does not contain any valid data for any
  168. * cache ID.
  169. *
  170. * @param $bin
  171. * The cache bin to check.
  172. *
  173. * @return
  174. * TRUE if the cache bin specified is empty.
  175. */
  176. function cache_is_empty($bin) {
  177. return _cache_get_object($bin)->isEmpty();
  178. }
  179. /**
  180. * Defines an interface for cache implementations.
  181. *
  182. * All cache implementations have to implement this interface.
  183. * DrupalDatabaseCache provides the default implementation, which can be
  184. * consulted as an example.
  185. *
  186. * To make Drupal use your implementation for a certain cache bin, you have to
  187. * set a variable with the name of the cache bin as its key and the name of
  188. * your class as its value. For example, if your implementation of
  189. * DrupalCacheInterface was called MyCustomCache, the following line would make
  190. * Drupal use it for the 'cache_page' bin:
  191. * @code
  192. * variable_set('cache_class_cache_page', 'MyCustomCache');
  193. * @endcode
  194. *
  195. * Additionally, you can register your cache implementation to be used by
  196. * default for all cache bins by setting the variable 'cache_default_class' to
  197. * the name of your implementation of the DrupalCacheInterface, e.g.
  198. * @code
  199. * variable_set('cache_default_class', 'MyCustomCache');
  200. * @endcode
  201. *
  202. * To implement a completely custom cache bin, use the same variable format:
  203. * @code
  204. * variable_set('cache_class_custom_bin', 'MyCustomCache');
  205. * @endcode
  206. * To access your custom cache bin, specify the name of the bin when storing
  207. * or retrieving cached data:
  208. * @code
  209. * cache_set($cid, $data, 'custom_bin', $expire);
  210. * cache_get($cid, 'custom_bin');
  211. * @endcode
  212. *
  213. * @see _cache_get_object()
  214. * @see DrupalDatabaseCache
  215. */
  216. interface DrupalCacheInterface {
  217. /**
  218. * Returns data from the persistent cache.
  219. *
  220. * Data may be stored as either plain text or as serialized data. cache_get()
  221. * will automatically return unserialized objects and arrays.
  222. *
  223. * @param $cid
  224. * The cache ID of the data to retrieve.
  225. *
  226. * @return
  227. * The cache or FALSE on failure.
  228. */
  229. function get($cid);
  230. /**
  231. * Returns data from the persistent cache when given an array of cache IDs.
  232. *
  233. * @param $cids
  234. * An array of cache IDs for the data to retrieve. This is passed by
  235. * reference, and will have the IDs successfully returned from cache
  236. * removed.
  237. *
  238. * @return
  239. * An array of the items successfully returned from cache indexed by cid.
  240. */
  241. function getMultiple(&$cids);
  242. /**
  243. * Stores data in the persistent cache.
  244. *
  245. * @param $cid
  246. * The cache ID of the data to store.
  247. * @param $data
  248. * The data to store in the cache. Complex data types will be automatically
  249. * serialized before insertion. Strings will be stored as plain text and not
  250. * serialized. Some storage engines only allow objects up to a maximum of
  251. * 1MB in size to be stored by default. When caching large arrays or
  252. * similar, take care to ensure $data does not exceed this size.
  253. * @param $expire
  254. * (optional) 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 or an array of cache IDs. Otherwise, all cache
  271. * entries that can expire are deleted. The $wildcard argument will be
  272. * ignored if set to NULL.
  273. * @param $wildcard
  274. * If TRUE, the $cid argument must contain a string value and cache IDs
  275. * starting with $cid are deleted in addition to the exact cache ID
  276. * specified by $cid. If $wildcard is TRUE and $cid is '*', the entire
  277. * cache is emptied.
  278. */
  279. function clear($cid = NULL, $wildcard = FALSE);
  280. /**
  281. * Checks if a cache bin is empty.
  282. *
  283. * A cache bin is considered empty if it does not contain any valid data for
  284. * any cache ID.
  285. *
  286. * @return
  287. * TRUE if the cache bin specified is empty.
  288. */
  289. function isEmpty();
  290. }
  291. /**
  292. * Defines a default cache implementation.
  293. *
  294. * This is Drupal's default cache implementation. It uses the database to store
  295. * cached data. Each cache bin corresponds to a database table by the same name.
  296. */
  297. class DrupalDatabaseCache implements DrupalCacheInterface {
  298. protected $bin;
  299. /**
  300. * Constructs a DrupalDatabaseCache object.
  301. *
  302. * @param $bin
  303. * The cache bin for which the object is created.
  304. */
  305. function __construct($bin) {
  306. $this->bin = $bin;
  307. }
  308. /**
  309. * Implements DrupalCacheInterface::get().
  310. */
  311. function get($cid) {
  312. $cids = array($cid);
  313. $cache = $this->getMultiple($cids);
  314. return reset($cache);
  315. }
  316. /**
  317. * Implements DrupalCacheInterface::getMultiple().
  318. */
  319. function getMultiple(&$cids) {
  320. try {
  321. // Garbage collection necessary when enforcing a minimum cache lifetime.
  322. $this->garbageCollection($this->bin);
  323. // When serving cached pages, the overhead of using db_select() was found
  324. // to add around 30% overhead to the request. Since $this->bin is a
  325. // variable, this means the call to db_query() here uses a concatenated
  326. // string. This is highly discouraged under any other circumstances, and
  327. // is used here only due to the performance overhead we would incur
  328. // otherwise. When serving an uncached page, the overhead of using
  329. // db_select() is a much smaller proportion of the request.
  330. $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
  331. $cache = array();
  332. foreach ($result as $item) {
  333. $item = $this->prepareItem($item);
  334. if ($item) {
  335. $cache[$item->cid] = $item;
  336. }
  337. }
  338. $cids = array_diff($cids, array_keys($cache));
  339. return $cache;
  340. }
  341. catch (Exception $e) {
  342. // If the database is never going to be available, cache requests should
  343. // return FALSE in order to allow exception handling to occur.
  344. return array();
  345. }
  346. }
  347. /**
  348. * Garbage collection for get() and getMultiple().
  349. *
  350. * @param $bin
  351. * The bin being requested.
  352. */
  353. protected function garbageCollection() {
  354. $cache_lifetime = variable_get('cache_lifetime', 0);
  355. // Clean-up the per-user cache expiration session data, so that the session
  356. // handler can properly clean-up the session data for anonymous users.
  357. if (isset($_SESSION['cache_expiration'])) {
  358. $expire = REQUEST_TIME - $cache_lifetime;
  359. foreach ($_SESSION['cache_expiration'] as $bin => $timestamp) {
  360. if ($timestamp < $expire) {
  361. unset($_SESSION['cache_expiration'][$bin]);
  362. }
  363. }
  364. if (!$_SESSION['cache_expiration']) {
  365. unset($_SESSION['cache_expiration']);
  366. }
  367. }
  368. // Garbage collection of temporary items is only necessary when enforcing
  369. // a minimum cache lifetime.
  370. if (!$cache_lifetime) {
  371. return;
  372. }
  373. // When cache lifetime is in force, avoid running garbage collection too
  374. // often since this will remove temporary cache items indiscriminately.
  375. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  376. if ($cache_flush && ($cache_flush + $cache_lifetime <= REQUEST_TIME)) {
  377. // Reset the variable immediately to prevent a meltdown in heavy load situations.
  378. variable_set('cache_flush_' . $this->bin, 0);
  379. // Time to flush old cache data
  380. db_delete($this->bin)
  381. ->condition('expire', CACHE_PERMANENT, '<>')
  382. ->condition('expire', $cache_flush, '<=')
  383. ->execute();
  384. }
  385. }
  386. /**
  387. * Prepares a cached item.
  388. *
  389. * Checks that items are either permanent or did not expire, and unserializes
  390. * data as appropriate.
  391. *
  392. * @param $cache
  393. * An item loaded from cache_get() or cache_get_multiple().
  394. *
  395. * @return
  396. * The item with data unserialized as appropriate or FALSE if there is no
  397. * valid item to load.
  398. */
  399. protected function prepareItem($cache) {
  400. global $user;
  401. if (!isset($cache->data)) {
  402. return FALSE;
  403. }
  404. // If the cached data is temporary and subject to a per-user minimum
  405. // lifetime, compare the cache entry timestamp with the user session
  406. // cache_expiration timestamp. If the cache entry is too old, ignore it.
  407. if ($cache->expire != CACHE_PERMANENT && variable_get('cache_lifetime', 0) && isset($_SESSION['cache_expiration'][$this->bin]) && $_SESSION['cache_expiration'][$this->bin] > $cache->created) {
  408. // Ignore cache data that is too old and thus not valid for this user.
  409. return FALSE;
  410. }
  411. // If the data is permanent or not subject to a minimum cache lifetime,
  412. // unserialize and return the cached data.
  413. if ($cache->serialized) {
  414. $cache->data = unserialize($cache->data);
  415. }
  416. return $cache;
  417. }
  418. /**
  419. * Implements DrupalCacheInterface::set().
  420. */
  421. function set($cid, $data, $expire = CACHE_PERMANENT) {
  422. $fields = array(
  423. 'serialized' => 0,
  424. 'created' => REQUEST_TIME,
  425. 'expire' => $expire,
  426. );
  427. if (!is_string($data)) {
  428. $fields['data'] = serialize($data);
  429. $fields['serialized'] = 1;
  430. }
  431. else {
  432. $fields['data'] = $data;
  433. $fields['serialized'] = 0;
  434. }
  435. try {
  436. db_merge($this->bin)
  437. ->key(array('cid' => $cid))
  438. ->fields($fields)
  439. ->execute();
  440. }
  441. catch (Exception $e) {
  442. // The database may not be available, so we'll ignore cache_set requests.
  443. }
  444. }
  445. /**
  446. * Implements DrupalCacheInterface::clear().
  447. */
  448. function clear($cid = NULL, $wildcard = FALSE) {
  449. global $user;
  450. if (empty($cid)) {
  451. if (variable_get('cache_lifetime', 0)) {
  452. // We store the time in the current user's session. We then simulate
  453. // that the cache was flushed for this user by not returning cached
  454. // data that was cached before the timestamp.
  455. $_SESSION['cache_expiration'][$this->bin] = REQUEST_TIME;
  456. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  457. if ($cache_flush == 0) {
  458. // This is the first request to clear the cache, start a timer.
  459. variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  460. }
  461. elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
  462. // Clear the cache for everyone, cache_lifetime seconds have
  463. // passed since the first request to clear the cache.
  464. db_delete($this->bin)
  465. ->condition('expire', CACHE_PERMANENT, '<>')
  466. ->condition('expire', REQUEST_TIME, '<')
  467. ->execute();
  468. variable_set('cache_flush_' . $this->bin, 0);
  469. }
  470. }
  471. else {
  472. // No minimum cache lifetime, flush all temporary cache entries now.
  473. db_delete($this->bin)
  474. ->condition('expire', CACHE_PERMANENT, '<>')
  475. ->condition('expire', REQUEST_TIME, '<')
  476. ->execute();
  477. }
  478. }
  479. else {
  480. if ($wildcard) {
  481. if ($cid == '*') {
  482. // Check if $this->bin is a cache table before truncating. Other
  483. // cache_clear_all() operations throw a PDO error in this situation,
  484. // so we don't need to verify them first. This ensures that non-cache
  485. // tables cannot be truncated accidentally.
  486. if ($this->isValidBin()) {
  487. db_truncate($this->bin)->execute();
  488. }
  489. else {
  490. throw new Exception(t('Invalid or missing cache bin specified: %bin', array('%bin' => $this->bin)));
  491. }
  492. }
  493. else {
  494. db_delete($this->bin)
  495. ->condition('cid', db_like($cid) . '%', 'LIKE')
  496. ->execute();
  497. }
  498. }
  499. elseif (is_array($cid)) {
  500. // Delete in chunks when a large array is passed.
  501. do {
  502. db_delete($this->bin)
  503. ->condition('cid', array_splice($cid, 0, 1000), 'IN')
  504. ->execute();
  505. }
  506. while (count($cid));
  507. }
  508. else {
  509. db_delete($this->bin)
  510. ->condition('cid', $cid)
  511. ->execute();
  512. }
  513. }
  514. }
  515. /**
  516. * Implements DrupalCacheInterface::isEmpty().
  517. */
  518. function isEmpty() {
  519. $this->garbageCollection();
  520. $query = db_select($this->bin);
  521. $query->addExpression('1');
  522. $result = $query->range(0, 1)
  523. ->execute()
  524. ->fetchField();
  525. return empty($result);
  526. }
  527. /**
  528. * Checks if $this->bin represents a valid cache table.
  529. *
  530. * This check is required to ensure that non-cache tables are not truncated
  531. * accidentally when calling cache_clear_all().
  532. *
  533. * @return boolean
  534. */
  535. function isValidBin() {
  536. if ($this->bin == 'cache' || substr($this->bin, 0, 6) == 'cache_') {
  537. // Skip schema check for bins with standard table names.
  538. return TRUE;
  539. }
  540. // These fields are required for any cache table.
  541. $fields = array('cid', 'data', 'expire', 'created', 'serialized');
  542. // Load the table schema.
  543. $schema = drupal_get_schema($this->bin);
  544. // Confirm that all fields are present.
  545. return isset($schema['fields']) && !array_diff($fields, array_keys($schema['fields']));
  546. }
  547. }