Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
24.84% covered (danger)
24.84%
76 / 306
26.47% covered (danger)
26.47%
9 / 34
CRAP
0.00% covered (danger)
0.00%
0 / 1
Boost_Cache
20.42% covered (danger)
20.42%
59 / 289
26.47% covered (danger)
26.47%
9 / 34
6097.84
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 init_actions
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 load_extra
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 serve
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 is_loaded
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_storage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 serve_cached
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
56
 send_header
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 ob_start
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 ob_callback
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
72
 rebuild_front_page
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 invalidate_on_comment_transition
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 rebuild_on_comment_edit
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 rebuild_on_comment_post
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 is_published
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 is_empty_global_styles
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 invalidate_on_post_transition
26.09% covered (danger)
26.09%
6 / 23
0.00% covered (danger)
0.00%
0 / 1
59.86
 rebuild_on_site_wide_post_delete
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 delete_on_post_trash
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 get_post_path_for_invalidation
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
56
 rebuild_post_terms_cache
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 rebuild_author_page
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 rebuild_all
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 delete_post_cache
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 rebuild_post_cache
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 rebuild_page
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 delete_page
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 rebuild_recursive
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 delete_recursive
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 invalidate_cache_success
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 ignore_get_parameters
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
42
 ignore_cookies
0.00% covered (danger)
0.00%
0 / 52
0.00% covered (danger)
0.00%
0 / 1
110
 disable_caching_on_error
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 init_do_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/*
3 * This file is loaded by advanced-cache.php, and so cannot rely on autoloading.
4 */
5
6namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress;
7
8use WP_Comment;
9use WP_Post;
10
11/*
12 * Require all pre-wordpress files here. These files aren't autoloaded as they are loaded before WordPress is fully initialized.
13 * pre-wordpress files assume all other pre-wordpress files are loaded here.
14 */
15require_once __DIR__ . '/path-actions/interface-path-action.php';
16require_once __DIR__ . '/path-actions/class-filter-older.php';
17require_once __DIR__ . '/path-actions/class-rebuild-file.php';
18require_once __DIR__ . '/path-actions/class-simple-delete.php';
19require_once __DIR__ . '/boost-cache-actions.php';
20require_once __DIR__ . '/class-boost-cache-error.php';
21require_once __DIR__ . '/class-boost-cache-settings.php';
22require_once __DIR__ . '/class-boost-cache-utils.php';
23require_once __DIR__ . '/class-filesystem-utils.php';
24require_once __DIR__ . '/class-logger.php';
25require_once __DIR__ . '/class-request.php';
26require_once __DIR__ . '/storage/interface-storage.php';
27require_once __DIR__ . '/storage/class-file-storage.php';
28
29// Define how many seconds the cache should last for each cached page.
30if ( ! defined( 'JETPACK_BOOST_CACHE_DURATION' ) ) {
31    define( 'JETPACK_BOOST_CACHE_DURATION', HOUR_IN_SECONDS );
32}
33
34// Define how many seconds the rebuild cache should be considered stale, but usable, for each cached page.
35if ( ! defined( 'JETPACK_BOOST_CACHE_REBUILD_DURATION' ) ) {
36    define( 'JETPACK_BOOST_CACHE_REBUILD_DURATION', 10 );
37}
38
39class Boost_Cache {
40    /**
41     * Post types whose changes can affect every page on the site.
42     */
43    const SITE_WIDE_POST_TYPES = array( 'wp_template', 'wp_template_part', 'wp_global_styles' );
44
45    /**
46     * @var Boost_Cache_Settings - The settings for the page cache.
47     */
48    private $settings;
49
50    /**
51     * @var Storage\Storage - The storage system used by Boost Cache.
52     */
53    private $storage;
54
55    /**
56     * @var Request - The request object that provides utility for the current request.
57     */
58    private $request = null;
59
60    /**
61     * @var bool - Indicates whether the cache engine has been loaded.
62     */
63    private static $cache_engine_loaded = false;
64
65    /**
66     * @var bool - Indicates whether WordPress initialized correctly and we can cache the page.
67     */
68    private $do_cache = false;
69
70    /**
71     * @var string - The ignored cookies that were removed from the cache parameters.
72     */
73    private $ignored_cookies = '';
74
75    /**
76     * @var string - The ignored GET parameters that were removed from the cache parameters.
77     */
78    private $ignored_get_parameters = '';
79
80    /**
81     * @param ?Storage\Storage $storage - Optionally provide a Storage subclass to handle actually storing and retrieving cached content. Defaults to a new instance of File_Storage.
82     */
83    public function __construct( $storage = null ) {
84        $this->settings = Boost_Cache_Settings::get_instance();
85        $home           = isset( $_SERVER['HTTP_HOST'] ) ? strtolower( $_SERVER['HTTP_HOST'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
86        $this->storage  = $storage ?? new Storage\File_Storage( $home );
87        $this->request  = Request::current();
88    }
89
90    /**
91     * Initialize the actions for the cache.
92     */
93    public function init_actions() {
94        add_action( 'transition_post_status', array( $this, 'invalidate_on_post_transition' ), 10, 3 );
95        add_action( 'transition_comment_status', array( $this, 'invalidate_on_comment_transition' ), 10, 3 );
96        add_action( 'comment_post', array( $this, 'rebuild_on_comment_post' ), 10, 3 );
97        add_action( 'edit_comment', array( $this, 'rebuild_on_comment_edit' ), 10, 2 );
98        add_action( 'switch_theme', array( $this, 'rebuild_all' ) );
99        add_action( 'wp_trash_post', array( $this, 'delete_on_post_trash' ), 10, 2 );
100        add_action( 'deleted_post', array( $this, 'rebuild_on_site_wide_post_delete' ), 10, 2 );
101        add_filter( 'wp_php_error_message', array( $this, 'disable_caching_on_error' ) );
102        add_filter( 'init', array( $this, 'init_do_cache' ) );
103        add_filter( 'jetpack_boost_cache_parameters', array( $this, 'ignore_cookies' ) );
104        add_filter( 'jetpack_boost_cache_parameters', array( $this, 'ignore_get_parameters' ) );
105        $this->load_extra();
106    }
107
108    private function load_extra() {
109        if ( file_exists( WP_CONTENT_DIR . '/boost-cache-extra.php' ) ) {
110            include_once WP_CONTENT_DIR . '/boost-cache-extra.php';
111        }
112    }
113
114    /**
115     * Serve the cached page if it exists, otherwise start output buffering.
116     */
117    public function serve() {
118        if ( ! $this->settings->get_enabled() ) {
119            return;
120        }
121
122        // Indicate that the cache engine has been loaded.
123        self::$cache_engine_loaded = true;
124
125        if ( ! $this->request->is_cacheable() ) {
126            return;
127        }
128
129        if ( ! $this->serve_cached() ) {
130            $this->ob_start();
131        }
132    }
133
134    /**
135     * Check if the cache engine has been loaded.
136     *
137     * @return bool - True if the cache engine has been loaded, false otherwise.
138     */
139    public static function is_loaded() {
140        return self::$cache_engine_loaded;
141    }
142
143    /**
144     * Get the storage instance used by Boost Cache.
145     *
146     * @return Storage\Storage
147     */
148    public function get_storage() {
149        return $this->storage;
150    }
151
152    /**
153     * Serve cached content, if any is available for the current request. Will terminate if it does so.
154     * Otherwise, returns false.
155     */
156    public function serve_cached() {
157        if ( ! $this->request->is_cacheable() ) {
158            return false;
159        }
160
161        // check if rebuild file exists and rename it to the correct file
162        $rebuild_found = $this->storage->reset_rebuild_file( $this->request->get_uri(), $this->request->get_parameters() );
163        if ( $rebuild_found ) {
164            Logger::debug( 'Rebuild file found. Will be used for cache until new file created.' );
165            $cached = false;
166        } else {
167            $cached = $this->storage->read( $this->request->get_uri(), $this->request->get_parameters() );
168        }
169
170        if ( is_string( $cached ) ) {
171            $this->send_header( 'X-Jetpack-Boost-Cache: hit' );
172            $ignored_cookies_message = $this->ignored_cookies === '' ? '' : " and ignored cookies: {$this->ignored_cookies}";
173            $ignored_get_message     = $this->ignored_get_parameters === '' ? '' : " and ignored GET parameters: {$this->ignored_get_parameters}";
174            Logger::debug( 'Serving cached page' . $ignored_cookies_message . $ignored_get_message );
175            echo $cached; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
176            die( 0 );
177        }
178
179        $cache_status = $rebuild_found ? 'rebuild' : 'miss';
180        $this->send_header( 'X-Jetpack-Boost-Cache: ' . $cache_status );
181
182        return false;
183    }
184
185    private function send_header( $header ) {
186        if ( ! headers_sent() ) {
187            header( $header );
188        }
189    }
190
191    /**
192     * Starts output buffering and sets the callback to save the cache file.
193     *
194     * @return bool - false if page is not cacheable.
195     */
196    public function ob_start() {
197        if ( ! $this->request->is_cacheable() ) {
198            return false;
199        }
200
201        ob_start( array( $this, 'ob_callback' ) );
202        return true;
203    }
204
205    /**
206     * Callback function from output buffer. This function saves the output
207     * buffer to a cache file and then returns the buffer so PHP will send it
208     * to the browser.
209     *
210     * @param string $buffer - The output buffer to save to the cache file.
211     * @return string - The output buffer.
212     */
213    public function ob_callback( $buffer ) {
214        if ( strlen( $buffer ) > 0 && $this->request->is_cacheable() ) {
215
216            // Do not cache the page as WordPress did not initialize correctly.
217            if ( ! $this->do_cache ) {
218                Logger::debug( 'Page exited early. Do not cache.' );
219                return $buffer;
220            }
221
222            if ( false === stripos( $buffer, '</html>' ) ) {
223                Logger::debug( 'Closing HTML tag not found, not caching' );
224                return $buffer;
225            }
226
227            $result = $this->storage->write( $this->request->get_uri(), $this->request->get_parameters(), $buffer );
228
229            if ( $result instanceof Boost_Cache_Error ) {
230                Logger::debug( 'Error writing cache file: ' . $result->get_error_message() );
231            } else {
232                $ignored_cookies_message = $this->ignored_cookies === '' ? '' : " and ignored cookies: {$this->ignored_cookies}";
233                $ignored_get_message     = $this->ignored_get_parameters === '' ? '' : " and ignored GET parameters: {$this->ignored_get_parameters}";
234                Logger::debug( 'Cache file created' . $ignored_cookies_message . $ignored_get_message );
235            }
236        }
237
238        return $buffer;
239    }
240
241    /**
242     * Delete/rebuild the cache for the front page and paged archives.
243     * This is called when a post is edited, deleted, or published.
244     */
245    public function rebuild_front_page() {
246        if ( get_option( 'show_on_front' ) === 'page' ) {
247            $this->rebuild_page( home_url() );
248            $posts_page_id = get_option( 'page_for_posts' ); // posts page
249            if ( $posts_page_id ) {
250                Logger::debug( 'rebuild_front_page: deleting posts page cache' );
251                $this->rebuild_post_cache( get_post( $posts_page_id ) );
252            }
253        } else {
254            $this->rebuild_page( home_url() );
255            $home_path = parse_url( home_url(), PHP_URL_PATH ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url
256            Logger::debug( 'delete front page cache ' . Boost_Cache_Utils::normalize_request_uri( $home_path ? $home_path : '/' ) );
257        }
258    }
259
260    /**
261     * Rebuild the cache for the post if the comment transitioned from one state to another.
262     *
263     * @param string     $new_status - The new status of the comment.
264     * @param string     $old_status - The old status of the comment.
265     * @param WP_Comment $comment - The comment that transitioned.
266     */
267    public function invalidate_on_comment_transition( $new_status, $old_status, $comment ) {
268        if ( $new_status === $old_status ) {
269            return;
270        }
271        Logger::debug( "invalidate_on_comment_transition: $new_status, $old_status" );
272
273        if ( $new_status !== 'approved' && $old_status !== 'approved' ) {
274            Logger::debug( 'invalidate_on_comment_transition: comment not approved' );
275            return;
276        }
277
278        $post = get_post( (int) $comment->comment_post_ID );
279        $this->rebuild_post_cache( $post );
280    }
281
282    /**
283     * After editing a comment, rebuild the cache for the post if the comment is approved.
284     * If changing state and editing, both actions will be called, but the cache will only be rebuilt once.
285     *
286     * @param int   $comment_id - The id of the comment.
287     * @param array $commentdata - The comment data.
288     */
289    public function rebuild_on_comment_edit( $comment_id, $commentdata ) {
290        $post = get_post( $commentdata['comment_post_ID'] );
291
292        if ( (int) $commentdata['comment_approved'] === 1 ) {
293            $this->rebuild_post_cache( $post );
294        }
295    }
296
297    /**
298     * After a comment is posted, rebuild the cache for the post if the comment is approved.
299     * If the comment is not approved, only rebuild the cache for this post for this visitor.
300     *
301     * @param int   $comment_id - The id of the comment.
302     * @param int   $comment_approved - The approval status of the comment.
303     * @param array $commentdata - The comment data.
304     */
305    public function rebuild_on_comment_post( $comment_id, $comment_approved, $commentdata ) {
306        $post = get_post( $commentdata['comment_post_ID'] );
307        Logger::debug( "rebuild_on_comment_post: $comment_id, $comment_approved, {$post->ID}" );
308        /**
309         * If a comment is not approved, we only need to delete the cache for
310         * this post for this visitor so the unmoderated comment is shown to them.
311         */
312        if ( $comment_approved !== 1 ) {
313            $parameters = $this->request->get_parameters();
314
315            /*
316             * If there are no cookies, then visitor did not click "remember me".
317             * They'll be redirected to a page with a hash in the URL for the
318             * moderation message.
319             * Only delete the cache for visitors who clicked "remember me".
320             */
321            if ( isset( $parameters['cookies'] ) && ! empty( $parameters['cookies'] ) ) {
322                $this->delete_page( get_permalink( $post->ID ), $parameters );
323            }
324            return;
325        }
326
327        $this->rebuild_post_cache( $post );
328    }
329
330    /**
331     * Returns true if the post is published or private.
332     *
333     * @param string $status - The status of the post.
334     * @return bool
335     */
336    private function is_published( $status ) {
337        return $status === 'publish' || $status === 'private';
338    }
339
340    /**
341     * Whether a Global Styles post holds only the keys core writes into an empty one.
342     *
343     * @param WP_Post $post - The Global Styles post.
344     * @return bool
345     */
346    private function is_empty_global_styles( $post ) {
347        $styles = json_decode( $post->post_content, true );
348
349        return is_array( $styles ) && array() === array_diff_key(
350            $styles,
351            array(
352                'version'                     => true,
353                'isGlobalStylesUserThemeJSON' => true,
354            )
355        );
356    }
357
358    /**
359     * Delete the cached post if it transitioned from one state to another.
360     *
361     * @param string  $new_status - The new status of the post.
362     * @param string  $old_status - The old status of the post.
363     * @param WP_Post $post - The post that transitioned.
364     */
365    public function invalidate_on_post_transition( $new_status, $old_status, $post ) {
366        // Special case: Delete cache if the post type can effect the whole site.
367        if ( in_array( $post->post_type, self::SITE_WIDE_POST_TYPES, true ) ) {
368            // Core inserts an empty Global Styles post the first time the editor loads for a theme.
369            if ( 'wp_global_styles' === $post->post_type && 'new' === $old_status && $this->is_empty_global_styles( $post ) ) {
370                return;
371            }
372
373            Logger::debug( 'invalidate_on_post_transition: special post type ' . $post->post_type );
374            $this->rebuild_all();
375            return;
376        }
377
378        if ( ! Boost_Cache_Utils::is_visible_post_type( $post ) ) {
379            return;
380        }
381
382        if ( $new_status === 'trash' ) {
383            return;
384        }
385
386        Logger::debug( "invalidate_on_post_transition: $new_status, $old_status, {$post->ID}" );
387
388        // Don't delete the cache for posts that weren't published and aren't published now
389        if ( ! $this->is_published( $new_status ) && ! $this->is_published( $old_status ) ) {
390            Logger::debug( 'invalidate_on_post_transition: not published' );
391            return;
392        }
393
394        // delete the cache files entirely if the post was unpublished
395        if ( 'publish' === $old_status && 'publish' !== $new_status ) {
396            Logger::debug( 'invalidate_on_post_transition: delete cache on new private page' );
397            $this->delete_on_post_trash( $post->ID, $old_status );
398            return;
399        }
400        Logger::debug( "invalidate_on_post_transition: rebuilding post {$post->ID}" );
401
402        $this->rebuild_post_cache( $post );
403        $this->rebuild_post_terms_cache( $post );
404        $this->rebuild_front_page();
405        $this->rebuild_author_page( (int) $post->post_author );
406    }
407
408    /**
409     * Rebuild the whole cache when a site-wide post is deleted, which skips transition_post_status.
410     *
411     * @param int     $post_id - The id of the deleted post.
412     * @param WP_Post $post - The deleted post.
413     */
414    public function rebuild_on_site_wide_post_delete( $post_id, $post ) {
415        if ( in_array( $post->post_type, self::SITE_WIDE_POST_TYPES, true ) ) {
416            $this->rebuild_all();
417        }
418    }
419
420    /**
421     * Delete the cache for the post if it was trashed.
422     *
423     * @param int    $post_id - The id of the post.
424     * @param string $old_status - The old status of the post.
425     */
426    public function delete_on_post_trash( $post_id, $old_status ) {
427        if ( $this->is_published( $old_status ) ) {
428            $post      = get_post( $post_id );
429            $post_path = $this->get_post_path_for_invalidation( $post );
430            if ( $post_path ) {
431                $this->delete_recursive( $post_path );
432            }
433            $this->rebuild_post_terms_cache( $post );
434            $this->rebuild_front_page();
435            $this->rebuild_author_page( (int) $post->post_author );
436        }
437    }
438
439    private function get_post_path_for_invalidation( $post ) {
440        static $already_deleted = -1;
441        if ( $already_deleted === $post->ID ) {
442            return null;
443        }
444
445        /**
446         * Don't invalidate the cache for post types that are not public.
447         */
448        if ( ! Boost_Cache_Utils::is_visible_post_type( $post ) ) {
449            return null;
450        }
451
452        $already_deleted = $post->ID;
453
454        /**
455         * If a post is unpublished, the permalink will be deleted. In that case,
456         * get_sample_permalink() will return a permalink with ?p=123 instead of
457         * the post name. We need to get the post name from the post object.
458         */
459        $permalink = get_permalink( $post->ID );
460        if ( strpos( $permalink, '?p=' ) !== false || strpos( $permalink, '?page_id=' ) !== false ) {
461            if ( $post->post_type === 'page' ) {
462                $permalink = get_page_link( $post->ID, false, true );
463            } else {
464                if ( ! function_exists( 'get_sample_permalink' ) ) {
465                    require_once ABSPATH . 'wp-admin/includes/post.php';
466                }
467                list( $permalink, $post_name ) = get_sample_permalink( $post->ID );
468                $permalink                     = str_replace( '%postname%', $post_name, $permalink );
469            }
470        }
471        return $permalink;
472    }
473
474    /**
475     * Delete the cache for terms associated with this post.
476     *
477     * @param WP_Post $post - The post to delete the cache for.
478     */
479    public function rebuild_post_terms_cache( $post ) {
480        $categories = get_the_category( $post->ID );
481        if ( is_array( $categories ) ) {
482            foreach ( $categories as $category ) {
483                $link = trailingslashit( get_category_link( $category->term_id ) );
484                $this->rebuild_recursive( $link );
485            }
486        }
487
488        $tags = get_the_tags( $post->ID );
489        if ( is_array( $tags ) ) {
490            foreach ( $tags as $tag ) {
491                $link = trailingslashit( get_tag_link( $tag->term_id ) );
492                $this->rebuild_recursive( $link );
493            }
494        }
495    }
496
497    /**
498     * Delete the entire cache for the author's archive page.
499     *
500     * @param int $author_id - The id of the author.
501     */
502    public function rebuild_author_page( $author_id ) {
503        $author = get_userdata( $author_id );
504        if ( ! $author ) {
505            return;
506        }
507
508        $author_link = get_author_posts_url( $author_id, $author->user_nicename );
509        $this->rebuild_recursive( $author_link );
510    }
511
512    /**
513     * Rebuild the entire cache.
514     */
515    public function rebuild_all() {
516        $this->rebuild_recursive( home_url() );
517    }
518
519    public function delete_post_cache( $post ) {
520        $post_path = $this->get_post_path_for_invalidation( $post );
521        if ( null === $post_path ) {
522            return;
523        }
524
525        if ( Boost_Cache_Utils::trailingslashit( $post_path ) !== Boost_Cache_Utils::trailingslashit( home_url() ) ) {
526            $this->delete_recursive( $post_path );
527        } else {
528            $this->delete_page( $post_path );
529        }
530    }
531
532    public function rebuild_post_cache( $post ) {
533        $post_path = $this->get_post_path_for_invalidation( $post );
534        if ( null === $post_path ) {
535            return;
536        }
537
538        if ( Boost_Cache_Utils::trailingslashit( $post_path ) !== Boost_Cache_Utils::trailingslashit( home_url() ) ) {
539            $this->rebuild_recursive( $post_path );
540        } else {
541            $this->rebuild_page( $post_path );
542        }
543    }
544
545    public function rebuild_page( $path, $parameters = false ) {
546        $this->storage->clear(
547            $path,
548            array(
549                'rebuild'    => true,
550                'parameters' => $parameters,
551            )
552        );
553        $this->invalidate_cache_success( $path, 'rebuild', 'page' );
554    }
555
556    public function delete_page( $path, $parameters = false ) {
557        $this->storage->clear(
558            $path,
559            array(
560                'rebuild'    => false,
561                'parameters' => $parameters,
562            )
563        );
564        $this->invalidate_cache_success( $path, 'delete', 'page' );
565    }
566
567    public function rebuild_recursive( $path ) {
568        $this->storage->clear(
569            $path,
570            array(
571                'rebuild'   => true,
572                'recursive' => true,
573            )
574        );
575        $this->invalidate_cache_success( $path, 'rebuild', 'recursive' );
576    }
577
578    public function delete_recursive( $path ) {
579        $this->storage->clear(
580            $path,
581            array(
582                'rebuild'   => false,
583                'recursive' => true,
584            )
585        );
586        $this->invalidate_cache_success( $path, 'delete', 'recursive' );
587    }
588
589    private function invalidate_cache_success( $path, $type, $scope ) {
590        do_action( 'jetpack_boost_invalidate_cache_success', $path, $type, $scope );
591    }
592
593    /**
594     * Ignore certain GET parameters in the cache parameters so cached pages can be served to these visitors.
595     *
596     * @param array $parameters - The parameters with the GET array to filter.
597     * @return array - The parameters with GET parameters removed.
598     */
599    public function ignore_get_parameters( $parameters ) {
600        static $params = false;
601
602        // Only run this once as it may be called multiple times on uncached pages.
603        if ( $params ) {
604            return $params;
605        }
606
607        /**
608         * Filters the GET parameters so cached pages can be served to these visitors.
609         * The list is an array of regex patterns. The default list contains the
610         * most common GET parameters used by analytics services.
611         *
612         * @since 3.8.0
613         *
614         * @param array $get_parameters An array of regexes to remove items from the GET parameter list.
615         */
616        $get_parameters = apply_filters(
617            'jetpack_boost_ignore_get_parameters',
618            array( 'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'ysclid', 'srsltid', 'yclid' )
619        );
620
621        $get_parameters = array_unique(
622            array_map(
623                'trim',
624                $get_parameters
625            )
626        );
627
628        foreach ( $get_parameters as $get_parameter ) {
629            foreach ( array_keys( $parameters['get'] ) as $get_parameter_name ) {
630                if ( preg_match( '/^' . $get_parameter . '$/', $get_parameter_name ) ) {
631                    unset( $parameters['get'][ $get_parameter_name ] );
632                    $this->ignored_get_parameters .= $get_parameter_name . ',';
633                }
634            }
635        }
636        if ( $this->ignored_get_parameters !== '' ) {
637            $this->ignored_get_parameters = rtrim( $this->ignored_get_parameters, ',' );
638        }
639
640        $params = $parameters;
641
642        return $parameters;
643    }
644
645    /**
646     * Ignore certain cookies in the cache parameters so cached pages can be served to these visitors.
647     *
648     * @param array $parameters - The parameters with the cookies array to filter.
649     * @return array - The parameters with cookies removed.
650     */
651    public function ignore_cookies( $parameters ) {
652        static $params = false;
653
654        // Only run this once as it may be called multiple times on uncached pages.
655        if ( $params ) {
656            return $params;
657        }
658
659        $default_cookies = array(
660            'cf_clearance',
661            'cf_chl_rc_i',
662            'cf_chl_rc_ni',
663            'cf_chl_rc_m',
664            '_cfuvid',
665            '__cfruid',
666            '__cfwaitingroom',
667            'cf_ob_info',
668            'cf_use_ob',
669            '__cfseq',
670            '__cf_bm',
671            '__cflb',
672
673            // Sourcebuster
674            'sbjs_(.*)',
675
676            // Google Analytics
677            '_ga(?:_[A-Z0-9]*)?',
678
679            // AWS Load Balancer
680            'AWSELB',
681            'AWSELBCORS',
682            'AWSALB',
683            'AWSALBCORS',
684        );
685        $jetpack_cookies = array( 'tk_ai', 'tk_qs' );
686        $cookies         = array_merge( $default_cookies, $jetpack_cookies );
687
688        /**
689         * Filters the browser cookies so cached pages can be served to these visitors.
690         * The list is an array of regex patterns. The default list contains the
691         * cookies used by Cloudflare, and the regex pattern for the sbjs_ cookies
692         * used by sourcebuster.js
693         *
694         * @since 3.8.0
695         *
696         * @param array $cookies An array of regexes to remove items from the cookie list.
697         */
698        $cookies = apply_filters(
699            'jetpack_boost_ignore_cookies',
700            $cookies
701        );
702
703        $cookies = array_unique(
704            array_map(
705                'trim',
706                $cookies
707            )
708        );
709
710        /**
711         * The Jetpack Cookie Banner plugin sets a cookie to indicate that the
712         * user has accepted the cookie policy.
713         * The value of the cookie is the expiry date of the cookie, which means
714         * that everyone who has accepted the cookie policy will use a different
715         * cache file.
716         * Set it to 1 here so those visitors will use the same cache file.
717         */
718        if ( isset( $parameters['cookies']['eucookielaw'] ) ) {
719            $parameters['cookies']['eucookielaw'] = 1;
720        }
721
722        /**
723         * This is for the personalized ads consent cookie.
724         */
725        if ( isset( $parameters['cookies']['personalized-ads-consent'] ) ) {
726            $parameters['cookies']['personalized-ads-consent'] = 1;
727        }
728
729        $cookie_keys = array();
730        if ( isset( $parameters['cookies'] ) && is_array( $parameters['cookies'] ) ) {
731            $cookie_keys = array_keys( $parameters['cookies'] );
732        } else {
733            return $parameters;
734        }
735
736        foreach ( $cookies as $cookie ) {
737            foreach ( $cookie_keys as $cookie_name ) {
738                if ( preg_match( '/^' . $cookie . '$/', $cookie_name ) ) {
739                    unset( $parameters['cookies'][ $cookie_name ] );
740                    $this->ignored_cookies .= $cookie_name . ',';
741                }
742            }
743        }
744        if ( $this->ignored_cookies !== '' ) {
745            $this->ignored_cookies = rtrim( $this->ignored_cookies, ',' );
746        }
747
748        $params = $parameters;
749
750        return $parameters;
751    }
752
753    public function disable_caching_on_error( $message ) {
754        if ( ! defined( 'DONOTCACHEPAGE' ) ) {
755            define( 'DONOTCACHEPAGE', true );
756        }
757        Logger::debug( 'Fatal error detected, caching disabled' );
758        return $message;
759    }
760
761    /**
762     * This function is called after WordPress is loaded, on "init".
763     * It is used to indicate that it is safe to cache and that no
764     * fatal errors occurred.
765     */
766    public function init_do_cache() {
767        $this->do_cache = true;
768    }
769}