Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
71.15% covered (warning)
71.15%
74 / 104
50.00% covered (danger)
50.00%
9 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
72.55% covered (warning)
72.55%
74 / 102
50.00% covered (danger)
50.00%
9 / 18
75.77
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 load_sections
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 has_section_of_class
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 register_section
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 register_rest_routes
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_initial_state
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 print_initial_state
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 can_manage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 has_scan_plan
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_module_state
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 maybe_load_wp_build
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 is_dashboard_request
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 load_wp_build
54.17% covered (warning)
54.17%
13 / 24
0.00% covered (danger)
0.00%
0 / 1
7.41
 alias_screen_id
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 restore_screen_id
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 enqueue_i18n_loader
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 add_menu
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 render
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
2.15
1<?php
2/**
3 * Protect dashboard: a wp-build page in the Jetpack sidebar.
4 *
5 * @package automattic/jetpack-protect
6 */
7
8namespace Automattic\Jetpack\Protect;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Modules;
12use Automattic\Jetpack\Protect_Status\Plan;
13use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
14use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
15
16if ( ! defined( 'ABSPATH' ) ) {
17    exit( 0 );
18}
19
20/**
21 * Registers the Protect sidebar item and renders its wp-build route.
22 */
23class Dashboard {
24
25    /**
26     * Package version, bumped at release through composer.json `version-constants`.
27     *
28     * @var string
29     */
30    const PACKAGE_VERSION = '0.1.0-alpha';
31
32    /**
33     * Sidebar menu slug, shared with the Jetpack Protect plugin so the page address never changes.
34     *
35     * @var string
36     */
37    const MENU_SLUG = 'jetpack-protect';
38
39    /**
40     * The wp-build route's page id. It must not be the menu slug: the generated
41     * standalone page.php intercepts `admin_init` for its own id and exits.
42     *
43     * @var string
44     */
45    const WP_BUILD_PAGE_ID = 'jetpack-protect-dashboard';
46
47    /**
48     * Name of the wp-build render function generated for WP_BUILD_PAGE_ID.
49     *
50     * @var string
51     */
52    const RENDER_FUNCTION = 'jetpack_protect_jetpack_protect_dashboard_wp_admin_render_page';
53
54    /**
55     * Extra Admin_Menu item options, such as the module that owns the item.
56     *
57     * @var array
58     */
59    private static $menu_options = array();
60
61    /**
62     * The screen ID alias_screen_id() replaced, until it is restored.
63     *
64     * @var string|null
65     */
66    private static $original_screen_id = null;
67
68    /**
69     * Registered sections, keyed by section key.
70     *
71     * @var Dashboard_Section[]
72     */
73    private static $sections = array();
74
75    /**
76     * Wire the hooks.
77     *
78     * @param array $menu_options Admin_Menu item options merged over the defaults, e.g. `module`.
79     * @return void
80     */
81    public static function init( array $menu_options = array() ) {
82        self::$menu_options = $menu_options;
83
84        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
85        // Before Admin_Menu registers its items at 1000, and after the Protect plugin adds its own on `_admin_menu`.
86        add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 999 );
87        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
88
89        self::load_sections( __DIR__ . '/sections' );
90
91        /**
92         * Fires once the Protect dashboard has wired its hooks, so the page exists.
93         *
94         * @since $$next-version$$
95         */
96        do_action( 'jetpack_protect_dashboard_initialized' );
97    }
98
99    /**
100     * Register the section class each `class-<name>.php` file in a folder declares.
101     *
102     * Each feature lives in its own file, so features can land independently. The class for
103     * `class-login-protection.php` is `Sections\Login_Protection`; the file must have no side effects,
104     * since the classmap autoloader can also load it.
105     *
106     * @param string $dir Folder holding the section files.
107     * @return void
108     */
109    public static function load_sections( $dir ) {
110        $files = glob( $dir . '/class-*.php' );
111        foreach ( is_array( $files ) ? $files : array() as $file ) {
112            $name  = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', substr( basename( $file, '.php' ), 6 ) ) ) );
113            $class = __NAMESPACE__ . '\\Sections\\' . $name;
114            if ( ! class_exists( $class ) ) {
115                require_once $file;
116            }
117            if ( ! is_subclass_of( $class, Dashboard_Section::class ) || self::has_section_of_class( $class ) ) {
118                continue;
119            }
120            self::register_section( new $class() );
121        }
122    }
123
124    /**
125     * Whether a section of the given class is already registered, so init() can run twice.
126     *
127     * @param string $class Section class name.
128     * @return bool
129     */
130    private static function has_section_of_class( $class ) {
131        foreach ( self::$sections as $section ) {
132            if ( $section instanceof $class ) {
133                return true;
134            }
135        }
136        return false;
137    }
138
139    /**
140     * Add a section to the dashboard.
141     *
142     * @param Dashboard_Section $section The section.
143     * @return void
144     */
145    public static function register_section( Dashboard_Section $section ) {
146        $key = $section->get_key();
147        if ( isset( self::$sections[ $key ] ) ) {
148            /* translators: %s is a dashboard section key. */
149            $message = sprintf( __( 'A Protect dashboard section with the key "%s" is already registered.', 'jetpack-protect-pkg' ), $key );
150            _doing_it_wrong( __METHOD__, esc_html( $message ), '$$next-version$$' );
151            return;
152        }
153        self::$sections[ $key ] = $section;
154    }
155
156    /**
157     * Register every section's REST routes.
158     *
159     * @return void
160     */
161    public static function register_rest_routes() {
162        foreach ( self::$sections as $section ) {
163            $section->register_routes();
164        }
165    }
166
167    /**
168     * Each section's state, keyed by section key.
169     *
170     * @return array
171     */
172    public static function get_initial_state() {
173        $state = array();
174        foreach ( self::$sections as $key => $section ) {
175            $state[ $key ] = $section->get_state();
176        }
177        return $state;
178    }
179
180    /**
181     * Print each section's state as `window.jetpackProtectDashboard`, for the page's scripts.
182     *
183     * @return void
184     */
185    public static function print_initial_state() {
186        $state = wp_json_encode( (object) self::get_initial_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
187        wp_print_inline_script_tag( 'window.jetpackProtectDashboard = ' . ( false === $state ? '{}' : $state ) . ';' );
188    }
189
190    /**
191     * Whether the current user may see and use the dashboard's REST routes.
192     *
193     * @return bool
194     */
195    public static function can_manage() {
196        return current_user_can( 'manage_options' );
197    }
198
199    /**
200     * Whether the site has a plan that includes Scan.
201     *
202     * @return bool
203     */
204    public static function has_scan_plan() {
205        return Plan::has_required_plan();
206    }
207
208    /**
209     * Whether a module can run on this site, and whether it is on.
210     *
211     * @param string $module Module slug.
212     * @return array
213     */
214    public static function get_module_state( $module ) {
215        $modules = new Modules();
216
217        return array(
218            'available' => $modules->is_module( $module ),
219            'active'    => $modules->is_active( $module ),
220        );
221    }
222
223    /**
224     * Load wp-build output, only on this page's request.
225     *
226     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
227     *
228     * @return void
229     */
230    public static function maybe_load_wp_build() {
231        if ( ! self::is_dashboard_request() ) {
232            return;
233        }
234
235        self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
236    }
237
238    /**
239     * Whether the request is for the dashboard's page.
240     *
241     * @return bool
242     */
243    public static function is_dashboard_request() {
244        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
245        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
246    }
247
248    /**
249     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
250     *
251     * @param string $build_index Path to the generated build.php.
252     * @return bool Whether the build can render the page.
253     */
254    public static function load_wp_build( $build_index ) {
255        if ( ! file_exists( $build_index ) ) {
256            return false;
257        }
258
259        $load_wp_build = static function () use ( $build_index ) {
260            require_once $build_index;
261        };
262
263        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
264        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
265            WP_Build_Screen_Id::load_with_alias(
266                array( __CLASS__, 'alias_screen_id' ),
267                array( __CLASS__, 'restore_screen_id' ),
268                $load_wp_build
269            );
270        } else {
271            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
272            $load_wp_build();
273            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
274        }
275
276        // A stale or partial build can't render the page, so don't swap core's scripts for it.
277        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
278            return false;
279        }
280
281        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
282
283        // wp-build hooks module registration to wp_default_scripts, which has already fired by
284        // admin_menu — call it directly or the init module never reaches the import map.
285        if ( function_exists( 'jetpack_protect_register_script_modules' ) ) {
286            jetpack_protect_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
287        }
288
289        WP_Build_Polyfills::register(
290            'jetpack-protect',
291            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
292        );
293
294        return true;
295    }
296
297    /**
298     * Point the screen ID at the wp-build page while its generated enqueue check runs.
299     *
300     * @return void
301     */
302    public static function alias_screen_id() {
303        $screen = get_current_screen();
304        if ( ! $screen ) {
305            return;
306        }
307
308        self::$original_screen_id = $screen->id;
309        $screen->id               = self::WP_BUILD_PAGE_ID;
310    }
311
312    /**
313     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
314     *
315     * @return void
316     */
317    public static function restore_screen_id() {
318        $screen = get_current_screen();
319        if ( ! $screen || null === self::$original_screen_id ) {
320            return;
321        }
322
323        $screen->id               = self::$original_screen_id;
324        self::$original_screen_id = null;
325    }
326
327    /**
328     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
329     *
330     * @return void
331     */
332    public static function enqueue_i18n_loader() {
333        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
334            wp_enqueue_script( 'wp-jp-i18n-loader' );
335        }
336    }
337
338    /**
339     * Add the "Protect" item to the Jetpack sidebar, in place of the Jetpack Protect plugin's.
340     *
341     * @return void
342     */
343    public static function add_menu() {
344        // Take the slug over from the Jetpack Protect plugin: drop its item and the scripts it loads for that page.
345        // The plugin's instance isn't reachable, so this clears every earlier callback on those load hooks, not just its own.
346        while ( Admin_Menu::remove_menu( self::MENU_SLUG ) ) {
347            continue;
348        }
349        remove_all_actions( 'load-jetpack_page_' . self::MENU_SLUG );
350        remove_all_actions( 'load-admin_page_' . self::MENU_SLUG );
351
352        Admin_Menu::add_menu(
353            // "Protect" is a product name and is not translated.
354            'Protect',
355            'Protect',
356            'manage_options',
357            self::MENU_SLUG,
358            array( __CLASS__, 'render' ),
359            null,
360            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
361        );
362    }
363
364    /**
365     * Render the wp-build page, or say why it could not be rendered.
366     *
367     * @return void
368     */
369    public static function render() {
370        $render_fn = self::RENDER_FUNCTION;
371        if ( function_exists( $render_fn ) ) {
372            self::print_initial_state();
373            // @phan-suppress-next-line PhanUndeclaredFunctionInCallable -- Checked with function_exists(); defined in the generated build/, which Phan excludes.
374            $render_fn();
375            return;
376        }
377
378        printf(
379            '<div class="wrap"><h1>Protect</h1><div class="notice notice-error"><p>%s</p></div></div>',
380            esc_html__( 'The Protect dashboard could not be loaded because its assets are missing.', 'jetpack-protect-pkg' )
381        );
382    }
383}