*/ const OPTIMISERS = array( 'autoptimizeMain::end_buffering' => 'autoptimize_html_after_minify', 'Perfmatters\\Buffer::process' => 'perfmatters_output_buffer', 'Hummingbird\\Core\\Modules\\Page_Cache::wphb_maybe_process_buffer' => 'wphb_buffer', 'ewww_image_optimizer_filter_page_output' => 'ewww_image_optimizer_filter_page_output', 'TenWebOptimizer\\OptimizerMain::end_buffering' => 'two_content_after_optimization', ); /** * Optimisation plugins whose buffer's handler is a closure, which PHP names only by its file (PHP 8.4 and later: * "{closure:/path/file.php:line}") or not at all ("Closure::__invoke" before 8.4). Each entry: the end of that * file's path, the function the plugin hooks to open its buffer (hook and function), and its filter for the * finished page. Optimization Detective (from WordPress's performance team, also behind Image Prioritizer and * Embed Optimizer) opens its buffer on "template_include" at the last priority, so it is the buffer just outside * WordPress's. * * @var array */ const CLOSURE_OPTIMISERS = array( 'optimization-detective/optimization.php' => array( 'hook' => 'template_include', 'function' => 'od_buffer_output', 'filter' => 'od_template_output_buffer', ), ); /** * Buffers PHP itself opens (php.ini's output_buffering, compression, URL rewriting): they never change the HTML * of the page, so the page is still final inside them. * * @var string[] */ const NEUTRAL_BUFFERS = array( 'default output handler', 'zlib output compression', 'ob_gzhandler', 'URL-Rewriter', 'mb_output_handler' ); /** * Where this page is taken from: 'core' (WordPress's own buffer), an optimiser's filter name, or '' when it is * not stored (no template, or another buffer would still change the page after it is taken). * * @var string */ private $capture = ''; /** * Why the page is not stored, when the buffers decided it: an unknown buffer outside the capture point. * * @var array{reason:string, detail:string}|null */ private $refused = null; /** * Whether the page was handed over (stored or refused) in this request. * * @var bool */ private $handled = false; /** * When this request started, to the microsecond (see mark_start()). * * @var float */ private $started = 0.0; /** * The pages folder's inode when this request started; null when not recorded (unit tests). * * @var int|false|null */ private $root_inode = null; /** * Keeps the current response out of the cache. * * @param string $reason Short reason code. */ public static function skip( $reason ) { self::$skip = (string) $reason; } /** * The reason set by skip(), if any. * * @return string */ public static function skipped() { return self::$skip; } /** * Handles one request. * * @param array $config Configuration. * @param array $server Server variables. * @param array $cookies Cookies. * @param int|null $now Current time (tests pass a fixed one). * @return string "hit" (the response was sent; the caller exits), "miss" (buffer opened, its closing registered) or "bypass". */ public static function start( array $config, array $server, array $cookies, $now = null ) { $config = array_merge( GorillaCache_Engine_Rules::default_config(), $config ); $now = null === $now ? time() : (int) $now; $request = GorillaCache_Engine_Request::from_arrays( $server, $cookies ); $decision = GorillaCache_Engine_Rules::explain( $request, $config ); if ( $decision['cache'] && '' === $config['cache_dir'] ) { $decision['reason'] = 'no_cache_dir'; $decision['cache'] = false; } if ( ! $decision['cache'] ) { self::header( 'X-Gorilla-Cache: BYPASS (' . $decision['reason'] . ')' ); return 'bypass'; } $file = rtrim( $config['cache_dir'], '/' ) . '/' . $decision['key']; $open = GorillaCache_Engine_Store::open( $file, $config['lifespan'], $now ); if ( null !== $open ) { self::serve( $open, $request->method, $now ); return 'hit'; } // A tracking link with no stored copy yet: answered by WordPress, not stored (see Rules::explain()). if ( empty( $decision['store'] ) ) { self::header( 'X-Gorilla-Cache: BYPASS (tracking)' ); return 'bypass'; } $engine = new self( $config, $file, $request->scheme . '://' . $request->host . $request->path ); $engine->mark_start( $now ); $engine->note = '' !== (string) $config['probe_token'] && '' !== $request->warm && hash_equals( (string) $config['probe_token'], $request->warm ); // The page is stored from WordPress's own output buffer, which WordPress opens just before the theme's // template because this action is registered; no buffer of our own is opened. Without WordPress's hooks // nothing can be stored. if ( ! function_exists( 'add_action' ) || ! function_exists( 'add_filter' ) ) { self::header( 'X-Gorilla-Cache: BYPASS (no_hooks)' ); return 'bypass'; } $engine->watch(); self::header( 'X-Gorilla-Cache: MISS' ); return 'miss'; } /** * Registers what takes the finished page: WordPress's buffer, each known optimiser's filter, and a last look * at the end of the request for a page that never reached a template. */ public function watch() { add_action( 'wp_template_enhancement_output_buffer_started', array( $this, 'on_started' ) ); add_action( 'wp_finalized_template_enhancement_output_buffer', array( $this, 'on_finalized' ), PHP_INT_MAX ); foreach ( self::filters() as $filter ) { add_filter( $filter, array( $this, 'on_optimised' ), PHP_INT_MAX ); } add_action( 'shutdown', array( $this, 'on_shutdown' ), PHP_INT_MAX ); } /** * Every known optimiser's filter for its finished page. * * @return string[] */ public static function filters() { $filters = array_values( self::OPTIMISERS ); foreach ( self::CLOSURE_OPTIMISERS as $closure ) { $filters[] = $closure['filter']; } return array_values( array_unique( $filters ) ); } /** * WordPress has just opened its buffer, so every buffer opened before it is still open and wraps it. Decides * where the finished page is taken from. */ public function on_started() { $levels = ob_get_status( true ); array_pop( $levels ); // WordPress's own, the newest. $names = array(); foreach ( $levels as $level ) { $names[] = isset( $level['name'] ) ? (string) $level['name'] : ''; } $active = array(); foreach ( self::CLOSURE_OPTIMISERS as $file => $closure ) { if ( function_exists( 'has_filter' ) && false !== has_filter( $closure['hook'], $closure['function'] ) ) { $active[] = $file; } } $point = self::capture_point( $names, $active ); $this->capture = $point['capture']; $this->refused = '' === $point['unknown'] ? null : array( 'reason' => 'outer_buffer', 'detail' => $point['unknown'], ); } /** * Where a page is final, given the buffers open around WordPress's, oldest first. Walking outwards from * WordPress's buffer: a neutral buffer changes nothing; a known optimiser's buffer moves the capture point to its * filter; any other buffer outside the capture point would still change the page after it is taken, so the page * is not stored. * * @param string[] $names Handler names of the buffers around WordPress's, oldest (outermost) first. * @param string[] $active Keys of CLOSURE_OPTIMISERS whose plugin hooked its buffer in this request. * @return array{capture:string, unknown:string} The capture point ('core' or a filter) and the first buffer * outside it that is not known ('' when none). */ public static function capture_point( array $names, array $active = array() ) { $capture = 'core'; $unknown = ''; $first = true; // The innermost buffer that is not PHP's own. foreach ( array_reverse( $names ) as $name ) { if ( in_array( $name, self::NEUTRAL_BUFFERS, true ) ) { continue; } $filter = isset( self::OPTIMISERS[ $name ] ) ? self::OPTIMISERS[ $name ] : self::closure_filter( $name, $active, $first ); $first = false; if ( '' !== $filter ) { $capture = $filter; $unknown = ''; // A buffer inside the optimiser's has already changed the page it receives. continue; } if ( '' === $unknown ) { $unknown = '' !== $name ? self::short_name( $name ) : 'unnamed'; } } return array( 'capture' => $capture, 'unknown' => $unknown, ); } /** * The filter of a known optimiser whose buffer's handler is this closure, or ''. Named by its file (PHP 8.4 and * later); unnamed before 8.4, then only the buffer just outside WordPress's can be one, and only when exactly one * such optimiser hooked its buffer. * * @param string $name Handler name. * @param string[] $active Keys of CLOSURE_OPTIMISERS active in this request. * @param bool $innermost Whether this is the innermost buffer around WordPress's that is not PHP's own. * @return string */ private static function closure_filter( $name, array $active, $innermost ) { if ( 0 === strpos( $name, '{closure:' ) ) { $path = str_replace( '\\', '/', $name ); foreach ( $active as $file ) { if ( false !== strpos( $path, '/' . $file . ':' ) ) { return self::CLOSURE_OPTIMISERS[ $file ]['filter']; } } return ''; } if ( 'Closure::__invoke' === $name && $innermost && 1 === count( $active ) ) { return self::CLOSURE_OPTIMISERS[ $active[0] ]['filter']; } return ''; } /** * A handler name fit for a note: a closure's file is given from the plugins or themes folder on, never as the * server's full path. * * @param string $name Handler name. * @return string */ public static function short_name( $name ) { if ( preg_match( '#^\{closure:(.*):(\d+)\}$#', $name, $m ) ) { $path = str_replace( '\\', '/', $m[1] ); $cut = max( (int) strrpos( $path, '/plugins/' ), (int) strrpos( $path, '/themes/' ) ); $path = $cut > 0 ? substr( $path, $cut + 1 ) : basename( $path ); return '{closure:' . $path . ':' . $m[2] . '}'; } return substr( $name, 0, 200 ); } /** * WordPress's buffer finished: the page is final here when nothing known wraps it. * * @param string $output The page. */ public function on_finalized( $output ) { if ( 'core' === $this->capture ) { $this->store( (string) $output ); } } /** * An optimiser's filter for its finished page: stores it when this optimiser is the capture point, and always * returns the page unchanged. * * @param mixed $html The page. * @return mixed */ public function on_optimised( $html ) { if ( is_string( $html ) && '' !== $this->capture && 'core' !== $this->capture && current_filter() === $this->capture ) { $this->store( $html ); } return $html; } /** * End of the request: on Gorilla Cache's own visit, a page that never reached a theme template (WordPress opened * no buffer for it: a redirect, a feed, a page ended early) leaves a note of why it was not stored. A page that * did reach one is handed over by the buffers themselves, some of which PHP closes only after this. */ public function on_shutdown() { if ( $this->handled || ! $this->note || '' !== $this->capture ) { return; } $this->handled = true; try { $status = (int) call_user_func( $this->env['status'] ); $headers = (array) call_user_func( $this->env['headers'] ); $reason = 200 !== $status ? 'status' : 'no_template'; $detail = 'status' === $reason ? GorillaCache_Engine_Rules::refusal_detail( $reason, $status, $headers ) : ''; if ( call_user_func( $this->env['plugin'] ) ) { GorillaCache_Engine_Store::write_note( $this->file, $reason, $detail, (int) call_user_func( $this->env['now'] ) ); } } catch ( Throwable $e ) { return; } } /** * Sets up a buffer handler for one request. * * @param array $config Configuration. * @param string $file Cache file. * @param string $url Request URL. * @param array $env Optional replacements for the status, headers, clock and plugin-loaded sources. */ public function __construct( array $config, $file, $url, array $env = array() ) { $this->config = array_merge( GorillaCache_Engine_Rules::default_config(), $config ); $this->file = (string) $file; $this->url = (string) $url; $this->env = array_merge( array( 'status' => 'http_response_code', 'headers' => 'headers_list', 'now' => 'time', 'plugin' => array( __CLASS__, 'plugin_ran' ), ), $env ); } /** * Whether the Gorilla Cache plugin itself loaded in this request. * * @return bool */ public static function plugin_ran() { return defined( 'GORILLA_CACHE_VERSION' ); } /** * Notes when this request started and which pages folder it would store into. * * @param int $now Request start time (unused: the clock is read to the microsecond here). */ public function mark_start( $now ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter -- kept for the callers' signature. $this->started = microtime( true ); $this->root_inode = @fileinode( rtrim( $this->config['cache_dir'], '/' ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- the folder may not exist yet. } /** * Whether a clear ran while this page was being built: then the page may show the old content and must not * be stored. Clearing everything swaps the pages folder (another inode); clearing one address leaves a * ".cleared" mark beside its copies. * * @return bool */ private function cleared_since_start() { if ( null === $this->root_inode ) { return false; } $root = rtrim( $this->config['cache_dir'], '/' ); $marker = dirname( $this->file ) . '/.cleared'; clearstatcache( true, $root ); clearstatcache( true, $marker ); if ( @fileinode( $root ) !== $this->root_inode ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- may be gone. return true; } // Read at the end of a request in which the plugin loaded; usually there is no marker (false). $cleared = class_exists( 'GorillaCache_Installer' ) && file_exists( $marker ) ? GorillaCache_Installer::filesystem()->get_contents( $marker ) : false; return false !== $cleared && (float) $cleared >= $this->started; } /** * Stores the finished page when the rules allow. Called once, from inside an output buffer's handler * (WordPress's or an optimiser's), so it never prints, never opens a buffer, and never throws: storing is * optional, the visitor's page is not. * * @param string $buffer The finished page. */ public function store( $buffer ) { if ( $this->handled ) { return; } $this->handled = true; try { if ( null !== $this->refused ) { if ( $this->note && call_user_func( $this->env['plugin'] ) ) { GorillaCache_Engine_Store::write_note( $this->file, $this->refused['reason'], $this->refused['detail'], (int) call_user_func( $this->env['now'] ) ); } return; } $status = (int) call_user_func( $this->env['status'] ); $headers = (array) call_user_func( $this->env['headers'] ); // Without the plugin in this request (deactivated without its own hook, or unloaded on some pages) // nothing would keep store pages out or clear this copy later: pass the page through, store nothing. $do_not_cache = ( defined( 'DONOTCACHEPAGE' ) && DONOTCACHEPAGE ) || '' !== self::$skip || ! call_user_func( $this->env['plugin'] ); $reason = GorillaCache_Engine_Rules::storable( $status, $headers, (string) $buffer, $do_not_cache, $this->config['lifespan'], (array) $this->config['never_store_if'] ); // Gorilla Cache's own visit notes why the page was not stored. Not for a refusal that belongs to this one // request rather than to the page: the plugin not loaded, a visitor's cookie, the setup just changed. if ( '' !== $reason && $this->note && call_user_func( $this->env['plugin'] ) && ! in_array( self::$skip, array( 'cookie', 'settings_changed' ), true ) ) { $detail = 'donotcachepage' === $reason ? ( '' !== self::$skip ? self::$skip : 'DONOTCACHEPAGE' ) : GorillaCache_Engine_Rules::refusal_detail( $reason, $status, $headers ); GorillaCache_Engine_Store::write_note( $this->file, $reason, $detail, (int) call_user_func( $this->env['now'] ) ); } if ( '' === $reason && ! $this->cleared_since_start() ) { $created = (int) call_user_func( $this->env['now'] ); GorillaCache_Engine_Store::write( $this->file, array( 'status' => $status, 'headers' => GorillaCache_Engine_Rules::replayed_headers( $headers ), 'created' => $created, 'url' => $this->url, ), // Only the stored copy carries this line, so finding it in View Source shows the page came from // the cache. A plain comment: no link, nothing visible. (string) $buffer . "\n\n" ); } } catch ( Throwable $e ) { return; } } /** * Sends a stored response. * * @param array $open Result of GorillaCache_Engine_Store::open(). * @param string $method Request method. * @param int $now Current time. */ public static function serve( array $open, $method, $now ) { if ( ! headers_sent() ) { http_response_code( (int) $open['meta']['status'] ); foreach ( (array) $open['meta']['headers'] as $line ) { header( (string) $line, false ); } header( 'X-Gorilla-Cache: HIT' ); header( 'Age: ' . max( 0, (int) $now - (int) $open['meta']['created'] ) ); } if ( 'HEAD' === $method ) { fclose( $open['handle'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- presubmit-allow: check-10 (serves a stored page before WordPress loads, so no WordPress function exists yet) return; } GorillaCache_Engine_Store::send_body( $open['handle'] ); } /** * Sends a header when that is still possible. * * @param string $line Header line. */ private static function header( $line ) { if ( ! headers_sent() ) { header( $line ); } } }