cache.inc 18 KB

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