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