Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.60% covered (warning)
87.60%
325 / 371
78.38% covered (warning)
78.38%
29 / 37
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin_Shell
87.60% covered (warning)
87.60%
325 / 371
78.38% covered (warning)
78.38%
29 / 37
260.54
0.00% covered (danger)
0.00%
0 / 1
 register_feature_flag
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 init
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 is_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_members
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 requested_guest
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
8
 get_host
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolve_host
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
9
 screen_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 setup
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
7
 enqueue_client
21.43% covered (danger)
21.43%
3 / 14
0.00% covered (danger)
0.00%
0 / 1
3.94
 load_guest
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 run_page_init
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 add_guest_dependencies
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 get_client_config
100.00% covered (success)
100.00%
46 / 46
100.00% covered (success)
100.00%
1 / 1
6
 feature_gate
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 ajax_feature
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
240
 feature_off_card
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 feature
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
11
 stands_in
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 can_turn_on
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_member_gate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 gate_action
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 max_live_apps
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 admin_title
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
9.16
 ajax_guest_assets
16.67% covered (danger)
16.67%
1 / 6
0.00% covered (danger)
0.00%
0 / 1
4.31
 guest_assets
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
6
 register_admin_menu_pages
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
9.02
 guard_api_fetch_setup
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
6.10
 fire_print_hook
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
11
 is_core_callback
