Guest User

Untitled

a guest
Aug 24th, 2014
320
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. // nananananananananananananananana BATCACHE!!!
  4.  
  5. function batcache_cancel() {
  6.     global $batcache;
  7.  
  8.     if ( is_object($batcache) )
  9.         $batcache->cancel = true;
  10. }
  11.  
  12. class batcache {
  13.     // This is the base configuration. You can edit these variables or move them into your wp-config.php file.
  14.     var $max_age =  300; // Expire batcache items aged this many seconds (zero to disable batcache)
  15.  
  16.     var $remote  =    0; // Zero disables sending buffers to remote datacenters (req/sec is never sent)
  17.  
  18.     var $times   =    2; // Only batcache a page after it is accessed this many times... (two or more)
  19.     var $seconds =  120; // ...in this many seconds (zero to ignore this and use batcache immediately)
  20.  
  21.     var $group   = 'batcache'; // Name of memcached group. You can simulate a cache flush by changing this.
  22.  
  23.     var $unique  = array(); // If you conditionally serve different content, put the variable values here.
  24.  
  25.     var $headers = array(); // Add headers here. These will be sent with every response from the cache.
  26.  
  27.     var $cache_redirects = false; // Set true to enable redirect caching.
  28.     var $redirect_status = false; // This is set to the response code during a redirect.
  29.     var $redirect_location = false; // This is set to the redirect location.
  30.  
  31.     var $uncached_headers = array('transfer-encoding'); // These headers will never be cached. Apply strtolower.
  32.  
  33.     var $debug   = true; // Set false to hide the batcache info <!-- comment -->
  34.  
  35.     var $cache_control = true; // Set false to disable Last-Modified and Cache-Control headers
  36.  
  37.     var $cancel = false; // Change this to cancel the output buffer. Use batcache_cancel();
  38.  
  39.     var $genlock; // Used internally
  40.     var $do; // Used internally
  41.  
  42.     function batcache( $settings ) {
  43.         if ( is_array( $settings ) ) foreach ( $settings as $k => $v )
  44.             $this->$k = $v;
  45.     }
  46.  
  47.     function is_ssl() {
  48.         if ( isset($_SERVER['HTTPS']) ) {
  49.             if ( 'on' == strtolower($_SERVER['HTTPS']) )
  50.                 return true;
  51.             if ( '1' == $_SERVER['HTTPS'] )
  52.                 return true;
  53.         } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  54.             return true;
  55.         }
  56.         return false;
  57.     }
  58.  
  59.     function status_header( $status_header ) {
  60.         $this->status_header = $status_header;
  61.  
  62.         return $status_header;
  63.     }
  64.  
  65.     function redirect_status( $status, $location ) {
  66.         if ( $this->cache_redirects ) {
  67.             $this->redirect_status = $status;
  68.             $this->redirect_location = $location;
  69.         }
  70.  
  71.         return $status;
  72.     }
  73.  
  74.     function configure_groups() {
  75.         // Configure the memcached client
  76.         if ( ! $this->remote )
  77.             if ( function_exists('wp_cache_add_no_remote_groups') )
  78.                 wp_cache_add_no_remote_groups(array($this->group));
  79.         if ( function_exists('wp_cache_add_global_groups') )
  80.             wp_cache_add_global_groups(array($this->group));
  81.     }
  82.  
  83.     // Defined here because timer_stop() calls number_format_i18n()
  84.     function timer_stop($display = 0, $precision = 3) {
  85.         global $timestart, $timeend;
  86.         $mtime = microtime();
  87.         $mtime = explode(' ',$mtime);
  88.         $mtime = $mtime[1] + $mtime[0];
  89.         $timeend = $mtime;
  90.         $timetotal = $timeend-$timestart;
  91.         $r = number_format($timetotal, $precision);
  92.         if ( $display )
  93.             echo $r;
  94.         return $r;
  95.     }
  96.  
  97.     function ob($output) {
  98.         if ( $this->cancel !== false )
  99.             return $output;
  100.  
  101.         // PHP5 and objects disappearing before output buffers?
  102.         wp_cache_init();
  103.  
  104.         // Remember, $wp_object_cache was clobbered in wp-settings.php so we have to repeat this.
  105.         $this->configure_groups();
  106.  
  107.         // Do not batcache blank pages unless they are HTTP redirects
  108.         $output = trim($output);
  109.         if ( $output === '' && (!$this->redirect_status || !$this->redirect_location) )
  110.             return;
  111.  
  112.         // Construct and save the batcache
  113.         $cache = array(
  114.             'output' => $output,
  115.             'time' => time(),
  116.             'timer' => $this->timer_stop(false, 3),
  117.             'status_header' => $this->status_header,
  118.             'redirect_status' => $this->redirect_status,
  119.             'redirect_location' => $this->redirect_location,
  120.             'version' => $this->url_version
  121.         );
  122.  
  123.         if ( function_exists( 'headers_list' ) ) {
  124.             foreach ( headers_list() as $header ) {
  125.                 list($k, $v) = array_map('trim', explode(':', $header, 2));
  126.                 $cache['headers'][$k] = $v;
  127.             }
  128.         } elseif ( function_exists( 'apache_response_headers' ) ) {
  129.             $cache['headers'] = apache_response_headers();
  130.         }
  131.  
  132.         if ( $cache['headers'] && !empty( $this->uncached_headers ) ) {
  133.             foreach ( $cache['headers'] as $header => $value ) {
  134.                 if ( in_array( strtolower( $header ), $this->uncached_headers ) )
  135.                     unset( $cache['headers'][$header] );
  136.             }
  137.         }
  138.  
  139.         wp_cache_set($this->key, $cache, $this->group, $this->max_age + $this->seconds + 30);
  140.  
  141.         // Unlock regeneration
  142.         wp_cache_delete("{$this->url_key}_genlock", $this->group);
  143.  
  144.         if ( $this->cache_control ) {
  145.             header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $cache['time'] ) . ' GMT', true );
  146.             header("Cache-Control: max-age=$this->max_age, must-revalidate", false);
  147.         }
  148.  
  149.         if ( !empty($this->headers) ) foreach ( $this->headers as $k => $v ) {
  150.             if ( is_array( $v ) )
  151.                 header("{$v[0]}: {$v[1]}", false);
  152.             else
  153.                 header("$k: $v", true);
  154.         }
  155.  
  156.         // Add some debug info just before </head>
  157.         if ( $this->debug ) {
  158.             $tag = "<!--\n\tgenerated in " . $cache['timer'] . " seconds\n\t" . strlen(serialize($cache)) . " bytes batcached for " . $this->max_age . " seconds\n-->\n";
  159.             if ( false !== $tag_position = strpos($output, '</head>') ) {
  160.                 $tag = "<!--\n\tgenerated in " . $cache['timer'] . " seconds\n\t" . strlen(serialize($cache)) . " bytes batcached for " . $this->max_age . " seconds\n-->\n";
  161.                 $output = substr($output, 0, $tag_position) . $tag . substr($output, $tag_position);
  162.             }
  163.         }
  164.  
  165.         // Pass output to next ob handler
  166.         return $output;
  167.     }
  168. }
  169. global $batcache;
  170. // Pass in the global variable which may be an array of settings to override defaults.
  171. $batcache = new batcache($batcache);
  172.  
  173. if ( ! defined( 'WP_CONTENT_DIR' ) )
  174.     return;
  175.  
  176. // Never batcache interactive scripts or API endpoints.
  177. if ( in_array(
  178.         basename( $_SERVER['SCRIPT_FILENAME'] ),
  179.         array(
  180.             'wp-app.php',
  181.             'xmlrpc.php',
  182.             'ms-files.php',
  183.         ) ) )
  184.     return;
  185.  
  186. // Never batcache WP javascript generators
  187. if ( strstr( $_SERVER['SCRIPT_FILENAME'], 'wp-includes/js' ) )
  188.     return;
  189.  
  190. // Never batcache when POST data is present.
  191. if ( ! empty( $GLOBALS['HTTP_RAW_POST_DATA'] ) || ! empty( $_POST ) )
  192.     return;
  193.  
  194. // Never batcache when cookies indicate a cache-exempt visitor.
  195. if ( is_array( $_COOKIE) && ! empty( $_COOKIE ) )
  196.     foreach ( array_keys( $_COOKIE ) as $batcache->cookie )
  197.         if ( $batcache->cookie != 'wordpress_test_cookie' && ( substr( $batcache->cookie, 0, 2 ) == 'wp' || substr( $batcache->cookie, 0, 9 ) == 'wordpress' || substr( $batcache->cookie, 0, 14 ) == 'comment_author' ) )
  198.             return;
  199.  
  200. if ( ! include_once( WP_CONTENT_DIR . '/object-cache.php' ) )
  201.     return;
  202.  
  203. wp_cache_init(); // Note: wp-settings.php calls wp_cache_init() which clobbers the object made here.
  204.  
  205. if ( ! is_object( $wp_object_cache ) )
  206.     return;
  207.  
  208. // Now that the defaults are set, you might want to use different settings under certain conditions.
  209.  
  210. /* 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.
  211. $batcache->unique['mobile'] = is_mobile_user_agent();
  212. */
  213.  
  214. /* Example: never batcache for this host
  215. if ( $_SERVER['HTTP_HOST'] == 'do-not-batcache-me.com' )
  216.     return;
  217. */
  218.  
  219. /* Example: batcache everything on this host regardless of traffic level
  220. if ( $_SERVER['HTTP_HOST'] == 'always-batcache-me.com' ) {
  221.     $batcache->max_age = 600; // Cache for 10 minutes
  222.     $batcache->seconds = $batcache->times = 0; // No need to wait till n number of people have accessed the page, cache instantly
  223. }
  224. */
  225.  
  226. /* 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.
  227. if ( include_once( 'plugins/searchterm-highlighter.php') && referrer_has_search_terms() )
  228.     return;
  229. */
  230.  
  231. // Disabled
  232. if ( $batcache->max_age < 1 )
  233.     return;
  234.  
  235. // Make sure we can increment. If not, turn off the traffic sensor.
  236. if ( ! method_exists( $GLOBALS['wp_object_cache'], 'incr' ) )
  237.     $batcache->times = 0;
  238.  
  239. // 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.
  240. header('Vary: Cookie', false);
  241.  
  242. // Things that define a unique page.
  243. if ( isset( $_SERVER['QUERY_STRING'] ) )
  244.     parse_str($_SERVER['QUERY_STRING'], $batcache->query);
  245. $batcache->keys = array(
  246.     'host' => $_SERVER['HTTP_HOST'],
  247.     'method' => $_SERVER['REQUEST_METHOD'],
  248.     'path' => ( $batcache->pos = strpos($_SERVER['REQUEST_URI'], '?') ) ? substr($_SERVER['REQUEST_URI'], 0, $batcache->pos) : $_SERVER['REQUEST_URI'],
  249.     'query' => $batcache->query,
  250.     'extra' => $batcache->unique
  251. );
  252.  
  253. if ( $batcache->is_ssl() )
  254.     $batcache->keys['ssl'] = true;
  255.  
  256. $batcache->configure_groups();
  257.  
  258. // Generate the batcache key
  259. $batcache->key = md5(serialize($batcache->keys));
  260.  
  261. // Generate the traffic threshold measurement key
  262. $batcache->req_key = $batcache->key . '_req';
  263.  
  264. // Get the batcache
  265. $batcache->cache = wp_cache_get($batcache->key, $batcache->group);
  266.  
  267. // Are we only caching frequently-requested pages?
  268. if ( $batcache->seconds < 1 || $batcache->times < 2 ) {
  269.     $batcache->do = true;
  270. } else {
  271.     // No batcache item found, or ready to sample traffic again at the end of the batcache life?
  272.     if ( !is_array($batcache->cache) || time() >= $batcache->cache['time'] + $batcache->max_age - $batcache->seconds ) {
  273.         wp_cache_add($batcache->req_key, 0, $batcache->group);
  274.         $batcache->requests = wp_cache_incr($batcache->req_key, 1, $batcache->group);
  275.  
  276.         if ( $batcache->requests >= $batcache->times )
  277.             $batcache->do = true;
  278.         else
  279.             $batcache->do = false;
  280.     }
  281. }
  282.  
  283. // Recreate the permalink from the URL
  284. $batcache->permalink = 'http://' . $batcache->keys['host'] . $batcache->keys['path'] . ( isset($batcache->keys['query']['p']) ? "?p=" . $batcache->keys['query']['p'] : '' );
  285. $batcache->url_key = md5($batcache->permalink);
  286. $batcache->url_version = (int) wp_cache_get("{$batcache->url_key}_version", $batcache->group);
  287.  
  288. // If the document has been updated and we are the first to notice, regenerate it.
  289. if ( $batcache->do !== false && isset($batcache->cache['version']) && $batcache->cache['version'] < $batcache->url_version )
  290.     $batcache->genlock = wp_cache_add("{$batcache->url_key}_genlock", 1, $batcache->group);
  291.  
  292. // Did we find a batcached page that hasn't expired?
  293. if ( isset($batcache->cache['time']) && ! $batcache->genlock && time() < $batcache->cache['time'] + $batcache->max_age ) {
  294.     // Issue redirect if cached and enabled
  295.     if ( $batcache->cache['redirect_status'] && $batcache->cache['redirect_location'] && $batcache->cache_redirects ) {
  296.         $status = $batcache->cache['redirect_status'];
  297.         $location = $batcache->cache['redirect_location'];
  298.         // From vars.php
  299.         $is_IIS = (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'ExpressionDevServer') !== false);
  300.         if ( $is_IIS ) {
  301.             header("Refresh: 0;url=$location");
  302.         } else {
  303.             if ( php_sapi_name() != 'cgi-fcgi' ) {
  304.                 $texts = array(
  305.                     300 => 'Multiple Choices',
  306.                     301 => 'Moved Permanently',
  307.                     302 => 'Found',
  308.                     303 => 'See Other',
  309.                     304 => 'Not Modified',
  310.                     305 => 'Use Proxy',
  311.                     306 => 'Reserved',
  312.                     307 => 'Temporary Redirect',
  313.                 );
  314.                 $protocol = $_SERVER["SERVER_PROTOCOL"];
  315.                 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  316.                     $protocol = 'HTTP/1.0';
  317.                 if ( isset($texts[$status]) )
  318.                     header("$protocol $status " . $texts[$status]);
  319.                 else
  320.                     header("$protocol 302 Found");
  321.             }
  322.             header("Location: $location");
  323.         }
  324.         exit;
  325.     }
  326.  
  327.     // Issue "304 Not Modified" only if the dates match exactly.
  328.     if ( $batcache->cache_control && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ) {
  329.         $since = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
  330.         if ( isset($batcache->cache['headers']['Last-Modified']) )
  331.             $batcache->cache['time'] = strtotime( $batcache->cache['headers']['Last-Modified'] );
  332.         if ( $batcache->cache['time'] == $since ) {
  333.             header('Last-Modified: ' . $_SERVER['HTTP_IF_MODIFIED_SINCE'], true, 304);
  334.             exit;
  335.         }
  336.     }
  337.  
  338.     // Use the batcache save time for Last-Modified so we can issue "304 Not Modified"
  339.     if ( $batcache->cache_control ) {
  340.         header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $batcache->cache['time'] ) . ' GMT', true );
  341.         header('Cache-Control: max-age=' . ($batcache->max_age - time() + $batcache->cache['time']) . ', must-revalidate', true);
  342.     }
  343.  
  344.     // Add some debug info just before </head>
  345.     if ( $batcache->debug ) {
  346.         if ( false !== $tag_position = strpos($batcache->cache['output'], '</head>') ) {
  347.             $tag = "<!--\n\tgenerated " . (time() - $batcache->cache['time']) . " seconds ago\n\tgenerated in " . $batcache->cache['timer'] . " seconds\n\tserved from batcache in " . $batcache->timer_stop(false, 3) . " seconds\n\texpires in " . ($batcache->max_age - time() + $batcache->cache['time']) . " seconds\n-->\n";
  348.             $batcache->cache['output'] = substr($batcache->cache['output'], 0, $tag_position) . $tag . substr($batcache->cache['output'], $tag_position);
  349.         }
  350.     }
  351.  
  352.     if ( !empty($batcache->cache['headers']) ) foreach ( $batcache->cache['headers'] as $k => $v )
  353.         header("$k: $v", true);
  354.  
  355.     if ( !empty($batcache->headers) ) foreach ( $batcache->headers as $k => $v ) {
  356.         if ( is_array( $v ) )
  357.             header("{$v[0]}: {$v[1]}", false);
  358.         else
  359.             header("$k: $v", true);
  360.     }
  361.  
  362.     if ( !empty($batcache->cache['status_header']) )
  363.         header($batcache->cache['status_header'], true);
  364.  
  365.     // Have you ever heard a death rattle before?
  366.     die($batcache->cache['output']);
  367. }
  368.  
  369. // Didn't meet the minimum condition?
  370. if ( !$batcache->do && !$batcache->genlock )
  371.     return;
  372.  
  373. $wp_filter['status_header'][10]['batcache'] = array( 'function' => array(&$batcache, 'status_header'), 'accepted_args' => 1 );
  374. $wp_filter['wp_redirect_status'][10]['batcache'] = array( 'function' => array(&$batcache, 'redirect_status'), 'accepted_args' => 2 );
  375.  
  376. ob_start(array(&$batcache, 'ob'));
  377.  
  378. // It is safer to omit the final PHP closing tag.
RAW Paste Data