cache.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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 with the arguments $cid and $bin set to NULL or omitted, then
  135. * expirable entries will be cleared from the cache_page and cache_block bins,
  136. * and the $wildcard argument is ignored.
  137. *
  138. * @param $cid
  139. * If set, the cache ID or an array of cache IDs. Otherwise, all cache entries
  140. * that can expire are deleted. The $wildcard argument will be ignored if set
  141. * to NULL.
  142. * @param $bin
  143. * If set, the cache bin to delete from. Mandatory argument if $cid is set.
  144. * @param $wildcard
  145. * If TRUE, the $cid argument must contain a string value and cache IDs
  146. * starting with $cid are deleted in addition to the exact cache ID specified
  147. * by $cid. If $wildcard is TRUE and $cid is '*', the entire cache is emptied.
  148. */
  149. function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
  150. if (!isset($cid) && !isset($bin)) {
  151. // Clear the block cache first, so stale data will
  152. // not end up in the page cache.
  153. if (module_exists('block')) {
  154. cache_clear_all(NULL, 'cache_block');
  155. }
  156. cache_clear_all(NULL, 'cache_page');
  157. return;
  158. }
  159. return _cache_get_object($bin)->clear($cid, $wildcard);
  160. }
  161. /**
  162. * Checks if a cache bin is empty.
  163. *
  164. * A cache bin is considered empty if it does not contain any valid data for any
  165. * cache ID.
  166. *
  167. * @param $bin
  168. * The cache bin to check.
  169. *
  170. * @return
  171. * TRUE if the cache bin specified is empty.
  172. */
  173. function cache_is_empty($bin) {
  174. return _cache_get_object($bin)->isEmpty();
  175. }
  176. /**
  177. * Defines an interface for cache implementations.
  178. *
  179. * All cache implementations have to implement this interface.
  180. * DrupalDatabaseCache provides the default implementation, which can be
  181. * consulted as an example.
  182. *
  183. * To make Drupal use your implementation for a certain cache bin, you have to
  184. * set a variable with the name of the cache bin as its key and the name of
  185. * your class as its value. For example, if your implementation of
  186. * DrupalCacheInterface was called MyCustomCache, the following line would make
  187. * Drupal use it for the 'cache_page' bin:
  188. * @code
  189. * variable_set('cache_class_cache_page', 'MyCustomCache');
  190. * @endcode
  191. *
  192. * Additionally, you can register your cache implementation to be used by
  193. * default for all cache bins by setting the variable 'cache_default_class' to
  194. * the name of your implementation of the DrupalCacheInterface, e.g.
  195. * @code
  196. * variable_set('cache_default_class', 'MyCustomCache');
  197. * @endcode
  198. *
  199. * To implement a completely custom cache bin, use the same variable format:
  200. * @code
  201. * variable_set('cache_class_custom_bin', 'MyCustomCache');
  202. * @endcode
  203. * To access your custom cache bin, specify the name of the bin when storing
  204. * or retrieving cached data:
  205. * @code
  206. * cache_set($cid, $data, 'custom_bin', $expire);
  207. * cache_get($cid, 'custom_bin');
  208. * @endcode
  209. *
  210. * @see _cache_get_object()
  211. * @see DrupalDatabaseCache
  212. */
  213. interface DrupalCacheInterface {
  214. /**
  215. * Returns data from the persistent cache.
  216. *
  217. * Data may be stored as either plain text or as serialized data. cache_get()
  218. * will automatically return unserialized objects and arrays.
  219. *
  220. * @param $cid
  221. * The cache ID of the data to retrieve.
  222. *
  223. * @return
  224. * The cache or FALSE on failure.
  225. */
  226. function get($cid);
  227. /**
  228. * Returns data from the persistent cache when given an array of cache IDs.
  229. *
  230. * @param $cids
  231. * An array of cache IDs for the data to retrieve. This is passed by
  232. * reference, and will have the IDs successfully returned from cache
  233. * removed.
  234. *
  235. * @return
  236. * An array of the items successfully returned from cache indexed by cid.
  237. */
  238. function getMultiple(&$cids);
  239. /**
  240. * Stores data in the persistent cache.
  241. *
  242. * @param $cid
  243. * The cache ID of the data to store.
  244. * @param $data
  245. * The data to store in the cache. Complex data types will be automatically
  246. * serialized before insertion.
  247. * Strings will be stored as plain text and not serialized.
  248. * @param $expire
  249. * One of the following values:
  250. * - CACHE_PERMANENT: Indicates that the item should never be removed unless
  251. * explicitly told to using cache_clear_all() with a cache ID.
  252. * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
  253. * general cache wipe.
  254. * - A Unix timestamp: Indicates that the item should be kept at least until
  255. * the given time, after which it behaves like CACHE_TEMPORARY.
  256. */
  257. function set($cid, $data, $expire = CACHE_PERMANENT);
  258. /**
  259. * Expires data from the cache.
  260. *
  261. * If called without arguments, expirable entries will be cleared from the
  262. * cache_page and cache_block bins.
  263. *
  264. * @param $cid
  265. * If set, the cache ID or an array of cache IDs. Otherwise, all cache
  266. * entries that can expire are deleted. The $wildcard argument will be
  267. * ignored if set to NULL.
  268. * @param $wildcard
  269. * If TRUE, the $cid argument must contain a string value and cache IDs
  270. * starting with $cid are deleted in addition to the exact cache ID
  271. * specified by $cid. If $wildcard is TRUE and $cid is '*', the entire
  272. * cache is emptied.
  273. */
  274. function clear($cid = NULL, $wildcard = FALSE);
  275. /**
  276. * Checks if a cache bin is empty.
  277. *
  278. * A cache bin is considered empty if it does not contain any valid data for
  279. * any cache ID.
  280. *
  281. * @return
  282. * TRUE if the cache bin specified is empty.
  283. */
  284. function isEmpty();
  285. }
  286. /**
  287. * Defines a default cache implementation.
  288. *
  289. * This is Drupal's default cache implementation. It uses the database to store
  290. * cached data. Each cache bin corresponds to a database table by the same name.
  291. */
  292. class DrupalDatabaseCache implements DrupalCacheInterface {
  293. protected $bin;
  294. /**
  295. * Constructs a DrupalDatabaseCache object.
  296. *
  297. * @param $bin
  298. * The cache bin for which the object is created.
  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. // Check if $this->bin is a cache table before truncating. Other
  478. // cache_clear_all() operations throw a PDO error in this situation,
  479. // so we don't need to verify them first. This ensures that non-cache
  480. // tables cannot be truncated accidentally.
  481. if ($this->isValidBin()) {
  482. db_truncate($this->bin)->execute();
  483. }
  484. else {
  485. throw new Exception(t('Invalid or missing cache bin specified: %bin', array('%bin' => $this->bin)));
  486. }
  487. }
  488. else {
  489. db_delete($this->bin)
  490. ->condition('cid', db_like($cid) . '%', 'LIKE')
  491. ->execute();
  492. }
  493. }
  494. elseif (is_array($cid)) {
  495. // Delete in chunks when a large array is passed.
  496. do {
  497. db_delete($this->bin)
  498. ->condition('cid', array_splice($cid, 0, 1000), 'IN')
  499. ->execute();
  500. }
  501. while (count($cid));
  502. }
  503. else {
  504. db_delete($this->bin)
  505. ->condition('cid', $cid)
  506. ->execute();
  507. }
  508. }
  509. }
  510. /**
  511. * Implements DrupalCacheInterface::isEmpty().
  512. */
  513. function isEmpty() {
  514. $this->garbageCollection();
  515. $query = db_select($this->bin);
  516. $query->addExpression('1');
  517. $result = $query->range(0, 1)
  518. ->execute()
  519. ->fetchField();
  520. return empty($result);
  521. }
  522. /**
  523. * Checks if $this->bin represents a valid cache table.
  524. *
  525. * This check is required to ensure that non-cache tables are not truncated
  526. * accidentally when calling cache_clear_all().
  527. *
  528. * @return boolean
  529. */
  530. function isValidBin() {
  531. if ($this->bin == 'cache' || substr($this->bin, 0, 6) == 'cache_') {
  532. // Skip schema check for bins with standard table names.
  533. return TRUE;
  534. }
  535. // These fields are required for any cache table.
  536. $fields = array('cid', 'data', 'expire', 'created', 'serialized');
  537. // Load the table schema.
  538. $schema = drupal_get_schema($this->bin);
  539. // Confirm that all fields are present.
  540. return isset($schema['fields']) && !array_diff($fields, array_keys($schema['fields']));
  541. }
  542. }