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