Açıklama Yok

class-wc-cache-helper.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /**
  3. * WC_Cache_Helper class.
  4. *
  5. * @package WooCommerce\Classes
  6. */
  7. defined( 'ABSPATH' ) || exit;
  8. /**
  9. * WC_Cache_Helper.
  10. */
  11. class WC_Cache_Helper {
  12. /**
  13. * Transients to delete on shutdown.
  14. *
  15. * @var array Array of transient keys.
  16. */
  17. private static $delete_transients = array();
  18. /**
  19. * Hook in methods.
  20. */
  21. public static function init() {
  22. add_filter( 'nocache_headers', array( __CLASS__, 'additional_nocache_headers' ), 10 );
  23. add_action( 'shutdown', array( __CLASS__, 'delete_transients_on_shutdown' ), 10 );
  24. add_action( 'template_redirect', array( __CLASS__, 'geolocation_ajax_redirect' ) );
  25. add_action( 'wc_ajax_update_order_review', array( __CLASS__, 'update_geolocation_hash' ), 5 );
  26. add_action( 'admin_notices', array( __CLASS__, 'notices' ) );
  27. add_action( 'delete_version_transients', array( __CLASS__, 'delete_version_transients' ), 10 );
  28. add_action( 'wp', array( __CLASS__, 'prevent_caching' ) );
  29. add_action( 'clean_term_cache', array( __CLASS__, 'clean_term_cache' ), 10, 2 );
  30. add_action( 'edit_terms', array( __CLASS__, 'clean_term_cache' ), 10, 2 );
  31. }
  32. /**
  33. * Set additional nocache headers.
  34. *
  35. * @param array $headers Header names and field values.
  36. * @since 3.6.0
  37. */
  38. public static function additional_nocache_headers( $headers ) {
  39. $agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
  40. $set_cache = false;
  41. /**
  42. * Allow plugins to enable nocache headers. Enabled for Google weblight.
  43. *
  44. * @param bool $enable_nocache_headers Flag indicating whether to add nocache headers. Default: false.
  45. */
  46. if ( apply_filters( 'woocommerce_enable_nocache_headers', false ) ) {
  47. $set_cache = true;
  48. }
  49. /**
  50. * Enabled for Google weblight.
  51. *
  52. * @see https://support.google.com/webmasters/answer/1061943?hl=en
  53. */
  54. if ( false !== strpos( $agent, 'googleweblight' ) ) {
  55. // no-transform: Opt-out of Google weblight. https://support.google.com/webmasters/answer/6211428?hl=en.
  56. $set_cache = true;
  57. }
  58. if ( false !== strpos( $agent, 'Chrome' ) && is_cart() ) {
  59. $set_cache = true;
  60. }
  61. if ( $set_cache ) {
  62. $headers['Cache-Control'] = 'no-transform, no-cache, no-store, must-revalidate';
  63. }
  64. return $headers;
  65. }
  66. /**
  67. * Add a transient to delete on shutdown.
  68. *
  69. * @since 3.6.0
  70. * @param string|array $keys Transient key or keys.
  71. */
  72. public static function queue_delete_transient( $keys ) {
  73. self::$delete_transients = array_unique( array_merge( is_array( $keys ) ? $keys : array( $keys ), self::$delete_transients ) );
  74. }
  75. /**
  76. * Transients that don't need to be cleaned right away can be deleted on shutdown to avoid repetition.
  77. *
  78. * @since 3.6.0
  79. */
  80. public static function delete_transients_on_shutdown() {
  81. if ( self::$delete_transients ) {
  82. foreach ( self::$delete_transients as $key ) {
  83. delete_transient( $key );
  84. }
  85. self::$delete_transients = array();
  86. }
  87. }
  88. /**
  89. * Used to clear layered nav counts based on passed attribute names.
  90. *
  91. * @since 3.6.0
  92. * @param array $attribute_keys Attribute keys.
  93. */
  94. public static function invalidate_attribute_count( $attribute_keys ) {
  95. if ( $attribute_keys ) {
  96. foreach ( $attribute_keys as $attribute_key ) {
  97. self::queue_delete_transient( 'wc_layered_nav_counts_' . $attribute_key );
  98. }
  99. }
  100. }
  101. /**
  102. * Get prefix for use with wp_cache_set. Allows all cache in a group to be invalidated at once.
  103. *
  104. * @param string $group Group of cache to get.
  105. * @return string
  106. */
  107. public static function get_cache_prefix( $group ) {
  108. // Get cache key - uses cache key wc_orders_cache_prefix to invalidate when needed.
  109. $prefix = wp_cache_get( 'wc_' . $group . '_cache_prefix', $group );
  110. if ( false === $prefix ) {
  111. $prefix = microtime();
  112. wp_cache_set( 'wc_' . $group . '_cache_prefix', $prefix, $group );
  113. }
  114. return 'wc_cache_' . $prefix . '_';
  115. }
  116. /**
  117. * Increment group cache prefix (invalidates cache).
  118. *
  119. * @param string $group Group of cache to clear.
  120. */
  121. public static function incr_cache_prefix( $group ) {
  122. wc_deprecated_function( 'WC_Cache_Helper::incr_cache_prefix', '3.9.0', 'WC_Cache_Helper::invalidate_cache_group' );
  123. self::invalidate_cache_group( $group );
  124. }
  125. /**
  126. * Invalidate cache group.
  127. *
  128. * @param string $group Group of cache to clear.
  129. * @since 3.9.0
  130. */
  131. public static function invalidate_cache_group( $group ) {
  132. wp_cache_set( 'wc_' . $group . '_cache_prefix', microtime(), $group );
  133. }
  134. /**
  135. * Get a hash of the customer location.
  136. *
  137. * @return string
  138. */
  139. public static function geolocation_ajax_get_location_hash() {
  140. $customer = new WC_Customer( 0, true );
  141. $location = array();
  142. $location['country'] = $customer->get_billing_country();
  143. $location['state'] = $customer->get_billing_state();
  144. $location['postcode'] = $customer->get_billing_postcode();
  145. $location['city'] = $customer->get_billing_city();
  146. return apply_filters( 'woocommerce_geolocation_ajax_get_location_hash', substr( md5( implode( '', $location ) ), 0, 12 ), $location, $customer );
  147. }
  148. /**
  149. * Prevent caching on certain pages
  150. */
  151. public static function prevent_caching() {
  152. if ( ! is_blog_installed() ) {
  153. return;
  154. }
  155. $page_ids = array_filter( array( wc_get_page_id( 'cart' ), wc_get_page_id( 'checkout' ), wc_get_page_id( 'myaccount' ) ) );
  156. if ( is_page( $page_ids ) ) {
  157. self::set_nocache_constants();
  158. nocache_headers();
  159. }
  160. }
  161. /**
  162. * When using geolocation via ajax, to bust cache, redirect if the location hash does not equal the querystring.
  163. *
  164. * This prevents caching of the wrong data for this request.
  165. */
  166. public static function geolocation_ajax_redirect() {
  167. if ( 'geolocation_ajax' === get_option( 'woocommerce_default_customer_address' ) && ! is_checkout() && ! is_cart() && ! is_account_page() && ! is_ajax() && empty( $_POST ) ) { // WPCS: CSRF ok, input var ok.
  168. $location_hash = self::geolocation_ajax_get_location_hash();
  169. $current_hash = isset( $_GET['v'] ) ? wc_clean( wp_unslash( $_GET['v'] ) ) : ''; // WPCS: sanitization ok, input var ok, CSRF ok.
  170. if ( empty( $current_hash ) || $current_hash !== $location_hash ) {
  171. global $wp;
  172. $redirect_url = trailingslashit( home_url( $wp->request ) );
  173. if ( ! empty( $_SERVER['QUERY_STRING'] ) ) { // WPCS: Input var ok.
  174. $redirect_url = add_query_arg( wp_unslash( $_SERVER['QUERY_STRING'] ), '', $redirect_url ); // WPCS: sanitization ok, Input var ok.
  175. }
  176. if ( ! get_option( 'permalink_structure' ) ) {
  177. $redirect_url = add_query_arg( $wp->query_string, '', $redirect_url );
  178. }
  179. $redirect_url = add_query_arg( 'v', $location_hash, remove_query_arg( 'v', $redirect_url ) );
  180. wp_safe_redirect( esc_url_raw( $redirect_url ), 307 );
  181. exit;
  182. }
  183. }
  184. }
  185. /**
  186. * Updates the `woocommerce_geo_hash` cookie, which is used to help ensure we display
  187. * the correct pricing etc to customers, according to their billing country.
  188. *
  189. * Note that:
  190. *
  191. * A) This only sets the cookie if the default customer address is set to "Geolocate (with
  192. * Page Caching Support)".
  193. *
  194. * B) It is hooked into the `wc_ajax_update_order_review` action, which has the benefit of
  195. * ensuring we update the cookie any time the billing country is changed.
  196. */
  197. public static function update_geolocation_hash() {
  198. if ( 'geolocation_ajax' === get_option( 'woocommerce_default_customer_address' ) ) {
  199. wc_setcookie( 'woocommerce_geo_hash', static::geolocation_ajax_get_location_hash(), time() + HOUR_IN_SECONDS );
  200. }
  201. }
  202. /**
  203. * Get transient version.
  204. *
  205. * When using transients with unpredictable names, e.g. those containing an md5
  206. * hash in the name, we need a way to invalidate them all at once.
  207. *
  208. * When using default WP transients we're able to do this with a DB query to
  209. * delete transients manually.
  210. *
  211. * With external cache however, this isn't possible. Instead, this function is used
  212. * to append a unique string (based on time()) to each transient. When transients
  213. * are invalidated, the transient version will increment and data will be regenerated.
  214. *
  215. * Raised in issue https://github.com/woocommerce/woocommerce/issues/5777.
  216. * Adapted from ideas in http://tollmanz.com/invalidation-schemes/.
  217. *
  218. * @param string $group Name for the group of transients we need to invalidate.
  219. * @param boolean $refresh true to force a new version.
  220. * @return string transient version based on time(), 10 digits.
  221. */
  222. public static function get_transient_version( $group, $refresh = false ) {
  223. $transient_name = $group . '-transient-version';
  224. $transient_value = get_transient( $transient_name );
  225. if ( false === $transient_value || true === $refresh ) {
  226. $transient_value = (string) time();
  227. set_transient( $transient_name, $transient_value );
  228. }
  229. return $transient_value;
  230. }
  231. /**
  232. * Set constants to prevent caching by some plugins.
  233. *
  234. * @param mixed $return Value to return. Previously hooked into a filter.
  235. * @return mixed
  236. */
  237. public static function set_nocache_constants( $return = true ) {
  238. wc_maybe_define_constant( 'DONOTCACHEPAGE', true );
  239. wc_maybe_define_constant( 'DONOTCACHEOBJECT', true );
  240. wc_maybe_define_constant( 'DONOTCACHEDB', true );
  241. return $return;
  242. }
  243. /**
  244. * Notices function.
  245. */
  246. public static function notices() {
  247. if ( ! function_exists( 'w3tc_pgcache_flush' ) || ! function_exists( 'w3_instance' ) ) {
  248. return;
  249. }
  250. $config = w3_instance( 'W3_Config' );
  251. $enabled = $config->get_integer( 'dbcache.enabled' );
  252. $settings = array_map( 'trim', $config->get_array( 'dbcache.reject.sql' ) );
  253. if ( $enabled && ! in_array( '_wc_session_', $settings, true ) ) {
  254. ?>
  255. <div class="error">
  256. <p>
  257. <?php
  258. /* translators: 1: key 2: URL */
  259. echo wp_kses_post( sprintf( __( 'In order for <strong>database caching</strong> to work with WooCommerce you must add %1$s to the "Ignored Query Strings" option in <a href="%2$s">W3 Total Cache settings</a>.', 'woocommerce' ), '<code>_wc_session_</code>', esc_url( admin_url( 'admin.php?page=w3tc_dbcache' ) ) ) );
  260. ?>
  261. </p>
  262. </div>
  263. <?php
  264. }
  265. }
  266. /**
  267. * Clean term caches added by WooCommerce.
  268. *
  269. * @since 3.3.4
  270. * @param array|int $ids Array of ids or single ID to clear cache for.
  271. * @param string $taxonomy Taxonomy name.
  272. */
  273. public static function clean_term_cache( $ids, $taxonomy ) {
  274. if ( 'product_cat' === $taxonomy ) {
  275. $ids = is_array( $ids ) ? $ids : array( $ids );
  276. $clear_ids = array( 0 );
  277. foreach ( $ids as $id ) {
  278. $clear_ids[] = $id;
  279. $clear_ids = array_merge( $clear_ids, get_ancestors( $id, 'product_cat', 'taxonomy' ) );
  280. }
  281. $clear_ids = array_unique( $clear_ids );
  282. foreach ( $clear_ids as $id ) {
  283. wp_cache_delete( 'product-category-hierarchy-' . $id, 'product_cat' );
  284. }
  285. }
  286. }
  287. /**
  288. * When the transient version increases, this is used to remove all past transients to avoid filling the DB.
  289. *
  290. * Note; this only works on transients appended with the transient version, and when object caching is not being used.
  291. *
  292. * @deprecated 3.6.0 Adjusted transient usage to include versions within the transient values, making this cleanup obsolete.
  293. * @since 2.3.10
  294. * @param string $version Version of the transient to remove.
  295. */
  296. public static function delete_version_transients( $version = '' ) {
  297. if ( ! wp_using_ext_object_cache() && ! empty( $version ) ) {
  298. global $wpdb;
  299. $limit = apply_filters( 'woocommerce_delete_version_transients_limit', 1000 );
  300. if ( ! $limit ) {
  301. return;
  302. }
  303. $affected = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d;", '\_transient\_%' . $version, $limit ) ); // WPCS: cache ok, db call ok.
  304. // If affected rows is equal to limit, there are more rows to delete. Delete in 30 secs.
  305. if ( $affected === $limit ) {
  306. wp_schedule_single_event( time() + 30, 'delete_version_transients', array( $version ) );
  307. }
  308. }
  309. }
  310. }
  311. WC_Cache_Helper::init();