Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
83.63% covered (warning)
83.63%
143 / 171
42.86% covered (danger)
42.86%
6 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin_Menu
83.63% covered (warning)
83.63%
143 / 171
42.86% covered (danger)
42.86%
6 / 14
81.98
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 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
93.33% covered (success)
93.33%
42 / 45
0.00% covered (danger)
0.00%
0 / 1
10.03
 add_menu
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 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
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 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_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.8.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     * Whether this class has been initialized
40     *
41     * @var boolean
42     */
43    private static $initialized = false;
44
45    /**
46     * List of menu items enqueued to be added
47     *
48     * @var array
49     */
50    private static $menu_items = array();
51
52    /**
53     * Optional connection manager dependency.
54     *
55     * @var object|null
56     */
57    private static $connection_manager = null;
58
59    /**
60     * Initialize the class and set up the main hook
61     *
62     * @return void
63     */
64    public static function init() {
65        if ( ! self::$initialized ) {
66            self::$initialized = true;
67            self::handle_akismet_menu();
68            add_action( 'admin_menu', array( __CLASS__, 'admin_menu_hook_callback' ), 1000 ); // Jetpack uses 998.
69            add_action( 'network_admin_menu', array( __CLASS__, 'admin_menu_hook_callback' ), 1000 ); // Jetpack uses 998.
70            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'add_upgrade_menu_item_styles' ) );
71        }
72    }
73
74    /**
75     * Handles the Akismet menu item when used alongside other stand-alone plugins
76     *
77     * 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,
78     * we use this method to move the menu item.
79     */
80    private static function handle_akismet_menu() {
81        if ( class_exists( 'Akismet_Admin' ) ) {
82            add_action(
83                'admin_menu',
84                function () {
85                    // Prevent Akismet from adding a menu item.
86                    remove_action( 'admin_menu', array( 'Akismet_Admin', 'admin_menu' ), 5 );
87
88                    // Add an Anti-spam menu item for Jetpack.
89                    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' ), 6 );
90                },
91                4
92            );
93
94        }
95    }
96
97    /**
98     * Callback to the admin_menu and network_admin_menu hooks that will register the enqueued menu items
99     *
100     * @return void
101     */
102    public static function admin_menu_hook_callback() {
103        $can_see_toplevel_menu  = true;
104        $jetpack_plugin_present = class_exists( 'Jetpack_React_Page' );
105        $icon                   = method_exists( '\Automattic\Jetpack\Assets\Logo', 'get_base64_logo' )
106            ? ( new \Automattic\Jetpack\Assets\Logo() )->get_base64_logo()
107            : 'dashicons-admin-plugins';
108
109        if ( ! $jetpack_plugin_present ) {
110            add_menu_page(
111                'Jetpack',
112                'Jetpack',
113                'edit_posts',
114                'jetpack',
115                '__return_null',
116                $icon,
117                3
118            );
119
120            // 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.
121            $can_see_toplevel_menu = false;
122        }
123
124        /**
125         * The add_sub_menu function has a bug and will not keep the right order of menu items.
126         *
127         * @see https://core.trac.wordpress.org/ticket/52035
128         * Let's order the items before registering them.
129         * Since this all happens after the Jetpack plugin menu items were added, all items will be added after Jetpack plugin items - unless position is very low number (smaller than the number of menu items present in Jetpack plugin).
130         */
131        usort(
132            self::$menu_items,
133            function ( $a, $b ) {
134                $position_a = empty( $a['position'] ) ? 0 : $a['position'];
135                $position_b = empty( $b['position'] ) ? 0 : $b['position'];
136                $result     = $position_a <=> $position_b;
137
138                if ( 0 === $result ) {
139                    $result = strcmp( $a['menu_title'], $b['menu_title'] );
140                }
141
142                return $result;
143            }
144        );
145
146        foreach ( self::$menu_items as $menu_item ) {
147            if ( ! current_user_can( $menu_item['capability'] ) ) {
148                continue;
149            }
150
151            $can_see_toplevel_menu = true;
152
153            add_submenu_page(
154                'jetpack',
155                $menu_item['page_title'],
156                $menu_item['menu_title'],
157                $menu_item['capability'],
158                $menu_item['menu_slug'],
159                $menu_item['function'],
160                $menu_item['position']
161            );
162        }
163
164        if ( ! $jetpack_plugin_present ) {
165            remove_submenu_page( 'jetpack', 'jetpack' );
166        }
167
168        if ( ! $can_see_toplevel_menu ) {
169            remove_menu_page( 'jetpack' );
170        }
171
172        self::maybe_add_upgrade_menu_item();
173    }
174
175    /**
176     * Adds a new submenu to the Jetpack Top level menu
177     *
178     * The parameters this method accepts are the same as @see add_submenu_page. This class will
179     * aggreagate all menu items registered by stand-alone plugins and make sure they all go under the same
180     * Jetpack top level menu. It will also handle the top level menu registration in case the Jetpack plugin is not present.
181     *
182     * @param string        $page_title  The text to be displayed in the title tags of the page when the menu
183     *                                   is selected.
184     * @param string        $menu_title  The text to be used for the menu.
185     * @param string        $capability  The capability required for this menu to be displayed to the user.
186     * @param string        $menu_slug   The slug name to refer to this menu by. Should be unique for this menu
187     *                                   and only include lowercase alphanumeric, dashes, and underscores characters
188     *                                   to be compatible with sanitize_key().
189     * @param callable|null $function    The function to be called to output the content for this page.
190     * @param int           $position    The position in the menu order this item should appear. Leave empty typically.
191     *
192     * @return string The resulting page's hook_suffix
193     */
194    public static function add_menu( $page_title, $menu_title, $capability, $menu_slug, $function, $position = null ) {
195        self::init();
196        self::$menu_items[] = compact( 'page_title', 'menu_title', 'capability', 'menu_slug', 'function', 'position' );
197
198        /**
199         * Let's return the page hook so consumers can use.
200         * We know all pages will be under Jetpack top level menu page, so we can hardcode the first part of the string.
201         * Using get_plugin_page_hookname here won't work because the top level page is not registered yet.
202         */
203        return 'jetpack_page_' . $menu_slug;
204    }
205
206    /**
207     * Removes an already added submenu
208     *
209     * @param string $menu_slug   The slug of the submenu to remove.
210     *
211     * @return array|false The removed submenu on success, false if not found.
212     */
213    public static function remove_menu( $menu_slug ) {
214
215        foreach ( self::$menu_items as $index => $menu_item ) {
216            if ( $menu_item['menu_slug'] === $menu_slug ) {
217                unset( self::$menu_items[ $index ] );
218
219                return $menu_item;
220            }
221        }
222
223        return false;
224    }
225
226    /**
227     * Gets the slug for the first item under the Jetpack top level menu
228     *
229     * @return string|null
230     */
231    public static function get_top_level_menu_item_slug() {
232        global $submenu;
233        if ( ! empty( $submenu['jetpack'] ) ) {
234            $item = reset( $submenu['jetpack'] );
235            if ( isset( $item[2] ) ) {
236                return $item[2];
237            }
238        }
239    }
240
241    /**
242     * Gets the URL for the first item under the Jetpack top level menu
243     *
244     * @param string $fallback If Jetpack menu is not there or no children is found, return this fallback instead. Default to admin_url().
245     * @return string
246     */
247    public static function get_top_level_menu_item_url( $fallback = false ) {
248        $slug = self::get_top_level_menu_item_slug();
249
250        if ( $slug ) {
251            $url = menu_page_url( $slug, false );
252            return $url;
253        }
254
255        $url = $fallback ? $fallback : admin_url();
256        return $url;
257    }
258
259    /**
260     * Checks whether the current site should show the upgrade menu item.
261     *
262     * The upgrade menu is only shown to administrators on free-plan sites
263     * that are not hosted on WordPress.com.
264     *
265     * @return bool True if the upgrade menu should be shown.
266     */
267    private static function should_show_upgrade_menu() {
268
269        // Only show to administrators.
270        if ( ! current_user_can( 'manage_options' ) ) {
271            return false;
272        }
273
274        // Don't show upsells on WordPress.com platform.
275        if ( class_exists( '\Automattic\Jetpack\Status\Host' ) ) {
276            $host = new \Automattic\Jetpack\Status\Host();
277            if ( $host->is_wpcom_platform() ) {
278                return false;
279            }
280        }
281
282        // Don't show upsells in offline/development mode.
283        if ( class_exists( '\Automattic\Jetpack\Status' ) ) {
284            $status = new \Automattic\Jetpack\Status();
285            if ( $status->is_offline_mode() ) {
286                return false;
287            }
288        }
289
290        // Only show after the site and current user are connected.
291        if ( ! self::is_site_and_user_connected() ) {
292            return false;
293        }
294
295        // Only show to free-plan sites.
296        return self::is_free_plan();
297    }
298
299    /**
300     * Checks whether the site and current user are connected to WordPress.com.
301     *
302     * @return bool True if site and current user are connected.
303     */
304    private static function is_site_and_user_connected() {
305        $connection_manager = self::$connection_manager;
306        if ( ! $connection_manager && class_exists( '\Automattic\Jetpack\Connection\Manager' ) ) {
307            $connection_manager       = new \Automattic\Jetpack\Connection\Manager();
308            self::$connection_manager = $connection_manager;
309        }
310
311        if (
312            $connection_manager
313            && is_callable( array( $connection_manager, 'is_connected' ) )
314            && is_callable( array( $connection_manager, 'is_user_connected' ) )
315        ) {
316            return (bool) $connection_manager->is_connected()
317                && (bool) $connection_manager->is_user_connected( get_current_user_id() );
318        }
319
320        return false;
321    }
322
323    /**
324     * Sets the connection manager dependency; used by tests.
325     *
326     * @param object|null $connection_manager Connection manager object.
327     * @return void
328     */
329    public static function set_connection_manager( $connection_manager ) {
330        self::$connection_manager = $connection_manager;
331    }
332
333    /**
334     * Checks whether the current site is on a free Jetpack plan with no active paid license.
335     *
336     * @return bool True if the site has no paid plan.
337     */
338    private static function is_free_plan() {
339        // Check the active plan - use the is_free field or product_slug.
340        $plan = get_option( 'jetpack_active_plan', array() );
341
342        // Back-compat: older plan payloads use class to indicate paid plans.
343        if ( isset( $plan['class'] ) && 'free' !== $plan['class'] ) {
344            return false;
345        }
346
347        // If the plan explicitly says it's not free, trust that.
348        if ( isset( $plan['is_free'] ) && false === $plan['is_free'] ) {
349            return false;
350        }
351
352        // Check if the product slug indicates a paid plan.
353        if ( isset( $plan['product_slug'] ) && 'jetpack_free' !== $plan['product_slug'] ) {
354            return false;
355        }
356
357        // Also check for site products (licenses can add products without changing plan).
358        $products = get_option( 'jetpack_site_products', array() );
359        if ( ! empty( $products ) && is_array( $products ) ) {
360            return false;
361        }
362
363        return true;
364    }
365
366    /**
367     * Conditionally adds an "Upgrade Jetpack" submenu item for free-plan sites.
368     *
369     * Only shown to users with manage_options capability on self-hosted sites without a paid Jetpack plan or license.
370     *
371     * @return void
372     */
373    private static function maybe_add_upgrade_menu_item() {
374        if ( ! self::should_show_upgrade_menu() ) {
375            return;
376        }
377
378        $upgrade_url = class_exists( '\Automattic\Jetpack\Redirect' )
379            ? \Automattic\Jetpack\Redirect::get_url( self::UPGRADE_MENU_SLUG )
380            : self::UPGRADE_MENU_FALLBACK_URL;
381
382        $menu_title = esc_html__( 'Upgrade Jetpack', 'jetpack-admin-ui' );
383
384        add_submenu_page(
385            'jetpack',
386            $menu_title,
387            $menu_title,
388            'manage_options',
389            esc_url( $upgrade_url ),
390            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
391            999
392        );
393
394        // Add a CSS class to the <li> element so styles can target it precisely.
395        global $submenu;
396        if ( ! empty( $submenu['jetpack'] ) ) {
397            foreach ( $submenu['jetpack'] as $index => $item ) {
398                if ( isset( $item[2] ) && false !== strpos( $item[2], self::UPGRADE_MENU_SLUG ) ) {
399                    // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
400                    $submenu['jetpack'][ $index ][4] = ( ! empty( $item[4] ) ? $item[4] . ' ' : '' ) . self::UPGRADE_MENU_SLUG;
401                    break;
402                }
403            }
404        }
405    }
406
407    /**
408     * Enqueues admin styles for the "Upgrade Jetpack" menu item.
409     *
410     * The sidebar menu is visible on every admin page, so styles load globally.
411     * Only enqueues for free-plan sites on self-hosted installs.
412     *
413     * @return void
414     */
415    public static function add_upgrade_menu_item_styles() {
416        if ( ! self::should_show_upgrade_menu() ) {
417            return;
418        }
419
420        $asset_file = dirname( __DIR__ ) . '/build/admin-ui-upgrade-menu.asset.php';
421        $asset      = file_exists( $asset_file ) ? require $asset_file : array();
422
423        wp_enqueue_style(
424            'jetpack-admin-ui-upgrade-menu',
425            plugins_url( '../build/admin-ui-upgrade-menu.css', __FILE__ ),
426            $asset['dependencies'] ?? array(),
427            $asset['version'] ?? self::PACKAGE_VERSION
428        );
429
430        self::enqueue_upgrade_menu_tracks_script( $asset );
431    }
432
433    /**
434     * Enqueues Tracks for the upgrade submenu item.
435     *
436     * @param array $asset Parsed contents of admin-ui-upgrade-menu.asset.php.
437     * @return void
438     */
439    private static function enqueue_upgrade_menu_tracks_script( $asset ) {
440        if ( ! class_exists( '\Automattic\Jetpack\Tracking' ) ) {
441            return;
442        }
443
444        Tracking::register_tracks_functions_scripts( true );
445
446        wp_enqueue_script(
447            'jetpack-admin-ui-upgrade-menu-tracking',
448            plugins_url( '../build/admin-ui-upgrade-menu-tracking.js', __FILE__ ),
449            $asset['dependencies'] ?? array(),
450            $asset['version'] ?? self::PACKAGE_VERSION,
451            true
452        );
453
454        $current_screen   = get_current_screen();
455        $is_admin         = current_user_can( 'jetpack_disconnect' );
456        $site_id          = class_exists( 'Jetpack_Options' ) ? Jetpack_Options::get_option( 'id' ) : null;
457        $tracks_user_data = class_exists( 'Jetpack_Tracks_Client' ) ? Jetpack_Tracks_Client::get_connected_user_tracks_identity() : null;
458
459        wp_localize_script(
460            'jetpack-admin-ui-upgrade-menu-tracking',
461            'jetpackAdminUiUpgradeMenu',
462            array(
463                'menuItemClass'   => self::UPGRADE_MENU_SLUG,
464                'tracksUserData'  => $tracks_user_data,
465                'tracksEventData' => array(
466                    'is_admin'       => $is_admin,
467                    'current_screen' => $current_screen ? $current_screen->id : false,
468                    'blog_id'        => $site_id,
469                ),
470            )
471        );
472    }
473}