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