cache.inc 20 KB

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