PageRenderTime 26ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wordpress-seo/inc/sitemaps/class-sitemaps-cache-validator.php

https://bitbucket.org/reareaf/wp-re
PHP | 304 lines | 106 code | 54 blank | 144 comment | 11 complexity | c7651e5fe0fcdd8128144bedebd4e559 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, Apache-2.0
  1. <?php
  2. /**
  3. * @package WPSEO\XML_Sitemaps
  4. */
  5. /**
  6. * Handles storage keys for sitemaps caching and invalidation.
  7. *
  8. * @since 3.2
  9. */
  10. class WPSEO_Sitemaps_Cache_Validator {
  11. /** @var string Prefix of the transient key for sitemap caches */
  12. const STORAGE_KEY_PREFIX = 'yst_sm_';
  13. /** Name of the option that holds the global validation value */
  14. const VALIDATION_GLOBAL_KEY = 'wpseo_sitemap_cache_validator_global';
  15. /** The format which creates the key of the option that holds the type validation value */
  16. const VALIDATION_TYPE_KEY_FORMAT = 'wpseo_sitemap_%s_cache_validator';
  17. /**
  18. * Get the cache key for a certain type and page
  19. *
  20. * A type of cache would be something like 'page', 'post' or 'video'.
  21. *
  22. * Example key format for sitemap type "post", page 1: wpseo_sitemap_post_1:akfw3e_23azBa
  23. *
  24. * @since 3.2
  25. *
  26. * @param null|string $type The type to get the key for. Null or self::SITEMAP_INDEX_TYPE for index cache.
  27. * @param int $page The page of cache to get the key for.
  28. *
  29. * @return bool|string The key where the cache is stored on. False if the key could not be generated.
  30. */
  31. public static function get_storage_key( $type = null, $page = 1 ) {
  32. // Using SITEMAP_INDEX_TYPE for sitemap index cache.
  33. $type = is_null( $type ) ? WPSEO_Sitemaps::SITEMAP_INDEX_TYPE : $type;
  34. $global_cache_validator = self::get_validator();
  35. $type_cache_validator = self::get_validator( $type );
  36. $prefix = self::STORAGE_KEY_PREFIX;
  37. $postfix = sprintf( '_%d:%s_%s', $page, $global_cache_validator, $type_cache_validator );
  38. try {
  39. $type = self::truncate_type( $type, $prefix, $postfix );
  40. } catch ( OutOfBoundsException $exception ) {
  41. // Maybe do something with the exception, for now just mark as invalid.
  42. return false;
  43. }
  44. // Build key.
  45. $full_key = $prefix . $type . $postfix;
  46. return $full_key;
  47. }
  48. /**
  49. * If the type is over length make sure we compact it so we don't have any database problems
  50. *
  51. * When there are more 'extremely long' post types, changes are they have variations in either the start or ending.
  52. * Because of this, we cut out the excess in the middle which should result in less chance of collision.
  53. *
  54. * @since 3.2
  55. *
  56. * @param string $type The type of sitemap to be used.
  57. * @param string $prefix The part before the type in the cache key. Only the length is used.
  58. * @param string $postfix The part after the type in the cache key. Only the length is used.
  59. *
  60. * @return string The type with a safe length to use
  61. *
  62. * @throws OutOfRangeException When there is less than 15 characters of space for a key that is originally longer.
  63. */
  64. public static function truncate_type( $type, $prefix = '', $postfix = '' ) {
  65. /**
  66. * This length has been restricted by the database column length of 64 in the past.
  67. * The prefix added by WordPress is '_transient_' because we are saving to a transient.
  68. * We need to use a timeout on the transient, otherwise the values get autoloaded, this adds
  69. * another restriction to the length.
  70. */
  71. $max_length = 45; // 64 - 19 ('_transient_timeout_')
  72. $max_length -= strlen( $prefix );
  73. $max_length -= strlen( $postfix );
  74. if ( strlen( $type ) > $max_length ) {
  75. if ( $max_length < 15 ) {
  76. /**
  77. * If this happens the most likely cause is a page number that is too high.
  78. *
  79. * So this would not happen unintentionally..
  80. * Either by trying to cause a high server load, finding backdoors or misconfiguration.
  81. */
  82. throw new OutOfRangeException(
  83. __(
  84. 'Trying to build the sitemap cache key, but the postfix and prefix combination leaves too little room to do this. You are probably requesting a page that is way out of the expected range.',
  85. 'wordpress-seo'
  86. )
  87. );
  88. }
  89. $half = ( $max_length / 2 );
  90. $first_part = substr( $type, 0, ( ceil( $half ) - 1 ) );
  91. $last_part = substr( $type, ( 1 - floor( $half ) ) );
  92. $type = $first_part . '..' . $last_part;
  93. }
  94. return $type;
  95. }
  96. /**
  97. * Invalidate sitemap cache
  98. *
  99. * @since 3.2
  100. *
  101. * @param null|string $type The type to get the key for. Null for all caches.
  102. *
  103. * @return void
  104. */
  105. public static function invalidate_storage( $type = null ) {
  106. // Global validator gets cleared when no type is provided.
  107. $old_validator = null;
  108. // Get the current type validator.
  109. if ( ! is_null( $type ) ) {
  110. $old_validator = self::get_validator( $type );
  111. }
  112. // Refresh validator.
  113. self::create_validator( $type );
  114. if ( ! wp_using_ext_object_cache() ) {
  115. // Clean up current cache from the database.
  116. self::cleanup_database( $type, $old_validator );
  117. }
  118. // External object cache pushes old and unretrieved items out by itself so we don't have to do anything for that.
  119. }
  120. /**
  121. * Cleanup invalidated database cache
  122. *
  123. * @since 3.2
  124. *
  125. * @param null|string $type The type of sitemap to clear cache for.
  126. * @param null|string $validator The validator to clear cache of.
  127. *
  128. * @return void
  129. */
  130. public static function cleanup_database( $type = null, $validator = null ) {
  131. global $wpdb;
  132. if ( is_null( $type ) ) {
  133. // Clear all cache if no type is provided.
  134. $like = sprintf( '%s%%', self::STORAGE_KEY_PREFIX );
  135. }
  136. else {
  137. // Clear type cache for all type keys.
  138. $like = sprintf( '%1$s%2$s_%%', self::STORAGE_KEY_PREFIX, $type );
  139. }
  140. /**
  141. * Add slashes to the LIKE "_" single character wildcard.
  142. *
  143. * We can't use `esc_like` here because we need the % in the query.
  144. */
  145. $where = array();
  146. $where[] = sprintf( "option_name LIKE '%s'", addcslashes( '_transient_' . $like, '_' ) );
  147. $where[] = sprintf( "option_name LIKE '%s'", addcslashes( '_transient_timeout_' . $like, '_' ) );
  148. // Delete transients.
  149. $query = sprintf( 'DELETE FROM %1$s WHERE %2$s', $wpdb->options, implode( ' OR ', $where ) );
  150. $wpdb->query( $query );
  151. }
  152. /**
  153. * Get the current cache validator
  154. *
  155. * Without the type the global validator is returned.
  156. * This can invalidate -all- keys in cache at once
  157. *
  158. * With the type parameter the validator for that specific
  159. * type can be invalidated
  160. *
  161. * @since 3.2
  162. *
  163. * @param string $type Provide a type for a specific type validator, empty for global validator.
  164. *
  165. * @return null|string The validator for the supplied type.
  166. */
  167. public static function get_validator( $type = '' ) {
  168. $key = self::get_validator_key( $type );
  169. $current = get_option( $key, null );
  170. if ( ! is_null( $current ) ) {
  171. return $current;
  172. }
  173. if ( self::create_validator( $type ) ) {
  174. return self::get_validator( $type );
  175. }
  176. return null;
  177. }
  178. /**
  179. * Get the cache validator option key for the specified type
  180. *
  181. * @since 3.2
  182. *
  183. * @param string $type Provide a type for a specific type validator, empty for global validator.
  184. *
  185. * @return string Validator to be used to generate the cache key.
  186. */
  187. public static function get_validator_key( $type = '' ) {
  188. if ( empty( $type ) ) {
  189. return self::VALIDATION_GLOBAL_KEY;
  190. }
  191. return sprintf( self::VALIDATION_TYPE_KEY_FORMAT, $type );
  192. }
  193. /**
  194. * Refresh the cache validator value
  195. *
  196. * @since 3.2
  197. *
  198. * @param string $type Provide a type for a specific type validator, empty for global validator.
  199. *
  200. * @return bool True if validator key has been saved as option.
  201. */
  202. public static function create_validator( $type = '' ) {
  203. $key = self::get_validator_key( $type );
  204. // Generate new validator.
  205. $microtime = microtime();
  206. // Remove space.
  207. list( $milliseconds, $seconds ) = explode( ' ', $microtime );
  208. // Transients are purged every 24h.
  209. $seconds = ( $seconds % DAY_IN_SECONDS );
  210. $milliseconds = intval( substr( $milliseconds, 2, 3 ), 10 );
  211. // Combine seconds and milliseconds and convert to integer.
  212. $validator = intval( $seconds . '' . $milliseconds, 10 );
  213. // Apply base 61 encoding.
  214. $compressed = self::convert_base10_to_base61( $validator );
  215. return update_option( $key, $compressed, false );
  216. }
  217. /**
  218. * Encode to base61 format.
  219. *
  220. * @since 3.2
  221. *
  222. * This is base64 (numeric + alpha + alpha upper case) without the 0.
  223. *
  224. * @param int $base10 The number that has to be converted to base 61.
  225. *
  226. * @return string Base 61 converted string.
  227. *
  228. * @throws InvalidArgumentException When the input is not an integer.
  229. */
  230. public static function convert_base10_to_base61( $base10 ) {
  231. if ( ! is_int( $base10 ) ) {
  232. throw new InvalidArgumentException( __( 'Expected an integer as input.', 'wordpress-seo' ) );
  233. }
  234. // Characters that will be used in the conversion.
  235. $characters = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  236. $length = strlen( $characters );
  237. $remainder = $base10;
  238. $output = '';
  239. do {
  240. // Building from right to left in the result.
  241. $index = ( $remainder % $length );
  242. // Prepend the character to the output.
  243. $output = $characters[ $index ] . $output;
  244. // Determine the remainder after removing the applied number.
  245. $remainder = floor( $remainder / $length );
  246. // Keep doing it until we have no remainder left.
  247. } while ( $remainder );
  248. return $output;
  249. }
  250. }