Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.00% covered (success)
94.00%
141 / 150
68.75% covered (warning)
68.75%
11 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin
94.00% covered (success)
94.00%
141 / 150
68.75% covered (warning)
68.75%
11 / 16
44.42
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 add_admin_shell_member
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 load_as_admin_shell_guest
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 handle_admin_menu
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
3
 maybe_load_wp_build
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 register_wp_build
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 build_file
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dashboard_build_is_available
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 alias_screen_id_for_wp_build
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 restore_screen_id_after_wp_build
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 admin_init
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 add_enqueue_hooks
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_scripts
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
6
 plugin_page_settings_link
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 localize_api_settings
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 render_missing_build_notice
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 is_modernization_enabled
n/a
0 / 0
n/a
0 / 0
1
 render_settings
n/a
0 / 0
n/a
0 / 0
1
1<?php
2/**
3 * The admin-specific functionality of the plugin.
4 *
5 * @since      1.0.0
6 * @package    automattic/jetpack-boost
7 */
8
9namespace Automattic\Jetpack_Boost\Admin;
10
11use Automattic\Jetpack\Admin_UI\Admin_Menu;
12use Automattic\Jetpack\Admin_UI\Admin_Shell;
13use Automattic\Jetpack\Assets;
14use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
15use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
16use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
17use Automattic\Jetpack\WP_JS_Data_Sync\Data_Sync;
18use Automattic\Jetpack_Boost\Data_Sync\Getting_Started_Entry;
19use Automattic\Jetpack_Boost\Lib\Analytics;
20use Automattic\Jetpack_Boost\Lib\Debug;
21use Automattic\Jetpack_Boost\Lib\Environment_Change_Detector;
22use Automattic\Jetpack_Boost\Lib\Premium_Features;
23use Automattic\Jetpack_Boost\Modules\Modules_Setup;
24
25class Admin {
26    /**
27     * Menu slug.
28     */
29    const MENU_SLUG = 'jetpack-boost';
30
31    /**
32     * Whether this request loaded the dashboard build.
33     *
34     * @var bool
35     */
36    private $dashboard_build_loaded = false;
37
38    /**
39     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
40     *
41     * @var string|null
42     */
43    private $wp_build_original_screen_id = null;
44
45    public function init( Modules_Setup $modules ) {
46        Environment_Change_Detector::init();
47
48        // Initiate speed scores.
49        new Speed_Score( $modules->get_ready_active_optimization_modules(), 'boost-plugin' );
50
51        add_action( 'init', array( new Analytics(), 'init' ) );
52        add_filter( 'plugin_action_links_' . JETPACK_BOOST_PLUGIN_BASE, array( $this, 'plugin_page_settings_link' ) );
53        add_action( 'admin_menu', array( $this, 'handle_admin_menu' ), 1 ); // Akismet uses 4, so we use 1 to ensure both menus are added when only they exist.
54        if ( class_exists( Admin_Shell::class ) ) {
55            add_filter( 'jetpack_admin_shell_members', array( $this, 'add_admin_shell_member' ) );
56        }
57    }
58
59    /**
60     * Register Boost with the admin shell, which switches between Jetpack dashboards without a page load.
61     *
62     * @since 4.9.0
63     *
64     * @param array $members Shell members keyed by admin page slug.
65     * @return array
66     */
67    public function add_admin_shell_member( $members ) {
68        if ( ! file_exists( self::build_file() ) ) {
69            return $members;
70        }
71
72        $members[ JETPACK_BOOST_SLUG ] = array(
73            'build_prefix' => 'jetpack_boost',
74            'build_page'   => 'jetpack-boost-dashboard',
75            'init_modules' => array( '@jetpack-boost/init' ),
76            'title'        => 'Boost', // "Boost" is a product name, do not translate.
77            'capability'   => 'manage_options',
78            // The webpack bundle renders the dashboard's content into the wp-build page; it carries the Boost and DataSync data.
79            // My Jetpack's header controls script fills the account control in Boost's header.
80            'handles'      => array( 'jetpack-boost-admin', 'my-jetpack-header-controls', 'wp-jp-i18n-loader' ),
81            'load'         => array( $this, 'load_as_admin_shell_guest' ),
82        );
83        // The Getting Started screen, which a bare menu link opens until it's done, has no page header.
84        $members[ JETPACK_BOOST_SLUG ]['header'] = ( new Getting_Started_Entry() )->get() ? false : array(
85            'title'    => 'Boost',
86            'subtitle' => __( 'Improve your site speed and performance.', 'jetpack-boost' ),
87        );
88        return $members;
89    }
90
91    /**
92     * Ready Boost's routes and page data while another dashboard's page is open, without the screen ID alias.
93     *
94     * Skips admin_init()'s premium feature refresh, since a guest must not write options; Boost's own page load still runs it.
95     *
96     * @since 4.9.0
97     *
98     * @return void
99     */
100    public function load_as_admin_shell_guest() {
101        $build_file = self::build_file();
102        require_once $build_file;
103        if ( ! function_exists( 'jetpack_boost_register_script_modules' ) ) {
104            return;
105        }
106        $this->register_wp_build();
107
108        // On the host page the shell removes these again; the guest endpoint runs them.
109        $this->add_enqueue_hooks();
110        // Boost's own page attaches the DataSync state when it renders the page body, which the guest endpoint doesn't print.
111        Data_Sync::get_instance( JETPACK_BOOST_DATASYNC_NAMESPACE )->attach_to_plugin( 'jetpack-boost-admin', 'admin_enqueue_scripts' );
112    }
113
114    public function handle_admin_menu() {
115        $this->maybe_load_wp_build();
116
117        /**
118         * Filters the number of problems shown in the Boost sidebar menu
119         *
120         * @param int $count the number of problems shown.
121         *
122         * @since   1.0.0
123         */
124        // Only report the count to users who can actually reach the Boost menu
125        // (added below with the 'manage_options' cap). Otherwise the central
126        // menu-badges total would include problems the current user can't see.
127        if ( current_user_can( 'manage_options' ) ) {
128            $total_problems = apply_filters( 'jetpack_boost_total_problem_count', 0 );
129            \Automattic\Jetpack\Menu_Badges\Menu_Badges::init(); // idempotent; wires the renderer.
130            \Automattic\Jetpack\Menu_Badges\Notification_Counts::register(
131                'jetpack-boost',
132                array(
133                    'menu_slug' => JETPACK_BOOST_SLUG,
134                    'count'     => (int) $total_problems,
135                    'type'      => 'count',
136                )
137            );
138        }
139
140        $page_suffix = Admin_Menu::add_menu(
141            __( 'Jetpack Boost - Settings', 'jetpack-boost' ),
142            'Boost', // "Boost" is a product name, do not translate.
143            'manage_options',
144            JETPACK_BOOST_SLUG,
145            $this->dashboard_build_loaded ? 'jetpack_boost_jetpack_boost_dashboard_wp_admin_render_page' : array( $this, 'render_missing_build_notice' ),
146            null,
147            array(
148                'product' => 'boost',
149                'key'     => 'jetpack-boost',
150            )
151        );
152        add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) );
153    }
154
155    /**
156     * Load the dashboard build on Boost's admin page.
157     */
158    private function maybe_load_wp_build() {
159        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
160        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
161        if ( JETPACK_BOOST_SLUG !== $page || ! is_admin() || ! $this->dashboard_build_is_available() ) {
162            return;
163        }
164
165        $this->register_wp_build();
166    }
167
168    /**
169     * Register the polyfills and script modules of the generated build, once it is loaded.
170     */
171    private function register_wp_build() {
172        WP_Build_Polyfills::register(
173            'jetpack-boost',
174            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
175        );
176
177        // wp_default_scripts has already fired by admin_menu, so register the init module now.
178        jetpack_boost_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Defined by the generated build; callers check it exists.
179        $this->dashboard_build_loaded = true;
180    }
181
182    /**
183     * Path to the generated build's entry file.
184     *
185     * @return string
186     */
187    private static function build_file() {
188        return JETPACK_BOOST_DIR_PATH . '/build/build.php';
189    }
190
191    /**
192     * Load the generated dashboard, if its build is present.
193     *
194     * @return bool Whether the generated dashboard is available.
195     */
196    private function dashboard_build_is_available() {
197        $build_file = self::build_file();
198        if ( ! file_exists( $build_file ) ) {
199            Debug::log( 'Dashboard build is missing; showing the missing-build notice.' );
200            return false;
201        }
202
203        // Hooked around the require, so only the generated enqueue callback, with its init action and REST preloading, sees the alias.
204        add_action( 'admin_enqueue_scripts', array( $this, 'alias_screen_id_for_wp_build' ) );
205        require_once $build_file;
206        add_action( 'admin_enqueue_scripts', array( $this, 'restore_screen_id_after_wp_build' ) );
207
208        if ( function_exists( 'jetpack_boost_register_script_modules' )
209            && function_exists( 'jetpack_boost_jetpack_boost_dashboard_wp_admin_render_page' ) ) {
210            return true;
211        }
212
213        remove_action( 'admin_enqueue_scripts', array( $this, 'alias_screen_id_for_wp_build' ) );
214        remove_action( 'admin_enqueue_scripts', array( $this, 'restore_screen_id_after_wp_build' ) );
215        return false;
216    }
217
218    /**
219     * Match wp-build's enqueue screen without changing the Boost menu URL.
220     *
221     * @since 4.7.1
222     * @since 4.8.0 Reads the current screen itself and records the ID it replaces.
223     */
224    public function alias_screen_id_for_wp_build() {
225        $screen = get_current_screen();
226        if ( ! $screen ) {
227            return;
228        }
229
230        $this->wp_build_original_screen_id = $screen->id;
231        $screen->id                        = 'jetpack-boost-dashboard';
232    }
233
234    /**
235     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
236     *
237     * @since 4.8.0
238     */
239    public function restore_screen_id_after_wp_build() {
240        $screen = get_current_screen();
241        if ( ! $screen || null === $this->wp_build_original_screen_id ) {
242            return;
243        }
244
245        $screen->id                        = $this->wp_build_original_screen_id;
246        $this->wp_build_original_screen_id = null;
247    }
248
249    /**
250     * Enqueue scripts and styles for the admin page.
251     */
252    public function admin_init() {
253        // Refetch the premium features unless the site features this page loads anyway still match them.
254        $cache_confirmed = Premium_Features::is_cache_confirmed();
255        if ( ! $cache_confirmed ) {
256            Premium_Features::clear_cache();
257        }
258        if ( current_user_can( 'manage_options' ) ) {
259            $already_activated = get_option( Premium_Features::CLOUD_CSS_ACTIVATED_OPTION );
260            Premium_Features::enable_cloud_css_after_upgrade( $cache_confirmed );
261            if ( $this->dashboard_build_loaded && ! $already_activated && get_option( Premium_Features::CLOUD_CSS_ACTIVATED_OPTION ) ) {
262                jetpack_boost_ds_set( 'cloud_css_upgrade_notice', true );
263            }
264        }
265
266        $this->add_enqueue_hooks();
267    }
268
269    /**
270     * Hook the dashboard's scripts, on Boost's own page and in the admin shell's guest endpoint.
271     */
272    private function add_enqueue_hooks() {
273        add_action( 'admin_enqueue_scripts', array( My_Jetpack_Initializer::class, 'enqueue_scripts' ) );
274        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
275    }
276
277    /**
278     * Register the JavaScript for the admin area.
279     *
280     * @since    1.0.0
281     */
282    public function enqueue_scripts() {
283        /**
284         * Filters the internal path to the distributed assets used by the plugin
285         *
286         * @param string $path the path to the assets
287         */
288        $internal_path = apply_filters( 'jetpack_boost_asset_internal_path', 'app/assets/dist/' );
289
290        $admin_js_handle = 'jetpack-boost-admin';
291
292        $admin_js_dependencies = array(
293            'wp-i18n',
294            'wp-components',
295            'my_jetpack_main_app',
296        );
297
298        Assets::register_script(
299            $admin_js_handle,
300            $internal_path . 'jetpack-boost.js',
301            JETPACK_BOOST_PATH,
302            array(
303                'dependencies' => $admin_js_dependencies,
304                'in_footer'    => true,
305                'textdomain'   => 'jetpack-boost',
306                'css_path'     => $internal_path . 'jetpack-boost.css',
307            )
308        );
309
310        wp_localize_script(
311            $admin_js_handle,
312            'Jetpack_Boost',
313            ( new Config() )->constants()
314        );
315
316        Assets::enqueue_script( $admin_js_handle );
317
318        if ( $this->dashboard_build_loaded ) {
319            $this->localize_api_settings( $admin_js_handle );
320            $i18n_loader_registered = wp_script_is( 'wp-jp-i18n-loader', 'registered' );
321            if ( $i18n_loader_registered ) {
322                wp_enqueue_script( 'wp-jp-i18n-loader' );
323            }
324
325            // The webpack handle carries Boost constants and DataSync bootstrap needed before modules run.
326            $prerequisites = wp_scripts()->query( 'jetpack-boost-dashboard-wp-admin-prerequisites', 'registered' );
327            if ( $prerequisites ) {
328                $prerequisites->deps[] = $admin_js_handle;
329                if ( $i18n_loader_registered ) {
330                    $prerequisites->deps[] = 'wp-jp-i18n-loader';
331                }
332            } elseif ( ! wp_doing_ajax() ) {
333                // The admin shell's guest endpoint has no prerequisites handle: the shell runs the bundle before it boots the page.
334                Debug::log( 'Modern dashboard prerequisites are not registered; bootstrap dependencies could not be attached.' );
335            }
336        }
337    }
338
339    /**
340     * Get settings link.
341     *
342     * @param array $links the array of links.
343     */
344    public function plugin_page_settings_link( $links ) {
345        $settings_link = '<a href="' . admin_url( 'admin.php?page=jetpack-boost' ) . '">' . esc_html__( 'Settings', 'jetpack-boost' ) . '</a>';
346        array_unshift( $links, $settings_link );
347
348        return $links;
349    }
350
351    /**
352     * Localize the REST API settings for a script.
353     *
354     * @param string $handle Script handle.
355     */
356    private function localize_api_settings( $handle ) {
357        wp_localize_script(
358            $handle,
359            'wpApiSettings',
360            array(
361                'root'  => esc_url_raw( rest_url() ),
362                'nonce' => wp_create_nonce( 'wp_rest' ),
363            )
364        );
365    }
366
367    /**
368     * Explain why the page is empty when the dashboard build is missing or incomplete.
369     */
370    public function render_missing_build_notice() {
371        ?>
372        <div class="wrap">
373            <div class="notice notice-error">
374                <p><?php esc_html_e( 'Jetpack Boost could not load its dashboard because some plugin files are missing. Reinstall Jetpack Boost to fix this.', 'jetpack-boost' ); ?></p>
375            </div>
376        </div>
377        <?php
378    }
379
380    /**
381     * Whether the modern dashboard is enabled. It always is, now that the legacy dashboard is gone.
382     *
383     * @deprecated $$next-version$$
384     *
385     * @return bool Always true.
386     */
387    public static function is_modernization_enabled() {
388        _deprecated_function( __METHOD__, 'jetpack-boost-$$next-version$$' );
389        return true;
390    }
391
392    /**
393     * Render the page body the legacy dashboard used to mount into.
394     *
395     * @deprecated $$next-version$$ Renders the missing-build notice, since the legacy dashboard is gone.
396     */
397    public function render_settings() {
398        _deprecated_function( __METHOD__, 'jetpack-boost-$$next-version$$' );
399        $this->render_missing_build_notice();
400    }
401}