80.00% covered (warning)
80.00%
16 / 20
0.00% covered (danger)
0.00%
0 / 1
9.65
 hook_snapshot
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 added_keys
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 added_callbacks
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
6
 remove_added_callbacks
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 normalize_member
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
21
 is_header
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
7
 is_string_list
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2/**
3 * Admin shell: switch between Jetpack wp-build dashboards without a page load.
4 *
5 * @package automattic/jetpack-admin-ui
6 */
7
8namespace Automattic\Jetpack\Admin_UI;
9
10use Automattic\Jetpack\Feature_Flags\Feature_Flags;
11
12/**
13 * Decides whether the admin shell is on, and which dashboards have joined it.
14 */
15class Admin_Shell {
16
17    /**
18     * Feature flag that turns the shell on. Off by default.
19     */
20    const FLAG = 'jetpack-admin-shell';
21
22    /**
23     * Query argument that turns the shell off for one request when set to `0`.
24     */
25    const DISABLE_QUERY_ARG = 'jetpack_admin_shell';
26
27    /**
28     * Member keys that must be non-empty strings.
29     */
30    const REQUIRED_STRING_KEYS = array( 'build_prefix', 'build_page', 'title' );
31
32    /**
33     * The admin-ajax action that returns a guest's page data.
34     */
35    const GUEST_ACTION = 'jetpack_admin_shell_guest';
36
37    /**
38     * The admin-ajax action that says whether a member's feature is on, and turns it on.
39     */
40    const FEATURE_ACTION = 'jetpack_admin_shell_feature';
41
42    /**
43     * Script module ID of the client.
44     */
45    const CLIENT_MODULE = '@automattic/jetpack-admin-shell';
46
47    /**
48     * Hooks where guests add their page data. On a host page, callbacks a guest adds here are removed: the guest endpoint runs them later.
49     */
50    const DEFERRED_HOOKS = array( 'admin_enqueue_scripts', 'admin_print_scripts', 'admin_print_footer_scripts', 'jetpack_admin_js_script_data' );
51
52    /**
53     * Whether init() has run.
54     *
55     * @var bool
56     */
57    private static $initialized = false;
58
59    /**
60     * Register the feature flag.
61     *
62     * @return void
63     */
64    public static function register_feature_flag() {
65        Feature_Flags::register(
66            self::FLAG,
67            array(
68                'default'     => false,
69                'description' => 'Switch between Jetpack dashboards in wp-admin without a page load.',
70                'owner'       => 'jetpack-admin-ui',
71            )
72        );
73    }
74
75    /**
76     * Hook the shell up. Each hook checks is_enabled() itself, so this is safe to call on every request.
77     *
78     * @return void
79     */
80    public static function init() {
81        if ( self::$initialized ) {
82            return;
83        }
84        self::$initialized = true;
85
86        // Priority 0: guests must register their modules before the host page builds its import map.
87        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'setup' ), 0 );
88        add_action( 'wp_ajax_' . self::GUEST_ACTION, array( __CLASS__, 'ajax_guest_assets' ) );
89        add_action( 'wp_ajax_' . self::FEATURE_ACTION, array( __CLASS__, 'ajax_feature' ) );
90        // Plugins call init() on admin-ajax requests too, where the shell's members load the media library.
91        Media_Library::init();
92    }
93
94    /**
95     * Whether the shell is on for this request.
96     *
97     * @return bool
98     */
99    public static function is_enabled() {
100        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only opt-out; it can only turn the shell off.
101        if ( isset( $_GET[ self::DISABLE_QUERY_ARG ] ) && '0' === $_GET[ self::DISABLE_QUERY_ARG ] ) {
102            return false;
103        }
104
105        /**
106         * Filters whether Jetpack dashboards share one wp-admin page.
107         *
108         * @since 0.14.15
109         *
110         * @param bool $enabled Whether the shell is on. Defaults to the `jetpack-admin-shell` feature flag.
111         */
112        return (bool) apply_filters( 'jetpack_admin_shell_enabled', Feature_Flags::is_enabled( self::FLAG ) );
113    }
114
115    /**
116     * Member dashboards, keyed by admin page slug. Entries that don't match the contract are dropped.
117     *
118     * @return array<string, array{build_prefix: string, build_page: string, init_modules: string[], title: string, header: array{title: string, subtitle: string|null}|false|null, default_path: string|null, load: callable, capability: string, handles: string[], admin_menu: bool}>
119     */
120    public static function get_members() {
121        /**
122         * Filters the dashboards that share the admin shell.
123         *
124         * Each entry is keyed by its admin page slug and holds:
125         * - build_prefix (string)   The wp-build prefix of the generated page functions.
126         * - build_page (string)     The wp-build page name.
127         * - init_modules (string[]) Script modules to import before the app boots, along with any its page init action enqueues.
128         * - title (string)          Document title while the page is shown.
129         * - header (array|false)    Optional. `title` and `subtitle` of the view a bare menu link opens, as the dashboard renders them, shown while it opens. `subtitle` is '' for none, or null when the dashboard picks it as it renders. False shows no stand-in on any of its views, for a page whose landing view has no standard page header. A malformed one is dropped, not the member.
130         * - default_path (string)   Optional. The `p` a bare menu link opens.
131         * - load (callable)         Loads the build that defines `<build_prefix>_get_<build_page>_wp_admin_routes()`, leaving its page init action to the shell, registers the page's scripts and prints its initial data. Must be safe to run twice, and must not redirect, print or write options. Add print hook callbacks here, not from admin_enqueue_scripts: the guest endpoint drops what those print.
132         * - capability (string)     Optional, default `manage_options`. Required to load the page into the shell.
133         * - handles (string[])      Optional. Script and style handles the guest endpoint prints, with their dependencies; nothing else is enqueued.
134         * - admin_menu (bool)       Optional, default false. Build the admin menu on the guest endpoint, after `load`, for page data read through menu_page_url(). What its callbacks print or hook is dropped.
135         *
136         * @since 0.14.15
137         *
138         * @param array $members Member definitions keyed by admin page slug.
139         */
140        $members = apply_filters( 'jetpack_admin_shell_members', array() );
141        if ( ! is_array( $members ) ) {
142            return array();
143        }
144
145        $valid = array();
146        foreach ( $members as $slug => $member ) {
147            $normalized = self::normalize_member( $slug, $member );
148            if ( null === $normalized ) {
149                $message = sprintf( 'Admin shell member "%s" is missing a required key or has one of the wrong type, so it was skipped.', $slug );
150                // Keep on one line: the release tooling only replaces the version in a single-line call.
151                _doing_it_wrong( __METHOD__, esc_html( $message ), '0.14.15' );
152                continue;
153            }
154            $valid[ $slug ] = $normalized;
155        }
156
157        return $valid;
158    }
159
160    /**
161     * The member the guest endpoint is loading in this request, readable from `init` on so members can scope their hooks to it.
162     *
163     * @since $$next-version$$
164     *
165     * @return string|null Member slug, or null on any other request.
166     */
167    public static function requested_guest() {
168        // phpcs:disable WordPress.Security.NonceVerification -- Only scopes hooks; the endpoint verifies the nonce before it prints anything.
169        // Not `page`: products treat a `page` naming them as a visit to their own screen.
170        $action = isset( $_REQUEST['action'] ) && is_string( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : '';
171        $member = isset( $_GET['member'] ) && is_string( $_GET['member'] ) ? sanitize_key( wp_unslash( $_GET['member'] ) ) : '';
172        if ( ! wp_doing_ajax() || self::GUEST_ACTION !== $action || '' === $member ) {
173            return null;
174        }
175        return $member;
176        // phpcs:enable WordPress.Security.NonceVerification
177    }
178
179    /**
180     * The member page this request is for, when the shell runs on it.
181     *
182     * @return string|null
183     */
184    public static function get_host() {
185        return self::resolve_host()[0];
186    }
187
188    /**
189     * The host page and the members, so callers that need both run the members filter once.
190     *
191     * @return array{0: string|null, 1: array} Host slug, or null when the shell doesn't run here; members.
192     */
193    private static function resolve_host() {
194        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks which page this is.
195        $page = isset( $_GET['page'] ) && is_string( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
196        // Members are Jetpack admin pages; checking the screen first keeps the members filter off other admin pages.
197        $on_jetpack_screen = isset( $GLOBALS['hook_suffix'] ) && self::screen_id( $page ) === $GLOBALS['hook_suffix'];
198        if ( '' === $page || ! $on_jetpack_screen || ! self::is_enabled() ) {
199            return array( null, array() );
200        }
201
202        $members = self::get_members();
203        if ( count( $members ) < 2 || ! isset( $members[ $page ] ) ) {
204            return array( null, $members );
205        }
206        return array( $page, $members );
207    }
208
209    /**
210     * The screen ID, hook suffix and body class of a member page.
211     *
212     * @param string $slug Admin page slug.
213     * @return string
214     */
215    public static function screen_id( $slug ) {
216        global $admin_page_hooks;
217        // Top-level pages, like Stats under the Dashboard, get core's prefix rather than the Jetpack menu's.
218        return isset( $admin_page_hooks[ $slug ] ) ? 'toplevel_page_' . $slug : 'jetpack_page_' . $slug;
219    }
220
221    /**
222     * On a member page, ready the other members and print the client.
223     *
224     * @return void
225     */
226    public static function setup() {
227        list( $host, $members ) = self::resolve_host();
228        if ( null === $host ) {
229            return;
230        }
231
232        $guests = array();
233        foreach ( $members as $slug => $member ) {
234            if ( $slug === $host || ! current_user_can( $member['capability'] ) ) {
235                continue;
236            }
237            list( $routes, $modules ) = self::load_guest( $member );
238            if ( null !== $routes ) {
239                $guests[ $slug ]                  = $routes;
240                $members[ $slug ]['init_modules'] = array_values( array_unique( array_merge( $member['init_modules'], $modules ) ) );
241            }
242        }
243        if ( ! $guests ) {
244            return;
245        }
246
247        add_filter(
248            $members[ $host ]['build_page'] . '-wp-admin_boot_dependencies',
249            static function ( $deps ) use ( $members, $guests ) {
250                return self::add_guest_dependencies( $deps, $members, $guests );
251            }
252        );
253
254        $config = self::get_client_config( $host, $members, $guests );
255        add_filter(
256            'script_module_data_' . self::CLIENT_MODULE,
257            static function () use ( $config ) {
258                return $config;
259            }
260        );
261        self::enqueue_client();
262    }
263
264    /**
265     * Enqueue the client: one script module, built from `src/admin-shell/` by webpack.
266     *
267     * @return void
268     */
269    private static function enqueue_client() {
270        $file = dirname( __DIR__ ) . '/build/admin-shell.js';
271        if ( ! is_readable( $file ) ) {
272            return;
273        }
274        // A hash of the file: CDNs cache script URLs by their version for a long time.
275        wp_enqueue_script_module(
276            self::CLIENT_MODULE,
277            plugins_url( 'build/admin-shell.js', __DIR__ ),
278            // Announces switches. Core prints the live regions it speaks into for its dependents.
279            array(
280                array(
281                    'id'     => '@wordpress/a11y',
282                    'import' => 'dynamic',
283                ),
284            ),
285            substr( (string) md5_file( $file ), 0, 12 )
286        );
287    }
288
289    /**
290     * Run a guest's loader and page init action on the host page, then drop the page hooks and script modules they added.
291     *
292     * @param array $member Normalized member.
293     * @return array{0: array[]|null, 1: string[]} Routes, or null when the guest's build or its routes aren't there; the script modules they enqueued.
294     */
295    private static function load_guest( $member ) {
296        $snapshot = self::hook_snapshot();
297        $queued   = wp_script_modules()->get_queue();
298        call_user_func( $member['load'] );
299        $routes = self::run_page_init( $member );
300        self::remove_added_callbacks( $snapshot );
301
302        // The shell imports them with the guest's init modules, so a host visit alone never runs them.
303        $modules = array_values( array_diff( wp_script_modules()->get_queue(), $queued ) );
304        foreach ( $modules as $id ) {
305            wp_dequeue_script_module( $id );
306        }
307
308        return array( $routes, $modules );
309    }
310
311    /**
312     * Fire a loaded member's wp-build page init action, which its enqueue check skips off its own screen.
313     *
314     * @param array $member Normalized member.
315     * @return array[]|null The page's routes, which its listeners can add to, or null when the guest's build or its routes aren't there.
316     */
317    private static function run_page_init( $member ) {
318        $page       = str_replace( '-', '_', $member['build_page'] );
319        $get_routes = $member['build_prefix'] . '_get_' . $page . '_wp_admin_routes';
320        // A build without its route registry still defines the getter, but would open a blank page.
321        if ( ! function_exists( $get_routes ) || ! isset( $GLOBALS[ $member['build_prefix'] . '_' . $page . '_routes_data' ] ) ) {
322            return null;
323        }
324        do_action( $member['build_page'] . '-wp-admin_init' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- wp-build names this hook.
325        return $get_routes();
326    }
327
328    /**
329     * Add the guests' modules to the host page's import map, without downloading them.
330     *
331     * @param array $deps    Host boot dependencies.
332     * @param array $members Members keyed by slug.
333     * @param array $guests  Guest routes keyed by slug.
334     * @return array
335     */
336    public static function add_guest_dependencies( $deps, $members, $guests ) {
337        foreach ( $guests as $slug => $routes ) {
338            $ids = $members[ $slug ]['init_modules'];
339            foreach ( $routes as $route ) {
340                $ids[] = $route['route_module'] ?? null;
341                $ids[] = $route['content_module'] ?? null;
342            }
343            // Modules a guest adds to its own page's import map, such as Stats' widgets, which it imports on demand.
344            $own_deps = apply_filters( $members[ $slug ]['build_page'] . '-wp-admin_boot_dependencies', array() ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound, WordPress.NamingConventions.ValidHookName.UseUnderscores -- The guest's generated wp-build hook.
345            $ids      = array_merge( $ids, array_column( (array) $own_deps, 'id' ) );
346            foreach ( array_unique( array_filter( $ids ) ) as $id ) {
347                $deps[] = array(
348                    'import' => 'dynamic',
349                    'id'     => $id,
350                );
351            }
352        }
353        return $deps;
354    }
355
356    /**
357     * What the client needs to know about the host and its guests.
358     *
359     * @param string $host    Host page slug.
360     * @param array  $members Members keyed by slug.
361     * @param array  $guests  Guest routes keyed by slug.
362     * @return array
363     */
364    private static function get_client_config( $host, $members, $guests ) {
365        $config = array(
366            'host'             => $host,
367            'members'          => array(),
368            // Saved headers are per site, user and release: subdirectory multisite sites share one origin.
369            'headerStorageKey' => sprintf( 'jetpack-admin-shell-header:%d:%d:%s:', get_current_blog_id(), get_current_user_id(), Admin_Menu::PACKAGE_VERSION ),
370            'guestAssetsUrl'   => add_query_arg(
371                array(
372                    'action' => self::GUEST_ACTION,
373                    'nonce'  => wp_create_nonce( self::GUEST_ACTION ),
374                ),
375                admin_url( 'admin-ajax.php' )
376            ),
377            'featureUrl'       => add_query_arg(
378                array(
379                    'action' => self::FEATURE_ACTION,
380                    'nonce'  => wp_create_nonce( self::FEATURE_ACTION ),
381                ),
382                admin_url( 'admin-ajax.php' )
383            ),
384            'featureOff'       => array(
385                /* translators: %s is a feature name, e.g. "Jetpack Forms". */
386                'heading' => __( '%s is off', 'jetpack-admin-ui' ),
387                'text'    => __( 'It was switched off in My Jetpack. Turning it on brings this page and its menu item back.', 'jetpack-admin-ui' ),
388                /* translators: %s is a feature name, e.g. "Jetpack Forms". */
389                'button'  => __( 'Turn on %s', 'jetpack-admin-ui' ),
390                'busy'    => __( 'Turning on…', 'jetpack-admin-ui' ),
391                'failed'  => __( 'It could not be turned on. Try again from My Jetpack.', 'jetpack-admin-ui' ),
392            ),
393            'maxLiveApps'      => self::max_live_apps(),
394        );
395        foreach ( array( $host => array() ) + $guests as $slug => $routes ) {
396            $member                     = $members[ $slug ];
397            $gate                       = self::feature_gate( $slug );
398            $config['members'][ $slug ] = array(
399                'mountId'     => $member['build_page'] . '-wp-admin-app',
400                'routes'      => $routes,
401                'initModules' => $member['init_modules'],
402                'defaultPath' => $member['default_path'],
403                'title'       => $member['title'],
404                'header'      => $member['header'],
405                'adminTitle'  => self::admin_title( $slug, $member['title'] ),
406                'bodyClass'   => self::screen_id( $slug ),
407                'gate'        => $gate,
408                // Ties the gate to this member, so the feature endpoint answers for no other.
409                'gateNonce'   => null === $gate ? null : wp_create_nonce( self::gate_action( $slug, $gate ) ),
410                // Guests are checked when they are opened; the host is on screen already.
411                'featureOn'   => $slug !== $host || null === $gate || ! self::stands_in( $gate ),
412            );
413            // So the host shows its card without asking again.
414            if ( false === $config['members'][ $slug ]['featureOn'] ) {
415                $config['members'][ $slug ]['featureCard'] = self::feature_off_card( $slug );
416            }
417        }
418        return $config;
419    }
420
421    /**
422     * The gate a member's menu item declared, while this admin-ui can answer for it.
423     *
424     * @param string $slug Admin page slug.
425     * @return array|null
426     */
427    private static function feature_gate( $slug ) {
428        // The admin-ui that won the autoloader may predate these methods.
429        if ( ! method_exists( Admin_Menu::class, 'get_feature_gate' ) ) {
430            return null;
431        }
432        return Admin_Menu::get_feature_gate( $slug );
433    }
434
435    /**
436     * Say whether a member's feature is on, or, on a POST with `activate`, turn it on.
437     *
438     * @return void
439     */
440    public static function ajax_feature() {
441        check_ajax_referer( self::FEATURE_ACTION, 'nonce' );
442        // phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing -- Checked above.
443        $slug = isset( $_REQUEST['member'] ) && is_string( $_REQUEST['member'] ) ? sanitize_key( wp_unslash( $_REQUEST['member'] ) ) : '';
444        $gate = array();
445        foreach ( array( 'product', 'module' ) as $key ) {
446            if ( isset( $_REQUEST[ $key ] ) && is_string( $_REQUEST[ $key ] ) && '' !== $_REQUEST[ $key ] ) {
447                $gate[ $key ] = sanitize_key( wp_unslash( $_REQUEST[ $key ] ) );
448            }
449        }
450        $activate   = isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] && ! empty( $_POST['activate'] );
451        $gate_nonce = isset( $_REQUEST['gate_nonce'] ) && is_string( $_REQUEST['gate_nonce'] ) ? sanitize_key( wp_unslash( $_REQUEST['gate_nonce'] ) ) : '';
452        // phpcs:enable
453
454        if ( ! self::is_member_gate( $slug, $gate, $gate_nonce ) ) {
455            wp_send_json_error( null, 403, JSON_UNESCAPED_SLASHES );
456        }
457
458        $result = self::feature( $slug, $gate, $activate );
459        if ( is_int( $result ) ) {
460            wp_send_json_error( null, $result, JSON_UNESCAPED_SLASHES );
461        }
462        if ( is_wp_error( $result ) ) {
463            wp_send_json_error( array( 'message' => $result->get_error_message() ), 200, JSON_UNESCAPED_SLASHES );
464        }
465        $data = array( 'on' => $result );
466        if ( ! $result ) {
467            $data['card'] = self::feature_off_card( $slug );
468        }
469        wp_send_json_success( $data, 200, JSON_UNESCAPED_SLASHES );
470    }
471
472    /**
473     * The HTML the shell shows in place of a member page whose feature is off.
474     *
475     * @param string $slug Admin page slug of the member.
476     * @return string Empty for the shell's plain panel.
477     */
478    private static function feature_off_card( $slug ) {
479        /**
480         * Filters the HTML the shell shows in place of a member page whose feature is off. Empty for the shell's plain panel.
481         *
482         * @since $$next-version$$
483         *
484         * @param string $html Card HTML.
485         * @param string $slug Admin page slug of the member.
486         */
487        return (string) apply_filters( 'jetpack_admin_shell_feature_off_card', '', $slug );
488    }
489
490    /**
491     * Whether a member's page shows as itself, after turning its feature on when asked to.
492     *
493     * @param string $slug     Member page slug.
494     * @param array  $gate     The gate the member's menu item declared.
495     * @param bool   $activate Whether to turn the feature on first.
496     * @return bool|\WP_Error|int False when the shell stands in for it, the activation error, or an HTTP status: 404 for no such member or gate, 403 when the user can't open it.
497     */
498    public static function feature( $slug, array $gate, $activate = false ) {
499        if ( ! self::is_enabled() || ! $gate || ! method_exists( Admin_Menu::class, 'is_feature_on' ) ) {
500            return 404;
501        }
502        $members = self::get_members();
503        if ( isset( $members[ $slug ] ) && ! current_user_can( $members[ $slug ]['capability'] ) ) {
504            return 403;
505        }
506        // Most members stop joining the shell while their feature is off, so a missing one is known only when the shell stands in for it.
507        if ( ! isset( $members[ $slug ] ) && ! self::stands_in( $gate ) ) {
508            return 404;
509        }
510        if ( $activate ) {
511            $result = self::can_turn_on( $gate )
512                ? Admin_Menu::turn_feature_on( $gate )
513                : new \WP_Error( 'not_available', __( 'This feature can only be turned on from My Jetpack.', 'jetpack-admin-ui' ) );
514            if ( is_wp_error( $result ) ) {
515                return $result;
516            }
517        }
518        return ! self::stands_in( $gate );
519    }
520
521    /**
522     * Whether the shell shows a turn-on panel instead of a page: its feature is off and can be turned on here.
523     *
524     * @param array $gate A member's gate.
525     * @return bool
526     */
527    private static function stands_in( array $gate ) {
528        return ! Admin_Menu::is_feature_on( $gate ) && self::can_turn_on( $gate );
529    }
530
531    /**
532     * Whether this admin-ui and the site's activator can turn a gate's feature on.
533     *
534     * @param array $gate A member's gate.
535     * @return bool
536     */
537    private static function can_turn_on( array $gate ) {
538        // An older Admin_Menu, loaded first from another plugin's copy, predates the check.
539        return method_exists( Admin_Menu::class, 'can_turn_feature_on' ) && Admin_Menu::can_turn_feature_on( $gate );
540    }
541
542    /**
543     * Whether a gate is the one this site gave the member, by the nonce sent with the shell config.
544     *
545     * @param string $slug  Member page slug.
546     * @param array  $gate  Gate from the request.
547     * @param string $nonce Gate nonce from the request.
548     * @return bool
549     */
550    public static function is_member_gate( $slug, array $gate, $nonce ) {
551        return '' !== $nonce && false !== wp_verify_nonce( $nonce, self::gate_action( $slug, $gate ) );
552    }
553
554    /**
555     * The nonce action that ties a gate to its member.
556     *
557     * @param string $slug Member page slug.
558     * @param array  $gate Its gate.
559     * @return string
560     */
561    private static function gate_action( $slug, array $gate ) {
562        ksort( $gate );
563        return self::FEATURE_ACTION . '|' . $slug . '|' . http_build_query( $gate );
564    }
565
566    /**
567     * How many dashboards the client may keep live in one document.
568     *
569     * @return int|null The limit, or null to let the client size it from the device's memory.
570     */
571    private static function max_live_apps() {
572        /**
573         * Filters how many dashboards the admin shell keeps live, prewarmed or mounted, in one document.
574         * Past the limit, opening another dashboard loads the page.
575         *
576         * @since $$next-version$$
577         *
578         * @param int|null $max_live_apps A positive limit, counting the page that loaded; null sizes it from the device's memory.
579         */
580        $max_live_apps = apply_filters( 'jetpack_admin_shell_max_live_apps', null );
581        return is_numeric( $max_live_apps ) && (int) $max_live_apps > 0 ? (int) $max_live_apps : null;
582    }
583
584    /**
585     * The document title a member page gets on its own page load.
586     *
587     * @param string $slug     Admin page slug.
588     * @param string $fallback Title to use when the page isn't in the admin menu.
589     * @return string
590     */
591    private static function admin_title( $slug, $fallback ) {
592        global $submenu;
593        $title = $fallback;
594        foreach ( is_array( $submenu ) ? $submenu : array() as $items ) {
595            foreach ( $items as $item ) {
596                if ( isset( $item[2] ) && $slug === $item[2] ) {
597                    $title = wp_strip_all_tags( $item[3] ?? $item[0] );
598                    break 2;
599                }
600            }
601        }
602        /* translators: Admin screen title. 1: Admin screen name, 2: Network or site name. */
603        $admin_title = sprintf( __( '%1$s &lsaquo; %2$s &#8212; WordPress' ), $title, get_bloginfo( 'name' ) ); // phpcs:ignore WordPress.WP.I18n.MissingArgDomain -- Core's string, so the title matches the one core prints.
604        /** This filter is documented in wp-admin/admin-header.php */
605        $admin_title = apply_filters( 'admin_title', $admin_title, $title ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core filter.
606        return html_entity_decode( wp_strip_all_tags( $admin_title ), ENT_QUOTES, 'UTF-8' );
607    }
608
609    /**
610     * Send the styles and scripts a guest prints on its own page, for the client to run before booting it.
611     *
612     * @return void
613     */
614    public static function ajax_guest_assets() {
615        check_ajax_referer( self::GUEST_ACTION, 'nonce' );
616        $slug = self::requested_guest() ?? '';
617
618        $html = self::guest_assets( $slug );
619        if ( is_int( $html ) ) {
620            wp_send_json_error( null, $html, JSON_UNESCAPED_SLASHES );
621        }
622        wp_send_json_success( array( 'html' => $html ), 200, JSON_UNESCAPED_SLASHES );
623    }
624
625    /**
626     * The styles and scripts a member prints on its own page.
627     *
628     * @param string $slug Member page slug.
629     * @return string|int The HTML, or an HTTP status: 404 for no such member while the shell is on, 403 when the user can't open it.
630     */
631    public static function guest_assets( $slug ) {
632        $members = self::is_enabled() ? self::get_members() : array();
633        if ( ! isset( $members[ $slug ] ) ) {
634            return 404;
635        }
636        if ( ! current_user_can( $members[ $slug ]['capability'] ) ) {
637            return 403;
638        }
639
640        $snapshot = self::hook_snapshot();
641        call_user_func( $members[ $slug ]['load'] );
642        if ( $members[ $slug ]['admin_menu'] ) {
643            self::register_admin_menu_pages();
644        }
645        self::run_page_init( $members[ $slug ] );
646        $own         = self::added_keys( $snapshot );
647        $hook_suffix = self::screen_id( $slug );
648        set_current_screen( $hook_suffix );
649        $GLOBALS['concatenate_scripts'] = false; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- One script tag per handle, so the client can skip what the host already has.
650
651        ob_start();
652        do_action( 'admin_enqueue_scripts', $hook_suffix ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core hook.
653        $handles = $members[ $slug ]['handles'];
654        // Only the member's own handles, and what they depend on, go back to the page. Printing them
655        // even when nothing enqueued them: a page can rely on another script pulling one in.
656        foreach ( array( wp_scripts(), wp_styles() ) as $dependencies ) {
657            $dependencies->queue = array_values( array_filter( $handles, array( $dependencies, 'query' ) ) );
658        }
659        self::guard_api_fetch_setup();
660        wp_print_styles();
661        self::fire_print_hook( 'admin_print_scripts', $own['admin_print_scripts'] );
662        print_head_scripts();
663        print_footer_scripts();
664        self::fire_print_hook( 'admin_print_footer_scripts', $own['admin_print_footer_scripts'] );
665        return ob_get_clean();
666    }
667
668    /**
669     * Register the admin menu's pages, which admin-ajax never does, keeping only the pages: what its callbacks print or hook is dropped.
670     *
671     * Runs `admin_menu` alone: core's wp-admin/menu.php would also run its page access check, which dies on admin-ajax.
672     *
673     * @return void
674     */
675    private static function register_admin_menu_pages() {
676        global $menu, $submenu, $wp_filter;
677        if ( did_action( 'admin_menu' ) ) {
678            return;
679        }
680        // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited -- Menu callbacks expect the arrays core's menu.php would have set up.
681        $menu    = is_array( $menu ) ? $menu : array();
682        $submenu = is_array( $submenu ) ? $submenu : array();
683        // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited
684        $before = array();
685        foreach ( $wp_filter as $hook => $callbacks ) {
686            $before[ $hook ] = $callbacks->callbacks;
687        }
688
689        ob_start();
690        do_action( 'admin_menu', '' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core hook.
691        ob_end_clean();
692
693        // A hover must not run them: Jetpack's plan check on current_screen, for one, turns off modules.
694        foreach ( $wp_filter as $hook => $callbacks ) {
695            foreach ( $callbacks->callbacks as $priority => $by_id ) {
696                foreach ( $by_id as $id => $callback ) {
697                    if ( ! isset( $before[ $hook ][ $priority ][ $id ] ) ) {
698                        remove_filter( $hook, $callback['function'], $priority );
699                    }
700                }
701            }
702        }
703    }
704
705    /**
706     * Skip core's api-fetch setup when the host page already ran it.
707     *
708     * A second nonce middleware would keep sending the stale nonce after a refresh, so requests loop.
709     *
710     * @return void
711     */
712    private static function guard_api_fetch_setup() {
713        $after = wp_scripts()->get_data( 'wp-api-fetch', 'after' );
714        if ( ! is_array( $after ) ) {
715            return;
716        }
717        foreach ( $after as $i => $code ) {
718            if ( is_string( $code ) && ( false !== strpos( $code, 'createRootURLMiddleware' ) || false !== strpos( $code, 'createNonceMiddleware' ) ) ) {
719                $after[ $i ] = "if ( ! wp.apiFetch.nonceMiddleware ) {\n" . $code . "\n}";
720            }
721        }
722        wp_scripts()->add_data( 'wp-api-fetch', 'after', $after );
723    }
724
725    /**
726     * Fire a print hook, discarding what callbacks echo or enqueue unless the member added them or core defines them.
727     *
728     * Every callback still runs, so data attached to the member's handles prints. Their output already ran on the host page.
729     *
730     * @param string             $hook Hook name.
731     * @param array<string,true> $own  Callbacks the member's loader added, keyed as hook_snapshot() keys them.
732     * @return void
733     */
734    private static function fire_print_hook( $hook, array $own ) {
735        global $wp_filter;
736        $wrapped = array();
737        foreach ( isset( $wp_filter[ $hook ] ) ? $wp_filter[ $hook ]->callbacks : array() as $priority => $by_id ) {
738            foreach ( $by_id as $id => $callback ) {
739                if ( isset( $own[ $priority . '|' . $id ] ) || self::is_core_callback( $callback['function'] ) ) {
740                    continue;
741                }
742                $function                    = $callback['function'];
743                $wrapped[ $priority ][ $id ] = $function;
744                $wp_filter[ $hook ]->callbacks[ $priority ][ $id ]['function'] = static function ( ...$args ) use ( $function ) {
745                    $level = ob_get_level();
746                    // WordPress.com enqueues jQuery here; printed again, it drops the host's plugins, like wpcom_proxy_request.
747                    $queues = array( wp_scripts()->queue, wp_styles()->queue );
748                    ob_start();
749                    try {
750                        call_user_func_array( $function, $args );
751                    } finally {
752                        wp_scripts()->queue = $queues[0];
753                        wp_styles()->queue  = $queues[1];
754                        // Also closes buffers the callback left open, stopping at one that can't be removed.
755                        while ( ob_get_level() > $level && ob_end_clean() ) {
756                            continue;
757                        }
758                    }
759                };
760            }
761        }
762
763        try {
764            do_action( $hook ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- A core print hook.
765        } finally {
766            foreach ( $wrapped as $priority => $by_id ) {
767                foreach ( $by_id as $id => $function ) {
768                    if ( isset( $wp_filter[ $hook ]->callbacks[ $priority ][ $id ] ) ) {
769                        $wp_filter[ $hook ]->callbacks[ $priority ][ $id ]['function'] = $function;
770                    }
771                }
772            }
773        }
774    }
775
776    /**
777     * Whether a callback is defined in WordPress core, which prints the member's handles and script module data.
778     *
779     * The Gutenberg plugin counts as core: it can replace core's script module printers.
780     *
781     * @param callable $callback Callback.
782     * @return bool
783     */
784    private static function is_core_callback( $callback ) {
785        static $core_dirs = null;
786        if ( null === $core_dirs ) {
787            $core_dirs = array();
788            $dirs      = array( ABSPATH . WPINC, ABSPATH . 'wp-admin' );
789            // Found from its main file: WordPress.com loads it from a versioned directory.
790            if ( function_exists( 'gutenberg_pre_init' ) ) {
791                // @phan-suppress-next-line PhanUndeclaredFunctionInCallable -- Defined by the Gutenberg plugin, when active.
792                $dirs[] = dirname( (string) ( new \ReflectionFunction( 'gutenberg_pre_init' ) )->getFileName() );
793            }
794            foreach ( $dirs as $dir ) {
795                $real = realpath( $dir );
796                if ( false !== $real ) {
797                    $core_dirs[] = trailingslashit( wp_normalize_path( $real ) );
798                }
799            }
800        }
801        try {
802            $file = ( new \ReflectionFunction( \Closure::fromCallable( $callback ) ) )->getFileName();
803        } catch ( \Throwable $e ) {
804            return false;
805        }
806        if ( ! is_string( $file ) ) {
807            return false;
808        }
809        $file = wp_normalize_path( $file );
810        foreach ( $core_dirs as $dir ) {
811            if ( 0 === strpos( $file, $dir ) ) {
812                return true;
813            }
814        }
815        return false;
816    }
817
818    /**
819     * Snapshot the callbacks on the deferred hooks.
820     *
821     * @return array<string, array<string, true>>
822     */
823    private static function hook_snapshot() {
824        global $wp_filter;
825        $snapshot = array();
826        foreach ( self::DEFERRED_HOOKS as $hook ) {
827            $snapshot[ $hook ] = array();
828            foreach ( isset( $wp_filter[ $hook ] ) ? $wp_filter[ $hook ]->callbacks : array() as $priority => $callbacks ) {
829                foreach ( array_keys( $callbacks ) as $id ) {
830                    $snapshot[ $hook ][ $priority . '|' . $id ] = true;
831                }
832            }
833        }
834        return $snapshot;
835    }
836
837    /**
838     * Keys of the callbacks added to the deferred hooks since the snapshot.
839     *
840     * @param array<string, array<string, true>> $snapshot From hook_snapshot().
841     * @return array<string, array<string, true>> Keyed by every deferred hook.
842     */
843    private static function added_keys( $snapshot ) {
844        $added = array();
845        foreach ( self::hook_snapshot() as $hook => $keys ) {
846            $added[ $hook ] = array_diff_key( $keys, $snapshot[ $hook ] );
847        }
848        return $added;
849    }
850
851    /**
852     * Callbacks added to the deferred hooks since the snapshot, in the order the hooks would run them.
853     *
854     * @param array<string, array<string, true>> $snapshot From hook_snapshot().
855     * @return array<string, array<array{function: callable, priority: int}>> Keyed by every deferred hook.
856     */
857    private static function added_callbacks( $snapshot ) {
858        global $wp_filter;
859        $added = array();
860        foreach ( self::DEFERRED_HOOKS as $hook ) {
861            $added[ $hook ] = array();
862            $callbacks      = isset( $wp_filter[ $hook ] ) ? $wp_filter[ $hook ]->callbacks : array();
863            ksort( $callbacks );
864            foreach ( $callbacks as $priority => $by_id ) {
865                foreach ( $by_id as $id => $callback ) {
866                    if ( ! isset( $snapshot[ $hook ][ $priority . '|' . $id ] ) ) {
867                        $added[ $hook ][] = array(
868                            'function' => $callback['function'],
869                            'priority' => $priority,
870                        );
871                    }
872                }
873            }
874        }
875        return $added;
876    }
877
878    /**
879     * Remove callbacks added to the deferred hooks since the snapshot.
880     *
881     * @param array<string, array<string, true>> $snapshot From hook_snapshot().
882     * @return void
883     */
884    private static function remove_added_callbacks( $snapshot ) {
885        foreach ( self::added_callbacks( $snapshot ) as $hook => $callbacks ) {
886            foreach ( $callbacks as $callback ) {
887                remove_filter( $hook, $callback['function'], $callback['priority'] );
888            }
889        }
890    }
891
892    /**
893     * Fill in a member's defaults, or return null when it can't be used.
894     *
895     * @param mixed $slug   Admin page slug.
896     * @param mixed $member Member definition.
897     * @return array|null
898     */
899    private static function normalize_member( $slug, $member ) {
900        if ( ! is_string( $slug ) || sanitize_key( $slug ) !== $slug || '' === $slug || ! is_array( $member ) ) {
901            return null;
902        }
903
904        foreach ( self::REQUIRED_STRING_KEYS as $key ) {
905            if ( ! isset( $member[ $key ] ) || ! is_string( $member[ $key ] ) || '' === $member[ $key ] ) {
906                return null;
907            }
908        }
909
910        if ( ! isset( $member['load'] ) || ! is_callable( $member['load'] ) ) {
911            return null;
912        }
913
914        $member += array(
915            'init_modules' => array(),
916            'header'       => null,
917            'default_path' => null,
918            'capability'   => 'manage_options',
919            'handles'      => array(),
920            'admin_menu'   => false,
921        );
922
923        if (
924            ! self::is_string_list( $member['init_modules'] )
925            || ! self::is_string_list( $member['handles'] )
926            || ! is_string( $member['capability'] ) || '' === $member['capability']
927            || ! is_bool( $member['admin_menu'] )
928            || ( null !== $member['default_path'] && ! is_string( $member['default_path'] ) )
929        ) {
930            return null;
931        }
932
933        // Only cosmetic, so a malformed header is dropped and the member kept.
934        if ( null !== $member['header'] && false !== $member['header'] && ! self::is_header( $member['header'] ) ) {
935            $member['header'] = null;
936            $message          = sprintf( 'Admin shell member "%s" has a header without a title and subtitle, so the header was skipped.', $slug );
937            // Keep on one line: the release tooling only replaces the version in a single-line call.
938            _doing_it_wrong( __CLASS__ . '::get_members', esc_html( $message ), '0.14.15' );
939        }
940
941        return $member;
942    }
943
944    /**
945     * Whether a value is a page header: a non-empty `title`, and a `subtitle` string or null.
946     *
947     * @param mixed $value Value to check.
948     * @return bool
949     */
950    private static function is_header( $value ) {
951        return is_array( $value )
952            && isset( $value['title'] ) && is_string( $value['title'] ) && '' !== $value['title']
953            && array_key_exists( 'subtitle', $value ) && ( null === $value['subtitle'] || is_string( $value['subtitle'] ) );
954    }
955
956    /**
957     * Whether a value is a list of strings.
958     *
959     * @param mixed $value Value to check.
960     * @return bool
961     */
962    private static function is_string_list( $value ) {
963        if ( ! is_array( $value ) || array_values( $value ) !== $value ) {
964            return false;
965        }
966        foreach ( $value as $item ) {
967            if ( ! is_string( $item ) ) {
968                return false;
969            }
970        }
971        return true;
972    }
973}