class-wc-cache-helper.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. * Hook in methods.
  14. */
  15. public static function init() {
  16. add_action( 'template_redirect', array( __CLASS__, 'geolocation_ajax_redirect' ) );
  17. add_action( 'admin_notices', array( __CLASS__, 'notices' ) );
  18. add_action( 'delete_version_transients', array( __CLASS__, 'delete_version_transients' ) );
  19. add_action( 'wp', array( __CLASS__, 'prevent_caching' ) );
  20. add_action( 'clean_term_cache', array( __CLASS__, 'clean_term_cache' ), 10, 2 );
  21. add_action( 'edit_terms', array( __CLASS__, 'clean_term_cache' ), 10, 2 );
  22. }
  23. /**
  24. * Get prefix for use with wp_cache_set. Allows all cache in a group to be invalidated at once.
  25. *
  26. * @param string $group Group of cache to get.
  27. * @return string
  28. */
  29. public static function get_cache_prefix( $group ) {
  30. // Get cache key - uses cache key wc_orders_cache_prefix to invalidate when needed.
  31. $prefix = wp_cache_get( 'wc_' . $group . '_cache_prefix', $group );
  32. if ( false === $prefix ) {
  33. $prefix = 1;
  34. wp_cache_set( 'wc_' . $group . '_cache_prefix', $prefix, $group );
  35. }
  36. return 'wc_cache_' . $prefix . '_';
  37. }
  38. /**
  39. * Increment group cache prefix (invalidates cache).
  40. *
  41. * @param string $group Group of cache to clear.
  42. */
  43. public static function incr_cache_prefix( $group ) {
  44. wp_cache_incr( 'wc_' . $group . '_cache_prefix', 1, $group );
  45. }
  46. /**
  47. * Get a hash of the customer location.
  48. *
  49. * @return string
  50. */
  51. public static function geolocation_ajax_get_location_hash() {
  52. $customer = new WC_Customer( 0, true );
  53. $location = array();
  54. $location['country'] = $customer->get_billing_country();
  55. $location['state'] = $customer->get_billing_state();
  56. $location['postcode'] = $customer->get_billing_postcode();
  57. $location['city'] = $customer->get_billing_city();
  58. return substr( md5( implode( '', $location ) ), 0, 12 );
  59. }
  60. /**
  61. * Prevent caching on certain pages
  62. */
  63. public static function prevent_caching() {
  64. if ( ! is_blog_installed() ) {
  65. return;
  66. }
  67. $page_ids = array_filter( array( wc_get_page_id( 'cart' ), wc_get_page_id( 'checkout' ), wc_get_page_id( 'myaccount' ) ) );
  68. if ( is_page( $page_ids ) ) {
  69. self::set_nocache_constants();
  70. nocache_headers();
  71. }
  72. }
  73. /**
  74. * When using geolocation via ajax, to bust cache, redirect if the location hash does not equal the querystring.
  75. *
  76. * This prevents caching of the wrong data for this request.
  77. */
  78. public static function geolocation_ajax_redirect() {
  79. 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.
  80. $location_hash = self::geolocation_ajax_get_location_hash();
  81. $current_hash = isset( $_GET['v'] ) ? wc_clean( wp_unslash( $_GET['v'] ) ) : ''; // WPCS: sanitization ok, input var ok, CSRF ok.
  82. if ( empty( $current_hash ) || $current_hash !== $location_hash ) {
  83. global $wp;
  84. $redirect_url = trailingslashit( home_url( $wp->request ) );
  85. if ( ! empty( $_SERVER['QUERY_STRING'] ) ) { // WPCS: Input var ok.
  86. $redirect_url = add_query_arg( wp_unslash( $_SERVER['QUERY_STRING'] ), '', $redirect_url ); // WPCS: sanitization ok, Input var ok.
  87. }
  88. if ( ! get_option( 'permalink_structure' ) ) {
  89. $redirect_url = add_query_arg( $wp->query_string, '', $redirect_url );
  90. }
  91. $redirect_url = add_query_arg( 'v', $location_hash, remove_query_arg( 'v', $redirect_url ) );
  92. wp_safe_redirect( esc_url_raw( $redirect_url ), 307 );
  93. exit;
  94. }
  95. }
  96. }
  97. /**
  98. * Get transient version.
  99. *
  100. * When using transients with unpredictable names, e.g. those containing an md5
  101. * hash in the name, we need a way to invalidate them all at once.
  102. *
  103. * When using default WP transients we're able to do this with a DB query to
  104. * delete transients manually.
  105. *
  106. * With external cache however, this isn't possible. Instead, this function is used
  107. * to append a unique string (based on time()) to each transient. When transients
  108. * are invalidated, the transient version will increment and data will be regenerated.
  109. *
  110. * Raised in issue https://github.com/woocommerce/woocommerce/issues/5777.
  111. * Adapted from ideas in http://tollmanz.com/invalidation-schemes/.
  112. *
  113. * @param string $group Name for the group of transients we need to invalidate.
  114. * @param boolean $refresh true to force a new version.
  115. * @return string transient version based on time(), 10 digits.
  116. */
  117. public static function get_transient_version( $group, $refresh = false ) {
  118. $transient_name = $group . '-transient-version';
  119. $transient_value = get_transient( $transient_name );
  120. $transient_value = strval( $transient_value ? $transient_value : '' );
  121. if ( '' === $transient_value || true === $refresh ) {
  122. $old_transient_value = $transient_value;
  123. $transient_value = (string) time();
  124. if ( $old_transient_value === $transient_value ) {
  125. // Time did not change but transient needs flushing now.
  126. self::delete_version_transients( $transient_value );
  127. } else {
  128. self::queue_delete_version_transients( $transient_value );
  129. }
  130. set_transient( $transient_name, $transient_value );
  131. }
  132. return $transient_value;
  133. }
  134. /**
  135. * Queues a cleanup event for version transients.
  136. *
  137. * @param string $version Version of the transient to remove.
  138. */
  139. protected static function queue_delete_version_transients( $version = '' ) {
  140. if ( ! wp_using_ext_object_cache() && ! empty( $version ) ) {
  141. wp_schedule_single_event( time() + 30, 'delete_version_transients', array( $version ) );
  142. }
  143. }
  144. /**
  145. * When the transient version increases, this is used to remove all past transients to avoid filling the DB.
  146. *
  147. * Note; this only works on transients appended with the transient version, and when object caching is not being used.
  148. *
  149. * @since 2.3.10
  150. * @param string $version Version of the transient to remove.
  151. */
  152. public static function delete_version_transients( $version = '' ) {
  153. if ( ! wp_using_ext_object_cache() && ! empty( $version ) ) {
  154. global $wpdb;
  155. $limit = apply_filters( 'woocommerce_delete_version_transients_limit', 1000 );
  156. if ( ! $limit ) {
  157. return;
  158. }
  159. $affected = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id LIMIT %d;", '\_transient\_%' . $version, $limit ) ); // WPCS: cache ok, db call ok.
  160. // If affected rows is equal to limit, there are more rows to delete. Delete in 30 secs.
  161. if ( $affected === $limit ) {
  162. self::queue_delete_version_transients( $version );
  163. }
  164. }
  165. }
  166. /**
  167. * Set constants to prevent caching by some plugins.
  168. *
  169. * @param mixed $return Value to return. Previously hooked into a filter.
  170. * @return mixed
  171. */
  172. public static function set_nocache_constants( $return = true ) {
  173. wc_maybe_define_constant( 'DONOTCACHEPAGE', true );
  174. wc_maybe_define_constant( 'DONOTCACHEOBJECT', true );
  175. wc_maybe_define_constant( 'DONOTCACHEDB', true );
  176. return $return;
  177. }
  178. /**
  179. * Notices function.
  180. */
  181. public static function notices() {
  182. if ( ! function_exists( 'w3tc_pgcache_flush' ) || ! function_exists( 'w3_instance' ) ) {
  183. return;
  184. }
  185. $config = w3_instance( 'W3_Config' );
  186. $enabled = $config->get_integer( 'dbcache.enabled' );
  187. $settings = array_map( 'trim', $config->get_array( 'dbcache.reject.sql' ) );
  188. if ( $enabled && ! in_array( '_wc_session_', $settings, true ) ) {
  189. ?>
  190. <div class="error">
  191. <p>
  192. <?php
  193. /* translators: 1: key 2: URL */
  194. 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' ) ) ) );
  195. ?>
  196. </p>
  197. </div>
  198. <?php
  199. }
  200. }
  201. /**
  202. * Clean term caches added by WooCommerce.
  203. *
  204. * @since 3.3.4
  205. * @param array|int $ids Array of ids or single ID to clear cache for.
  206. * @param string $taxonomy Taxonomy name.
  207. */
  208. public static function clean_term_cache( $ids, $taxonomy ) {
  209. if ( 'product_cat' === $taxonomy ) {
  210. $ids = is_array( $ids ) ? $ids : array( $ids );
  211. $clear_ids = array( 0 );
  212. foreach ( $ids as $id ) {
  213. $clear_ids[] = $id;
  214. $clear_ids = array_merge( $clear_ids, get_ancestors( $id, 'product_cat', 'taxonomy' ) );
  215. }
  216. $clear_ids = array_unique( $clear_ids );
  217. foreach ( $clear_ids as $id ) {
  218. wp_cache_delete( 'product-category-hierarchy-' . $id, 'product_cat' );
  219. }
  220. }
  221. }
  222. }
  223. WC_Cache_Helper::init();