Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.03% covered (warning)
78.03%
135 / 173
60.71% covered (warning)
60.71%
17 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
78.95% covered (warning)
78.95%
135 / 171
60.71% covered (warning)
60.71%
17 / 28
106.64
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
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 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\Protect_Status\Status as Protect_Status;
16use Automattic\Jetpack\Status;
17use Automattic\Jetpack\Status\Host;
18use Automattic\Jetpack\Terms_Of_Service;
19use Automattic\Jetpack\Tracking;
20use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
21use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
22
23if ( ! defined( 'ABSPATH' ) ) {
24    exit( 0 );
25}
26
27/**
28 * Registers the Protect sidebar item and renders its wp-build route.
29 */
30class Dashboard {
31
32    /**
33     * Package version, bumped at release through composer.json `version-constants`.
34     *
35     * @var string
36     */
37    const PACKAGE_VERSION = '0.6.0';
38
39    /**
40     * Sidebar menu slug, shared with the Jetpack Protect plugin so the page address never changes.
41     *
42     * @var string
43     */
44    const MENU_SLUG = 'jetpack-protect';
45
46    /**
47     * The wp-build route's page id. It must not be the menu slug: the generated
48     * standalone page.php intercepts `admin_init` for its own id and exits.
49     *
50     * @var string
51     */
52    const WP_BUILD_PAGE_ID = 'jetpack-protect-dashboard';
53
54    /**
55     * Name of the wp-build render function generated for WP_BUILD_PAGE_ID.
56     *
57     * @var string
58     */
59    const RENDER_FUNCTION = 'jetpack_protect_jetpack_protect_dashboard_wp_admin_render_page';
60
61    /**
62     * The settings section that owns each Jetpack security module, for links from other screens.
63     *
64     * @since 0.3.0
65     *
66     * @var array<string, string>
67     */
68    const MODULE_SECTIONS = array(
69        'waf'                => 'firewall',
70        'protect'            => 'loginProtection',
71        'account-protection' => 'loginProtection',
72        'sso'                => 'loginProtection',
73        'monitor'            => 'monitor',
74    );
75
76    /**
77     * The Jetpack filter that sets a module's Configure link, minus the module slug.
78     *
79     * @var string
80     */
81    const CONFIGURATION_URL_FILTER = 'jetpack_module_configuration_url_';
82
83    /**
84     * Extra Admin_Menu item options, such as the module that owns the item.
85     *
86     * @var array
87     */
88    private static $menu_options = array();
89
90    /**
91     * The screen ID alias_screen_id() replaced, until it is restored.
92     *
93     * @var string|null
94     */
95    private static $original_screen_id = null;
96
97    /**
98     * Registered sections, keyed by section key.
99     *
100     * @var Dashboard_Section[]
101     */
102    private static $sections = array();
103
104    /**
105     * Wire the hooks.
106     *
107     * @param array $menu_options Admin_Menu item options merged over the defaults, e.g. `module`.
108     * @return void
109     */
110    public static function init( array $menu_options = array() ) {
111        self::$menu_options = $menu_options;
112
113        add_action( 'admin_init', array( __CLASS__, 'maybe_redirect_threat_report' ) );
114        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
115        // Before Admin_Menu registers its items at 1000, and after the Protect plugin adds its own on `_admin_menu`.
116        add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 999 );
117        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
118        Threat_Count::init();
119        add_action( 'add_option_' . Scan_Status::OPTION_NAME, array( Dashboard_Threats::class, 'prune_on_stored_scan' ), 10, 2 );
120        add_action( 'update_option_' . Scan_Status::OPTION_NAME, array( Dashboard_Threats::class, 'prune_on_stored_scan' ), 10, 2 );
121
122        foreach ( array_keys( self::MODULE_SECTIONS ) as $module ) {
123            add_filter( self::CONFIGURATION_URL_FILTER . $module, array( __CLASS__, 'filter_module_configuration_url' ) );
124            // Firewall and Account protection have no Configure link otherwise.
125            add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
126        }
127
128        self::load_sections( __DIR__ . '/sections' );
129
130        /**
131         * Fires once the Protect dashboard has wired its hooks, so the page exists.
132         *
133         * @since 0.1.0
134         */
135        do_action( 'jetpack_protect_dashboard_initialized' );
136    }
137
138    /**
139     * Register the section class each `class-<name>.php` file in a folder declares.
140     *
141     * Each feature lives in its own file, so features can land independently. The class for
142     * `class-login-protection.php` is `Sections\Login_Protection`; the file must have no side effects,
143     * since the classmap autoloader can also load it.
144     *
145     * @param string $dir Folder holding the section files.
146     * @return void
147     */
148    public static function load_sections( $dir ) {
149        $files = glob( $dir . '/class-*.php' );
150        foreach ( is_array( $files ) ? $files : array() as $file ) {
151            $name  = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', substr( basename( $file, '.php' ), 6 ) ) ) );
152            $class = __NAMESPACE__ . '\\Sections\\' . $name;
153            if ( ! class_exists( $class ) ) {
154                require_once $file;
155            }
156            if ( ! is_subclass_of( $class, Dashboard_Section::class ) || self::has_section_of_class( $class ) ) {
157                continue;
158            }
159            self::register_section( new $class() );
160        }
161    }
162
163    /**
164     * Whether a section of the given class is already registered, so init() can run twice.
165     *
166     * @param string $class Section class name.
167     * @return bool
168     */
169    private static function has_section_of_class( $class ) {
170        foreach ( self::$sections as $section ) {
171            if ( $section instanceof $class ) {
172                return true;
173            }
174        }
175        return false;
176    }
177
178    /**
179     * Add a section to the dashboard.
180     *
181     * @param Dashboard_Section $section The section.
182     * @return void
183     */
184    public static function register_section( Dashboard_Section $section ) {
185        $key = $section->get_key();
186        if ( isset( self::$sections[ $key ] ) ) {
187            /* translators: %s is a dashboard section key. */
188            $message = sprintf( __( 'A Protect page section with the key "%s" is already registered.', 'jetpack-protect-pkg' ), $key );
189            _doing_it_wrong( __METHOD__, esc_html( $message ), '0.1.0' );
190            return;
191        }
192        self::$sections[ $key ] = $section;
193    }
194
195    /**
196     * Register every section's REST routes.
197     *
198     * @return void
199     */
200    public static function register_rest_routes() {
201        foreach ( self::$sections as $section ) {
202            $section->register_routes();
203        }
204    }
205
206    /**
207     * Each section's state, keyed by section key.
208     *
209     * @return array
210     */
211    public static function get_initial_state() {
212        $state = array();
213        foreach ( self::$sections as $key => $section ) {
214            $state[ $key ] = $section->get_state();
215        }
216        return $state;
217    }
218
219    /**
220     * Print each section's state as `window.jetpackProtectDashboard`, for the page's scripts.
221     *
222     * @return void
223     */
224    public static function print_initial_state() {
225        $state = wp_json_encode( (object) self::get_initial_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
226        wp_print_inline_script_tag( 'window.jetpackProtectDashboard = ' . ( false === $state ? '{}' : $state ) . ';' );
227    }
228
229    /**
230     * Whether the current user may see and use the dashboard's REST routes.
231     *
232     * @return bool
233     */
234    public static function can_manage() {
235        return current_user_can( 'manage_options' );
236    }
237
238    /**
239     * The Settings tab's URL, scrolled to a section's card.
240     *
241     * @since 0.3.0
242     *
243     * @param string $section Section key, such as `firewall`; empty for the top of the tab.
244     * @return string
245     */
246    public static function get_settings_url( $section = '' ) {
247        $query = array( 'tab' => 'settings' );
248        if ( '' !== $section ) {
249            $query['section'] = $section;
250        }
251
252        return admin_url( 'admin.php?page=' . self::MENU_SLUG . '&p=' . rawurlencode( '/?' . http_build_query( $query ) ) );
253    }
254
255    /**
256     * Each security module's card on the Settings tab, for screens that link here instead of offering the setting.
257     *
258     * @since 0.3.0
259     *
260     * @return array<string, string> Settings URLs keyed by module slug.
261     */
262    public static function get_module_settings_urls() {
263        return array_map( array( __CLASS__, 'get_settings_url' ), self::MODULE_SECTIONS );
264    }
265
266    /**
267     * Point a security module's Configure link at its card on the Settings tab.
268     *
269     * @since 0.3.0
270     *
271     * @param string $url The URL Jetpack would use.
272     * @return string
273     */
274    public static function filter_module_configuration_url( $url ) {
275        $module = substr( current_filter(), strlen( self::CONFIGURATION_URL_FILTER ) );
276        $urls   = self::get_module_settings_urls();
277
278        return $urls[ $module ] ?? $url;
279    }
280
281    /**
282     * Whether the site has a plan that includes Scan.
283     *
284     * @return bool
285     */
286    public static function has_scan_plan() {
287        return Plan::has_required_plan();
288    }
289
290    /**
291     * Where a site without Scan can buy it.
292     *
293     * @return string
294     */
295    public static function get_scan_upgrade_url() {
296        /** This filter is documented in projects/packages/my-jetpack/src/class-main-features.php */
297        $upgrade = apply_filters(
298            'jetpack_feature_upgrade',
299            array(
300                'path'     => '/add-scan',
301                'name'     => 'Jetpack Scan', // Product name, do not translate.
302                'back_url' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
303            ),
304            'protect-dashboard',
305            false
306        );
307
308        $url = is_array( $upgrade ) ? esc_url_raw( (string) ( $upgrade['url'] ?? '' ) ) : '';
309
310        return $url ? $url : admin_url( 'admin.php?page=my-jetpack#/add-scan' );
311    }
312
313    /**
314     * Whether a module can run on this site, and whether it is on.
315     *
316     * @param string $module Module slug.
317     * @return array
318     */
319    public static function get_module_state( $module ) {
320        $modules = new Modules();
321
322        return array(
323            'available' => $modules->is_module( $module ),
324            'active'    => $modules->is_active( $module ),
325        );
326    }
327
328    /**
329     * Load wp-build output, only on this page's request.
330     *
331     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
332     *
333     * @return void
334     */
335    public static function maybe_load_wp_build() {
336        if ( ! self::is_dashboard_request() ) {
337            return;
338        }
339
340        self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
341        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_tracks_identity' ), 20 );
342        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_tracks_transport' ) );
343    }
344
345    /**
346     * Load the Tracks script that sends queued events; other packages only load it for some plans.
347     *
348     * @return void
349     */
350    public static function enqueue_tracks_transport() {
351        if ( ( new Host() )->is_wpcom_simple() ) {
352            return;
353        }
354
355        if ( ! self::can_use_analytics() ) {
356            return;
357        }
358
359        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
360    }
361
362    /**
363     * Add the connected WordPress.com user to the script data, for Tracks, unless another package already did.
364     *
365     * @param array $data The script data.
366     * @return array
367     */
368    public static function add_tracks_identity( $data ) {
369        if ( ! empty( $data['user']['current_user']['wpcom']['ID'] ) ) {
370            return $data;
371        }
372        $connected = ( new Connection_Manager() )->get_connected_user_data();
373        if ( empty( $connected['ID'] ) || empty( $connected['login'] ) ) {
374            return $data;
375        }
376        $data['user']['current_user']['wpcom'] = array_merge(
377            $data['user']['current_user']['wpcom'] ?? array(),
378            array(
379                'ID'    => $connected['ID'],
380                'login' => $connected['login'],
381            )
382        );
383        return $data;
384    }
385
386    /**
387     * Whether the request is for the dashboard's page.
388     *
389     * @return bool
390     */
391    public static function is_dashboard_request() {
392        return Protect_Status::is_protect_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 page could not be loaded because its assets are missing.', 'jetpack-protect-pkg' )
599        );
600    }
601}