Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.56% covered (warning)
84.56%
230 / 272
58.62% covered (warning)
58.62%
17 / 29
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin_Menu
84.56% covered (warning)
84.56%
230 / 272
58.62% covered (warning)
58.62%
17 / 29
147.37
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 reset
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 handle_akismet_menu
11.11% covered (danger)
11.11%
1 / 9
0.00% covered (danger)
0.00%
0 / 1
4.81
 admin_menu_hook_callback
96.00% covered (success)
96.00%
48 / 50
0.00% covered (danger)
0.00%
0 / 1
12
 init_top_level
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 top_level_menu_hook_callback
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
4
 add_top_level_menu
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 add_menu
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 hide_core_admin_notices
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 print_hide_core_admin_notices_style
n/a
0 / 0
n/a
0 / 0
1
 get_hide_core_admin_notices_styles
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 set_visibility_resolver
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 remove_hidden_menu_items
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_item_key
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_visibility_states
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 is_menu_item_visible
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 is_gate_satisfied
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 remove_menu
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 get_top_level_menu_item_slug
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
5.58
 get_top_level_menu_item_url
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 should_show_upgrade_menu
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
7.02
 is_site_and_user_connected
70.00% covered (warning)
70.00%
7 / 10
0.00% covered (danger)
0.00%
0 / 1
8.32
 set_connection_manager
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_free_plan
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
9
 maybe_add_upgrade_menu_item
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
8
 add_upgrade_menu_item_styles
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_design_tokens
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 register_design_tokens_style
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 maybe_enqueue_design_tokens
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 enqueue_upgrade_menu_tracks_script
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
5
1<?php
2/**
3 * Admin Menu Registration
4 *
5 * @package automattic/jetpack-admin-ui
6 */
7
8namespace Automattic\Jetpack\Admin_UI;
9
10use Automattic\Jetpack\Feature_Policy;
11use Automattic\Jetpack\Tracking;
12use Jetpack_Options;
13use Jetpack_Tracks_Client;
14
15/**
16 * This class offers a wrapper to add_submenu_page and makes sure stand-alone plugin's menu items are always added under the Jetpack top level menu.
17 * If the Jetpack top level was not previously registered by other plugin, it will be registered here.
18 */
19class Admin_Menu {
20
21    const PACKAGE_VERSION = '0.14.0';
22
23    /**
24     * Slug used for the upgrade menu item and redirect URL.
25     *
26     * Keep the slug in sync with `$upgrade-menu-slug` at admin-ui-upgrade-menu.scss
27     *
28     * @var string
29     */
30    const UPGRADE_MENU_SLUG = 'jetpack-wpadmin-sidebar-free-plan-upsell-menu-item';
31
32    /**
33     * Fallback upgrade URL when the Redirect class is unavailable.
34     *
35     * @var string
36     */
37    const UPGRADE_MENU_FALLBACK_URL = 'https://jetpack.com/upgrade/';
38
39    /*
40     * The sidebar's position tiers. Items sharing a tier sort alphabetically by menu title, so a
41     * product should pass no position and land in POSITION_DEFAULT. add_menu() treats any value
42     * that is not a tier below as omitted, so an int of your own cannot opt an item out.
43     */
44
45    /**
46     * Owns the top-level Jetpack link, since WordPress points it at whichever item sorts first.
47     *
48     * @var int
49     */
50    const POSITION_FIRST = -10;
51
52    /**
53     * Takes the first slot when nothing claims POSITION_FIRST, as in offline mode.
54     *
55     * @var int
56     */
57    const POSITION_FIRST_FALLBACK = -5;
58
59    /**
60     * Products, in alphabetical order. Pass no position rather than this.
61     *
62     * @var int
63     */
64    const POSITION_DEFAULT = 0;
65
66    /**
67     * Links that leave wp-admin, grouped below the products.
68     *
69     * @var int
70     */
71    const POSITION_EXTERNAL = 100;
72
73    /**
74     * Site-level items that belong under everything else.
75     *
76     * @var int
77     */
78    const POSITION_LAST = 998;
79
80    /**
81     * The upgrade item this package adds, below every tier a caller can use.
82     *
83     * @var int
84     */
85    const POSITION_UPGRADE = 999;
86
87    /**
88     * The tiers add_menu() accepts. POSITION_UPGRADE is left out: only this class claims it.
89     *
90     * @var int[]
91     */
92    private const CALLER_POSITIONS = array(
93        self::POSITION_FIRST,
94        self::POSITION_FIRST_FALLBACK,
95        self::POSITION_DEFAULT,
96        self::POSITION_EXTERNAL,
97        self::POSITION_LAST,
98    );
99
100    /**
101     * Handle for the shared, token-only WPDS design-tokens stylesheet.
102     *
103     * Registered once and enqueued on every Jetpack admin page so that
104     * `var(--wpds-*)` values resolve at runtime instead of falling back to
105     * their hand-written hex defaults.
106     *
107     * @var string
108     */
109    const DESIGN_TOKENS_HANDLE = 'jetpack-admin-ui-design-tokens';
110
111    /**
112     * Handle for the source-less stylesheet that hides WordPress core admin notices.
113     *
114     * @var string
115     */
116    const HIDE_CORE_NOTICES_HANDLE = 'jetpack-admin-ui-hide-core-notices';
117
118    /**
119     * Visibility state: show the item only when its declared gate is satisfied.
120     *
121     * @var string
122     */
123    const VISIBILITY_DEFAULT = 'default';
124
125    /**
126     * Visibility state: show the item whatever its gate says.
127     *
128     * @var string
129     */
130    const VISIBILITY_VISIBLE = 'visible';
131
132    /**
133     * Visibility state: keep the item out whatever its gate says.
134     *
135     * @var string
136     */
137    const VISIBILITY_HIDDEN = 'hidden';
138
139    /**
140     * Whether this class has been initialized
141     *
142     * @var boolean
143     */
144    private static $initialized = false;
145
146    /**
147     * List of menu items enqueued to be added
148     *
149     * @var array
150     */
151    private static $menu_items = array();
152
153    /**
154     * List of top level menu items enqueued to be added
155     *
156     * @var array
157     */
158    private static $top_level_items = array();
159
160    /**
161     * Hook suffixes of the pages registered through this class.
162     *
163     * Used to scope the design-tokens stylesheet to Jetpack admin pages.
164     *
165     * @var array
166     */
167    private static $page_hooks = array();
168
169    /**
170     * Optional connection manager dependency.
171     *
172     * @var object|null
173     */
174    private static $connection_manager = null;
175
176    /**
177     * Callback that answers whether a menu item's declared gate is satisfied.
178     *
179     * Set by My Jetpack, which owns the product classes the gates name. Stays null on a
180     * site without it, where every gate then fails open.
181     *
182     * @var callable|null
183     */
184    private static $visibility_resolver = null;
185
186    /**
187     * Menu slugs registered this request but kept out of the rendered sidebar.
188     *
189     * @var string[]
190     */
191    private static $hidden_menu_slugs = array();
192
193    /**
194     * Top level menu slugs registered this request but kept out of the rendered sidebar.
195     *
196     * @var string[]
197     */
198    private static $hidden_top_level_slugs = array();
199
200    /**
201     * Whether the top level registration pass has been hooked.
202     *
203     * Separate from $initialized, which also builds the Jetpack menu.
204     *
205     * @var boolean
206     */
207    private static $top_level_initialized = false;
208
209    /**
210     * Initialize the class and set up the main hook
211     *
212     * @return void
213     */
214    public static function init() {
215        if ( ! self::$initialized ) {
216            self::$initialized = true;
217            self::handle_akismet_menu();
218            add_action( 'admin_menu', array( __CLASS__, 'admin_menu_hook_callback' ), 1000 ); // Jetpack uses 998.
219            add_action( 'network_admin_menu', array( __CLASS__, 'admin_menu_hook_callback' ), 1000 ); // Jetpack uses 998.
220            add_action( 'admin_head', array( __CLASS__, 'remove_hidden_menu_items' ) );
221            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'add_upgrade_menu_item_styles' ) );
222            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'maybe_enqueue_design_tokens' ) );
223        }
224    }
225
226    /**
227     * Drops every queued item and unhooks the registration passes.
228     *
229     * Intended for tests.
230     *
231     * @return void
232     */
233    public static function reset() {
234        self::$menu_items             = array();
235        self::$top_level_items        = array();
236        self::$page_hooks             = array();
237        self::$hidden_menu_slugs      = array();
238        self::$hidden_top_level_slugs = array();
239        self::$initialized            = false;
240        self::$top_level_initialized  = false;
241
242        remove_action( 'admin_menu', array( __CLASS__, 'admin_menu_hook_callback' ), 1000 );
243        remove_action( 'network_admin_menu', array( __CLASS__, 'admin_menu_hook_callback' ), 1000 );
244        remove_action( 'admin_menu', array( __CLASS__, 'top_level_menu_hook_callback' ), 1000 );
245        remove_action( 'admin_head', array( __CLASS__, 'remove_hidden_menu_items' ) );
246        remove_action( 'admin_enqueue_scripts', array( __CLASS__, 'add_upgrade_menu_item_styles' ) );
247        remove_action( 'admin_enqueue_scripts', array( __CLASS__, 'maybe_enqueue_design_tokens' ) );
248    }
249
250    /**
251     * Handles the Akismet menu item when used alongside other stand-alone plugins
252     *
253     * When Jetpack plugin is present, Akismet menu item is moved under the Jetpack top level menu, but if Akismet is active alongside other stand-alone plugins,
254     * we use this method to move the menu item.
255     */
256    private static function handle_akismet_menu() {
257        if ( class_exists( 'Akismet_Admin' ) ) {
258            add_action(
259                'admin_menu',
260                function () {
261                    // Prevent Akismet from adding a menu item.
262                    remove_action( 'admin_menu', array( 'Akismet_Admin', 'admin_menu' ), 5 );
263
264                    // Add an Anti-spam menu item for Jetpack.
265                    self::add_menu( __( 'Akismet Anti-spam', 'jetpack-admin-ui' ), __( 'Akismet Anti-spam', 'jetpack-admin-ui' ), 'manage_options', 'akismet-key-config', array( 'Akismet_Admin', 'display_page' ) );
266                },
267                4
268            );
269
270        }
271    }
272
273    /**
274     * Callback to the admin_menu and network_admin_menu hooks that will register the enqueued menu items
275     *
276     * @return void
277     */
278    public static function admin_menu_hook_callback() {
279        $can_see_toplevel_menu  = true;
280        $jetpack_plugin_present = class_exists( 'Jetpack_React_Page' );
281        $icon                   = 'dashicons-admin-plugins';
282        if ( method_exists( '\Automattic\Jetpack\Assets\Logo', 'get_base64_admin_menu_logo' ) ) {
283            $icon = ( new \Automattic\Jetpack\Assets\Logo() )->get_base64_admin_menu_logo();
284        } elseif ( method_exists( '\Automattic\Jetpack\Assets\Logo', 'get_base64_logo' ) ) {
285            $icon = ( new \Automattic\Jetpack\Assets\Logo() )->get_base64_logo();
286        }
287
288        if ( ! $jetpack_plugin_present ) {
289            add_menu_page(
290                'Jetpack',
291                'Jetpack',
292                'edit_posts',
293                'jetpack',
294                '__return_null',
295                $icon,
296                3
297            );
298
299            // If Jetpack plugin is not present, user will only be able to see this menu if they have enough capability to at least one of the sub menus being added.
300            $can_see_toplevel_menu = false;
301        }
302
303        /*
304         * Sort here and register in that order, without passing the position on: core splices an
305         * int back in, and prepends 0 or less. See https://core.trac.wordpress.org/ticket/52035.
306         */
307        usort(
308            self::$menu_items,
309            function ( $a, $b ) {
310                $position_a = empty( $a['position'] ) ? 0 : $a['position'];
311                $position_b = empty( $b['position'] ) ? 0 : $b['position'];
312                $result     = $position_a <=> $position_b;
313
314                if ( 0 === $result ) {
315                    // Case-insensitive and number-aware, so "eCommerce" sorts with the Es.
316                    // Still a byte compare: a leading accented character sorts after Z.
317                    $result = strnatcasecmp( $a['menu_title'], $b['menu_title'] );
318                }
319
320                return $result;
321            }
322        );
323
324        $visibility = self::get_visibility_states();
325
326        self::$hidden_menu_slugs = array();
327
328        foreach ( self::$menu_items as $menu_item ) {
329            if ( ! current_user_can( $menu_item['capability'] ) ) {
330                continue;
331            }
332
333            /*
334             * A hidden item is still registered, so its page keeps resolving for links into it.
335             * It leaves the submenu on admin_head instead: core's access check reads $submenu.
336             */
337            if ( self::is_menu_item_visible( $menu_item, $visibility ) ) {
338                $can_see_toplevel_menu = true;
339            } else {
340                self::$hidden_menu_slugs[] = $menu_item['menu_slug'];
341            }
342
343            add_submenu_page(
344                'jetpack',
345                $menu_item['page_title'],
346                $menu_item['menu_title'],
347                $menu_item['capability'],
348                $menu_item['menu_slug'],
349                $menu_item['function']
350            );
351        }
352
353        if ( ! $jetpack_plugin_present ) {
354            remove_submenu_page( 'jetpack', 'jetpack' );
355        }
356
357        if ( ! $can_see_toplevel_menu ) {
358            remove_menu_page( 'jetpack' );
359        }
360
361        self::maybe_add_upgrade_menu_item();
362    }
363
364    /**
365     * Hooks the top level registration pass, without building the Jetpack menu that init() does.
366     *
367     * @return void
368     */
369    private static function init_top_level() {
370        if ( ! self::$top_level_initialized ) {
371            self::$top_level_initialized = true;
372            add_action( 'admin_menu', array( __CLASS__, 'top_level_menu_hook_callback' ), 1000 );
373            add_action( 'admin_head', array( __CLASS__, 'remove_hidden_menu_items' ) );
374        }
375    }
376
377    /**
378     * Registers the queued top level items, skipping the ones that should not be seen.
379     *
380     * These sit beside the Jetpack menu, so they never count towards keeping it alive.
381     *
382     * @return void
383     */
384    public static function top_level_menu_hook_callback() {
385        $visibility = self::get_visibility_states();
386
387        self::$hidden_top_level_slugs = array();
388
389        foreach ( self::$top_level_items as $menu_item ) {
390            if ( ! current_user_can( $menu_item['capability'] ) ) {
391                continue;
392            }
393
394            if ( ! self::is_menu_item_visible( $menu_item, $visibility ) ) {
395                self::$hidden_top_level_slugs[] = $menu_item['menu_slug'];
396            }
397
398            add_menu_page(
399                $menu_item['page_title'],
400                $menu_item['menu_title'],
401                $menu_item['capability'],
402                $menu_item['menu_slug'],
403                $menu_item['function'],
404                $menu_item['icon_url'],
405                $menu_item['position']
406            );
407        }
408    }
409
410    /**
411     * Adds a top level menu item under the same visibility gate and filter as add_menu().
412     *
413     * Unlike add_menu(), the page gets neither the core-notice CSS nor the design tokens.
414     * Parameters mirror add_menu_page(), with $args appended.
415     *
416     * @since 0.13.0
417     *
418     * @param string        $page_title The text to be displayed in the title tags of the page when the menu
419     *                                  is selected.
420     * @param string        $menu_title The text to be used for the menu.
421     * @param string        $capability The capability required for this menu to be displayed to the user.
422     * @param string        $menu_slug  The slug name to refer to this menu by. Should be unique for this menu.
423     * @param callable|null $function   The function to be called to output the content for this page.
424     * @param string        $icon_url   The URL to the icon to be used for this menu, or a dashicons class.
425     * @param int|null      $position   The position in the menu order this item should appear.
426     * @param array         $args       Optional. Visibility declaration for this item; see add_menu().
427     *
428     * @return string The resulting page's hook_suffix
429     */
430    public static function add_top_level_menu( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url = '', $position = null, $args = array() ) {
431        self::init_top_level();
432        self::$top_level_items[] = compact( 'page_title', 'menu_title', 'capability', 'menu_slug', 'function', 'icon_url', 'position', 'args' );
433
434        // Same derivation as get_plugin_page_hookname(), which strips ".php" anywhere in the slug.
435        return 'toplevel_page_' . preg_replace( '!\.php!', '', plugin_basename( $menu_slug ) );
436    }
437
438    /**
439     * Adds a new submenu to the Jetpack Top level menu
440     *
441     * The parameters this method accepts are the same as @see add_submenu_page. This class will
442     * aggreagate all menu items registered by stand-alone plugins and make sure they all go under the same
443     * Jetpack top level menu. It will also handle the top level menu registration in case the Jetpack plugin is not present.
444     *
445     * @param string        $page_title  The text to be displayed in the title tags of the page when the menu
446     *                                   is selected.
447     * @param string        $menu_title  The text to be used for the menu.
448     * @param string        $capability  The capability required for this menu to be displayed to the user.
449     * @param string        $menu_slug   The slug name to refer to this menu by. Should be unique for this menu
450     *                                   and only include lowercase alphanumeric, dashes, and underscores characters
451     *                                   to be compatible with sanitize_key().
452     * @param callable|null $function    The function to be called to output the content for this page.
453     * @param int|null      $position    One of the POSITION_* tiers; any other value is ignored. Leave empty typically.
454     * @param array         $args        Optional. Visibility declaration for this item:
455     *                                   - 'product' (string) My Jetpack product slug whose activation gates the item.
456     *                                   - 'module'  (string) Jetpack module name, for items with no product class.
457     *                                   - 'key'     (string) The name hosts use for this item in the visibility
458     *                                                        filter. Declare one on every item; see get_item_key().
459     *                                   An item that declares no gate is always shown.
460     *
461     * @return string The resulting page's hook_suffix
462     */
463    public static function add_menu( $page_title, $menu_title, $capability, $menu_slug, $function, $position = null, $args = array() ) {
464        self::init();
465
466        /*
467         * Anything but a tier would opt the item out of the alphabetical order, so treat it as omitted.
468         * @todo Add _doing_it_wrong() here after December 2026. Until all our own plugins ship tier-only
469         * positions, it would have the latest release of one Jetpack plugin warning about another.
470         */
471        $position = is_numeric( $position ) && in_array( (int) $position, self::CALLER_POSITIONS, true ) ? (int) $position : null;
472
473        self::$menu_items[] = compact( 'page_title', 'menu_title', 'capability', 'menu_slug', 'function', 'position', 'args' );
474
475        /**
476         * Let's return the page hook so consumers can use.
477         * We know all pages will be under Jetpack top level menu page, so we can hardcode the first part of the string.
478         * Using get_plugin_page_hookname here won't work because the top level page is not registered yet.
479         */
480        $hook = 'jetpack_page_' . $menu_slug;
481
482        // Track the page hook so the design-tokens stylesheet can be scoped to it.
483        self::$page_hooks[] = $hook;
484
485        // Hide WordPress core admin notices on this Jetpack page. The load-<hook>
486        // action only fires when the matching screen is being rendered, so this
487        // stays scoped to Jetpack pages and reaches every page registered here.
488        add_action( 'load-' . $hook, array( __CLASS__, 'hide_core_admin_notices' ) );
489        add_action( 'load-' . $hook . '-network', array( __CLASS__, 'hide_core_admin_notices' ) );
490
491        return $hook;
492    }
493
494    /**
495     * Enqueues the stylesheet that hides WordPress core admin notices on the current Jetpack page.
496     *
497     * Hooked from the page's load-<hook> action so it only runs on Jetpack screens. That action
498     * runs before admin_enqueue_scripts, so the handle is queued in time to be printed.
499     *
500     * @return void
501     */
502    public static function hide_core_admin_notices() {
503        // wp_add_inline_style() appends, so the CSS is attached only while the handle is new to the request.
504        if ( ! wp_style_is( self::HIDE_CORE_NOTICES_HANDLE, 'registered' ) ) {
505            wp_register_style( self::HIDE_CORE_NOTICES_HANDLE, false, array(), self::PACKAGE_VERSION );
506            wp_add_inline_style( self::HIDE_CORE_NOTICES_HANDLE, self::get_hide_core_admin_notices_styles() );
507        }
508
509        wp_enqueue_style( self::HIDE_CORE_NOTICES_HANDLE );
510    }
511
512    /**
513     * Enqueues the CSS that hides WordPress core admin notices.
514     *
515     * Callers must run this before WordPress flushes the style queue in
516     * print_admin_styles() (admin_print_styles, priority 20). Later than that,
517     * the handle is never printed. The previous admin_print_styles priority-10
518     * hook still works.
519     *
520     * @deprecated 0.10.0 Use hide_core_admin_notices(), which enqueues the CSS.
521     *
522     * @return void
523     */
524    public static function print_hide_core_admin_notices_style() {
525        _deprecated_function( __METHOD__, 'admin-ui-0.10.0', __CLASS__ . '::hide_core_admin_notices' );
526        self::hide_core_admin_notices();
527    }
528
529    /**
530     * Gets the CSS that hides WordPress core admin notices.
531     *
532     * We only target direct children of #wpbody-content (where core renders notices via the
533     * admin_notices / all_admin_notices hooks). This intentionally leaves JITMs untouched â€”
534     * they output `.jetpack-jitm-message`, not `.notice` â€” and leaves in-app/React notices
535     * untouched, since those render deeper inside `.wrap`. The CSS rides on a source-less
536     * handle rather than a build asset so it also reaches older Jetpack pages that ship no
537     * stylesheet of their own.
538     *
539     * @return string CSS rules.
540     */
541    private static function get_hide_core_admin_notices_styles() {
542        return '
543        #wpbody-content > .notice,
544        #wpbody-content > .update-nag,
545        #wpbody-content > .updated,
546        #wpbody-content > .error { display: none !important; }
547        ';
548    }
549
550    /**
551     * Sets the callback that resolves a menu item's declared gate.
552     *
553     * The callback receives the item's $args array and returns true (gate satisfied),
554     * false (not satisfied), or null when it cannot answer â€” an unknown product slug,
555     * for instance. Null is treated as satisfied, so a gate this package cannot resolve
556     * never removes a menu item.
557     *
558     * This is the seam My Jetpack fills. Hosts wanting to shape the sidebar should use the
559     * `jetpack_admin_menu_visibility` filter instead, which takes precedence: an item the
560     * filter names is never put to this callback at all.
561     *
562     * @param callable|null $resolver Resolver callback, or null to clear it.
563     * @return void
564     */
565    public static function set_visibility_resolver( $resolver ) {
566        self::$visibility_resolver = $resolver;
567    }
568
569    /**
570     * Takes hidden items out of the sidebar before it renders.
571     *
572     * Runs on admin_head, after core's access check has already resolved the current page,
573     * so a hidden item's page stays reachable while its entry disappears.
574     *
575     * @return void
576     */
577    public static function remove_hidden_menu_items() {
578        foreach ( self::$hidden_menu_slugs as $menu_slug ) {
579            remove_submenu_page( 'jetpack', plugin_basename( $menu_slug ) );
580        }
581
582        foreach ( self::$hidden_top_level_slugs as $menu_slug ) {
583            remove_menu_page( plugin_basename( $menu_slug ) );
584        }
585    }
586
587    /**
588     * Returns the name a host uses for a menu item in the visibility filter.
589     *
590     * The menu slug is only a fallback. It is the wrong thing to hand a host as an identifier:
591     * several items register a URL as their slug, Blaze's is filterable, and VideoPress swaps
592     * between two slugs depending on whether the module is active â€” so a host naming one of
593     * them is naming a moving target, or only half an item.
594     *
595     * @param array $menu_item A registered menu item.
596     * @return string
597     */
598    private static function get_item_key( array $menu_item ) {
599        if ( ! empty( $menu_item['args']['key'] ) ) {
600            return (string) $menu_item['args']['key'];
601        }
602
603        return (string) $menu_item['menu_slug'];
604    }
605
606    /**
607     * Builds the item => state map and hands it to hosts to amend.
608     *
609     * @return array Map of item key to one of the VISIBILITY_* states.
610     */
611    private static function get_visibility_states() {
612        // This filter is one a policy feeds, and nothing else need have read the policy this request.
613        if ( method_exists( Feature_Policy::class, 'ensure_hooks' ) ) {
614            Feature_Policy::ensure_hooks();
615        }
616
617        $states = array();
618        $items  = array_merge( self::$menu_items, self::$top_level_items );
619
620        foreach ( $items as $menu_item ) {
621            $states[ self::get_item_key( $menu_item ) ] = self::VISIBILITY_DEFAULT;
622        }
623
624        /**
625         * Filters which Jetpack items appear in the wp-admin sidebar.
626         *
627         * Governs the sidebar entry only â€” a hidden item's page stays reachable by URL, so this
628         * is not an access control. States: 'default' follows the item's feature, 'visible' shows it, 'hidden' removes it.
629         *
630         * @since 0.12.0
631         *
632         * @param array $states     Map of item key (menu slug unless the item declared one) to state.
633         * @param array $menu_items The registered menu items, for context.
634         */
635        $states = apply_filters( 'jetpack_admin_menu_visibility', $states, $items );
636
637        return is_array( $states ) ? $states : array();
638    }
639
640    /**
641     * Decides whether a single menu item should appear in the sidebar.
642     *
643     * @param array $menu_item  A registered menu item.
644     * @param array $visibility The resolved state map from get_visibility_states().
645     * @return bool
646     */
647    private static function is_menu_item_visible( array $menu_item, array $visibility ) {
648        $key   = self::get_item_key( $menu_item );
649        $state = $visibility[ $key ] ?? self::VISIBILITY_DEFAULT;
650
651        if ( self::VISIBILITY_HIDDEN === $state ) {
652            return false;
653        }
654
655        if ( self::VISIBILITY_VISIBLE === $state ) {
656            return true;
657        }
658
659        return self::is_gate_satisfied( $menu_item['args'] ?? array() );
660    }
661
662    /**
663     * Asks the resolver whether an item's declared gate is satisfied.
664     *
665     * Everything here fails open. An item that declares no gate, a site with no resolver
666     * registered, and a gate the resolver does not recognize all keep the item in the
667     * sidebar, so adopting this mechanism cannot remove an item nobody asked it to.
668     *
669     * @param array $args The item's visibility declaration.
670     * @return bool
671     */
672    private static function is_gate_satisfied( array $args ) {
673        if ( ! isset( $args['product'] ) && ! isset( $args['module'] ) ) {
674            return true;
675        }
676
677        if ( ! is_callable( self::$visibility_resolver ) ) {
678            return true;
679        }
680
681        $resolved = call_user_func( self::$visibility_resolver, $args );
682
683        return null === $resolved ? true : (bool) $resolved;
684    }
685
686    /**
687     * Removes an already added submenu
688     *
689     * @param string $menu_slug   The slug of the submenu to remove.
690     *
691     * @return array|false The removed submenu on success, false if not found.
692     */
693    public static function remove_menu( $menu_slug ) {
694
695        foreach ( self::$menu_items as $index => $menu_item ) {
696            if ( $menu_item['menu_slug'] === $menu_slug ) {
697                unset( self::$menu_items[ $index ] );
698
699                return $menu_item;
700            }
701        }
702
703        return false;
704    }
705
706    /**
707     * Gets the slug for the first item under the Jetpack top level menu
708     *
709     * Skips hidden items rather than reading $submenu alone, because callers on admin_enqueue_scripts
710     * and outside wp-admin ask before â€” or without â€” the admin_head pass that drops them.
711     *
712     * @return string|null
713     */
714    public static function get_top_level_menu_item_slug() {
715        global $submenu;
716
717        if ( empty( $submenu['jetpack'] ) ) {
718            return null;
719        }
720
721        $hidden = array_map( 'plugin_basename', self::$hidden_menu_slugs );
722
723        foreach ( $submenu['jetpack'] as $item ) {
724            if ( isset( $item[2] ) && ! in_array( $item[2], $hidden, true ) ) {
725                return $item[2];
726            }
727        }
728
729        return null;
730    }
731
732    /**
733     * Gets the URL for the first item under the Jetpack top level menu
734     *
735     * @param string $fallback If Jetpack menu is not there or no children is found, return this fallback instead. Default to admin_url().
736     * @return string
737     */
738    public static function get_top_level_menu_item_url( $fallback = false ) {
739        $slug = self::get_top_level_menu_item_slug();
740
741        if ( $slug ) {
742            $url = menu_page_url( $slug, false );
743            return $url;
744        }
745
746        $url = $fallback ? $fallback : admin_url();
747        return $url;
748    }
749
750    /**
751     * Checks whether the current site should show the upgrade menu item.
752     *
753     * The upgrade menu is only shown to administrators on free-plan sites
754     * that are not hosted on WordPress.com.
755     *
756     * @return bool True if the upgrade menu should be shown.
757     */
758    private static function should_show_upgrade_menu() {
759
760        // Only show to administrators.
761        if ( ! current_user_can( 'manage_options' ) ) {
762            return false;
763        }
764
765        // Don't show upsells on WordPress.com platform.
766        if ( class_exists( '\Automattic\Jetpack\Status\Host' ) ) {
767            $host = new \Automattic\Jetpack\Status\Host();
768            if ( $host->is_wpcom_platform() ) {
769                return false;
770            }
771        }
772
773        // Don't show upsells in offline/development mode.
774        if ( class_exists( '\Automattic\Jetpack\Status' ) ) {
775            $status = new \Automattic\Jetpack\Status();
776            if ( $status->is_offline_mode() ) {
777                return false;
778            }
779        }
780
781        // Only show after the site and current user are connected.
782        if ( ! self::is_site_and_user_connected() ) {
783            return false;
784        }
785
786        // Only show to free-plan sites.
787        return self::is_free_plan();
788    }
789
790    /**
791     * Checks whether the site and current user are connected to WordPress.com.
792     *
793     * @return bool True if site and current user are connected.
794     */
795    private static function is_site_and_user_connected() {
796        $connection_manager = self::$connection_manager;
797        if ( ! $connection_manager && class_exists( '\Automattic\Jetpack\Connection\Manager' ) ) {
798            $connection_manager       = new \Automattic\Jetpack\Connection\Manager();
799            self::$connection_manager = $connection_manager;
800        }
801
802        if (
803            $connection_manager
804            && is_callable( array( $connection_manager, 'is_connected' ) )
805            && is_callable( array( $connection_manager, 'is_user_connected' ) )
806        ) {
807            return (bool) $connection_manager->is_connected()
808                && (bool) $connection_manager->is_user_connected( get_current_user_id() );
809        }
810
811        return false;
812    }
813
814    /**
815     * Sets the connection manager dependency; used by tests.
816     *
817     * @param object|null $connection_manager Connection manager object.
818     * @return void
819     */
820    public static function set_connection_manager( $connection_manager ) {
821        self::$connection_manager = $connection_manager;
822    }
823
824    /**
825     * Checks whether the current site is on a free Jetpack plan with no active paid license.
826     *
827     * @return bool True if the site has no paid plan.
828     */
829    private static function is_free_plan() {
830        // Check the active plan - use the is_free field or product_slug.
831        $plan = get_option( 'jetpack_active_plan', array() );
832
833        // Back-compat: older plan payloads use class to indicate paid plans.
834        if ( isset( $plan['class'] ) && 'free' !== $plan['class'] ) {
835            return false;
836        }
837
838        // If the plan explicitly says it's not free, trust that.
839        if ( isset( $plan['is_free'] ) && false === $plan['is_free'] ) {
840            return false;
841        }
842
843        // Check if the product slug indicates a paid plan.
844        if ( isset( $plan['product_slug'] ) && 'jetpack_free' !== $plan['product_slug'] ) {
845            return false;
846        }
847
848        // Also check for site products (licenses can add products without changing plan).
849        $products = get_option( 'jetpack_site_products', array() );
850        if ( ! empty( $products ) && is_array( $products ) ) {
851            return false;
852        }
853
854        return true;
855    }
856
857    /**
858     * Conditionally adds an "Upgrade Jetpack" submenu item for free-plan sites.
859     *
860     * Only shown to users with manage_options capability on self-hosted sites without a paid Jetpack plan or license.
861     *
862     * @return void
863     */
864    private static function maybe_add_upgrade_menu_item() {
865        if ( ! self::should_show_upgrade_menu() ) {
866            return;
867        }
868
869        $upgrade_url = class_exists( '\Automattic\Jetpack\Redirect' )
870            ? \Automattic\Jetpack\Redirect::get_url( self::UPGRADE_MENU_SLUG )
871            : self::UPGRADE_MENU_FALLBACK_URL;
872
873        $menu_title = esc_html__( 'Upgrade Jetpack', 'jetpack-admin-ui' );
874
875        add_submenu_page(
876            'jetpack',
877            $menu_title,
878            $menu_title,
879            'manage_options',
880            esc_url( $upgrade_url ),
881            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
882            self::POSITION_UPGRADE
883        );
884
885        // Add a CSS class to the <li> element so styles can target it precisely.
886        global $submenu;
887        if ( ! empty( $submenu['jetpack'] ) ) {
888            foreach ( $submenu['jetpack'] as $index => $item ) {
889                if ( isset( $item[2] ) && false !== strpos( $item[2], self::UPGRADE_MENU_SLUG ) ) {
890                    // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
891                    $submenu['jetpack'][ $index ][4] = ( ! empty( $item[4] ) ? $item[4] . ' ' : '' ) . self::UPGRADE_MENU_SLUG;
892                    break;
893                }
894            }
895        }
896    }
897
898    /**
899     * Enqueues admin styles for the "Upgrade Jetpack" menu item.
900     *
901     * The sidebar menu is visible on every admin page, so styles load globally.
902     * Only enqueues for free-plan sites on self-hosted installs.
903     *
904     * @return void
905     */
906    public static function add_upgrade_menu_item_styles() {
907        if ( ! self::should_show_upgrade_menu() ) {
908            return;
909        }
910
911        $asset_file = dirname( __DIR__ ) . '/build/admin-ui-upgrade-menu.asset.php';
912        $asset      = file_exists( $asset_file ) ? require $asset_file : array();
913
914        wp_enqueue_style(
915            'jetpack-admin-ui-upgrade-menu',
916            plugins_url( '../build/admin-ui-upgrade-menu.css', __FILE__ ),
917            $asset['dependencies'] ?? array(),
918            $asset['version'] ?? self::PACKAGE_VERSION
919        );
920
921        self::enqueue_upgrade_menu_tracks_script( $asset );
922    }
923
924    /**
925     * Enqueues the shared, token-only WPDS design-tokens stylesheet.
926     *
927     * Single entry point for any consumer that needs WPDS `var(--wpds-*)` values
928     * to resolve at runtime on a Jetpack admin page. Registers the handle on
929     * first use (idempotent) and enqueues it; the caller is responsible for
930     * scoping the call to the right page(s). Since admin-ui is a dependency of
931     * the Jetpack plugin and the modernized packages, both the plugin's
932     * legacy/wrap_ui gate and this package's own dashboards call through here,
933     * so the handle has a single owner and there is no duplicated enqueue logic.
934     *
935     * @return void
936     */
937    public static function enqueue_design_tokens() {
938        self::register_design_tokens_style();
939        wp_enqueue_style( self::DESIGN_TOKENS_HANDLE );
940    }
941
942    /**
943     * Registers the shared, token-only WPDS design-tokens stylesheet.
944     *
945     * The stylesheet only defines `:root{--wpds-*}` custom properties (no
946     * component or class styles), giving every Jetpack admin page a single
947     * runtime source for design tokens. It is safe to call repeatedly:
948     * wp_register_style() is a no-op once the handle is registered.
949     *
950     * @return void
951     */
952    private static function register_design_tokens_style() {
953        if ( wp_style_is( self::DESIGN_TOKENS_HANDLE, 'registered' ) ) {
954            return;
955        }
956
957        $asset_file = dirname( __DIR__ ) . '/build/design-tokens.asset.php';
958        $asset      = file_exists( $asset_file ) ? require $asset_file : array();
959
960        wp_register_style(
961            self::DESIGN_TOKENS_HANDLE,
962            plugins_url( '../build/design-tokens.css', __FILE__ ),
963            $asset['dependencies'] ?? array(),
964            $asset['version'] ?? self::PACKAGE_VERSION
965        );
966    }
967
968    /**
969     * Enqueues the design tokens on the pages registered through this class.
970     *
971     * This is the admin_enqueue_scripts callback for the modernized Jetpack
972     * dashboards. Scoped to self::$page_hooks so the tokens load wherever a
973     * modernized dashboard renders, regardless of plan or connection state; the
974     * actual enqueue is delegated to the reusable enqueue_design_tokens() API.
975     *
976     * @param string $hook_suffix The current admin page's hook suffix.
977     * @return void
978     */
979    public static function maybe_enqueue_design_tokens( $hook_suffix ) {
980        if ( ! in_array( $hook_suffix, self::$page_hooks, true ) ) {
981            return;
982        }
983
984        self::enqueue_design_tokens();
985    }
986
987    /**
988     * Enqueues Tracks for the upgrade submenu item.
989     *
990     * @param array $asset Parsed contents of admin-ui-upgrade-menu.asset.php.
991     * @return void
992     */
993    private static function enqueue_upgrade_menu_tracks_script( $asset ) {
994        if ( ! class_exists( '\Automattic\Jetpack\Tracking' ) ) {
995            return;
996        }
997
998        Tracking::register_tracks_functions_scripts( true );
999
1000        wp_enqueue_script(
1001            'jetpack-admin-ui-upgrade-menu-tracking',
1002            plugins_url( '../build/admin-ui-upgrade-menu-tracking.js', __FILE__ ),
1003            $asset['dependencies'] ?? array(),
1004            $asset['version'] ?? self::PACKAGE_VERSION,
1005            true
1006        );
1007
1008        $current_screen   = get_current_screen();
1009        $is_admin         = current_user_can( 'jetpack_disconnect' );
1010        $site_id          = class_exists( 'Jetpack_Options' ) ? Jetpack_Options::get_option( 'id' ) : null;
1011        $tracks_user_data = class_exists( 'Jetpack_Tracks_Client' ) ? Jetpack_Tracks_Client::get_connected_user_tracks_identity() : null;
1012
1013        wp_localize_script(
1014            'jetpack-admin-ui-upgrade-menu-tracking',
1015            'jetpackAdminUiUpgradeMenu',
1016            array(
1017                'menuItemClass'   => self::UPGRADE_MENU_SLUG,
1018                'tracksUserData'  => $tracks_user_data,
1019                'tracksEventData' => array(
1020                    'is_admin'       => $is_admin,
1021                    'current_screen' => $current_screen ? $current_screen->id : false,
1022                    'blog_id'        => $site_id,
1023                ),
1024            )
1025        );
1026    }
1027}