Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.36% covered (warning)
78.36%
134 / 171
64.29% covered (warning)
64.29%
18 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
79.29% covered (warning)
79.29%
134 / 169
64.29% covered (warning)
64.29%
18 / 28
106.87
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
11 / 11
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_scan_upgrade_url
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 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 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_tracks_transport
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 add_tracks_identity
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 is_dashboard_request
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 maybe_redirect_threat_report
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 get_threat_report_redirect
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
 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
 can_use_analytics
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 print_tracks_state
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 add_menu
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 render
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
2.26
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\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Modules;
13use Automattic\Jetpack\Protect_Status\Plan;
14use Automattic\Jetpack\Status;
15use Automattic\Jetpack\Status\Host;
16use Automattic\Jetpack\Terms_Of_Service;
17use Automattic\Jetpack\Tracking;
18use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
19use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
20
21if ( ! defined( 'ABSPATH' ) ) {
22    exit( 0 );
23}
24
25/**
26 * Registers the Protect sidebar item and renders its wp-build route.
27 */
28class Dashboard {
29
30    /**
31     * Package version, bumped at release through composer.json `version-constants`.
32     *
33     * @var string
34     */
35    const PACKAGE_VERSION = '0.3.0';
36
37    /**
38     * Sidebar menu slug, shared with the Jetpack Protect plugin so the page address never changes.
39     *
40     * @var string
41     */
42    const MENU_SLUG = 'jetpack-protect';
43
44    /**
45     * The wp-build route's page id. It must not be the menu slug: the generated
46     * standalone page.php intercepts `admin_init` for its own id and exits.
47     *
48     * @var string
49     */
50    const WP_BUILD_PAGE_ID = 'jetpack-protect-dashboard';
51
52    /**
53     * Name of the wp-build render function generated for WP_BUILD_PAGE_ID.
54     *
55     * @var string
56     */
57    const RENDER_FUNCTION = 'jetpack_protect_jetpack_protect_dashboard_wp_admin_render_page';
58
59    /**
60     * The settings section that owns each Jetpack security module, for links from other screens.
61     *
62     * @since 0.3.0
63     *
64     * @var array<string, string>
65     */
66    const MODULE_SECTIONS = array(
67        'waf'                => 'firewall',
68        'protect'            => 'loginProtection',
69        'account-protection' => 'loginProtection',
70        'sso'                => 'loginProtection',
71        'monitor'            => 'monitor',
72    );
73
74    /**
75     * The Jetpack filter that sets a module's Configure link, minus the module slug.
76     *
77     * @var string
78     */
79    const CONFIGURATION_URL_FILTER = 'jetpack_module_configuration_url_';
80
81    /**
82     * Extra Admin_Menu item options, such as the module that owns the item.
83     *
84     * @var array
85     */
86    private static $menu_options = array();
87
88    /**
89     * The screen ID alias_screen_id() replaced, until it is restored.
90     *
91     * @var string|null
92     */
93    private static $original_screen_id = null;
94
95    /**
96     * Registered sections, keyed by section key.
97     *
98     * @var Dashboard_Section[]
99     */
100    private static $sections = array();
101
102    /**
103     * Wire the hooks.
104     *
105     * @param array $menu_options Admin_Menu item options merged over the defaults, e.g. `module`.
106     * @return void
107     */
108    public static function init( array $menu_options = array() ) {
109        self::$menu_options = $menu_options;
110
111        add_action( 'admin_init', array( __CLASS__, 'maybe_redirect_threat_report' ) );
112        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
113        // Before Admin_Menu registers its items at 1000, and after the Protect plugin adds its own on `_admin_menu`.
114        add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 999 );
115        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
116        Threat_Count::init();
117
118        foreach ( array_keys( self::MODULE_SECTIONS ) as $module ) {
119            add_filter( self::CONFIGURATION_URL_FILTER . $module, array( __CLASS__, 'filter_module_configuration_url' ) );
120            // Firewall and Account protection have no Configure link otherwise.
121            add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
122        }
123
124        self::load_sections( __DIR__ . '/sections' );
125
126        /**
127         * Fires once the Protect dashboard has wired its hooks, so the page exists.
128         *
129         * @since 0.1.0
130         */
131        do_action( 'jetpack_protect_dashboard_initialized' );
132    }
133
134    /**
135     * Register the section class each `class-<name>.php` file in a folder declares.
136     *
137     * Each feature lives in its own file, so features can land independently. The class for
138     * `class-login-protection.php` is `Sections\Login_Protection`; the file must have no side effects,
139     * since the classmap autoloader can also load it.
140     *
141     * @param string $dir Folder holding the section files.
142     * @return void
143     */
144    public static function load_sections( $dir ) {
145        $files = glob( $dir . '/class-*.php' );
146        foreach ( is_array( $files ) ? $files : array() as $file ) {
147            $name  = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', substr( basename( $file, '.php' ), 6 ) ) ) );
148            $class = __NAMESPACE__ . '\\Sections\\' . $name;
149            if ( ! class_exists( $class ) ) {
150                require_once $file;
151            }
152            if ( ! is_subclass_of( $class, Dashboard_Section::class ) || self::has_section_of_class( $class ) ) {
153                continue;
154            }
155            self::register_section( new $class() );
156        }
157    }
158
159    /**
160     * Whether a section of the given class is already registered, so init() can run twice.
161     *
162     * @param string $class Section class name.
163     * @return bool
164     */
165    private static function has_section_of_class( $class ) {
166        foreach ( self::$sections as $section ) {
167            if ( $section instanceof $class ) {
168                return true;
169            }
170        }
171        return false;
172    }
173
174    /**
175     * Add a section to the dashboard.
176     *
177     * @param Dashboard_Section $section The section.
178     * @return void
179     */
180    public static function register_section( Dashboard_Section $section ) {
181        $key = $section->get_key();
182        if ( isset( self::$sections[ $key ] ) ) {
183            /* translators: %s is a dashboard section key. */
184            $message = sprintf( __( 'A Protect dashboard section with the key "%s" is already registered.', 'jetpack-protect-pkg' ), $key );
185            _doing_it_wrong( __METHOD__, esc_html( $message ), '0.1.0' );
186            return;
187        }
188        self::$sections[ $key ] = $section;
189    }
190
191    /**
192     * Register every section's REST routes.
193     *
194     * @return void
195     */
196    public static function register_rest_routes() {
197        foreach ( self::$sections as $section ) {
198            $section->register_routes();
199        }
200    }
201
202    /**
203     * Each section's state, keyed by section key.
204     *
205     * @return array
206     */
207    public static function get_initial_state() {
208        $state = array();
209        foreach ( self::$sections as $key => $section ) {
210            $state[ $key ] = $section->get_state();
211        }
212        return $state;
213    }
214
215    /**
216     * Print each section's state as `window.jetpackProtectDashboard`, for the page's scripts.
217     *
218     * @return void
219     */
220    public static function print_initial_state() {
221        $state = wp_json_encode( (object) self::get_initial_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
222        wp_print_inline_script_tag( 'window.jetpackProtectDashboard = ' . ( false === $state ? '{}' : $state ) . ';' );
223    }
224
225    /**
226     * Whether the current user may see and use the dashboard's REST routes.
227     *
228     * @return bool
229     */
230    public static function can_manage() {
231        return current_user_can( 'manage_options' );
232    }
233
234    /**
235     * The Settings tab's URL, scrolled to a section's card.
236     *
237     * @since 0.3.0
238     *
239     * @param string $section Section key, such as `firewall`; empty for the top of the tab.
240     * @return string
241     */
242    public static function get_settings_url( $section = '' ) {
243        $query = array( 'tab' => 'settings' );
244        if ( '' !== $section ) {
245            $query['section'] = $section;
246        }
247
248        return admin_url( 'admin.php?page=' . self::MENU_SLUG . '&p=' . rawurlencode( '/?' . http_build_query( $query ) ) );
249    }
250
251    /**
252     * Each security module's card on the Settings tab, for screens that link here instead of offering the setting.
253     *
254     * @since 0.3.0
255     *
256     * @return array<string, string> Settings URLs keyed by module slug.
257     */
258    public static function get_module_settings_urls() {
259        return array_map( array( __CLASS__, 'get_settings_url' ), self::MODULE_SECTIONS );
260    }
261
262    /**
263     * Point a security module's Configure link at its card on the Settings tab.
264     *
265     * @since 0.3.0
266     *
267     * @param string $url The URL Jetpack would use.
268     * @return string
269     */
270    public static function filter_module_configuration_url( $url ) {
271        $module = substr( current_filter(), strlen( self::CONFIGURATION_URL_FILTER ) );
272        $urls   = self::get_module_settings_urls();
273
274        return $urls[ $module ] ?? $url;
275    }
276
277    /**
278     * Whether the site has a plan that includes Scan.
279     *
280     * @return bool
281     */
282    public static function has_scan_plan() {
283        return Plan::has_required_plan();
284    }
285
286    /**
287     * Where a site without Scan can buy it.
288     *
289     * @return string
290     */
291    public static function get_scan_upgrade_url() {
292        /** This filter is documented in projects/packages/my-jetpack/src/class-main-features.php */
293        $upgrade = apply_filters(
294            'jetpack_feature_upgrade',
295            array(
296                'path'     => '/add-scan',
297                'name'     => 'Jetpack Scan', // Product name, do not translate.
298                'back_url' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
299            ),
300            'protect-dashboard',
301            false
302        );
303
304        $url = is_array( $upgrade ) ? esc_url_raw( (string) ( $upgrade['url'] ?? '' ) ) : '';
305
306        return $url ? $url : admin_url( 'admin.php?page=my-jetpack#/add-scan' );
307    }
308
309    /**
310     * Whether a module can run on this site, and whether it is on.
311     *
312     * @param string $module Module slug.
313     * @return array
314     */
315    public static function get_module_state( $module ) {
316        $modules = new Modules();
317
318        return array(
319            'available' => $modules->is_module( $module ),
320            'active'    => $modules->is_active( $module ),
321        );
322    }
323
324    /**
325     * Load wp-build output, only on this page's request.
326     *
327     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
328     *
329     * @return void
330     */
331    public static function maybe_load_wp_build() {
332        if ( ! self::is_dashboard_request() ) {
333            return;
334        }
335
336        self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
337        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_tracks_identity' ), 20 );
338        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_tracks_transport' ) );
339    }
340
341    /**
342     * Load the Tracks script that sends queued events; other packages only load it for some plans.
343     *
344     * @return void
345     */
346    public static function enqueue_tracks_transport() {
347        if ( ( new Host() )->is_wpcom_simple() ) {
348            return;
349        }
350
351        if ( ! self::can_use_analytics() ) {
352            return;
353        }
354
355        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
356    }
357
358    /**
359     * Add the connected WordPress.com user to the script data, for Tracks, unless another package already did.
360     *
361     * @param array $data The script data.
362     * @return array
363     */
364    public static function add_tracks_identity( $data ) {
365        if ( ! empty( $data['user']['current_user']['wpcom']['ID'] ) ) {
366            return $data;
367        }
368        $connected = ( new Connection_Manager() )->get_connected_user_data();
369        if ( empty( $connected['ID'] ) || empty( $connected['login'] ) ) {
370            return $data;
371        }
372        $data['user']['current_user']['wpcom'] = array_merge(
373            $data['user']['current_user']['wpcom'] ?? array(),
374            array(
375                'ID'    => $connected['ID'],
376                'login' => $connected['login'],
377            )
378        );
379        return $data;
380    }
381
382    /**
383     * Whether the request is for the dashboard's page.
384     *
385     * @return bool
386     */
387    public static function is_dashboard_request() {
388        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
389        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
390    }
391
392    /**
393     * Send a `&threats=` link, such as a threat email's, to the route that reads it.
394     *
395     * @return void
396     */
397    public static function maybe_redirect_threat_report() {
398        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only redirects; nothing is changed.
399        $redirect = self::is_dashboard_request() ? self::get_threat_report_redirect( wp_unslash( $_GET ) ) : null;
400        if ( $redirect ) {
401            wp_safe_redirect( $redirect );
402            exit( 0 );
403        }
404    }
405
406    /**
407     * The threat report URL for a request whose top-level `threats` param lists threat ids.
408     *
409     * The wp-build router reads search params only from inside `p`, so links name the ids at the top level instead.
410     *
411     * @since 0.3.0
412     *
413     * @param array $query The request's query args.
414     * @return string|null The URL, or null when the request needs no redirect.
415     */
416    public static function get_threat_report_redirect( array $query ) {
417        if ( isset( $query['p'] ) || ! isset( $query['threats'] ) || ! is_string( $query['threats'] ) ) {
418            return null;
419        }
420        // Drop any id that isn't all digits, as the client does, rather than merging what's left of it.
421        $ids = array_filter( array_map( 'trim', explode( ',', $query['threats'] ) ), 'ctype_digit' );
422        if ( ! $ids ) {
423            return null;
424        }
425        return add_query_arg(
426            array(
427                'page' => self::MENU_SLUG,
428                'p'    => rawurlencode( '/?threats=' . implode( ',', $ids ) ),
429            ),
430            admin_url( 'admin.php' )
431        );
432    }
433
434    /**
435     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
436     *
437     * @param string $build_index Path to the generated build.php.
438     * @return bool Whether the build can render the page.
439     */
440    public static function load_wp_build( $build_index ) {
441        if ( ! file_exists( $build_index ) ) {
442            return false;
443        }
444
445        $load_wp_build = static function () use ( $build_index ) {
446            require_once $build_index;
447        };
448
449        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
450        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
451            WP_Build_Screen_Id::load_with_alias(
452                array( __CLASS__, 'alias_screen_id' ),
453                array( __CLASS__, 'restore_screen_id' ),
454                $load_wp_build
455            );
456        } else {
457            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
458            $load_wp_build();
459            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
460        }
461
462        // A stale or partial build can't render the page, so don't swap core's scripts for it.
463        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
464            return false;
465        }
466
467        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
468
469        // wp-build hooks module registration to wp_default_scripts, which has already fired by
470        // admin_menu — call it directly or the init module never reaches the import map.
471        if ( function_exists( 'jetpack_protect_register_script_modules' ) ) {
472            jetpack_protect_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
473        }
474
475        WP_Build_Polyfills::register(
476            'jetpack-protect',
477            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
478        );
479
480        return true;
481    }
482
483    /**
484     * Point the screen ID at the wp-build page while its generated enqueue check runs.
485     *
486     * @return void
487     */
488    public static function alias_screen_id() {
489        $screen = get_current_screen();
490        if ( ! $screen ) {
491            return;
492        }
493
494        self::$original_screen_id = $screen->id;
495        $screen->id               = self::WP_BUILD_PAGE_ID;
496    }
497
498    /**
499     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
500     *
501     * @return void
502     */
503    public static function restore_screen_id() {
504        $screen = get_current_screen();
505        if ( ! $screen || null === self::$original_screen_id ) {
506            return;
507        }
508
509        $screen->id               = self::$original_screen_id;
510        self::$original_screen_id = null;
511    }
512
513    /**
514     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
515     *
516     * @return void
517     */
518    public static function enqueue_i18n_loader() {
519        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
520            wp_enqueue_script( 'wp-jp-i18n-loader' );
521        }
522    }
523
524    /**
525     * Whether the site and user allow Tracks, as on Jetpack's other admin pages.
526     *
527     * @since 0.3.0
528     *
529     * @return bool
530     */
531    public static function can_use_analytics() {
532        $tracking = new Tracking( 'jetpack', new Connection_Manager( 'jetpack' ) );
533
534        return $tracking->should_enable_tracking( new Terms_Of_Service(), new Status() );
535    }
536
537    /**
538     * Print the flag the page's Tracks client records under, only when Tracks is allowed.
539     *
540     * @since 0.3.0
541     *
542     * @return void
543     */
544    public static function print_tracks_state() {
545        if ( self::can_use_analytics() ) {
546            wp_print_inline_script_tag( 'window.jetpackProtectTracks = true;' );
547        }
548    }
549
550    /**
551     * Add the "Protect" item to the Jetpack sidebar, in place of the Jetpack Protect plugin's.
552     *
553     * @return void
554     */
555    public static function add_menu() {
556        // Take the slug over from the Jetpack Protect plugin: drop its item and the scripts it loads for that page.
557        // The plugin's instance isn't reachable, so this clears every earlier callback on those load hooks, not just its own.
558        while ( Admin_Menu::remove_menu( self::MENU_SLUG ) ) {
559            continue;
560        }
561        remove_all_actions( 'load-jetpack_page_' . self::MENU_SLUG );
562        remove_all_actions( 'load-admin_page_' . self::MENU_SLUG );
563
564        Admin_Menu::add_menu(
565            // "Protect" is a product name and is not translated.
566            'Protect',
567            'Protect',
568            'manage_options',
569            self::MENU_SLUG,
570            array( __CLASS__, 'render' ),
571            null,
572            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
573        );
574
575        Threat_Count::register_menu_badge();
576    }
577
578    /**
579     * Render the wp-build page, or say why it could not be rendered.
580     *
581     * @return void
582     */
583    public static function render() {
584        $render_fn = self::RENDER_FUNCTION;
585        if ( function_exists( $render_fn ) ) {
586            self::print_initial_state();
587            self::print_tracks_state();
588            // @phan-suppress-next-line PhanUndeclaredFunctionInCallable -- Checked with function_exists(); defined in the generated build/, which Phan excludes.
589            $render_fn();
590            return;
591        }
592
593        printf(
594            '<div class="wrap"><h1>Protect</h1><div class="notice notice-error"><p>%s</p></div></div>',
595            esc_html__( 'The Protect dashboard could not be loaded because its assets are missing.', 'jetpack-protect-pkg' )
596        );
597    }
598}