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