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. Idempotent, so it no-ops when the Jetpack plugin already
143        // initialized the package on this request.
144        Jetpack_Activity_Log::initialize();
145
146        Deactivation_Handler::init( $this->plugin_name, __DIR__ . '/admin/deactivation-dialog.php' );
147
148        // Register the core Image CDN hooks.
149        Image_CDN_Core::setup();
150
151        // Setup Site Health panel functionality.
152        Site_Health::init();
153
154        Super_Cache_Tracking::setup();
155
156        // Boost abilities (WP Abilities API). Gated by `jetpack_wp_abilities_enabled`;
157        // priority 20 leaves room for default-priority filter registrations to land first.
158        add_action( 'plugins_loaded', array( '\Automattic\Jetpack_Boost\Abilities\Boost_Abilities', 'init' ), 20 );
159    }
160
161    /**
162     * Register deactivation hook.
163     */
164    private function register_deactivation_hook() {
165        $plugin_file = trailingslashit( dirname( __DIR__ ) ) . 'jetpack-boost.php';
166        register_deactivation_hook( $plugin_file, array( $this, 'deactivate' ) );
167    }
168
169    public function schedule_version_change() {
170        $version = get_option( 'jetpack_boost_version' );
171
172        if ( $version === JETPACK_BOOST_VERSION ) {
173            return;
174        }
175        update_option( 'jetpack_boost_version', JETPACK_BOOST_VERSION );
176
177        // Schedule the cron event to handle the version change. This ensures the previous version's handle is always flushed.
178        if ( ! wp_next_scheduled( 'jetpack_boost_handle_version_change_cron' ) ) {
179            wp_schedule_single_event( time() + 2, 'jetpack_boost_handle_version_change_cron' );
180        }
181    }
182
183    public function handle_version_change() {
184        // Remove this option to prevent the notice from showing up.
185        delete_site_option( 'jetpack_boost_static_minification' );
186
187        // Add upgrade check for Cornerstone Pages.
188        $pages = jetpack_boost_ds_get( 'cornerstone_pages_list' );
189        if ( is_array( $pages ) && in_array( home_url( '' ), $pages, true ) ) {
190            // Remove homepage (empty string) from the cornerstone pages list.
191            $pages = array_filter(
192                $pages,
193                function ( $page ) {
194                    return $page !== home_url( '' );
195                }
196            );
197            jetpack_boost_ds_set( 'cornerstone_pages_list', $pages );
198        }
199
200        if ( jetpack_boost_minify_is_enabled() ) {
201            // We need to clear Minify scheduled events to ensure the latest scheduled jobs are only scheduled irrespective of scheduled arguments.
202            jetpack_boost_minify_clear_scheduled_events();
203            jetpack_boost_minify_activation();
204        }
205
206        $page_cache = new Module( new Page_Cache() );
207        if ( $page_cache->is_enabled() ) {
208            // Schedule the cronjob to preload the cache for Cornerstone Pages.
209            ( new Cache_Preload() )->schedule_cornerstone_cronjob();
210        }
211
212        // Setup a cleanup job
213        if ( ! wp_next_scheduled( 'jetpack_boost_general_cleanup' ) ) {
214            wp_schedule_event( time(), 'daily', 'jetpack_boost_general_cleanup' );
215        }
216    }
217
218    /**
219     * Adds the custom cron intervals to the schedules list.
220     */
221    public function setup_cron_schedules() {
222        add_filter( 'cron_schedules', array( $this, 'custom_cron_intervals' ) );
223    }
224
225    /**
226     * Adds custom cron intervals used by Boost.
227     *
228     * @param array $schedules The existing cron schedules.
229     * @return array The modified cron schedules.
230     *
231     * @since 3.12.0
232     */
233    public function custom_cron_intervals( $schedules ) {
234        // The "twicehourly" name maintains the same pattern as the default "twicedaily" name.
235        if ( ! isset( $schedules['twicehourly'] ) ) {
236            $schedules['twicehourly'] = array(
237                'interval' => 30 * MINUTE_IN_SECONDS,
238                'display'  => __( 'Twice Hourly', 'jetpack-boost' ),
239            );
240        }
241        return $schedules;
242    }
243
244    /**
245     * Add query args used by Boost to a list of allowed query args.
246     *
247     * @param array $allowed_query_args The list of allowed query args.
248     *
249     * @return array The modified list of allowed query args.
250     */
251    public static function whitelist_query_args( $allowed_query_args ) {
252        $allowed_query_args[] = Generator::GENERATE_QUERY_ACTION;
253        $allowed_query_args[] = Module::DISABLE_MODULE_QUERY_VAR;
254        return $allowed_query_args;
255    }
256
257    /**
258     * Plugin activation handler.
259     */
260    public static function activate() {
261        // Make sure user sees the "Get Started" when first time opening.
262        ( new Getting_Started_Entry() )->set( true );
263        Analytics::record_user_event( 'activate_plugin' );
264
265        $page_cache_status = new Status( Page_Cache::get_slug() );
266        if ( $page_cache_status->get() && Boost_Cache_Settings::get_instance()->get_enabled() ) {
267            Page_Cache_Setup::run_setup();
268        }
269
270        $modules_setup = new Modules_Setup();
271
272        // Setup a cleanup job
273        if ( ! wp_next_scheduled( 'jetpack_boost_general_cleanup' ) ) {
274            wp_schedule_event( time(), 'daily', 'jetpack_boost_general_cleanup' );
275        }
276
277        /*
278         * Check what modules are already active (from a previous activation for example).
279         * If there are active modules, we need to ensure each module-related event is triggered again.
280         */
281        $active_modules = $modules_setup->get_status();
282        if (
283            ! empty( $active_modules )
284            && ( new Connection() )->is_connected()
285        ) {
286            foreach ( $active_modules as $module => $status ) {
287                $modules_setup->on_module_status_update( $module, true );
288            }
289        }
290    }
291
292    /**
293     * Plugin deactivation handler. Clear cache, and reset admin notices.
294     */
295    public function deactivate() {
296        do_action( 'jetpack_boost_deactivate' );
297
298        wp_clear_scheduled_hook( 'jetpack_boost_general_cleanup' );
299
300        // Tell Minify JS/CSS to clean up.
301        jetpack_boost_page_optimize_deactivate();
302
303        Regenerate_Admin_Notice::dismiss();
304        Analytics::record_user_event( 'deactivate_plugin' );
305        Page_Cache_Setup::deactivate();
306
307        // Clean up Image Size Analysis data.
308        $this->cleanup_image_size_analysis_data();
309    }
310
311    /**
312     * Clean up Image Size Analysis data from the database.
313     *
314     * @since 4.3.0
315     */
316    private function cleanup_image_size_analysis_data() {
317        global $wpdb;
318
319        // Delete all post meta entries for Image Size Analysis fixes.
320        //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
321        $wpdb->delete(
322            $wpdb->postmeta,
323            array( 'meta_key' => '_jb_image_fixes' ),
324            array( '%s' )
325        );
326    }
327
328    /**
329     * Initialize the admin experience.
330     */
331    public function init_admin( $modules_setup ) {
332        REST_API::register( List_Site_Urls::class );
333        REST_API::register( List_Source_Providers::class );
334        REST_API::register( List_Cornerstone_Pages::class );
335        REST_API::register( List_LCP_Analysis::class );
336
337        ( new Admin() )->init( $modules_setup );
338    }
339
340    /**
341     * Initialize Jetpack packages via the Config class.
342     *
343     * Consolidates connection, sync, and identity crisis initialization
344     * into a single Config instance, matching the pattern used by other
345     * standalone Jetpack plugins (Protect, Social, VideoPress, etc.).
346     */
347    private function init_jetpack_config() {
348        $jetpack_config = new Jetpack_Config();
349
350        /**
351         * Filter that fakes the connection to WordPress.com. Useful for testing.
352         *
353         * @param bool $connection Return true to fake the connection.
354         *
355         * @since 1.0.0
356         */
357        if ( ! apply_filters( 'jetpack_boost_connection_bypass', false ) ) {
358            $jetpack_config->ensure(
359                'connection',
360                array(
361                    'slug'     => JETPACK_BOOST_SLUG,
362                    'name'     => 'Jetpack Boost',
363                    'url_info' => '',
364                )
365            );
366        }
367
368        $jetpack_config->ensure(
369            'sync',
370            array(
371                // Closures defer construction (and option reads) to Sync invocation time.
372                'jetpack_sync_callable_whitelist' => array(
373                    // boost_sub_modules_state was removed: it pointed at a method that never
374                    // existed, so the callable never resolved and Sync never sent it.
375                    'boost_modules'                => static function () {
376                        return ( new Modules_Setup() )->get_status();
377                    },
378                    'boost_latest_scores'          => static function () {
379                        return ( new Speed_Score_History( get_home_url() ) )->latest();
380                    },
381                    'boost_latest_no_boost_scores' => static function () {
382                        return ( new Speed_Score_History( add_query_arg( Module::DISABLE_MODULE_QUERY_VAR, 'all', get_home_url() ) ) )->latest();
383                    },
384                    'critical_css_state'           => static function () {
385                        return ( new Critical_CSS_State() )->get();
386                    },
387                    'lcp_state'                    => static function () {
388                        return ( new LCP_State() )->get();
389                    },
390                ),
391            )
392        );
393
394        $jetpack_config->ensure( 'identity_crisis' );
395    }
396
397    /**
398     * Loads the textdomain.
399     */
400    public function init_textdomain() {
401        load_plugin_textdomain(
402            'jetpack-boost',
403            false,
404            JETPACK_BOOST_DIR_PATH . '/languages/'
405        );
406    }
407
408    /**
409     * The name of the plugin used to uniquely identify it within the context of
410     * WordPress and to define internationalization functionality.
411     *
412     * @return string The name of the plugin.
413     * @since     1.0.0
414     */
415    public function get_plugin_name() {
416        return $this->plugin_name;
417    }
418
419    /**
420     * Retrieve the version number of the plugin.
421     *
422     * @return string The version number of the plugin.
423     * @since     1.0.0
424     */
425    public function get_version() {
426        return $this->version;
427    }
428
429    /**
430     * Handle an environment change to set the correct status to the Critical CSS request.
431     * This is done here so even if the Critical CSS module is switched off we can
432     * still capture the change of environment event and flag Critical CSS for a rebuild.
433     */
434    public function handle_environment_change( $is_major_change, $change_type ) {
435        if ( $is_major_change ) {
436            Regenerate_Admin_Notice::enable();
437        }
438
439        jetpack_boost_ds_set( 'critical_css_suggest_regenerate', $change_type );
440    }
441
442    /**
443     * Plugin uninstallation handler. Delete all settings and cache.
444     */
445    public function uninstall() {
446        global $wpdb;
447
448        // When uninstalling, make sure all deactivation cleanups have run as well.
449        $this->deactivate();
450
451        // Delete all Jetpack Boost options.
452        //phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
453        $option_names = $wpdb->get_col(
454            "
455                SELECT `option_name`
456                FROM   `$wpdb->options`
457                WHERE  `option_name` LIKE 'jetpack_boost_%';
458            "
459        );
460        //phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
461
462        foreach ( $option_names as $option_name ) {
463            delete_option( $option_name );
464        }
465
466        // Delete the last run options for the network-wide cron jobs.
467        delete_site_option( 'jetpack_boost_404_tester_last_run' );
468        delete_site_option( 'jetpack_boost_minify_cron_cache_cleanup_last_run' );
469
470        // Delete stored Critical CSS and LCP data.
471        ( new Critical_CSS_Storage() )->clear();
472        ( new LCP_Storage() )->clear();
473
474        // Delete all transients created by boost.
475        Transient::delete_bulk();
476
477        // Clear getting started value
478        ( new Getting_Started_Entry() )->set( false );
479
480        Page_Cache_Setup::uninstall();
481    }
482}