array( 'type' => 'int', 'label' => __( 'Keep pages at the edge for (hours)', 'zonepilot' ), 'default' => 8, 'min' => 1, 'max' => 720, 'help' => __( 'Pages are purged on every change, so a long time is safe.', 'zonepilot' ), ), 'auto_purge' => array( 'type' => 'bool', 'label' => __( 'Purge changed URLs automatically', 'zonepilot' ), 'default' => true, ), 'extra_bypass' => array( 'type' => 'lines', 'label' => __( 'Never cache these paths (one per line)', 'zonepilot' ), 'default' => '', 'help' => __( 'Example: /members/', 'zonepilot' ), ), 'cache_404' => array( 'type' => 'bool', 'label' => __( 'Cache "not found" pages for 10 minutes', 'zonepilot' ), 'default' => true, ), ); } /** * Paths that are never cached. * * @param array $opts Options. * @return string[] */ private function bypass_paths( array $opts ) { $p = Site::path_prefix(); // Real paths of this install (WordPress in a subfolder, custom REST prefix), never assumed ones. $urls = array( admin_url(), wp_login_url(), site_url( 'xmlrpc.php' ), site_url( 'wp-cron.php' ), site_url( 'wp-comments-post.php' ), site_url( 'wp-signup.php' ), site_url( 'wp-activate.php' ) ); $rest = rest_url(); if ( false === strpos( (string) wp_parse_url( $rest, PHP_URL_QUERY ), 'rest_route=' ) ) { $urls[] = $rest; } $paths = array(); foreach ( $urls as $url ) { $path = Site::url_path( $url ); if ( '' !== $path ) { $paths[] = $path; } } if ( function_exists( 'wc_get_page_id' ) ) { foreach ( array( 'cart', 'checkout', 'myaccount' ) as $page ) { $id = wc_get_page_id( $page ); if ( $id > 0 ) { $path = (string) wp_parse_url( get_permalink( $id ), PHP_URL_PATH ); if ( '' !== $path && '/' !== $path ) { $paths[] = untrailingslashit( $path ); } } } } else { // Common shop paths, harmless when they do not exist. $paths[] = $p . '/cart'; $paths[] = $p . '/checkout'; $paths[] = $p . '/my-account'; } foreach ( array_filter( explode( "\n", (string) $opts['extra_bypass'] ) ) as $extra ) { $extra = '/' . ltrim( trim( $extra ), '/' ); if ( '/' !== $extra ) { $paths[] = untrailingslashit( $extra ); } } return array_values( array_unique( $paths ) ); } /** * Cookies that mean "personal page, do not cache". * * @return string[] */ public static function bypass_cookies() { return array( 'wordpress_logged_in_', 'wp-postpass_', 'comment_author_', 'woocommerce_items_in_cart', 'wp_woocommerce_session_', 'woocommerce_recently_viewed', 'edd_items_in_cart', 'autopilot_nocache' ); } /** * Build the cache rule. * * @param array $opts Options. * @return array */ public function rule( array $opts ) { $not = array(); foreach ( $this->bypass_paths( $opts ) as $path ) { $not[] = 'starts_with(http.request.uri.path, ' . Site::q( $path ) . ')'; } foreach ( array( 'add-to-cart=', 'wc-ajax=', 'preview=', 'nocache', 'customize_changeset', 'doing_wp_cron' ) as $q ) { $not[] = 'http.request.uri.query contains ' . Site::q( $q ); } foreach ( self::bypass_cookies() as $cookie ) { $not[] = 'http.cookie contains ' . Site::q( $cookie ); } return array( 'description' => Site::describe( 'page cache' ), 'expression' => Site::host_expr() . ' and not (' . implode( ' or ', $not ) . ')', 'action' => 'set_cache_settings', 'action_parameters' => array( 'cache' => true, 'edge_ttl' => array( 'mode' => 'respect_origin' ), 'browser_ttl' => array( 'mode' => 'respect_origin' ), ), ); } /** {@inheritDoc} */ public function preview( array $opts ) { $items = array(); $items[] = array( 'type' => $this->enabled() ? 'update' : 'create', 'text' => sprintf( /* translators: %s: host name */ __( 'Cloudflare Cache Rule "page cache" for %s: HTML becomes cacheable at the edge.', 'zonepilot' ), implode( ', ', Site::hosts() ) ), ); $items[] = array( 'type' => 'info', 'text' => sprintf( /* translators: %s: list of paths */ __( 'Never cached: %s, plus visitors with login, cart or comment cookies.', 'zonepilot' ), implode( ', ', $this->bypass_paths( $opts ) ) ), ); $items[] = array( 'type' => 'local', 'text' => sprintf( /* translators: %d: hours */ __( 'WordPress sends "Cache-Control: s-maxage" (%d h) on public pages; browsers always revalidate HTML.', 'zonepilot' ), (int) $opts['ttl_hours'] ), ); if ( ! empty( $opts['auto_purge'] ) ) { $items[] = array( 'type' => 'local', 'text' => __( 'Changed posts, pages, products, menus, comments and theme settings purge only the affected URLs on this host.', 'zonepilot' ), ); } $items[] = array( 'type' => 'info', 'text' => __( 'Nothing else in your zone changes. Undo removes the rule.', 'zonepilot' ), ); return $items; } /** {@inheritDoc} */ public function apply( array $opts ) { $res = ( new Rules() )->ensure( self::PHASE, 'page_cache', $this->rule( $opts ) ); if ( is_wp_error( $res ) ) { return $res; } $this->mark_applied( $opts, array( 'rule' => $res ) ); Store::log( $this->id(), __( 'Cache rule saved on Cloudflare.', 'zonepilot' ), 'ok' ); $this->purge_host(); return array( 'messages' => array( __( 'Edge caching is on. Checking it now...', 'zonepilot' ) ) ); } /** {@inheritDoc} */ public function rollback() { $res = ( new Rules() )->remove( self::PHASE, 'page_cache' ); if ( is_wp_error( $res ) ) { return $res; } $this->mark_off(); $this->purge_host(); Store::log( $this->id(), __( 'Cache rule removed, cached pages of this host purged.', 'zonepilot' ), 'ok' ); return array( 'messages' => array( __( 'Edge caching is off.', 'zonepilot' ) ) ); } /** {@inheritDoc} */ public function time_needed( $operation ) { // apply and verify request the home page a few times while the new rule spreads. return in_array( $operation, array( 'apply', 'verify' ), true ) ? 90 : 0; } /** {@inheritDoc} */ public function verify() { $checks = array(); $rule = ( new Rules() )->get( self::PHASE, 'page_cache' ); if ( is_wp_error( $rule ) ) { $checks[] = self::check( __( 'Cache rule on Cloudflare', 'zonepilot' ), null, $rule->get_error_message() ); } else { $checks[] = self::check( __( 'Cache rule on Cloudflare', 'zonepilot' ), $rule && ! empty( $rule['enabled'] ), $rule ? __( 'Active', 'zonepilot' ) : __( 'Missing', 'zonepilot' ) ); } $url = home_url( '/' ); $status = ''; for ( $i = 0; $i < 4; $i++ ) { $res = Http::get( $url ); $status = Http::cache_status( $res ); if ( 'HIT' === $status ) { break; } sleep( 2 ); } $checks[] = self::check( __( 'Home page served from the edge', 'zonepilot' ), 'HIT' === $status, /* translators: %s: cache status */ sprintf( __( 'cf-cache-status: %s', 'zonepilot' ), '' !== $status ? $status : __( 'none (not through Cloudflare?)', 'zonepilot' ) ) ); $login = Http::get( wp_login_url() ); $lstatus = Http::cache_status( $login ); $checks[] = self::check( __( 'Login page bypasses the cache', 'zonepilot' ), in_array( $lstatus, array( 'DYNAMIC', 'BYPASS', 'MISS', 'EXPIRED' ), true ) && 'HIT' !== $lstatus, /* translators: %s: cache status */ sprintf( __( 'cf-cache-status: %s', 'zonepilot' ), '' !== $lstatus ? $lstatus : '-' ) ); $cookie = Http::get( $url, array( 'headers' => array( 'Cookie' => 'wordpress_logged_in_probe=1' ) ) ); $cstatus = Http::cache_status( $cookie ); $checks[] = self::check( __( 'Logged-in visitors bypass the cache', 'zonepilot' ), 'HIT' !== $cstatus && '' !== $cstatus, /* translators: %s: cache status */ sprintf( __( 'cf-cache-status: %s', 'zonepilot' ), '' !== $cstatus ? $cstatus : '-' ) ); return $this->store_checks( $checks ); } /** {@inheritDoc} */ public function action( $action, array $args ) { if ( 'purge_all' === $action ) { $res = $this->purge_host(); if ( is_wp_error( $res ) ) { return $res; } return array( 'messages' => array( __( 'All cached pages of this site were purged.', 'zonepilot' ) ) ); } return parent::action( $action, $args ); } /* ---------------------------------------------------------------- Runtime */ /** {@inheritDoc} */ public function register() { if ( ! $this->enabled() ) { return; } add_action( 'template_redirect', array( $this, 'send_cache_headers' ), PHP_INT_MAX ); $opts = $this->options(); if ( empty( $opts['auto_purge'] ) ) { return; } add_action( 'transition_post_status', array( $this, 'on_post_status' ), 10, 3 ); add_action( 'save_post', array( $this, 'on_save_post' ), 20, 2 ); add_action( 'before_delete_post', array( $this, 'on_post_id' ) ); add_action( 'wp_trash_post', array( $this, 'on_post_id' ) ); add_action( 'edited_term', array( $this, 'on_term' ), 10, 3 ); add_action( 'delete_term', array( $this, 'on_term' ), 10, 3 ); add_action( 'wp_update_nav_menu', array( $this, 'queue_all' ) ); add_action( 'switch_theme', array( $this, 'queue_all' ) ); add_action( 'customize_save_after', array( $this, 'queue_all' ) ); add_action( 'update_option_sidebars_widgets', array( $this, 'queue_all' ) ); add_action( 'update_option_blogname', array( $this, 'queue_all' ) ); add_action( 'update_option_blogdescription', array( $this, 'queue_all' ) ); add_action( 'update_option_permalink_structure', array( $this, 'queue_all' ) ); add_action( 'wp_insert_comment', array( $this, 'on_comment' ), 10, 2 ); add_action( 'transition_comment_status', array( $this, 'on_comment_status' ), 10, 3 ); add_action( 'woocommerce_product_set_stock', array( $this, 'on_wc_product' ) ); add_action( 'woocommerce_variation_set_stock', array( $this, 'on_wc_product' ) ); add_action( 'woocommerce_update_product', array( $this, 'on_post_id' ) ); add_action( 'shutdown', array( $this, 'flush_queue' ), 5 ); } /** * Whether this front-end request may be cached at the edge. * * @return bool */ private function cacheable_request() { if ( is_admin() || is_user_logged_in() || wp_doing_ajax() || wp_doing_cron() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) { return false; } $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET'; if ( ! in_array( $method, array( 'GET', 'HEAD' ), true ) ) { return false; } if ( is_preview() || is_customize_preview() || is_search() || is_feed() || is_trackback() || is_robots() ) { return false; } if ( function_exists( 'is_cart' ) && ( is_cart() || is_checkout() || is_account_page() ) ) { return false; } if ( is_singular() && post_password_required() ) { return false; } if ( defined( 'DONOTCACHEPAGE' ) && DONOTCACHEPAGE ) { return false; } foreach ( array_keys( $_COOKIE ) as $name ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated foreach ( self::bypass_cookies() as $prefix ) { if ( 0 === strpos( (string) $name, $prefix ) ) { return false; } } } return true; } /** * Send edge cache headers for public pages. */ public function send_cache_headers() { if ( headers_sent() ) { return; } if ( ! $this->cacheable_request() ) { header( 'X-Autopilot-Cache: bypass' ); return; } foreach ( headers_list() as $line ) { if ( 0 === stripos( $line, 'Set-Cookie:' ) ) { header( 'X-Autopilot-Cache: bypass-cookie' ); return; } } $opts = $this->options(); $ttl = max( 1, (int) $opts['ttl_hours'] ) * HOUR_IN_SECONDS; if ( is_404() ) { if ( empty( $opts['cache_404'] ) ) { return; } $ttl = 10 * MINUTE_IN_SECONDS; } header( 'Cache-Control: public, max-age=0, s-maxage=' . (int) $ttl . ', stale-while-revalidate=60', true ); header( 'X-Autopilot-Cache: edge' ); } /* ---------------------------------------------------------------- Purge */ /** * Queue a URL. * * @param string $url URL. */ public function queue( $url ) { if ( is_string( $url ) && '' !== $url ) { $this->queue[ $url ] = true; } } /** * Queue a whole-site purge. */ public function queue_all() { $this->purge_all = true; } /** * Post status changes. * * @param string $new New status. * @param string $old Old status. * @param \WP_Post $post Post. */ public function on_post_status( $new, $old, $post ) { if ( 'publish' === $new || 'publish' === $old ) { $this->queue_post( $post ); } } /** * Post saved. * * @param int $post_id Post id. * @param \WP_Post $post Post. */ public function on_save_post( $post_id, $post ) { if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) { return; } if ( 'publish' === $post->post_status ) { $this->queue_post( $post ); } } /** * Post by id. * * @param int $post_id Post id. */ public function on_post_id( $post_id ) { $post = get_post( $post_id ); if ( $post && 'publish' === $post->post_status ) { $this->queue_post( $post ); } } /** * WooCommerce product object. * * @param \WC_Product $product Product. */ public function on_wc_product( $product ) { if ( is_object( $product ) && method_exists( $product, 'get_id' ) ) { $id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id(); $this->on_post_id( $id ); } } /** * Term edited. * * @param int $term_id Term id. * @param int $tt_id Term taxonomy id. * @param string $taxonomy Taxonomy. */ public function on_term( $term_id, $tt_id, $taxonomy ) { $link = get_term_link( (int) $term_id, $taxonomy ); if ( ! is_wp_error( $link ) ) { $this->queue( $link ); } $this->queue( home_url( '/' ) ); } /** * New comment. * * @param int $id Comment id. * @param \WP_Comment $comment Comment. */ public function on_comment( $id, $comment ) { if ( 1 === (int) $comment->comment_approved ) { $this->on_post_id( (int) $comment->comment_post_ID ); } } /** * Comment status change. * * @param string $new New. * @param string $old Old. * @param \WP_Comment $comment Comment. */ public function on_comment_status( $new, $old, $comment ) { $this->on_post_id( (int) $comment->comment_post_ID ); } /** * Queue all URLs that show a post. * * @param \WP_Post $post Post. */ public function queue_post( $post ) { if ( ! $post || ! is_post_type_viewable( $post->post_type ) ) { return; } $this->queue( get_permalink( $post ) ); $this->queue( home_url( '/' ) ); $this->queue( get_post_type_archive_link( $post->post_type ) ); $this->queue( get_author_posts_url( (int) $post->post_author ) ); $posts_page = (int) get_option( 'page_for_posts' ); if ( $posts_page ) { $this->queue( get_permalink( $posts_page ) ); } $this->queue( get_feed_link() ); foreach ( get_object_taxonomies( $post->post_type ) as $tax ) { if ( ! is_taxonomy_viewable( $tax ) ) { continue; } $terms = get_the_terms( $post, $tax ); if ( is_array( $terms ) ) { foreach ( $terms as $term ) { $link = get_term_link( $term ); if ( ! is_wp_error( $link ) ) { $this->queue( $link ); } } } } if ( function_exists( 'wc_get_page_id' ) && 'product' === $post->post_type ) { $shop = wc_get_page_id( 'shop' ); if ( $shop > 0 ) { $this->queue( get_permalink( $shop ) ); } } } /** * Send queued purges at the end of the request. */ public function flush_queue() { if ( ! $this->purge_all && ! $this->queue ) { return; } if ( function_exists( 'fastcgi_finish_request' ) && ! is_admin() ) { fastcgi_finish_request(); } if ( $this->purge_all ) { $this->purge_host(); } else { $this->purge_urls( array_keys( $this->queue ) ); } $this->queue = array(); $this->purge_all = false; } /** * Purge specific URLs (30 per call). * * @param string[] $urls URLs. * @return true|WP_Error */ public function purge_urls( array $urls ) { $hosts = Site::hosts(); $urls = array_values( array_filter( array_unique( $urls ), static function ( $url ) use ( $hosts ) { return in_array( strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) ), $hosts, true ); } ) ); $cf = Cloudflare::stored(); foreach ( array_chunk( $urls, 30 ) as $chunk ) { $res = $cf->purge( Site::zone_id(), array( 'files' => $chunk ) ); if ( is_wp_error( $res ) ) { Store::log( $this->id(), sprintf( /* translators: %s: error */ __( 'Purge failed: %s', 'zonepilot' ), $res->get_error_message() ), 'error' ); return $res; } } if ( $urls ) { Store::log( $this->id(), sprintf( /* translators: %d: number */ _n( 'Purged %d URL.', 'Purged %d URLs.', count( $urls ), 'zonepilot' ), count( $urls ) ) ); } return true; } /** * Purge everything cached for this site's host names (never the whole zone). * * @return true|WP_Error */ public function purge_host() { $res = Cloudflare::stored()->purge( Site::zone_id(), array( 'hosts' => Site::hosts() ) ); if ( is_wp_error( $res ) ) { Store::log( $this->id(), sprintf( /* translators: %s: error */ __( 'Purge by host name failed: %s', 'zonepilot' ), $res->get_error_message() ), 'warn' ); // Fallback: the most important URLs. return $this->purge_urls( array( home_url( '/' ), get_feed_link() ) ); } Store::log( $this->id(), __( 'Purged all cached pages of this host.', 'zonepilot' ) ); return true; } }