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