Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.21% covered (warning)
75.21%
88 / 117
61.90% covered (warning)
61.90%
13 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
76.52% covered (warning)
76.52%
88 / 115
61.90% covered (warning)
61.90%
13 / 21
73.39
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 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
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_settings_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_module_settings_urls
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 filter_module_configuration_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 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%
14 / 14
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';
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     * The settings section that owns each Jetpack security module, for links from other screens.
56     *
57     * @since $$next-version$$
58     *
59     * @var array<string, string>
60     */
61    const MODULE_SECTIONS = array(
62        'waf'                => 'firewall',
63        'protect'            => 'loginProtection',
64        'account-protection' => 'loginProtection',
65        'sso'                => 'loginProtection',
66        'monitor'            => 'monitor',
67    );
68
69    /**
70     * The Jetpack filter that sets a module's Configure link, minus the module slug.
71     *
72     * @var string
73     */
74    const CONFIGURATION_URL_FILTER = 'jetpack_module_configuration_url_';
75
76    /**
77     * Extra Admin_Menu item options, such as the module that owns the item.
78     *
79     * @var array
80     */
81    private static $menu_options = array();
82
83    /**
84     * The screen ID alias_screen_id() replaced, until it is restored.
85     *
86     * @var string|null
87     */
88    private static $original_screen_id = null;
89
90    /**
91     * Registered sections, keyed by section key.
92     *
93     * @var Dashboard_Section[]
94     */
95    private static $sections = array();
96
97    /**
98     * Wire the hooks.
99     *
100     * @param array $menu_options Admin_Menu item options merged over the defaults, e.g. `module`.
101     * @return void
102     */
103    public static function init( array $menu_options = array() ) {
104        self::$menu_options = $menu_options;
105
106        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
107        // Before Admin_Menu registers its items at 1000, and after the Protect plugin adds its own on `_admin_menu`.
108        add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 999 );
109        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
110        Threat_Count::init();
111
112        foreach ( array_keys( self::MODULE_SECTIONS ) as $module ) {
113            add_filter( self::CONFIGURATION_URL_FILTER . $module, array( __CLASS__, 'filter_module_configuration_url' ) );
114            // Firewall and Account protection have no Configure link otherwise.
115            add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
116        }
117
118        self::load_sections( __DIR__ . '/sections' );
119
120        /**
121         * Fires once the Protect dashboard has wired its hooks, so the page exists.
122         *
123         * @since 0.1.0
124         */
125        do_action( 'jetpack_protect_dashboard_initialized' );
126    }
127
128    /**
129     * Register the section class each `class-<name>.php` file in a folder declares.
130     *
131     * Each feature lives in its own file, so features can land independently. The class for
132     * `class-login-protection.php` is `Sections\Login_Protection`; the file must have no side effects,
133     * since the classmap autoloader can also load it.
134     *
135     * @param string $dir Folder holding the section files.
136     * @return void
137     */
138    public static function load_sections( $dir ) {
139        $files = glob( $dir . '/class-*.php' );
140        foreach ( is_array( $files ) ? $files : array() as $file ) {
141            $name  = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', substr( basename( $file, '.php' ), 6 ) ) ) );
142            $class = __NAMESPACE__ . '\\Sections\\' . $name;
143            if ( ! class_exists( $class ) ) {
144                require_once $file;
145            }
146            if ( ! is_subclass_of( $class, Dashboard_Section::class ) || self::has_section_of_class( $class ) ) {
147                continue;
148            }
149            self::register_section( new $class() );
150        }
151    }
152
153    /**
154     * Whether a section of the given class is already registered, so init() can run twice.
155     *
156     * @param string $class Section class name.
157     * @return bool
158     */
159    private static function has_section_of_class( $class ) {
160        foreach ( self::$sections as $section ) {
161            if ( $section instanceof $class ) {
162                return true;
163            }
164        }
165        return false;
166    }
167
168    /**
169     * Add a section to the dashboard.
170     *
171     * @param Dashboard_Section $section The section.
172     * @return void
173     */
174    public static function register_section( Dashboard_Section $section ) {
175        $key = $section->get_key();
176        if ( isset( self::$sections[ $key ] ) ) {
177            /* translators: %s is a dashboard section key. */
178            $message = sprintf( __( 'A Protect dashboard section with the key "%s" is already registered.', 'jetpack-protect-pkg' ), $key );
179            _doing_it_wrong( __METHOD__, esc_html( $message ), '0.1.0' );
180            return;
181        }
182        self::$sections[ $key ] = $section;
183    }
184
185    /**
186     * Register every section's REST routes.
187     *
188     * @return void
189     */
190    public static function register_rest_routes() {
191        foreach ( self::$sections as $section ) {
192            $section->register_routes();
193        }
194    }
195
196    /**
197     * Each section's state, keyed by section key.
198     *
199     * @return array
200     */
201    public static function get_initial_state() {
202        $state = array();
203        foreach ( self::$sections as $key => $section ) {
204            $state[ $key ] = $section->get_state();
205        }
206        return $state;
207    }
208
209    /**
210     * Print each section's state as `window.jetpackProtectDashboard`, for the page's scripts.
211     *
212     * @return void
213     */
214    public static function print_initial_state() {
215        $state = wp_json_encode( (object) self::get_initial_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
216        wp_print_inline_script_tag( 'window.jetpackProtectDashboard = ' . ( false === $state ? '{}' : $state ) . ';' );
217    }
218
219    /**
220     * Whether the current user may see and use the dashboard's REST routes.
221     *
222     * @return bool
223     */
224    public static function can_manage() {
225        return current_user_can( 'manage_options' );
226    }
227
228    /**
229     * The Settings tab's URL, scrolled to a section's card.
230     *
231     * @since $$next-version$$
232     *
233     * @param string $section Section key, such as `firewall`; empty for the top of the tab.
234     * @return string
235     */
236    public static function get_settings_url( $section = '' ) {
237        $query = array( 'tab' => 'settings' );
238        if ( '' !== $section ) {
239            $query['section'] = $section;
240        }
241
242        return admin_url( 'admin.php?page=' . self::MENU_SLUG . '&p=' . rawurlencode( '/?' . http_build_query( $query ) ) );
243    }
244
245    /**
246     * Each security module's card on the Settings tab, for screens that link here instead of offering the setting.
247     *
248     * @since $$next-version$$
249     *
250     * @return array<string, string> Settings URLs keyed by module slug.
251     */
252    public static function get_module_settings_urls() {
253        return array_map( array( __CLASS__, 'get_settings_url' ), self::MODULE_SECTIONS );
254    }
255
256    /**
257     * Point a security module's Configure link at its card on the Settings tab.
258     *
259     * @since $$next-version$$
260     *
261     * @param string $url The URL Jetpack would use.
262     * @return string
263     */
264    public static function filter_module_configuration_url( $url ) {
265        $module = substr( current_filter(), strlen( self::CONFIGURATION_URL_FILTER ) );
266        $urls   = self::get_module_settings_urls();
267
268        return $urls[ $module ] ?? $url;
269    }
270
271    /**
272     * Whether the site has a plan that includes Scan.
273     *
274     * @return bool
275     */
276    public static function has_scan_plan() {
277        return Plan::has_required_plan();
278    }
279
280    /**
281     * Whether a module can run on this site, and whether it is on.
282     *
283     * @param string $module Module slug.
284     * @return array
285     */
286    public static function get_module_state( $module ) {
287        $modules = new Modules();
288
289        return array(
290            'available' => $modules->is_module( $module ),
291            'active'    => $modules->is_active( $module ),
292        );
293    }
294
295    /**
296     * Load wp-build output, only on this page's request.
297     *
298     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
299     *
300     * @return void
301     */
302    public static function maybe_load_wp_build() {
303        if ( ! self::is_dashboard_request() ) {
304            return;
305        }
306
307        self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
308    }
309
310    /**
311     * Whether the request is for the dashboard's page.
312     *
313     * @return bool
314     */
315    public static function is_dashboard_request() {
316        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
317        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
318    }
319
320    /**
321     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
322     *
323     * @param string $build_index Path to the generated build.php.
324     * @return bool Whether the build can render the page.
325     */
326    public static function load_wp_build( $build_index ) {
327        if ( ! file_exists( $build_index ) ) {
328            return false;
329        }
330
331        $load_wp_build = static function () use ( $build_index ) {
332            require_once $build_index;
333        };
334
335        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
336        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
337            WP_Build_Screen_Id::load_with_alias(
338                array( __CLASS__, 'alias_screen_id' ),
339                array( __CLASS__, 'restore_screen_id' ),
340                $load_wp_build
341            );
342        } else {
343            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
344            $load_wp_build();
345            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
346        }
347
348        // A stale or partial build can't render the page, so don't swap core's scripts for it.
349        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
350            return false;
351        }
352
353        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
354
355        // wp-build hooks module registration to wp_default_scripts, which has already fired by
356        // admin_menu — call it directly or the init module never reaches the import map.
357        if ( function_exists( 'jetpack_protect_register_script_modules' ) ) {
358            jetpack_protect_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
359        }
360
361        WP_Build_Polyfills::register(
362            'jetpack-protect',
363            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
364        );
365
366        return true;
367    }
368
369    /**
370     * Point the screen ID at the wp-build page while its generated enqueue check runs.
371     *
372     * @return void
373     */
374    public static function alias_screen_id() {
375        $screen = get_current_screen();
376        if ( ! $screen ) {
377            return;
378        }
379
380        self::$original_screen_id = $screen->id;
381        $screen->id               = self::WP_BUILD_PAGE_ID;
382    }
383
384    /**
385     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
386     *
387     * @return void
388     */
389    public static function restore_screen_id() {
390        $screen = get_current_screen();
391        if ( ! $screen || null === self::$original_screen_id ) {
392            return;
393        }
394
395        $screen->id               = self::$original_screen_id;
396        self::$original_screen_id = null;
397    }
398
399    /**
400     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
401     *
402     * @return void
403     */
404    public static function enqueue_i18n_loader() {
405        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
406            wp_enqueue_script( 'wp-jp-i18n-loader' );
407        }
408    }
409
410    /**
411     * Add the "Protect" item to the Jetpack sidebar, in place of the Jetpack Protect plugin's.
412     *
413     * @return void
414     */
415    public static function add_menu() {
416        // Take the slug over from the Jetpack Protect plugin: drop its item and the scripts it loads for that page.
417        // The plugin's instance isn't reachable, so this clears every earlier callback on those load hooks, not just its own.
418        while ( Admin_Menu::remove_menu( self::MENU_SLUG ) ) {
419            continue;
420        }
421        remove_all_actions( 'load-jetpack_page_' . self::MENU_SLUG );
422        remove_all_actions( 'load-admin_page_' . self::MENU_SLUG );
423
424        Admin_Menu::add_menu(
425            // "Protect" is a product name and is not translated.
426            'Protect',
427            'Protect',
428            'manage_options',
429            self::MENU_SLUG,
430            array( __CLASS__, 'render' ),
431            null,
432            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
433        );
434
435        Threat_Count::register_menu_badge();
436    }
437
438    /**
439     * Render the wp-build page, or say why it could not be rendered.
440     *
441     * @return void
442     */
443    public static function render() {
444        $render_fn = self::RENDER_FUNCTION;
445        if ( function_exists( $render_fn ) ) {
446            self::print_initial_state();
447            // @phan-suppress-next-line PhanUndeclaredFunctionInCallable -- Checked with function_exists(); defined in the generated build/, which Phan excludes.
448            $render_fn();
449            return;
450        }
451
452        printf(
453            '<div class="wrap"><h1>Protect</h1><div class="notice notice-error"><p>%s</p></div></div>',
454            esc_html__( 'The Protect dashboard could not be loaded because its assets are missing.', 'jetpack-protect-pkg' )
455        );
456    }
457}