Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.27% covered (success)
94.27%
148 / 157
68.75% covered (warning)
68.75%
11 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin
94.27% covered (success)
94.27%
148 / 157
68.75% covered (warning)
68.75%
11 / 16
44.36
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%
13 / 13
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            null,
176            array(
177                array(
178                    'prefix' => 'jetpack_boost',
179                    'slug'   => 'jetpack-boost-dashboard',
180                ),
181            )
182        );
183
184        // wp_default_scripts has already fired by admin_menu, so register the init module now.
185        jetpack_boost_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Defined by the generated build; callers check it exists.
186        $this->dashboard_build_loaded = true;
187    }
188
189    /**
190     * Path to the generated build's entry file.
191     *
192     * @return string
193     */
194    private static function build_file() {
195        return JETPACK_BOOST_DIR_PATH . '/build/build.php';
196    }
197
198    /**
199     * Load the generated dashboard, if its build is present.
200     *
201     * @return bool Whether the generated dashboard is available.
202     */
203    private function dashboard_build_is_available() {
204        $build_file = self::build_file();
205        if ( ! file_exists( $build_file ) ) {
206            Debug::log( 'Dashboard build is missing; showing the missing-build notice.' );
207            return false;
208        }
209
210        // Hooked around the require, so only the generated enqueue callback, with its init action and REST preloading, sees the alias.
211        add_action( 'admin_enqueue_scripts', array( $this, 'alias_screen_id_for_wp_build' ) );
212        require_once $build_file;
213        add_action( 'admin_enqueue_scripts', array( $this, 'restore_screen_id_after_wp_build' ) );
214
215        if ( function_exists( 'jetpack_boost_register_script_modules' )
216            && function_exists( 'jetpack_boost_jetpack_boost_dashboard_wp_admin_render_page' ) ) {
217            return true;
218        }
219
220        remove_action( 'admin_enqueue_scripts', array( $this, 'alias_screen_id_for_wp_build' ) );
221        remove_action( 'admin_enqueue_scripts', array( $this, 'restore_screen_id_after_wp_build' ) );
222        return false;
223    }
224
225    /**
226     * Match wp-build's enqueue screen without changing the Boost menu URL.
227     *
228     * @since 4.7.1
229     * @since 4.8.0 Reads the current screen itself and records the ID it replaces.
230     */
231    public function alias_screen_id_for_wp_build() {
232        $screen = get_current_screen();
233        if ( ! $screen ) {
234            return;
235        }
236
237        $this->wp_build_original_screen_id = $screen->id;
238        $screen->id                        = 'jetpack-boost-dashboard';
239    }
240
241    /**
242     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
243     *
244     * @since 4.8.0
245     */
246    public function restore_screen_id_after_wp_build() {
247        $screen = get_current_screen();
248        if ( ! $screen || null === $this->wp_build_original_screen_id ) {
249            return;
250        }
251
252        $screen->id                        = $this->wp_build_original_screen_id;
253        $this->wp_build_original_screen_id = null;
254    }
255
256    /**
257     * Enqueue scripts and styles for the admin page.
258     */
259    public function admin_init() {
260        // Refetch the premium features unless the site features this page loads anyway still match them.
261        $cache_confirmed = Premium_Features::is_cache_confirmed();
262        if ( ! $cache_confirmed ) {
263            Premium_Features::clear_cache();
264        }
265        if ( current_user_can( 'manage_options' ) ) {
266            $already_activated = get_option( Premium_Features::CLOUD_CSS_ACTIVATED_OPTION );
267            Premium_Features::enable_cloud_css_after_upgrade( $cache_confirmed );
268            if ( $this->dashboard_build_loaded && ! $already_activated && get_option( Premium_Features::CLOUD_CSS_ACTIVATED_OPTION ) ) {
269                jetpack_boost_ds_set( 'cloud_css_upgrade_notice', true );
270            }
271        }
272
273        $this->add_enqueue_hooks();
274    }
275
276    /**
277     * Hook the dashboard's scripts, on Boost's own page and in the admin shell's guest endpoint.
278     */
279    private function add_enqueue_hooks() {
280        add_action( 'admin_enqueue_scripts', array( My_Jetpack_Initializer::class, 'enqueue_scripts' ) );
281        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
282    }
283
284    /**
285     * Register the JavaScript for the admin area.
286     *
287     * @since    1.0.0
288     */
289    public function enqueue_scripts() {
290        /**
291         * Filters the internal path to the distributed assets used by the plugin
292         *
293         * @param string $path the path to the assets
294         */
295        $internal_path = apply_filters( 'jetpack_boost_asset_internal_path', 'app/assets/dist/' );
296
297        $admin_js_handle = 'jetpack-boost-admin';
298
299        $admin_js_dependencies = array(
300            'wp-i18n',
301            'wp-components',
302            'my_jetpack_main_app',
303        );
304
305        Assets::register_script(
306            $admin_js_handle,
307            $internal_path . 'jetpack-boost.js',
308            JETPACK_BOOST_PATH,
309            array(
310                'dependencies' => $admin_js_dependencies,
311                'in_footer'    => true,
312                'textdomain'   => 'jetpack-boost',
313                'css_path'     => $internal_path . 'jetpack-boost.css',
314            )
315        );
316
317        wp_localize_script(
318            $admin_js_handle,
319            'Jetpack_Boost',
320            ( new Config() )->constants()
321        );
322
323        Assets::enqueue_script( $admin_js_handle );
324
325        if ( $this->dashboard_build_loaded ) {
326            $this->localize_api_settings( $admin_js_handle );
327            $i18n_loader_registered = wp_script_is( 'wp-jp-i18n-loader', 'registered' );
328            if ( $i18n_loader_registered ) {
329                wp_enqueue_script( 'wp-jp-i18n-loader' );
330            }
331
332            // The webpack handle carries Boost constants and DataSync bootstrap needed before modules run.
333            $prerequisites = wp_scripts()->query( 'jetpack-boost-dashboard-wp-admin-prerequisites', 'registered' );
334            if ( $prerequisites ) {
335                $prerequisites->deps[] = $admin_js_handle;
336                if ( $i18n_loader_registered ) {
337                    $prerequisites->deps[] = 'wp-jp-i18n-loader';
338                }
339            } elseif ( ! wp_doing_ajax() ) {
340                // The admin shell's guest endpoint has no prerequisites handle: the shell runs the bundle before it boots the page.
341                Debug::log( 'Modern dashboard prerequisites are not registered; bootstrap dependencies could not be attached.' );
342            }
343        }
344    }
345
346    /**
347     * Get settings link.
348     *
349     * @param array $links the array of links.
350     */
351    public function plugin_page_settings_link( $links ) {
352        $settings_link = '<a href="' . admin_url( 'admin.php?page=jetpack-boost' ) . '">' . esc_html__( 'Settings', 'jetpack-boost' ) . '</a>';
353        array_unshift( $links, $settings_link );
354
355        return $links;
356    }
357
358    /**
359     * Localize the REST API settings for a script.
360     *
361     * @param string $handle Script handle.
362     */
363    private function localize_api_settings( $handle ) {
364        wp_localize_script(
365            $handle,
366            'wpApiSettings',
367            array(
368                'root'  => esc_url_raw( rest_url() ),
369                'nonce' => wp_create_nonce( 'wp_rest' ),
370            )
371        );
372    }
373
374    /**
375     * Explain why the page is empty when the dashboard build is missing or incomplete.
376     */
377    public function render_missing_build_notice() {
378        ?>
379        <div class="wrap">
380            <div class="notice notice-error">
381                <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>
382            </div>
383        </div>
384        <?php
385    }
386
387    /**
388     * Whether the modern dashboard is enabled. It always is, now that the legacy dashboard is gone.
389     *
390     * @deprecated $$next-version$$
391     *
392     * @return bool Always true.
393     */
394    public static function is_modernization_enabled() {
395        _deprecated_function( __METHOD__, 'jetpack-boost-$$next-version$$' );
396        return true;
397    }
398
399    /**
400     * Render the page body the legacy dashboard used to mount into.
401     *
402     * @deprecated $$next-version$$ Renders the missing-build notice, since the legacy dashboard is gone.
403     */
404    public function render_settings() {
405        _deprecated_function( __METHOD__, 'jetpack-boost-$$next-version$$' );
406        $this->render_missing_build_notice();
407    }
408}