= 0 ) { $taken = max( $taken, self::request( $url, true ) ); } ++$count; ++$state['done']; if ( $taken >= 0 ) { self::count_outcome( $state, $url ); } if ( $taken < 0 && empty( $state['retried'][ $url ] ) ) { $state['queue'][] = $url; // One more try at the end of the list; a second failure drops it. $state['retried'][ $url ] = true; --$state['done']; } if ( $taken < 0 || $taken > self::SLOW ) { $slow = true; break; } } if ( $blocked ) { $state['last'] = time(); update_option( self::OPTION, $state, false ); wp_clear_scheduled_hook( self::HOOK ); // An earlier, sooner run (preload --now schedules one) would not wait. self::schedule( HOUR_IN_SECONDS ); return; } $state['batch'] = $slow ? max( self::BATCH_MIN, (int) floor( $state['batch'] / 2 ) ) : min( self::BATCH_MAX, $state['batch'] + 5 ); $state['pause'] = $slow ? 5 * MINUTE_IN_SECONDS : 0; $state['last'] = time(); if ( array() === $state['queue'] ) { $state['total'] = $state['done']; } update_option( self::OPTION, $state, false ); if ( array() !== $state['queue'] ) { self::schedule( $slow ? 5 * MINUTE_IN_SECONDS : MINUTE_IN_SECONDS ); } } /** * Schedules the next run when work is waiting and none is scheduled. WordPress saves its whole list of scheduled * tasks at once, so two requests saving at the same moment can drop ours, and nothing else would bring it back. */ public static function heal() { if ( wp_next_scheduled( self::HOOK ) || ! self::enabled() ) { return; } $state = self::state(); if ( array() !== $state['queue'] || $state['rebuild'] ) { self::schedule( $state['blocked'] ? HOUR_IN_SECONDS : MINUTE_IN_SECONDS ); } } /** * Stops warming and forgets the list (standing down, deactivation). */ public static function stop() { wp_clear_scheduled_hook( self::HOOK ); delete_option( self::OPTION ); } /** * Progress for the status screen. * * @return array{queue:string[], total:int, done:int, batch:int, pause:int, last:int, rebuild:bool, blocked:int, stored:int, refused:array} */ public static function state() { $state = get_option( self::OPTION, array() ); return array_merge( array( 'queue' => array(), 'total' => 0, 'done' => 0, 'batch' => 10, 'pause' => 0, 'last' => 0, 'rebuild' => false, 'retried' => array(), 'blocked' => 0, 'stored' => 0, 'refused' => array(), ), is_array( $state ) ? $state : array() ); } /** * The public addresses to warm, most important first, without store and member pages. * * @return string[] */ public static function addresses() { $limit = (int) apply_filters( 'gorilla_cache_preload_limit', 2000 ); $urls = array( home_url( '/' ) ); $skip = array_flip( class_exists( 'GorillaCache_Registry' ) ? GorillaCache_Registry::page_ids() : array() ); $posts = (int) get_option( 'page_for_posts' ); if ( $posts ) { $urls[] = get_permalink( $posts ); } $types = array_values( array_diff( get_post_types( array( 'public' => true ) ), array( 'attachment' ) ) ); foreach ( $types as $type ) { $archive = get_post_type_archive_link( $type ); if ( $archive ) { $urls[] = $archive; } } $ids = get_posts( array( 'post_type' => $types, 'post_status' => 'publish', 'has_password' => false, 'orderby' => 'modified', 'order' => 'DESC', 'posts_per_page' => $limit, 'fields' => 'ids', 'no_found_rows' => true, ) ); // One query for all the posts instead of one per address (up to 2,000 on a large site). _prime_post_caches( array_map( 'intval', $ids ), false, false ); foreach ( $ids as $id ) { if ( ! isset( $skip[ (int) $id ] ) ) { $urls[] = get_permalink( $id ); } } $terms = get_terms( array( 'taxonomy' => array_values( get_taxonomies( array( 'public' => true ) ) ), 'hide_empty' => true, 'number' => 500, 'orderby' => 'count', 'order' => 'DESC', ) ); foreach ( is_array( $terms ) ? $terms : array() as $term ) { $link = get_term_link( $term ); if ( ! is_wp_error( $link ) ) { $urls[] = $link; } } $urls = array_values( array_unique( array_filter( array_map( 'strval', $urls ) ) ) ); return array_slice( $urls, 0, max( 1, $limit ) ); } /** * Where warming stands, for the Status tab and WP-CLI alike: "off", "paused" (the site refused our requests), * "waiting" (work is pending and no run is scheduled, or the next run is over an hour late: WP-Cron is not * running), "starting", "warming" or "done". * * @return string */ public static function summary() { $state = self::state(); $pending = array() !== $state['queue'] || $state['rebuild']; $next = wp_next_scheduled( self::HOOK ); if ( ! self::enabled() ) { return 'off'; } if ( $state['blocked'] ) { return 'paused'; } if ( $pending && ( ! $next || $next < time() - HOUR_IN_SECONDS ) ) { return 'waiting'; } // A new full run waits for its first batch: the counts on record belong to the previous run. if ( $pending && ( $state['rebuild'] || 0 === (int) $state['total'] ) ) { return 'starting'; } return $pending ? 'warming' : 'done'; } /** * Why warming is paused, in one sentence (callers add their own "Warming is paused" heading or prefix). * * @param int $code HTTP status the site answered. * @return string */ public static function blocked_message( $code ) { /* translators: %d: HTTP status code, such as 401 or 403. */ return sprintf( __( 'Your site answered %d to Gorilla Cache\'s own requests, so a password or a firewall is turning them away. Pages are still cached as visitors arrive, and warming tries again every hour.', 'gorilla-cache' ), (int) $code ); } /** * Requests one address and returns how long it took, -1 on failure, or BLOCKED when the site refuses it. * * @param string $url Address. * @param bool $mobile Ask as a phone (for the separate mobile copy). * @param int $code Set to the HTTP status the site answered. * @return float Seconds, -1 or BLOCKED. */ private static function request( $url, $mobile, &$code = 0 ) { // Only this site's own pages: a plugin can point a post's link anywhere (another site, a server inside the // network), and warming must never send a request there. $host = strtolower( (string) wp_parse_url( (string) $url, PHP_URL_HOST ) ); if ( '' === $host || strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ) !== $host ) { return -1; } $start = microtime( true ); $response = wp_remote_get( $url, array( 'timeout' => 10, 'redirection' => 0, 'sslverify' => (bool) apply_filters( 'https_local_ssl_verify', false ), // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- core's own filter, read, not added. 'user-agent' => $mobile ? 'Mozilla/5.0 (iPhone; Mobile) Gorilla Cache preload' : 'Mozilla/5.0 Gorilla Cache preload', // The site's secret token: the engine then notes why a page it could not store was refused. 'headers' => array( 'Accept' => 'text/html', 'X-Gorilla-Cache-Warm' => (string) GorillaCache_Installer::state()['token'], ), ) ); $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ); if ( 401 === $code || 403 === $code ) { return self::BLOCKED; } if ( 0 === $code || $code >= 500 ) { return -1; } return microtime( true ) - $start; } /** * Visits one address as warming does (wp gorilla-cache explain, before it answers), so the page is stored, or * the engine notes why it is not. * * @param string $url Address on this site. */ public static function visit( $url ) { self::request( (string) $url, false ); } /** * What the last full warm-up found: pages visited and stored, and the most common reason pages were not. * * @return array{visited:int, stored:int, top:array{count:int, reason:string, detail:string, url:string}|null} */ public static function refusals() { $state = self::state(); $visited = (int) $state['stored']; $top = null; foreach ( (array) $state['refused'] as $entry ) { $visited += (int) $entry['count']; if ( null === $top || (int) $entry['count'] > (int) $top['count'] ) { $top = $entry; } } return array( 'visited' => $visited, 'stored' => (int) $state['stored'], 'top' => $top, ); } /** * Counts whether a visited address was stored, and if not, why (from the note the engine left). * * @param array $state Warming state, updated. * @param string $url Address just visited. */ private static function count_outcome( array &$state, $url ) { $outcome = GorillaCache_Explain::outcome( $url ); if ( $outcome['stored'] ) { ++$state['stored']; return; } if ( '' === $outcome['reason'] ) { return; // Nothing says why (the cache was cleared while the page was built): neither stored nor refused. } // One entry per cause: per cookie name, per status code, per reason otherwise. $key = $outcome['reason']; if ( 'set_cookie' === $key || 'status' === $key ) { $key .= ':' . ( 'status' === $key ? (string) (int) $outcome['detail'] : $outcome['detail'] ); } if ( ! isset( $state['refused'][ $key ] ) ) { if ( count( $state['refused'] ) >= 20 ) { return; } $state['refused'][ $key ] = array( 'count' => 0, 'reason' => $outcome['reason'], 'detail' => $outcome['detail'], 'url' => (string) $url, ); } ++$state['refused'][ $key ]['count']; } /** * Schedules the next run once. * * @param int $delay Seconds from now. */ private static function schedule( $delay ) { if ( ! wp_next_scheduled( self::HOOK ) ) { wp_schedule_single_event( time() + (int) $delay, self::HOOK ); } } }