Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.72% covered (warning)
74.72%
133 / 178
42.11% covered (danger)
42.11%
8 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Boost
74.72% covered (warning)
74.72%
133 / 178
42.11% covered (danger)
42.11%
8 / 19
77.72
0.00% covered (danger)
0.00%
0 / 1
 __construct
93.10% covered (success)
93.10%
27 / 29
0.00% covered (danger)
0.00%
0 / 1
3.00
 register_deactivation_hook
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 schedule_version_change
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
4.12
 handle_version_change
85.71% covered (warning)
85.71%
24 / 28
0.00% covered (danger)
0.00%
0 / 1
9.24
 setup_cron_schedules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 custom_cron_intervals
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 whitelist_query_args
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 activate
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
10.01
 deactivate
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 cleanup_image_size_analysis_data
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 init_admin
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 init_jetpack_config
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
2
 maybe_sync_module_status
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 sync_module_status
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init_textdomain
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_plugin_name
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_version
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handle_environment_change
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 uninstall
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * The file that defines the core plugin class
4 *
5 * A class definition that includes attributes and functions used across both the
6 * public-facing side of the site and the admin area.
7 *
8 * @link       https://automattic.com
9 * @since      1.0.0
10 * @package    automattic/jetpack-boost
11 */
12
13namespace Automattic\Jetpack_Boost;
14
15use Automattic\Jetpack\Activity_Log\Jetpack_Activity_Log;
16use Automattic\Jetpack\Boost_Core\Lib\Transient;
17use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
18use Automattic\Jetpack\Config as Jetpack_Config;
19use Automattic\Jetpack\Image_CDN\Image_CDN_Core;
20use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
21use Automattic\Jetpack\Plugin_Deactivation\Deactivation_Handler;
22use Automattic\Jetpack_Boost\Admin\Admin;
23use Automattic\Jetpack_Boost\Admin\Regenerate_Admin_Notice;
24use Automattic\Jetpack_Boost\Contracts\Sub_Feature;
25use Automattic\Jetpack_Boost\Data_Sync\Getting_Started_Entry;
26use Automattic\Jetpack_Boost\Lib\Analytics;
27use Automattic\Jetpack_Boost\Lib\Cleanup_Transients;
28use Automattic\Jetpack_Boost\Lib\CLI;
29use Automattic\Jetpack_Boost\Lib\Connection;
30use Automattic\Jetpack_Boost\Lib\Cornerstone\Cornerstone_Pages;
31use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State;
32use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage;
33use Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator;
34use Automattic\Jetpack_Boost\Lib\Setup;
35use Automattic\Jetpack_Boost\Lib\Site_Health;
36use Automattic\Jetpack_Boost\Lib\Status;
37use Automattic\Jetpack_Boost\Lib\Super_Cache_Tracking;
38use Automattic\Jetpack_Boost\Modules\Module;
39use Automattic\Jetpack_Boost\Modules\Modules_Setup;
40use Automattic\Jetpack_Boost\Modules\Optimizations\Lcp\LCP_State;
41use Automattic\Jetpack_Boost\Modules\Optimizations\Lcp\LCP_Storage;
42use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Cache_Preload;
43use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Page_Cache;
44use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Page_Cache_Setup;
45use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache;
46use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings;
47use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Storage\File_Storage;
48use Automattic\Jetpack_Boost\REST_API\Endpoints\List_Cornerstone_Pages;
49use Automattic\Jetpack_Boost\REST_API\Endpoints\List_LCP_Analysis;
50use Automattic\Jetpack_Boost\REST_API\Endpoints\List_Site_Urls;
51use Automattic\Jetpack_Boost\REST_API\Endpoints\List_Source_Providers;
52use Automattic\Jetpack_Boost\REST_API\REST_API;
53
54/**
55 * The core plugin class.
56 *
57 * This is used to define internationalization, admin-specific hooks, and
58 * public-facing site hooks.
59 *
60 * Also maintains the unique identifier of this plugin as well as the current
61 * version of the plugin.
62 *
63 * @since      1.0.0
64 * @author     Automattic <support@jetpack.com>
65 *
66 * @phan-constructor-used-for-side-effects
67 */
68class Jetpack_Boost {
69
70    /**
71     * The unique identifier of this plugin.
72     *
73     * @since    1.0.0
74     * @var string The string used to uniquely identify this plugin.
75     */
76    private $plugin_name;
77
78    /**
79     * The current version of the plugin.
80     *
81     * @since    1.0.0
82     * @var string The current version of the plugin.
83     */
84    private $version;
85
86    /**
87     * The Jetpack Boost Connection manager instance.
88     *
89     * @since    1.0.0
90     * @access   public
91     * @var Connection The Jetpack Boost Connection manager instance.
92     */
93    public $connection;
94
95    /**
96     * Define the core functionality of the plugin.
97     *
98     * Set the plugin name and the plugin version that can be used throughout the plugin.
99     * Load the dependencies, define the locale, and set the hooks for the admin area and
100     * the public-facing side of the site.
101     *
102     * @since    1.0.0
103     */
104    public function __construct() {
105        $this->version     = JETPACK_BOOST_VERSION;
106        $this->plugin_name = 'jetpack-boost';
107
108        $this->connection = new Connection();
109        $this->connection->init();
110
111        $this->register_deactivation_hook();
112
113        if ( defined( 'WP_CLI' ) && WP_CLI ) {
114            $cli_instance = new CLI( $this );
115            \WP_CLI::add_command( 'jetpack-boost', $cli_instance );
116        }
117
118        $modules_setup = new Modules_Setup();
119        Setup::add( $modules_setup );
120
121        $cornerstone_pages = new Cornerstone_Pages();
122        Setup::add( $cornerstone_pages );
123
124        // Initialize Jetpack packages (connection, sync, identity crisis).
125        $this->init_jetpack_config();
126
127        // Initialize the Admin experience.
128        $this->init_admin( $modules_setup );
129
130        add_action( 'admin_init', array( $this, 'schedule_version_change' ) );
131
132        add_action( 'init', array( $this, 'init_textdomain' ) );
133        add_action( 'init', array( $this, 'setup_cron_schedules' ) );
134
135        add_action( 'jetpack_boost_environment_changed', array( $this, 'handle_environment_change' ), 10, 2 );
136
137        add_action( 'jetpack_boost_handle_version_change_cron', array( $this, 'handle_version_change' ) );
138
139        add_action( 'jetpack_boost_general_cleanup', array( Cleanup_Transients::class, 'run_cleanup' ) );
140        add_action( Cleanup_Transients::FOLLOWUP_HOOK, array( Cleanup_Transients::class, 'run_cleanup' ) );
141
142        // Fired when plugin ready.
143        do_action( 'jetpack_boost_loaded', $this );
144
145        My_Jetpack_Initializer::init();
146
147        // Activity Log. No-ops while the `activity-log` module is off.
148        Jetpack_Activity_Log::initialize();
149
150        Deactivation_Handler::init( $this->plugin_name, __DIR__ . '/admin/deactivation-dialog.php' );
151
152        // Register the core Image CDN hooks.
153        Image_CDN_Core::setup();
154
155        // Setup Site Health panel functionality.
156        Site_Health::init();
157
158        Super_Cache_Tracking::setup();
159
160        // Boost abilities (WP Abilities API). Gated by `jetpack_wp_abilities_enabled`;
161        // priority 20 leaves room for default-priority filter registrations to land first.
162        add_action( 'plugins_loaded', array( '\Automattic\Jetpack_Boost\Abilities\Boost_Abilities', 'init' ), 20 );
163    }
164
165    /**
166     * Register deactivation hook.
167     */
168    private function register_deactivation_hook() {
169        $plugin_file = trailingslashit( dirname( __DIR__ ) ) . 'jetpack-boost.php';
170        register_deactivation_hook( $plugin_file, array( $this, 'deactivate' ) );
171    }
172
173    public function schedule_version_change() {
174        $version = get_option( 'jetpack_boost_version' );
175
176        if ( $version === JETPACK_BOOST_VERSION ) {
177            return;
178        }
179        update_option( 'jetpack_boost_version', JETPACK_BOOST_VERSION );
180
181        // Schedule the cron event to handle the version change. This ensures the previous version's handle is always flushed.
182        if ( ! wp_next_scheduled( 'jetpack_boost_handle_version_change_cron' ) ) {
183            wp_schedule_single_event( time() + 2, 'jetpack_boost_handle_version_change_cron' );
184        }
185    }
186
187    public function handle_version_change() {
188        // Remove this option to prevent the notice from showing up.
189        delete_site_option( 'jetpack_boost_static_minification' );
190
191        jetpack_boost_minify_empty_caches_for_rules();
192
193        // Add upgrade check for Cornerstone Pages.
194        $pages = jetpack_boost_ds_get( 'cornerstone_pages_list' );
195        if ( is_array( $pages ) && in_array( home_url( '' ), $pages, true ) ) {
196            // Remove homepage (empty string) from the cornerstone pages list.
197            $pages = array_filter(
198                $pages,
199                function ( $page ) {
200                    return $page !== home_url( '' );
201                }
202            );
203            jetpack_boost_ds_set( 'cornerstone_pages_list', $pages );
204        }
205
206        if ( jetpack_boost_minify_is_enabled() ) {
207            // We need to clear Minify scheduled events to ensure the latest scheduled jobs are only scheduled irrespective of scheduled arguments.
208            jetpack_boost_minify_clear_scheduled_events();
209            jetpack_boost_minify_activation();
210        }
211
212        if ( ! get_option( 'jetpack_boost_page_cache_uri_keys' ) ) {
213            $home_url  = home_url();
214            $home_host = wp_parse_url( $home_url, PHP_URL_HOST );
215            if ( is_string( $home_host ) ) {
216                $home_port = wp_parse_url( $home_url, PHP_URL_PORT );
217                if ( is_int( $home_port ) ) {
218                    $home_host .= ':' . $home_port;
219                }
220                ( new Boost_Cache( new File_Storage( strtolower( $home_host ) ) ) )->delete_recursive( $home_url );
221            }
222            update_option( 'jetpack_boost_page_cache_uri_keys', 1, false );
223        }
224
225        $page_cache = new Module( new Page_Cache() );
226        if ( $page_cache->is_enabled() ) {
227            // Schedule the cronjob to preload the cache for Cornerstone Pages.
228            ( new Cache_Preload() )->schedule_cornerstone_cronjob();
229        }
230
231        // Setup a cleanup job
232        if ( ! wp_next_scheduled( 'jetpack_boost_general_cleanup' ) ) {
233            wp_schedule_event( time(), 'daily', 'jetpack_boost_general_cleanup' );
234        }
235    }
236
237    /**
238     * Adds the custom cron intervals to the schedules list.
239     */
240    public function setup_cron_schedules() {
241        add_filter( 'cron_schedules', array( $this, 'custom_cron_intervals' ) );
242    }
243
244    /**
245     * Adds custom cron intervals used by Boost.
246     *
247     * @param array $schedules The existing cron schedules.
248     * @return array The modified cron schedules.
249     *
250     * @since 3.12.0
251     */
252    public function custom_cron_intervals( $schedules ) {
253        // The "twicehourly" name maintains the same pattern as the default "twicedaily" name.
254        if ( ! isset( $schedules['twicehourly'] ) ) {
255            $schedules['twicehourly'] = array(
256                'interval' => 30 * MINUTE_IN_SECONDS,
257                'display'  => __( 'Twice Hourly', 'jetpack-boost' ),
258            );
259        }
260        return $schedules;
261    }
262
263    /**
264     * Add query args used by Boost to a list of allowed query args.
265     *
266     * @param array $allowed_query_args The list of allowed query args.
267     *
268     * @return array The modified list of allowed query args.
269     */
270    public static function whitelist_query_args( $allowed_query_args ) {
271        $allowed_query_args[] = Generator::GENERATE_QUERY_ACTION;
272        $allowed_query_args[] = Module::DISABLE_MODULE_QUERY_VAR;
273        return $allowed_query_args;
274    }
275
276    /**
277     * Plugin activation handler.
278     */
279    public static function activate() {
280        // Make sure user sees the "Get Started" when first time opening.
281        ( new Getting_Started_Entry() )->set( true );
282        Analytics::record_user_event( 'activate_plugin' );
283
284        $page_cache_status = new Status( Page_Cache::get_slug() );
285        if ( $page_cache_status->get() && Boost_Cache_Settings::get_instance()->get_enabled() ) {
286            Page_Cache_Setup::run_setup();
287        }
288
289        $modules_setup = new Modules_Setup();
290
291        // Setup a cleanup job
292        if ( ! wp_next_scheduled( 'jetpack_boost_general_cleanup' ) ) {
293            wp_schedule_event( time(), 'daily', 'jetpack_boost_general_cleanup' );
294        }
295
296        /*
297         * Check what modules are already active (from a previous activation for example).
298         * If there are active modules, we need to ensure each module-related event is triggered again.
299         */
300        $active_modules = $modules_setup->get_status();
301        if (
302            ! empty( $active_modules )
303            && ( new Connection() )->is_connected()
304        ) {
305            $available_modules = $modules_setup->get_available_modules_and_submodules();
306            foreach ( $active_modules as $module => $status ) {
307                if ( ! $status ) {
308                    continue;
309                }
310
311                $module_instance = $available_modules[ $module ];
312                if ( $module_instance->feature instanceof Sub_Feature && empty( $module_instance->get_active_parent_modules() ) ) {
313                    continue;
314                }
315
316                $modules_setup->on_module_status_update( $module, true );
317            }
318        }
319    }
320
321    /**
322     * Plugin deactivation handler. Clear cache, and reset admin notices.
323     */
324    public function deactivate() {
325        do_action( 'jetpack_boost_deactivate' );
326
327        wp_clear_scheduled_hook( 'jetpack_boost_general_cleanup' );
328        wp_clear_scheduled_hook( Cleanup_Transients::FOLLOWUP_HOOK );
329
330        // Tell Minify JS/CSS to clean up.
331        jetpack_boost_page_optimize_deactivate();
332
333        Regenerate_Admin_Notice::dismiss();
334        Analytics::record_user_event( 'deactivate_plugin' );
335        Page_Cache_Setup::deactivate();
336
337        // Clean up Image Size Analysis data.
338        $this->cleanup_image_size_analysis_data();
339    }
340
341    /**
342     * Clean up Image Size Analysis data from the database.
343     *
344     * @since 4.3.0
345     */
346    private function cleanup_image_size_analysis_data() {
347        global $wpdb;
348
349        // Delete all post meta entries for Image Size Analysis fixes.
350        //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
351        $wpdb->delete(
352            $wpdb->postmeta,
353            array( 'meta_key' => '_jb_image_fixes' ),
354            array( '%s' )
355        );
356    }
357
358    /**
359     * Initialize the admin experience.
360     */
361    public function init_admin( $modules_setup ) {
362        REST_API::register( List_Site_Urls::class );
363        REST_API::register( List_Source_Providers::class );
364        REST_API::register( List_Cornerstone_Pages::class );
365        REST_API::register( List_LCP_Analysis::class );
366
367        ( new Admin() )->init( $modules_setup );
368    }
369
370    /**
371     * Initialize Jetpack packages via the Config class.
372     *
373     * Consolidates connection, sync, and identity crisis initialization
374     * into a single Config instance, matching the pattern used by other
375     * standalone Jetpack plugins (Protect, Social, VideoPress, etc.).
376     */
377    private function init_jetpack_config() {
378        $jetpack_config = new Jetpack_Config();
379
380        /**
381         * Filter that fakes the connection to WordPress.com. Useful for testing.
382         *
383         * @param bool $connection Return true to fake the connection.
384         *
385         * @since 1.0.0
386         */
387        if ( ! apply_filters( 'jetpack_boost_connection_bypass', false ) ) {
388            $jetpack_config->ensure(
389                'connection',
390                array(
391                    'slug'     => JETPACK_BOOST_SLUG,
392                    'name'     => 'Jetpack Boost',
393                    'url_info' => '',
394                )
395            );
396        }
397
398        $jetpack_config->ensure(
399            'sync',
400            array(
401                // Closures defer construction (and option reads) to Sync invocation time.
402                'jetpack_sync_callable_whitelist' => array(
403                    // boost_sub_modules_state was removed: it pointed at a method that never
404                    // existed, so the callable never resolved and Sync never sent it.
405                    'boost_modules'                => static function () {
406                        return ( new Modules_Setup() )->get_status();
407                    },
408                    'boost_latest_scores'          => static function () {
409                        return ( new Speed_Score_History( get_home_url() ) )->latest();
410                    },
411                    'boost_latest_no_boost_scores' => static function () {
412                        return ( new Speed_Score_History( add_query_arg( Module::DISABLE_MODULE_QUERY_VAR, 'all', get_home_url() ) ) )->latest();
413                    },
414                    'critical_css_state'           => static function () {
415                        return ( new Critical_CSS_State() )->get();
416                    },
417                    'lcp_state'                    => static function () {
418                        return ( new LCP_State() )->get();
419                    },
420                ),
421            )
422        );
423
424        add_action( 'added_option', array( $this, 'maybe_sync_module_status' ) );
425        add_action( 'updated_option', array( $this, 'maybe_sync_module_status' ) );
426        add_action( 'deleted_option', array( $this, 'maybe_sync_module_status' ) );
427
428        $jetpack_config->ensure( 'identity_crisis' );
429    }
430
431    /**
432     * Queue a fresh `boost_modules` snapshot when a module status option changes.
433     *
434     * Sync sends callables only when something else triggers a send, so a toggle alone can leave WP.com stale.
435     *
436     * @param string $option Option name.
437     */
438    public function maybe_sync_module_status( $option ) {
439        if ( ! str_starts_with( $option, Status::OPTION_PREFIX ) ) {
440            return;
441        }
442
443        // Deferred: some writes land before Sync's listener loads, and mapped modules change after the toggle.
444        add_action( 'shutdown', array( $this, 'sync_module_status' ) );
445    }
446
447    /**
448     * Send the current module status map to WP.com.
449     *
450     * This skips Sync's callable checksum, so its next routine callables check may send the same map again.
451     */
452    public function sync_module_status() {
453        do_action( 'jetpack_sync_callable', 'boost_modules', ( new Modules_Setup() )->get_status() );
454    }
455
456    /**
457     * Loads the textdomain.
458     */
459    public function init_textdomain() {
460        load_plugin_textdomain(
461            'jetpack-boost',
462            false,
463            JETPACK_BOOST_DIR_PATH . '/languages/'
464        );
465    }
466
467    /**
468     * The name of the plugin used to uniquely identify it within the context of
469     * WordPress and to define internationalization functionality.
470     *
471     * @return string The name of the plugin.
472     * @since     1.0.0
473     */
474    public function get_plugin_name() {
475        return $this->plugin_name;
476    }
477
478    /**
479     * Retrieve the version number of the plugin.
480     *
481     * @return string The version number of the plugin.
482     * @since     1.0.0
483     */
484    public function get_version() {
485        return $this->version;
486    }
487
488    /**
489     * Handle an environment change to set the correct status to the Critical CSS request.
490     * This is done here so even if the Critical CSS module is switched off we can
491     * still capture the change of environment event and flag Critical CSS for a rebuild.
492     */
493    public function handle_environment_change( $is_major_change, $change_type ) {
494        if ( $is_major_change ) {
495            Regenerate_Admin_Notice::enable();
496        }
497
498        jetpack_boost_ds_set( 'critical_css_suggest_regenerate', $change_type );
499    }
500
501    /**
502     * Plugin uninstallation handler. Delete all settings and cache.
503     */
504    public function uninstall() {
505        global $wpdb;
506
507        // When uninstalling, make sure all deactivation cleanups have run as well.
508        $this->deactivate();
509
510        // Delete all Jetpack Boost options.
511        //phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
512        $option_names = $wpdb->get_col(
513            "
514                SELECT `option_name`
515                FROM   `$wpdb->options`
516                WHERE  `option_name` LIKE 'jetpack_boost_%';
517            "
518        );
519        //phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
520
521        foreach ( $option_names as $option_name ) {
522            delete_option( $option_name );
523        }
524
525        // Delete the last run options for the network-wide cron jobs.
526        delete_site_option( 'jetpack_boost_404_tester_last_run' );
527        delete_site_option( 'jetpack_boost_minify_cron_cache_cleanup_last_run' );
528        delete_site_option( 'jetpack_boost_minify_cache_rules_applied' );
529
530        // Delete stored Critical CSS and LCP data.
531        ( new Critical_CSS_Storage() )->clear();
532        ( new LCP_Storage() )->clear();
533
534        // Delete all transients created by boost.
535        Transient::delete_bulk();
536
537        // Clear getting started value
538        ( new Getting_Started_Entry() )->set( false );
539
540        Page_Cache_Setup::uninstall();
541    }
542}