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