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