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