class-wp-object-cache.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. <?php
  2. /**
  3. * Object Cache API: WP_Object_Cache class
  4. *
  5. * @package WordPress
  6. * @subpackage Cache
  7. * @since 5.4.0
  8. */
  9. /**
  10. * Core class that implements an object cache.
  11. *
  12. * The WordPress Object Cache is used to save on trips to the database. The
  13. * Object Cache stores all of the cache data to memory and makes the cache
  14. * contents available by using a key, which is used to name and later retrieve
  15. * the cache contents.
  16. *
  17. * The Object Cache can be replaced by other caching mechanisms by placing files
  18. * in the wp-content folder which is looked at in wp-settings. If that file
  19. * exists, then this file will not be included.
  20. *
  21. * @since 2.0.0
  22. */
  23. #[AllowDynamicProperties]
  24. class WP_Object_Cache {
  25. /**
  26. * Holds the cached objects.
  27. *
  28. * @since 2.0.0
  29. * @var array
  30. */
  31. private $cache = array();
  32. /**
  33. * The amount of times the cache data was already stored in the cache.
  34. *
  35. * @since 2.5.0
  36. * @var int
  37. */
  38. public $cache_hits = 0;
  39. /**
  40. * Amount of times the cache did not have the request in cache.
  41. *
  42. * @since 2.0.0
  43. * @var int
  44. */
  45. public $cache_misses = 0;
  46. /**
  47. * List of global cache groups.
  48. *
  49. * @since 3.0.0
  50. * @var string[]
  51. */
  52. protected $global_groups = array();
  53. /**
  54. * The blog prefix to prepend to keys in non-global groups.
  55. *
  56. * @since 3.5.0
  57. * @var string
  58. */
  59. private $blog_prefix;
  60. /**
  61. * Holds the value of is_multisite().
  62. *
  63. * @since 3.5.0
  64. * @var bool
  65. */
  66. private $multisite;
  67. /**
  68. * Sets up object properties; PHP 5 style constructor.
  69. *
  70. * @since 2.0.8
  71. */
  72. public function __construct() {
  73. $this->multisite = is_multisite();
  74. $this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : '';
  75. }
  76. /**
  77. * Makes private properties readable for backward compatibility.
  78. *
  79. * @since 4.0.0
  80. *
  81. * @param string $name Property to get.
  82. * @return mixed Property.
  83. */
  84. public function __get( $name ) {
  85. return $this->$name;
  86. }
  87. /**
  88. * Makes private properties settable for backward compatibility.
  89. *
  90. * @since 4.0.0
  91. *
  92. * @param string $name Property to set.
  93. * @param mixed $value Property value.
  94. * @return mixed Newly-set property.
  95. */
  96. public function __set( $name, $value ) {
  97. return $this->$name = $value;
  98. }
  99. /**
  100. * Makes private properties checkable for backward compatibility.
  101. *
  102. * @since 4.0.0
  103. *
  104. * @param string $name Property to check if set.
  105. * @return bool Whether the property is set.
  106. */
  107. public function __isset( $name ) {
  108. return isset( $this->$name );
  109. }
  110. /**
  111. * Makes private properties un-settable for backward compatibility.
  112. *
  113. * @since 4.0.0
  114. *
  115. * @param string $name Property to unset.
  116. */
  117. public function __unset( $name ) {
  118. unset( $this->$name );
  119. }
  120. /**
  121. * Serves as a utility function to determine whether a key is valid.
  122. *
  123. * @since 6.1.0
  124. *
  125. * @param int|string $key Cache key to check for validity.
  126. * @return bool Whether the key is valid.
  127. */
  128. protected function is_valid_key( $key ) {
  129. if ( is_int( $key ) ) {
  130. return true;
  131. }
  132. if ( is_string( $key ) && trim( $key ) !== '' ) {
  133. return true;
  134. }
  135. $type = gettype( $key );
  136. if ( ! function_exists( '__' ) ) {
  137. wp_load_translations_early();
  138. }
  139. $message = is_string( $key )
  140. ? __( 'Cache key must not be an empty string.' )
  141. /* translators: %s: The type of the given cache key. */
  142. : sprintf( __( 'Cache key must be integer or non-empty string, %s given.' ), $type );
  143. _doing_it_wrong(
  144. sprintf( '%s::%s', __CLASS__, debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 )[1]['function'] ),
  145. $message,
  146. '6.1.0'
  147. );
  148. return false;
  149. }
  150. /**
  151. * Serves as a utility function to determine whether a key exists in the cache.
  152. *
  153. * @since 3.4.0
  154. *
  155. * @param int|string $key Cache key to check for existence.
  156. * @param string $group Cache group for the key existence check.
  157. * @return bool Whether the key exists in the cache for the given group.
  158. */
  159. protected function _exists( $key, $group ) {
  160. return isset( $this->cache[ $group ] ) && ( isset( $this->cache[ $group ][ $key ] ) || array_key_exists( $key, $this->cache[ $group ] ) );
  161. }
  162. /**
  163. * Adds data to the cache if it doesn't already exist.
  164. *
  165. * @since 2.0.0
  166. *
  167. * @uses WP_Object_Cache::_exists() Checks to see if the cache already has data.
  168. * @uses WP_Object_Cache::set() Sets the data after the checking the cache
  169. * contents existence.
  170. *
  171. * @param int|string $key What to call the contents in the cache.
  172. * @param mixed $data The contents to store in the cache.
  173. * @param string $group Optional. Where to group the cache contents. Default 'default'.
  174. * @param int $expire Optional. When to expire the cache contents, in seconds.
  175. * Default 0 (no expiration).
  176. * @return bool True on success, false if cache key and group already exist.
  177. */
  178. public function add( $key, $data, $group = 'default', $expire = 0 ) {
  179. if ( wp_suspend_cache_addition() ) {
  180. return false;
  181. }
  182. if ( ! $this->is_valid_key( $key ) ) {
  183. return false;
  184. }
  185. if ( empty( $group ) ) {
  186. $group = 'default';
  187. }
  188. $id = $key;
  189. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  190. $id = $this->blog_prefix . $key;
  191. }
  192. if ( $this->_exists( $id, $group ) ) {
  193. return false;
  194. }
  195. return $this->set( $key, $data, $group, (int) $expire );
  196. }
  197. /**
  198. * Adds multiple values to the cache in one call.
  199. *
  200. * @since 6.0.0
  201. *
  202. * @param array $data Array of keys and values to be added.
  203. * @param string $group Optional. Where the cache contents are grouped. Default empty.
  204. * @param int $expire Optional. When to expire the cache contents, in seconds.
  205. * Default 0 (no expiration).
  206. * @return bool[] Array of return values, grouped by key. Each value is either
  207. * true on success, or false if cache key and group already exist.
  208. */
  209. public function add_multiple( array $data, $group = '', $expire = 0 ) {
  210. $values = array();
  211. foreach ( $data as $key => $value ) {
  212. $values[ $key ] = $this->add( $key, $value, $group, $expire );
  213. }
  214. return $values;
  215. }
  216. /**
  217. * Replaces the contents in the cache, if contents already exist.
  218. *
  219. * @since 2.0.0
  220. *
  221. * @see WP_Object_Cache::set()
  222. *
  223. * @param int|string $key What to call the contents in the cache.
  224. * @param mixed $data The contents to store in the cache.
  225. * @param string $group Optional. Where to group the cache contents. Default 'default'.
  226. * @param int $expire Optional. When to expire the cache contents, in seconds.
  227. * Default 0 (no expiration).
  228. * @return bool True if contents were replaced, false if original value does not exist.
  229. */
  230. public function replace( $key, $data, $group = 'default', $expire = 0 ) {
  231. if ( ! $this->is_valid_key( $key ) ) {
  232. return false;
  233. }
  234. if ( empty( $group ) ) {
  235. $group = 'default';
  236. }
  237. $id = $key;
  238. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  239. $id = $this->blog_prefix . $key;
  240. }
  241. if ( ! $this->_exists( $id, $group ) ) {
  242. return false;
  243. }
  244. return $this->set( $key, $data, $group, (int) $expire );
  245. }
  246. /**
  247. * Sets the data contents into the cache.
  248. *
  249. * The cache contents are grouped by the $group parameter followed by the
  250. * $key. This allows for duplicate IDs in unique groups. Therefore, naming of
  251. * the group should be used with care and should follow normal function
  252. * naming guidelines outside of core WordPress usage.
  253. *
  254. * The $expire parameter is not used, because the cache will automatically
  255. * expire for each time a page is accessed and PHP finishes. The method is
  256. * more for cache plugins which use files.
  257. *
  258. * @since 2.0.0
  259. * @since 6.1.0 Returns false if cache key is invalid.
  260. *
  261. * @param int|string $key What to call the contents in the cache.
  262. * @param mixed $data The contents to store in the cache.
  263. * @param string $group Optional. Where to group the cache contents. Default 'default'.
  264. * @param int $expire Optional. Not used.
  265. * @return bool True if contents were set, false if key is invalid.
  266. */
  267. public function set( $key, $data, $group = 'default', $expire = 0 ) {
  268. if ( ! $this->is_valid_key( $key ) ) {
  269. return false;
  270. }
  271. if ( empty( $group ) ) {
  272. $group = 'default';
  273. }
  274. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  275. $key = $this->blog_prefix . $key;
  276. }
  277. if ( is_object( $data ) ) {
  278. $data = clone $data;
  279. }
  280. $this->cache[ $group ][ $key ] = $data;
  281. return true;
  282. }
  283. /**
  284. * Sets multiple values to the cache in one call.
  285. *
  286. * @since 6.0.0
  287. *
  288. * @param array $data Array of key and value to be set.
  289. * @param string $group Optional. Where the cache contents are grouped. Default empty.
  290. * @param int $expire Optional. When to expire the cache contents, in seconds.
  291. * Default 0 (no expiration).
  292. * @return bool[] Array of return values, grouped by key. Each value is always true.
  293. */
  294. public function set_multiple( array $data, $group = '', $expire = 0 ) {
  295. $values = array();
  296. foreach ( $data as $key => $value ) {
  297. $values[ $key ] = $this->set( $key, $value, $group, $expire );
  298. }
  299. return $values;
  300. }
  301. /**
  302. * Retrieves the cache contents, if it exists.
  303. *
  304. * The contents will be first attempted to be retrieved by searching by the
  305. * key in the cache group. If the cache is hit (success) then the contents
  306. * are returned.
  307. *
  308. * On failure, the number of cache misses will be incremented.
  309. *
  310. * @since 2.0.0
  311. *
  312. * @param int|string $key The key under which the cache contents are stored.
  313. * @param string $group Optional. Where the cache contents are grouped. Default 'default'.
  314. * @param bool $force Optional. Unused. Whether to force an update of the local cache
  315. * from the persistent cache. Default false.
  316. * @param bool $found Optional. Whether the key was found in the cache (passed by reference).
  317. * Disambiguates a return of false, a storable value. Default null.
  318. * @return mixed|false The cache contents on success, false on failure to retrieve contents.
  319. */
  320. public function get( $key, $group = 'default', $force = false, &$found = null ) {
  321. if ( ! $this->is_valid_key( $key ) ) {
  322. return false;
  323. }
  324. if ( empty( $group ) ) {
  325. $group = 'default';
  326. }
  327. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  328. $key = $this->blog_prefix . $key;
  329. }
  330. if ( $this->_exists( $key, $group ) ) {
  331. $found = true;
  332. $this->cache_hits += 1;
  333. if ( is_object( $this->cache[ $group ][ $key ] ) ) {
  334. return clone $this->cache[ $group ][ $key ];
  335. } else {
  336. return $this->cache[ $group ][ $key ];
  337. }
  338. }
  339. $found = false;
  340. $this->cache_misses += 1;
  341. return false;
  342. }
  343. /**
  344. * Retrieves multiple values from the cache in one call.
  345. *
  346. * @since 5.5.0
  347. *
  348. * @param array $keys Array of keys under which the cache contents are stored.
  349. * @param string $group Optional. Where the cache contents are grouped. Default 'default'.
  350. * @param bool $force Optional. Whether to force an update of the local cache
  351. * from the persistent cache. Default false.
  352. * @return array Array of return values, grouped by key. Each value is either
  353. * the cache contents on success, or false on failure.
  354. */
  355. public function get_multiple( $keys, $group = 'default', $force = false ) {
  356. $values = array();
  357. foreach ( $keys as $key ) {
  358. $values[ $key ] = $this->get( $key, $group, $force );
  359. }
  360. return $values;
  361. }
  362. /**
  363. * Removes the contents of the cache key in the group.
  364. *
  365. * If the cache key does not exist in the group, then nothing will happen.
  366. *
  367. * @since 2.0.0
  368. *
  369. * @param int|string $key What the contents in the cache are called.
  370. * @param string $group Optional. Where the cache contents are grouped. Default 'default'.
  371. * @param bool $deprecated Optional. Unused. Default false.
  372. * @return bool True on success, false if the contents were not deleted.
  373. */
  374. public function delete( $key, $group = 'default', $deprecated = false ) {
  375. if ( ! $this->is_valid_key( $key ) ) {
  376. return false;
  377. }
  378. if ( empty( $group ) ) {
  379. $group = 'default';
  380. }
  381. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  382. $key = $this->blog_prefix . $key;
  383. }
  384. if ( ! $this->_exists( $key, $group ) ) {
  385. return false;
  386. }
  387. unset( $this->cache[ $group ][ $key ] );
  388. return true;
  389. }
  390. /**
  391. * Deletes multiple values from the cache in one call.
  392. *
  393. * @since 6.0.0
  394. *
  395. * @param array $keys Array of keys to be deleted.
  396. * @param string $group Optional. Where the cache contents are grouped. Default empty.
  397. * @return bool[] Array of return values, grouped by key. Each value is either
  398. * true on success, or false if the contents were not deleted.
  399. */
  400. public function delete_multiple( array $keys, $group = '' ) {
  401. $values = array();
  402. foreach ( $keys as $key ) {
  403. $values[ $key ] = $this->delete( $key, $group );
  404. }
  405. return $values;
  406. }
  407. /**
  408. * Increments numeric cache item's value.
  409. *
  410. * @since 3.3.0
  411. *
  412. * @param int|string $key The cache key to increment.
  413. * @param int $offset Optional. The amount by which to increment the item's value.
  414. * Default 1.
  415. * @param string $group Optional. The group the key is in. Default 'default'.
  416. * @return int|false The item's new value on success, false on failure.
  417. */
  418. public function incr( $key, $offset = 1, $group = 'default' ) {
  419. if ( ! $this->is_valid_key( $key ) ) {
  420. return false;
  421. }
  422. if ( empty( $group ) ) {
  423. $group = 'default';
  424. }
  425. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  426. $key = $this->blog_prefix . $key;
  427. }
  428. if ( ! $this->_exists( $key, $group ) ) {
  429. return false;
  430. }
  431. if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) {
  432. $this->cache[ $group ][ $key ] = 0;
  433. }
  434. $offset = (int) $offset;
  435. $this->cache[ $group ][ $key ] += $offset;
  436. if ( $this->cache[ $group ][ $key ] < 0 ) {
  437. $this->cache[ $group ][ $key ] = 0;
  438. }
  439. return $this->cache[ $group ][ $key ];
  440. }
  441. /**
  442. * Decrements numeric cache item's value.
  443. *
  444. * @since 3.3.0
  445. *
  446. * @param int|string $key The cache key to decrement.
  447. * @param int $offset Optional. The amount by which to decrement the item's value.
  448. * Default 1.
  449. * @param string $group Optional. The group the key is in. Default 'default'.
  450. * @return int|false The item's new value on success, false on failure.
  451. */
  452. public function decr( $key, $offset = 1, $group = 'default' ) {
  453. if ( ! $this->is_valid_key( $key ) ) {
  454. return false;
  455. }
  456. if ( empty( $group ) ) {
  457. $group = 'default';
  458. }
  459. if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
  460. $key = $this->blog_prefix . $key;
  461. }
  462. if ( ! $this->_exists( $key, $group ) ) {
  463. return false;
  464. }
  465. if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) {
  466. $this->cache[ $group ][ $key ] = 0;
  467. }
  468. $offset = (int) $offset;
  469. $this->cache[ $group ][ $key ] -= $offset;
  470. if ( $this->cache[ $group ][ $key ] < 0 ) {
  471. $this->cache[ $group ][ $key ] = 0;
  472. }
  473. return $this->cache[ $group ][ $key ];
  474. }
  475. /**
  476. * Clears the object cache of all data.
  477. *
  478. * @since 2.0.0
  479. *
  480. * @return true Always returns true.
  481. */
  482. public function flush() {
  483. $this->cache = array();
  484. return true;
  485. }
  486. /**
  487. * Removes all cache items in a group.
  488. *
  489. * @since 6.1.0
  490. *
  491. * @param string $group Name of group to remove from cache.
  492. * @return true Always returns true.
  493. */
  494. public function flush_group( $group ) {
  495. unset( $this->cache[ $group ] );
  496. return true;
  497. }
  498. /**
  499. * Sets the list of global cache groups.
  500. *
  501. * @since 3.0.0
  502. *
  503. * @param string|string[] $groups List of groups that are global.
  504. */
  505. public function add_global_groups( $groups ) {
  506. $groups = (array) $groups;
  507. $groups = array_fill_keys( $groups, true );
  508. $this->global_groups = array_merge( $this->global_groups, $groups );
  509. }
  510. /**
  511. * Switches the internal blog ID.
  512. *
  513. * This changes the blog ID used to create keys in blog specific groups.
  514. *
  515. * @since 3.5.0
  516. *
  517. * @param int $blog_id Blog ID.
  518. */
  519. public function switch_to_blog( $blog_id ) {
  520. $blog_id = (int) $blog_id;
  521. $this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
  522. }
  523. /**
  524. * Resets cache keys.
  525. *
  526. * @since 3.0.0
  527. *
  528. * @deprecated 3.5.0 Use WP_Object_Cache::switch_to_blog()
  529. * @see switch_to_blog()
  530. */
  531. public function reset() {
  532. _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Object_Cache::switch_to_blog()' );
  533. // Clear out non-global caches since the blog ID has changed.
  534. foreach ( array_keys( $this->cache ) as $group ) {
  535. if ( ! isset( $this->global_groups[ $group ] ) ) {
  536. unset( $this->cache[ $group ] );
  537. }
  538. }
  539. }
  540. /**
  541. * Echoes the stats of the caching.
  542. *
  543. * Gives the cache hits, and cache misses. Also prints every cached group,
  544. * key and the data.
  545. *
  546. * @since 2.0.0
  547. */
  548. public function stats() {
  549. echo '<p>';
  550. echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />";
  551. echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />";
  552. echo '</p>';
  553. echo '<ul>';
  554. foreach ( $this->cache as $group => $cache ) {
  555. echo '<li><strong>Group:</strong> ' . esc_html( $group ) . ' - ( ' . number_format( strlen( serialize( $cache ) ) / KB_IN_BYTES, 2 ) . 'k )</li>';
  556. }
  557. echo '</ul>';
  558. }
  559. }