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