Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.14% covered (warning)
75.14%
133 / 177
42.11% covered (danger)
42.11%
8 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Boost
75.14% covered (warning)
75.14%
133 / 177
42.11% covered (danger)
42.11%
8 / 19
73.74
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
88.89% covered (warning)
88.89%
24 / 27
0.00% covered (danger)
0.00%
0 / 1
8.09
 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        delete_option( 'jetpack_boost_page_cache_uri_keys' );
213
214        $page_cache = new Module( new Page_Cache() );
215        if ( $page_cache->is_enabled() ) {
216            // Schedule the recurring preload first so a one-off from the purge cannot block it.
217            ( new Cache_Preload() )->schedule_cornerstone_cronjob();
218        }
219
220        $home_url  = home_url();
221        $home_host = wp_parse_url( $home_url, PHP_URL_HOST );
222        if ( is_string( $home_host ) ) {
223            $home_port = wp_parse_url( $home_url, PHP_URL_PORT );
224            if ( is_int( $home_port ) ) {
225                $home_host .= ':' . $home_port;
226            }
227            ( new Boost_Cache( new File_Storage( strtolower( $home_host ) ) ) )->delete_recursive( $home_url );
228        }
229
230        // Setup a cleanup job
231        if ( ! wp_next_scheduled( 'jetpack_boost_general_cleanup' ) ) {
232            wp_schedule_event( time(), 'daily', 'jetpack_boost_general_cleanup' );
233        }
234    }
235
236    /**
237     * Adds the custom cron intervals to the schedules list.
238     */
239    public function setup_cron_schedules() {
240        add_filter( 'cron_schedules', array( $this, 'custom_cron_intervals' ) );
241    }
242
243    /**
244     * Adds custom cron intervals used by Boost.
245     *
246     * @param array $schedules The existing cron schedules.
247     * @return array The modified cron schedules.
248     *
249     * @since 3.12.0
250     */
251    public function custom_cron_intervals( $schedules ) {
252        // The "twicehourly" name maintains the same pattern as the default "twicedaily" name.
253        if ( ! isset( $schedules['twicehourly'] ) ) {
254            $schedules['twicehourly'] = array(
255                'interval' => 30 * MINUTE_IN_SECONDS,
256                'display'  => __( 'Twice Hourly', 'jetpack-boost' ),
257            );
258        }
259        return $schedules;
260    }
261
262    /**
263     * Add query args used by Boost to a list of allowed query args.
264     *
265     * @param array $allowed_query_args The list of allowed query args.
266     *
267     * @return array The modified list of allowed query args.
268     */
269    public static function whitelist_query_args( $allowed_query_args ) {
270        $allowed_query_args[] = Generator::GENERATE_QUERY_ACTION;
271        $allowed_query_args[] = Module::DISABLE_MODULE_QUERY_VAR;
272        return $allowed_query_args;
273    }
274
275    /**
276     * Plugin activation handler.
277     */
278    public static function activate() {
279        // Make sure user sees the "Get Started" when first time opening.
280        ( new Getting_Started_Entry() )->set( true );
281        Analytics::record_user_event( 'activate_plugin' );
282
283        $page_cache_status = new Status( Page_Cache::get_slug() );
284        if ( $page_cache_status->get() && Boost_Cache_Settings::get_instance()->get_enabled() ) {
285            Page_Cache_Setup::run_setup();
286        }
287
288        $modules_setup = new Modules_Setup();
289
290        // Setup a cleanup job
291        if ( ! wp_next_scheduled( 'jetpack_boost_general_cleanup' ) ) {
292            wp_schedule_event( time(), 'daily', 'jetpack_boost_general_cleanup' );
293        }
294
295        /*
296         * Check what modules are already active (from a previous activation for example).
297         * If there are active modules, we need to ensure each module-related event is triggered again.
298         */
299        $active_modules = $modules_setup->get_status();
300        if (
301            ! empty( $active_modules )
302            && ( new Connection() )->is_connected()
303        ) {
304            $available_modules = $modules_setup->get_available_modules_and_submodules();
305            foreach ( $active_modules as $module => $status ) {
306                if ( ! $status ) {
307                    continue;
308                }
309
310                $module_instance = $available_modules[ $module ];
311                if ( $module_instance->feature instanceof Sub_Feature && empty( $module_instance->get_active_parent_modules() ) ) {
312                    continue;
313                }
314
315                $modules_setup->on_module_status_update( $module, true );
316            }
317        }
318    }
319
320    /**
321     * Plugin deactivation handler. Clear cache, and reset admin notices.
322     */
323    public function deactivate() {
324        do_action( 'jetpack_boost_deactivate' );
325
326        wp_clear_scheduled_hook( 'jetpack_boost_general_cleanup' );
327        wp_clear_scheduled_hook( Cleanup_Transients::FOLLOWUP_HOOK );
328
329        // Tell Minify JS/CSS to clean up.
330        jetpack_boost_page_optimize_deactivate();
331
332        Regenerate_Admin_Notice::dismiss();
333        Analytics::record_user_event( 'deactivate_plugin' );
334        Page_Cache_Setup::deactivate();
335
336        // Clean up Image Size Analysis data.
337        $this->cleanup_image_size_analysis_data();
338    }
339
340    /**
341     * Clean up Image Size Analysis data from the database.
342     *
343     * @since 4.3.0
344     */
345    private function cleanup_image_size_analysis_data() {
346        global $wpdb;
347
348        // Delete all post meta entries for Image Size Analysis fixes.
349        //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
350        $wpdb->delete(
351            $wpdb->postmeta,
352            array( 'meta_key' => '_jb_image_fixes' ),
353            array( '%s' )
354        );
355    }
356
357    /**
358     * Initialize the admin experience.
359     */
360    public function init_admin( $modules_setup ) {
361        REST_API::register( List_Site_Urls::class );
362        REST_API::register( List_Source_Providers::class );
363        REST_API::register( List_Cornerstone_Pages::class );
364        REST_API::register( List_LCP_Analysis::class );
365
366        ( new Admin() )->init( $modules_setup );
367    }
368
369    /**
370     * Initialize Jetpack packages via the Config class.
371     *
372     * Consolidates connection, sync, and identity crisis initialization
373     * into a single Config instance, matching the pattern used by other
374     * standalone Jetpack plugins (Protect, Social, VideoPress, etc.).
375     */
376    private function init_jetpack_config() {
377        $jetpack_config = new Jetpack_Config();
378
379        /**
380         * Filter that fakes the connection to WordPress.com. Useful for testing.
381         *
382         * @param bool $connection Return true to fake the connection.
383         *
384         * @since 1.0.0
385         */
386        if ( ! apply_filters( 'jetpack_boost_connection_bypass', false ) ) {
387            $jetpack_config->ensure(
388                'connection',
389                array(
390                    'slug'     => JETPACK_BOOST_SLUG,
391                    'name'     => 'Jetpack Boost',
392                    'url_info' => '',
393                )
394            );
395        }
396
397        $jetpack_config->ensure(
398            'sync',
399            array(
400                // Closures defer construction (and option reads) to Sync invocation time.
401                'jetpack_sync_callable_whitelist' => array(
402                    // boost_sub_modules_state was removed: it pointed at a method that never
403                    // existed, so the callable never resolved and Sync never sent it.
404                    'boost_modules'                => static function () {
405                        return ( new Modules_Setup() )->get_status();
406                    },
407                    'boost_latest_scores'          => static function () {
408                        return ( new Speed_Score_History( get_home_url() ) )->latest();
409                    },
410                    'boost_latest_no_boost_scores' => static function () {
411                        return ( new Speed_Score_History( add_query_arg( Module::DISABLE_MODULE_QUERY_VAR, 'all', get_home_url() ) ) )->latest();
412                    },
413                    'critical_css_state'           => static function () {
414                        return ( new Critical_CSS_State() )->get();
415                    },
416                    'lcp_state'                    => static function () {
417                        return ( new LCP_State() )->get();
418                    },
419                ),
420            )
421        );
422
423        add_action( 'added_option', array( $this, 'maybe_sync_module_status' ) );
424        add_action( 'updated_option', array( $this, 'maybe_sync_module_status' ) );
425        add_action( 'deleted_option', array( $this, 'maybe_sync_module_status' ) );
426
427        $jetpack_config->ensure( 'identity_crisis' );
428    }
429
430    /**
431     * Queue a fresh `boost_modules` snapshot when a module status option changes.
432     *
433     * Sync sends callables only when something else triggers a send, so a toggle alone can leave WP.com stale.
434     *
435     * @param string $option Option name.
436     */
437    public function maybe_sync_module_status( $option ) {
438        if ( ! str_starts_with( $option, Status::OPTION_PREFIX ) ) {
439            return;
440        }
441
442        // Deferred: some writes land before Sync's listener loads, and mapped modules change after the toggle.
443        add_action( 'shutdown', array( $this, 'sync_module_status' ) );
444    }
445
446    /**
447     * Send the current module status map to WP.com.
448     *
449     * This skips Sync's callable checksum, so its next routine callables check may send the same map again.
450     */
451    public function sync_module_status() {
452        do_action( 'jetpack_sync_callable', 'boost_modules', ( new Modules_Setup() )->get_status() );
453    }
454
455    /**
456     * Loads the textdomain.
457     */
458    public function init_textdomain() {
459        load_plugin_textdomain(
460            'jetpack-boost',
461            false,
462            JETPACK_BOOST_DIR_PATH . '/languages/'
463        );
464    }
465
466    /**
467     * The name of the plugin used to uniquely identify it within the context of
468     * WordPress and to define internationalization functionality.
469     *
470     * @return string The name of the plugin.
471     * @since     1.0.0
472     */
473    public function get_plugin_name() {
474        return $this->plugin_name;
475    }
476
477    /**
478     * Retrieve the version number of the plugin.
479     *
480     * @return string The version number of the plugin.
481     * @since     1.0.0
482     */
483    public function get_version() {
484        return $this->version;
485    }
486
487    /**
488     * Handle an environment change to set the correct status to the Critical CSS request.
489     * This is done here so even if the Critical CSS module is switched off we can
490     * still capture the change of environment event and flag Critical CSS for a rebuild.
491     */
492    public function handle_environment_change( $is_major_change, $change_type ) {
493        if ( $is_major_change ) {
494            Regenerate_Admin_Notice::enable();
495        }
496
497        jetpack_boost_ds_set( 'critical_css_suggest_regenerate', $change_type );
498    }
499
500    /**
501     * Plugin uninstallation handler. Delete all settings and cache.
502     */
503    public function uninstall() {
504        global $wpdb;
505
506        // When uninstalling, make sure all deactivation cleanups have run as well.
507        $this->deactivate();
508
509        // Delete all Jetpack Boost options.
510        //phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
511        $option_names = $wpdb->get_col(
512            "
513                SELECT `option_name`
514                FROM   `$wpdb->options`
515                WHERE  `option_name` LIKE 'jetpack_boost_%';
516            "
517        );
518        //phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
519
520        foreach ( $option_names as $option_name ) {
521            delete_option( $option_name );
522        }
523
524        // Delete the last run options for the network-wide cron jobs.
525        delete_site_option( 'jetpack_boost_404_tester_last_run' );
526        delete_site_option( 'jetpack_boost_minify_cron_cache_cleanup_last_run' );
527        delete_site_option( 'jetpack_boost_minify_cache_rules_applied' );
528
529        // Delete stored Critical CSS and LCP data.
530        ( new Critical_CSS_Storage() )->clear();
531        ( new LCP_Storage() )->clear();
532
533        // Delete all transients created by boost.
534        Transient::delete_bulk();
535
536        // Clear getting started value
537        ( new Getting_Started_Entry() )->set( false );
538
539        Page_Cache_Setup::uninstall();
540    }
541}