PageRenderTime 65ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/www/wp-content/advanced-cache.php

https://gitlab.com/Blueprint-Marketing/vip-quickstart
PHP | 523 lines | 350 code | 102 blank | 71 comment | 101 complexity | c8d2c034a0c6869fb9b11874fda83bae MD5 | raw file
  1. <?php
  2. if ( is_readable( dirname( __FILE__ ) . '/batcache-stats.php' ) )
  3. require_once dirname( __FILE__ ) . '/batcache-stats.php';
  4. if ( !function_exists( 'batcache_stats' ) ) {
  5. function batcache_stats( $name, $value, $num = 1, $today = FALSE, $hour = FALSE ) { }
  6. }
  7. // nananananananananananananananana BATCACHE!!!
  8. function batcache_cancel() {
  9. global $batcache;
  10. if ( is_object($batcache) )
  11. $batcache->cancel = true;
  12. }
  13. // Variants can be set by functions which use early-set globals like $_SERVER to run simple tests.
  14. // Functions defined in WordPress, plugins, and themes are not available and MUST NOT be used.
  15. // Example: vary_cache_on_function('return preg_match("/feedburner/i", $_SERVER["HTTP_USER_AGENT"]);');
  16. // This will cause batcache to cache a variant for requests from Feedburner.
  17. // Tips for writing $function:
  18. // X_X DO NOT use any functions from your theme or plugins. Those files have not been included. Fatal error.
  19. // X_X DO NOT use any WordPress functions except is_admin() and is_multisite(). Fatal error.
  20. // X_X DO NOT include or require files from anywhere without consulting expensive professionals first. Fatal error.
  21. // X_X DO NOT use $wpdb, $blog_id, $current_user, etc. These have not been initialized.
  22. // ^_^ DO understand how create_function works. This is how your code is used: create_function('', $function);
  23. // ^_^ DO remember to return something. The return value determines the cache variant.
  24. function vary_cache_on_function($function) {
  25. global $batcache;
  26. if ( preg_match('/include|require|echo|print|dump|export|open|sock|unlink|`|eval/i', $function) )
  27. die('Illegal word in variant determiner.');
  28. if ( !preg_match('/\$_/', $function) )
  29. die('Variant determiner should refer to at least one $_ variable.');
  30. $batcache->add_variant($function);
  31. }
  32. class batcache {
  33. // This is the base configuration. You can edit these variables or move them into your wp-config.php file.
  34. var $max_age = 300; // Expire batcache items aged this many seconds (zero to disable batcache)
  35. var $remote = 0; // Zero disables sending buffers to remote datacenters (req/sec is never sent)
  36. var $times = 2; // Only batcache a page after it is accessed this many times... (two or more)
  37. var $seconds = 120; // ...in this many seconds (zero to ignore this and use batcache immediately)
  38. var $group = 'batcache'; // Name of memcached group. You can simulate a cache flush by changing this.
  39. var $unique = array(); // If you conditionally serve different content, put the variable values here.
  40. var $vary = array(); // Array of functions for create_function. The return value is added to $unique above.
  41. var $headers = array(); // Add headers here as name=>value or name=>array(values). These will be sent with every response from the cache.
  42. var $cache_redirects = false; // Set true to enable redirect caching.
  43. var $redirect_status = false; // This is set to the response code during a redirect.
  44. var $redirect_location = false; // This is set to the redirect location.
  45. var $uncached_headers = array('transfer-encoding'); // These headers will never be cached. Apply strtolower.
  46. var $debug = true; // Set false to hide the batcache info <!-- comment -->
  47. var $cache_control = true; // Set false to disable Last-Modified and Cache-Control headers
  48. var $cancel = false; // Change this to cancel the output buffer. Use batcache_cancel();
  49. var $noskip_cookies = array( 'wordpress_test_cookie' ); // Names of cookies - if they exist and the cache would normally be bypassed, don't bypass it
  50. var $genlock = false;
  51. var $do = false;
  52. function batcache( $settings ) {
  53. if ( is_array( $settings ) ) foreach ( $settings as $k => $v )
  54. $this->$k = $v;
  55. }
  56. function is_ssl() {
  57. if ( isset($_SERVER['HTTPS']) ) {
  58. if ( 'on' == strtolower($_SERVER['HTTPS']) )
  59. return true;
  60. if ( '1' == $_SERVER['HTTPS'] )
  61. return true;
  62. } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  63. return true;
  64. }
  65. return false;
  66. }
  67. function status_header( $status_header, $status_code ) {
  68. $this->status_header = $status_header;
  69. $this->status_code = $status_code;
  70. return $status_header;
  71. }
  72. function redirect_status( $status, $location ) {
  73. if ( $this->cache_redirects ) {
  74. $this->redirect_status = $status;
  75. $this->redirect_location = $location;
  76. }
  77. return $status;
  78. }
  79. function do_headers( $headers1, $headers2 = array() ) {
  80. // Merge the arrays of headers into one
  81. $headers = array();
  82. $keys = array_unique( array_merge( array_keys( $headers1 ), array_keys( $headers2 ) ) );
  83. foreach ( $keys as $k ) {
  84. $headers[$k] = array();
  85. if ( isset( $headers1[$k] ) && isset( $headers2[$k] ) )
  86. $headers[$k] = array_merge( (array) $headers2[$k], (array) $headers1[$k] );
  87. elseif ( isset( $headers2[$k] ) )
  88. $headers[$k] = (array) $headers2[$k];
  89. else
  90. $headers[$k] = (array) $headers1[$k];
  91. $headers[$k] = array_unique( $headers[$k] );
  92. }
  93. // These headers take precedence over any previously sent with the same names
  94. foreach ( $headers as $k => $values ) {
  95. $clobber = true;
  96. foreach ( $values as $v ) {
  97. header( "$k: $v", $clobber );
  98. $clobber = false;
  99. }
  100. }
  101. }
  102. function configure_groups() {
  103. // Configure the memcached client
  104. if ( ! $this->remote )
  105. if ( function_exists('wp_cache_add_no_remote_groups') )
  106. wp_cache_add_no_remote_groups(array($this->group));
  107. if ( function_exists('wp_cache_add_global_groups') )
  108. wp_cache_add_global_groups(array($this->group));
  109. }
  110. // Defined here because timer_stop() calls number_format_i18n()
  111. function timer_stop($display = 0, $precision = 3) {
  112. global $timestart, $timeend;
  113. $mtime = microtime();
  114. $mtime = explode(' ',$mtime);
  115. $mtime = $mtime[1] + $mtime[0];
  116. $timeend = $mtime;
  117. $timetotal = $timeend-$timestart;
  118. $r = number_format($timetotal, $precision);
  119. if ( $display )
  120. echo $r;
  121. return $r;
  122. }
  123. function ob($output) {
  124. if ( $this->cancel !== false )
  125. return $output;
  126. // PHP5 and objects disappearing before output buffers?
  127. wp_cache_init();
  128. // Remember, $wp_object_cache was clobbered in wp-settings.php so we have to repeat this.
  129. $this->configure_groups();
  130. // Do not batcache blank pages unless they are HTTP redirects
  131. $output = trim($output);
  132. if ( $output === '' && (!$this->redirect_status || !$this->redirect_location) )
  133. return;
  134. // Do not cache 5xx responses
  135. if ( isset( $this->status_code ) && intval($this->status_code / 100) == 5 )
  136. return $output;
  137. $this->do_variants($this->vary);
  138. $this->generate_keys();
  139. // Construct and save the batcache
  140. $this->cache = array(
  141. 'output' => $output,
  142. 'time' => time(),
  143. 'timer' => $this->timer_stop(false, 3),
  144. 'headers' => array(),
  145. 'status_header' => $this->status_header,
  146. 'redirect_status' => $this->redirect_status,
  147. 'redirect_location' => $this->redirect_location,
  148. 'version' => $this->url_version
  149. );
  150. foreach ( headers_list() as $header ) {
  151. list($k, $v) = array_map('trim', explode(':', $header, 2));
  152. $this->cache['headers'][$k][] = $v;
  153. }
  154. if ( !empty( $this->cache['headers'] ) && !empty( $this->uncached_headers ) ) {
  155. foreach ( $this->uncached_headers as $header )
  156. unset( $this->cache['headers'][$header] );
  157. }
  158. foreach ( $this->cache['headers'] as $header => $values ) {
  159. // Do not cache if cookies were set
  160. if ( strtolower( $header ) === 'set-cookie' )
  161. return $output;
  162. foreach ( (array) $values as $value )
  163. if ( preg_match('/^Cache-Control:.*max-?age=(\d+)/i', "$header: $value", $matches) )
  164. $this->max_age = intval($matches[1]);
  165. }
  166. $this->cache['max_age'] = $this->max_age;
  167. wp_cache_set($this->key, $this->cache, $this->group, $this->max_age + $this->seconds + 30);
  168. // Unlock regeneration
  169. wp_cache_delete("{$this->url_key}_genlock", $this->group);
  170. if ( $this->cache_control ) {
  171. // Don't clobber Last-Modified header if already set, e.g. by WP::send_headers()
  172. if ( !isset($this->cache['headers']['Last-Modified']) )
  173. header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $this->cache['time'] ) . ' GMT', true );
  174. if ( !isset($this->cache['headers']['Cache-Control']) )
  175. header("Cache-Control: max-age=$this->max_age, must-revalidate", false);
  176. }
  177. $this->do_headers( $this->headers );
  178. // Add some debug info just before <head
  179. if ( $this->debug ) {
  180. $this->add_debug_just_cached();
  181. }
  182. // Pass output to next ob handler
  183. batcache_stats( 'batcache', 'total_page_views' );
  184. return $this->cache['output'];
  185. }
  186. function add_variant($function) {
  187. $key = md5($function);
  188. $this->vary[$key] = $function;
  189. }
  190. function do_variants($dimensions = false) {
  191. // This function is called without arguments early in the page load, then with arguments during the OB handler.
  192. if ( $dimensions === false )
  193. $dimensions = wp_cache_get("{$this->url_key}_vary", $this->group);
  194. else
  195. wp_cache_set("{$this->url_key}_vary", $dimensions, $this->group, $this->max_age + 10);
  196. if ( is_array($dimensions) ) {
  197. ksort($dimensions);
  198. foreach ( $dimensions as $key => $function ) {
  199. $fun = create_function('', $function);
  200. $value = $fun();
  201. $this->keys[$key] = $value;
  202. }
  203. }
  204. }
  205. function generate_keys() {
  206. // ksort($this->keys); // uncomment this when traffic is slow
  207. $this->key = md5(serialize($this->keys));
  208. $this->req_key = $this->key . '_req';
  209. }
  210. function add_debug_just_cached() {
  211. $generation = $this->cache['timer'];
  212. $bytes = strlen( serialize( $this->cache ) );
  213. $html = <<<HTML
  214. <!--
  215. generated in $generation seconds
  216. $bytes bytes batcached for {$this->max_age} seconds
  217. -->
  218. HTML;
  219. $this->add_debug_html_to_output( $html );
  220. }
  221. function add_debug_from_cache() {
  222. $seconds_ago = time() - $this->cache['time'];
  223. $generation = $this->cache['timer'];
  224. $serving = $this->timer_stop( false, 3 );
  225. $expires = $this->cache['max_age'] - time() + $this->cache['time'];
  226. $html = <<<HTML
  227. <!--
  228. generated $seconds_ago seconds ago
  229. generated in $generation seconds
  230. served from batcache in $serving seconds
  231. expires in $expires seconds
  232. -->
  233. HTML;
  234. $this->add_debug_html_to_output( $html );
  235. }
  236. function add_debug_html_to_output( $debug_html ) {
  237. // Casing on the Content-Type header is inconsistent
  238. foreach ( array( 'Content-Type', 'Content-type' ) as $key ) {
  239. if ( isset( $this->cache['headers'][ $key ][0] ) && 0 !== strpos( $this->cache['headers'][ $key ][0], 'text/html' ) )
  240. return;
  241. }
  242. $head_position = strpos( $this->cache['output'], '<head' );
  243. if ( false === $head_position ) {
  244. return;
  245. }
  246. $this->cache['output'] = substr_replace( $this->cache['output'], $debug_html, $head_position, 0 );
  247. }
  248. }
  249. global $batcache;
  250. // Pass in the global variable which may be an array of settings to override defaults.
  251. $batcache = new batcache($batcache);
  252. if ( ! defined( 'WP_CONTENT_DIR' ) )
  253. return;
  254. // Never batcache interactive scripts or API endpoints.
  255. if ( in_array(
  256. basename( $_SERVER['SCRIPT_FILENAME'] ),
  257. array(
  258. 'wp-app.php',
  259. 'xmlrpc.php',
  260. ) ) )
  261. return;
  262. // Never batcache WP javascript generators
  263. if ( strstr( $_SERVER['SCRIPT_FILENAME'], 'wp-includes/js' ) )
  264. return;
  265. // Never batcache when POST data is present.
  266. if ( ! empty( $GLOBALS['HTTP_RAW_POST_DATA'] ) || ! empty( $_POST ) )
  267. return;
  268. // Never batcache when cookies indicate a cache-exempt visitor.
  269. if ( is_array( $_COOKIE) && ! empty( $_COOKIE ) ) {
  270. foreach ( array_keys( $_COOKIE ) as $batcache->cookie ) {
  271. if ( ! in_array( $batcache->cookie, $batcache->noskip_cookies ) && ( substr( $batcache->cookie, 0, 2 ) == 'wp' || substr( $batcache->cookie, 0, 9 ) == 'wordpress' || substr( $batcache->cookie, 0, 14 ) == 'comment_author' ) ) {
  272. batcache_stats( 'batcache', 'cookie_skip' );
  273. return;
  274. }
  275. }
  276. }
  277. if ( ! include_once( WP_CONTENT_DIR . '/object-cache.php' ) )
  278. return;
  279. wp_cache_init(); // Note: wp-settings.php calls wp_cache_init() which clobbers the object made here.
  280. if ( ! is_object( $wp_object_cache ) )
  281. return;
  282. // Now that the defaults are set, you might want to use different settings under certain conditions.
  283. /* Example: if your documents have a mobile variant (a different document served by the same URL) you must tell batcache about the variance. Otherwise you might accidentally cache the mobile version and serve it to desktop users, or vice versa.
  284. $batcache->unique['mobile'] = is_mobile_user_agent();
  285. */
  286. /* Example: never batcache for this host
  287. if ( $_SERVER['HTTP_HOST'] == 'do-not-batcache-me.com' )
  288. return;
  289. */
  290. /* Example: batcache everything on this host regardless of traffic level
  291. if ( $_SERVER['HTTP_HOST'] == 'always-batcache-me.com' )
  292. return;
  293. */
  294. /* Example: If you sometimes serve variants dynamically (e.g. referrer search term highlighting) you probably don't want to batcache those variants. Remember this code is run very early in wp-settings.php so plugins are not yet loaded. You will get a fatal error if you try to call an undefined function. Either include your plugin now or define a test function in this file.
  295. if ( include_once( 'plugins/searchterm-highlighter.php') && referrer_has_search_terms() )
  296. return;
  297. */
  298. // Disabled
  299. if ( $batcache->max_age < 1 )
  300. return;
  301. // Make sure we can increment. If not, turn off the traffic sensor.
  302. if ( ! method_exists( $GLOBALS['wp_object_cache'], 'incr' ) )
  303. $batcache->times = 0;
  304. // Necessary to prevent clients using cached version after login cookies set. If this is a problem, comment it out and remove all Last-Modified headers.
  305. header('Vary: Cookie', false);
  306. // Things that define a unique page.
  307. if ( isset( $_SERVER['QUERY_STRING'] ) )
  308. parse_str($_SERVER['QUERY_STRING'], $batcache->query);
  309. $batcache->keys = array(
  310. 'host' => $_SERVER['HTTP_HOST'],
  311. 'method' => $_SERVER['REQUEST_METHOD'],
  312. 'path' => ( $batcache->pos = strpos($_SERVER['REQUEST_URI'], '?') ) ? substr($_SERVER['REQUEST_URI'], 0, $batcache->pos) : $_SERVER['REQUEST_URI'],
  313. 'query' => $batcache->query,
  314. 'extra' => $batcache->unique
  315. );
  316. if ( $batcache->is_ssl() )
  317. $batcache->keys['ssl'] = true;
  318. // Recreate the permalink from the URL
  319. $batcache->permalink = 'http://' . $batcache->keys['host'] . $batcache->keys['path'] . ( isset($batcache->keys['query']['p']) ? "?p=" . $batcache->keys['query']['p'] : '' );
  320. $batcache->url_key = md5($batcache->permalink);
  321. $batcache->url_version = (int) wp_cache_get("{$batcache->url_key}_version", $batcache->group);
  322. $batcache->configure_groups();
  323. $batcache->do_variants();
  324. $batcache->generate_keys();
  325. // Get the batcache
  326. $batcache->cache = wp_cache_get($batcache->key, $batcache->group);
  327. // Are we only caching frequently-requested pages?
  328. if ( $batcache->seconds < 1 || $batcache->times < 2 ) {
  329. $batcache->do = true;
  330. } else {
  331. // No batcache item found, or ready to sample traffic again at the end of the batcache life?
  332. if ( !is_array($batcache->cache) || time() >= $batcache->cache['time'] + $batcache->max_age - $batcache->seconds ) {
  333. wp_cache_add($batcache->req_key, 0, $batcache->group);
  334. $batcache->requests = wp_cache_incr($batcache->req_key, 1, $batcache->group);
  335. if ( $batcache->requests >= $batcache->times )
  336. $batcache->do = true;
  337. else
  338. $batcache->do = false;
  339. }
  340. }
  341. // If the document has been updated and we are the first to notice, regenerate it.
  342. if ( $batcache->do !== false && isset($batcache->cache['version']) && $batcache->cache['version'] < $batcache->url_version )
  343. $batcache->genlock = wp_cache_add("{$batcache->url_key}_genlock", 1, $batcache->group, 10);
  344. // Temporary: remove after 2010-11-12. I added max_age to the cache. This upgrades older caches on the fly.
  345. if ( !isset($batcache->cache['max_age']) )
  346. $batcache->cache['max_age'] = $batcache->max_age;
  347. // Did we find a batcached page that hasn't expired?
  348. if ( isset($batcache->cache['time']) && ! $batcache->genlock && time() < $batcache->cache['time'] + $batcache->cache['max_age'] ) {
  349. // Issue redirect if cached and enabled
  350. if ( $batcache->cache['redirect_status'] && $batcache->cache['redirect_location'] && $batcache->cache_redirects ) {
  351. $status = $batcache->cache['redirect_status'];
  352. $location = $batcache->cache['redirect_location'];
  353. // From vars.php
  354. $is_IIS = (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'ExpressionDevServer') !== false);
  355. $batcache->do_headers( $batcache->headers );
  356. if ( $is_IIS ) {
  357. header("Refresh: 0;url=$location");
  358. } else {
  359. if ( php_sapi_name() != 'cgi-fcgi' ) {
  360. $texts = array(
  361. 300 => 'Multiple Choices',
  362. 301 => 'Moved Permanently',
  363. 302 => 'Found',
  364. 303 => 'See Other',
  365. 304 => 'Not Modified',
  366. 305 => 'Use Proxy',
  367. 306 => 'Reserved',
  368. 307 => 'Temporary Redirect',
  369. );
  370. $protocol = $_SERVER["SERVER_PROTOCOL"];
  371. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  372. $protocol = 'HTTP/1.0';
  373. if ( isset($texts[$status]) )
  374. header("$protocol $status " . $texts[$status]);
  375. else
  376. header("$protocol 302 Found");
  377. }
  378. header("Location: $location");
  379. }
  380. exit;
  381. }
  382. // Respect ETags served with feeds.
  383. $three04 = false;
  384. if ( isset( $SERVER['HTTP_IF_NONE_MATCH'] ) && isset( $batcache->cache['headers']['ETag'][0] ) && $_SERVER['HTTP_IF_NONE_MATCH'] == $batcache->cache['headers']['ETag'][0] )
  385. $three04 = true;
  386. // Respect If-Modified-Since.
  387. elseif ( $batcache->cache_control && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ) {
  388. $client_time = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
  389. if ( isset($batcache->cache['headers']['Last-Modified'][0]) )
  390. $cache_time = strtotime($batcache->cache['headers']['Last-Modified'][0]);
  391. else
  392. $cache_time = $batcache->cache['time'];
  393. if ( $client_time >= $cache_time )
  394. $three04 = true;
  395. }
  396. // Use the batcache save time for Last-Modified so we can issue "304 Not Modified" but don't clobber a cached Last-Modified header.
  397. if ( $batcache->cache_control && !isset($batcache->cache['headers']['Last-Modified'][0]) ) {
  398. header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $batcache->cache['time'] ) . ' GMT', true );
  399. header('Cache-Control: max-age=' . ($batcache->cache['max_age'] - time() + $batcache->cache['time']) . ', must-revalidate', true);
  400. }
  401. // Add some debug info just before </head>
  402. if ( $batcache->debug ) {
  403. $batcache->add_debug_from_cache();
  404. }
  405. $batcache->do_headers( $batcache->headers, $batcache->cache['headers'] );
  406. if ( $three04 ) {
  407. header("HTTP/1.1 304 Not Modified", true, 304);
  408. die;
  409. }
  410. if ( !empty($batcache->cache['status_header']) )
  411. header($batcache->cache['status_header'], true);
  412. // Have you ever heard a death rattle before?
  413. die($batcache->cache['output']);
  414. }
  415. // Didn't meet the minimum condition?
  416. if ( !$batcache->do && !$batcache->genlock )
  417. return;
  418. $wp_filter['status_header'][10]['batcache'] = array( 'function' => array(&$batcache, 'status_header'), 'accepted_args' => 2 );
  419. $wp_filter['wp_redirect_status'][10]['batcache'] = array( 'function' => array(&$batcache, 'redirect_status'), 'accepted_args' => 2 );
  420. ob_start(array(&$batcache, 'ob'));
  421. // It is safer to omit the final PHP closing tag.