false, 'hosts' => array(), 'lifespan' => 36000, 'cache_dir' => '', 'bypass_params' => array(), 'bypass_cookies' => array(), 'ignored_params' => array(), 'cached_params' => array( 'v', 'lang' ), 'excluded_paths' => array(), 'mobile' => false, 'probe_token' => '', 'never_store_if' => array(), 'system_paths' => array(), ); } /** * Decides whether a request may be answered from the cache, and builds its key. * * @param GorillaCache_Engine_Request $request Request. * @param array $config Configuration (see default_config()). * @return array{cache:bool, reason:string, key:string} Reason is a short code; key is empty unless cache is true. */ public static function explain( GorillaCache_Engine_Request $request, array $config ) { $config = array_merge( self::default_config(), $config ); if ( ! $config['enabled'] ) { return self::no( 'disabled' ); } if ( 'GET' !== $request->method && 'HEAD' !== $request->method ) { return self::no( 'method' ); } $store_params = array_merge( self::STORE_ACTION_PARAMS, self::lower( $config['bypass_params'] ) ); foreach ( $request->query as $pair ) { if ( in_array( $pair[0], $store_params, true ) ) { return self::no( 'store_action' ); } } if ( '' === $request->host || ! in_array( $request->host, self::lower( $config['hosts'] ), true ) ) { return self::no( 'unknown_host' ); } if ( '' !== $config['probe_token'] && '' !== $request->probe && hash_equals( (string) $config['probe_token'], $request->probe ) ) { return self::no( 'probe' ); } $path_reason = self::path_reason( $request->path, (array) $config['system_paths'] ); if ( '' !== $path_reason ) { return self::no( $path_reason ); } // WordPress answers /Sample-Page/ and /SAMPLE-PAGE/ with the same page, and each spelling would be one more // copy on disk: its own addresses are lower case, so a capital letter means a made-up spelling. if ( 1 === preg_match( '/[A-Z]/', rawurldecode( $request->path ) ) ) { return self::no( 'path_case' ); } $kept = array(); $names = array(); $dropped = false; $ignored = array_merge( self::TRACKING_PARAMS, self::lower( $config['ignored_params'] ) ); $cached = self::lower( $config['cached_params'] ); foreach ( $request->query as $pair ) { if ( in_array( $pair[0], $ignored, true ) || 0 === strpos( $pair[0], 'utm_' ) ) { $dropped = true; continue; } $value = false === strpos( $pair[1], '=' ) ? '' : rawurldecode( substr( $pair[1], strpos( $pair[1], '=' ) + 1 ) ); $raw = rawurldecode( str_replace( '+', ' ', explode( '=', $pair[1], 2 )[0] ) ); // Only the exact name, once: ?V= or ?v=1&v=2 shows the same page as ?v=1, as one more copy on disk. if ( ! in_array( $pair[0], $cached, true ) || $raw !== $pair[0] || isset( $names[ $pair[0] ] ) || ! self::cacheable_value( $pair[0], $value ) ) { return self::no( 'query' ); } $names[ $pair[0] ] = true; // Keyed on the decoded value, encoded one way: ?v=a and ?v=%61 are one page, so they are one copy. $kept[] = $pair[0] . '=' . rawurlencode( $value ); } if ( '' !== $request->accept && false === strpos( $request->accept, 'text/html' ) && false === strpos( $request->accept, '*/*' ) && false === strpos( $request->accept, 'application/xhtml+xml' ) ) { return self::no( 'not_html' ); } if ( self::has_bypass_cookie( $request->cookies, self::lower( $config['bypass_cookies'] ) ) ) { return self::no( 'cookie' ); } foreach ( (array) $config['excluded_paths'] as $pattern ) { if ( self::path_matches( $request->path, (string) $pattern ) ) { return self::no( 'excluded' ); } } $mobile = $config['mobile'] && self::is_mobile( $request->user_agent ); $key = self::key( $request, $kept, $mobile ); if ( '' === $key ) { return self::no( 'unsafe_path' ); } // A tracking parameter is left out of the key, so the link is answered from the plain address's copy. But the // page WordPress builds for it can carry the parameter (pagination links, a form's prefilled fields), so a // page built for such a link is never stored: the plain address is stored by its own visits and by warming. return array( 'cache' => true, 'reason' => 'ok', 'key' => $key, 'store' => ! $dropped, ); } /** * A short code for this WordPress install: the folder of its Gorilla Cache engine, its database and its declared * environment. The settings file carries the code of the install that wrote it, so a copy of the files on another * install, a server, a folder, a database or an environment that differs, never serves or stores a page with them. * * @param string $folder The engine's folder (each install has its own copy of the plugin). * @param string $db_name Database name. * @param string $prefix Table prefix. * @param string $environment Declared environment (WP_ENVIRONMENT_TYPE), or ''. * @return string */ public static function site_hash( $folder, $db_name, $prefix, $environment ) { return substr( md5( self::real_folder( $folder ) . '|' . (string) $db_name . '|' . (string) $prefix . '|' . strtolower( (string) $environment ) ), 0, 12 ); } /** * A folder written the same way however it was reached: WP-CLI keeps the path it was given (a symlink such as * a deploy tool's "current", a path with "..", forward slashes on Windows), while the web server resolves it. * * @param string $folder Folder. * @return string */ public static function real_folder( $folder ) { $folder = (string) $folder; $real = '' !== $folder ? realpath( $folder ) : false; $folder = str_replace( '\\', '/', false !== $real ? $real : $folder ); if ( preg_match( '#^[a-z]:/#', $folder ) ) { $folder = ucfirst( $folder ); // A Windows drive letter. } return rtrim( $folder, '/' ); } /** * The environment wp-config.php declares (WP_ENVIRONMENT_TYPE), or '' when it declares none. Only the constant: * a server variable can be set for the web server and missing for WP-CLI and cron, and the two would then * disagree about which install this is. * * @return string */ public static function declared_environment() { return defined( 'WP_ENVIRONMENT_TYPE' ) && WP_ENVIRONMENT_TYPE ? strtolower( (string) WP_ENVIRONMENT_TYPE ) : ''; } /** * This request's install code. The drop-in records it in GORILLA_CACHE_INSTALL as soon as it loads, before any * plugin runs, and WordPress uses that same value, so a constant a plugin defines later, or a table prefix * that is not global yet, can never make the two disagree. Without the drop-in, it is worked out the same way. * * @return string */ public static function current_site_hash() { return defined( 'GORILLA_CACHE_INSTALL' ) ? (string) GORILLA_CACHE_INSTALL : self::computed_site_hash(); } /** * The install code from the engine's folder and what wp-config.php has defined (available before WordPress loads). * * @return string */ public static function computed_site_hash() { return self::site_hash( __DIR__, // This file's own folder, the engine's: the drop-in and the plugin reach the same files. defined( 'DB_NAME' ) ? DB_NAME : '', isset( $GLOBALS['table_prefix'] ) ? (string) $GLOBALS['table_prefix'] : '', self::declared_environment() ); } /** * Whether a value of a kept parameter may get its own copy. Each value is a new file, so a link with endless * made-up values must not fill the disk: WooCommerce's location hash (`v`) is a short hexadecimal code and a * language (`lang`) a short language code; any other kept parameter allows a value of up to 64 characters. * * @param string $name Parameter name (lower case). * @param string $value Its value. * @return bool */ public static function cacheable_value( $name, $value ) { // WooCommerce writes its location hash in lower case; any other spelling would be one more copy. if ( 'v' === $name ) { return 1 === preg_match( '/^[0-9a-f]{1,32}$/', $value ); } if ( 'lang' === $name ) { return 1 === preg_match( '/^[a-z]{2,3}(?:[-_][a-z0-9]{2,8})?$/i', $value ); } return strlen( $value ) <= 64; } /** * Decides whether a finished response may be stored. An empty string means yes; anything else is * the reason it may not. * * @param int $status HTTP status code. * @param string[] $headers Response headers as "Name: value" lines (headers_list() shape). * @param string $body Response body. * @param bool $do_not_cache Whether DONOTCACHEPAGE (or our own skip flag) is set. * @param int $lifespan Our lifespan in seconds. * @param string[] $markers Text that, found in the body, keeps a page out of the cache (for example * a session script that would hand every visitor the same session). * @return string */ public static function storable( $status, array $headers, $body, $do_not_cache, $lifespan, array $markers = array() ) { if ( 200 !== (int) $status ) { return 'status'; } if ( $do_not_cache ) { return 'donotcachepage'; } foreach ( $headers as $line ) { $parts = explode( ':', (string) $line, 2 ); $name = strtolower( trim( $parts[0] ) ); $value = isset( $parts[1] ) ? strtolower( trim( $parts[1] ) ) : ''; if ( 'set-cookie' === $name ) { return 'set_cookie'; } if ( 'content-type' === $name && false === strpos( $value, 'text/html' ) ) { return 'not_html'; } if ( 'cache-control' === $name ) { if ( 1 === preg_match( '/(^|[\s,])(no-cache|no-store|private)([\s,=]|$)/', $value ) ) { return 'no_cache_header'; } if ( 1 === preg_match( '/(?:s-)?max-age\s*=\s*(\d+)/', $value, $m ) && (int) $m[1] < (int) $lifespan ) { return 'short_max_age'; } } } if ( false === stripos( $body, '' ) ) { return 'incomplete'; } foreach ( $markers as $marker ) { if ( '' !== (string) $marker && false !== strpos( $body, (string) $marker ) ) { return 'marker'; } } // A PHP warning printed into the page (display_errors on, common on cheap hosts) shows file paths and must // not be served to every visitor for hours. if ( 1 === preg_match( '#(?:Warning|Notice|Deprecated|Fatal error|Parse error):\s#', $body ) || 1 === preg_match( '#(?:^|\n)(?:PHP )?(?:Warning|Notice|Deprecated|Fatal error): .{1,500}? on line \d+#', $body ) ) { return 'php_error'; } return ''; } /** * The detail that makes a refusal reason useful to the owner: the cookie names for set_cookie, the status code * (and the target of a redirect) for status, the header's value for no_cache_header, short_max_age and not_html. * Plain printable text, at most 200 characters; escaped where it is shown. * * @param string $reason Reason from storable(). * @param int $status HTTP status code. * @param string[] $headers Response headers as "Name: value" lines. * @return string */ public static function refusal_detail( $reason, $status, array $headers ) { $wanted = array( 'set_cookie' => 'set-cookie', 'no_cache_header' => 'cache-control', 'short_max_age' => 'cache-control', 'not_html' => 'content-type', 'status' => 'location', ); $detail = 'status' === $reason ? (string) (int) $status : ''; $values = array(); if ( isset( $wanted[ $reason ] ) ) { foreach ( $headers as $line ) { $parts = explode( ':', (string) $line, 2 ); if ( isset( $parts[1] ) && strtolower( trim( $parts[0] ) ) === $wanted[ $reason ] ) { $value = trim( $parts[1] ); // A cookie's name only: its value may be a visitor's own. $values[] = 'set_cookie' === $reason ? trim( explode( '=', $value, 2 )[0] ) : $value; } } } $values = array_values( array_unique( array_filter( $values, 'strlen' ) ) ); if ( array() !== $values ) { $detail .= ( '' !== $detail ? ' ' : '' ) . implode( ', ', $values ); } $detail = (string) preg_replace( '/[^\x20-\x7e]/', '', $detail ); return substr( $detail, 0, 200 ); } /** * Picks the headers worth replaying from a response. * * @param string[] $headers "Name: value" lines. * @return string[] */ public static function replayed_headers( array $headers ) { $out = array(); foreach ( $headers as $line ) { $name = strtolower( trim( explode( ':', (string) $line, 2 )[0] ) ); if ( in_array( $name, self::REPLAYED_HEADERS, true ) ) { $out[] = (string) $line; } } return $out; } /** * Builds the cache file path, relative to the cache folder, losslessly from the request. Each path * segment is percent-encoded again after decoding, so "/a-b/", "/a/b/" and "/a_b/" never share a file. * Returns an empty string for a path that cannot be stored safely. * * @param GorillaCache_Engine_Request $request Request. * @param string[] $kept Raw query pairs that are part of the key. * @param bool $mobile Whether this is the mobile copy. * @return string */ public static function key( GorillaCache_Engine_Request $request, array $kept, $mobile ) { $dir = self::dir_for( $request->host, $request->path ); if ( '' === $dir ) { return ''; } sort( $kept ); $file = '@' . $request->scheme . ( '/' === substr( $request->path, -1 ) ? '' : '-noslash' ) . ( $mobile ? '-mobile' : '' ) . ( array() !== $kept ? '-q' . substr( sha1( implode( '&', $kept ) ), 0, 16 ) : '' ) . '.gcache'; return $dir . '/' . $file; } /** * The folder, relative to the cache folder, that holds every cached copy of one address (all its * schemes, variants and kept queries). Clearing an address deletes the "@" files in it; its * sub-folders are other addresses (for example "page/2/"). Empty for a path that cannot be stored. * * @param string $host Host, lower case, with ":port" when given. * @param string $path Raw path. * @return string */ public static function dir_for( $host, $path ) { $segments = array( str_replace( ':', '_', (string) $host ) ); $trimmed = trim( (string) $path, '/' ); if ( '' !== $trimmed ) { foreach ( explode( '/', $trimmed ) as $segment ) { $decoded = rawurldecode( $segment ); if ( '' === $decoded || '.' === $decoded || '..' === $decoded || strlen( $decoded ) > 200 || false !== strpbrk( $decoded, "/\\\0" ) ) { return ''; } $segments[] = rawurlencode( $decoded ); } } return implode( '/', $segments ); } /** * Whether a path can never be a cacheable page, and why. * * @param string $path Request path. * @param string[] $system_paths This site's own system paths. * @return string Reason code, or empty. */ public static function path_reason( $path, array $system_paths = array() ) { if ( '' === $path || '/' !== $path[0] || false !== strpos( $path, '//' ) ) { return 'unsafe_path'; } $lower = strtolower( rawurldecode( $path ) ); // The usual WordPress paths, plus this site's own (a moved content folder, a REST prefix of its own). foreach ( array_merge( self::SYSTEM_PATH_PREFIXES, $system_paths ) as $prefix ) { if ( '' !== $prefix && 0 === strpos( $lower, strtolower( (string) $prefix ) ) ) { return 'system_path'; } } if ( 1 === preg_match( '#/(feed|trackback|embed)/?$#', $lower ) ) { return 'system_path'; } $last = basename( rtrim( $lower, '/' ) ); if ( 1 === preg_match( '/\.([a-z0-9]{1,8})$/', $last, $m ) && ! in_array( $m[1], array( 'html', 'htm' ), true ) ) { return 'not_page'; } return ''; } /** * Whether any cookie means "personal visitor". * * @param string[] $names Cookie names. * @param string[] $extra Extra prefixes from the configuration. * @return bool */ public static function has_bypass_cookie( array $names, array $extra ) { $prefixes = self::BYPASS_COOKIE_PREFIXES; foreach ( $extra as $prefix ) { // An owner's entry is a prefix: a trailing "*" adds nothing, and PHP hands over cookie names with "." and // spaces turned into "_". $prefixes[] = strtolower( str_replace( array( '.', ' ' ), '_', rtrim( trim( (string) $prefix ), '*' ) ) ); } foreach ( $names as $name ) { $name = strtolower( (string) $name ); foreach ( $prefixes as $prefix ) { if ( '' !== $prefix && 0 === strpos( $name, $prefix ) ) { return true; } } foreach ( self::BYPASS_COOKIE_CONTAINS as $fragment ) { if ( false !== strpos( $name, $fragment ) ) { return true; } } } return false; } /** * Matches a path against an owner's exclusion: a plain path, with "*" for "anything", ignoring a trailing * slash and percent-encoding. * * @param string $path Request path. * @param string $pattern Exclusion, for example "/members/*". * @return bool */ public static function path_matches( $path, $pattern ) { $pattern = rawurldecode( trim( (string) $pattern ) ); if ( '' === $pattern ) { return false; } $path = rawurldecode( (string) $path ); if ( '/*' === substr( $pattern, -2 ) ) { // "/members/*" covers "/members" itself and everything under it. $regex = '#^' . str_replace( '\*', '.*', preg_quote( substr( $pattern, 0, -2 ), '#' ) ) . '(?:/.*)?$#iu'; } else { // A trailing slash never matters: "/contact" and "/contact/" are the same page. $regex = '#^' . str_replace( '\*', '.*', preg_quote( rtrim( $pattern, '/' ), '#' ) ) . '/?$#iu'; } return 1 === preg_match( $regex, $path ); } /** * The same test WordPress's wp_is_mobile() uses, available before WordPress loads. * * @param string $user_agent User agent. * @return bool */ public static function is_mobile( $user_agent ) { return 1 === preg_match( '/Mobile|Android|Silk\/|Kindle|BlackBerry|Opera Mini|Opera Mobi/', (string) $user_agent ); } /** * A "no" answer. * * @param string $reason Reason code. * @return array{cache:bool, reason:string, key:string, store:bool} */ private static function no( $reason ) { return array( 'cache' => false, 'reason' => $reason, 'key' => '', 'store' => false, ); } /** * Lower-cases a list of strings. * * @param mixed $items List. * @return string[] */ private static function lower( $items ) { return array_map( 'strtolower', array_map( 'strval', (array) $items ) ); } }