Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.92% covered (warning)
50.92%
248 / 487
29.63% covered (danger)
29.63%
8 / 27
CRAP
n/a
0 / 0
wpcom_register_native_activity_log_flag
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_register_my_jetpack_all_atomic_plans_flag
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
current_user_has_wpcom_account
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
wpcom_add_dashboard_updates_menu
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
wpcom_display_dashboard_updates_page
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_can_link_to_calypso
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_add_my_home_menu
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
wpcom_add_hosting_menu
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
wpcom_admin_menu_enqueue_styles
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_add_upgrades_menu
92.96% covered (success)
92.96%
66 / 71
0.00% covered (danger)
0.00%
0 / 1
3.00
wpcom_get_current_plan_name
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
7.19
wpcom_reorder_submenu
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
8
jetpack_mu_wpcom_redirects_my_jetpack_to_stats
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
wpcom_jetpack_menu_has_my_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_backup_opens_in_wp_admin
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
wpcom_add_jetpack_submenu
94.59% covered (success)
94.59%
70 / 74
0.00% covered (danger)
0.00%
0 / 1
18.05
wpcom_sort_jetpack_submenu
97.14% covered (success)
97.14%
34 / 35
0.00% covered (danger)
0.00%
0 / 1
10
wpcom_add_native_activity_log_submenu
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
wpcom_hide_customizer_submenu_on_block_theme
8.33% covered (danger)
8.33%
1 / 12
0.00% covered (danger)
0.00%
0 / 1
16.32
wpcom_maybe_enable_link_manager
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
4.01
wpcom_hide_submenu_page
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
wpcom_add_plugins_menu
0.00% covered (danger)
0.00%
0 / 52
0.00% covered (danger)
0.00%
0 / 1
182
wpcom_add_tools_menu
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
12
wpcom_redirect_retired_marketing_page
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
wpcom_display_export_erase_personal_data_page
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
wpcom_display_site_health_page
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_add_settings_menu
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * WordPress.com admin menu
4 *
5 * Adds WordPress.com-specific stuff to WordPress admin menu.
6 *
7 * @package automattic/jetpack-mu-wpcom
8 */
9
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\Feature_Flags\Feature_Flags;
12use Automattic\Jetpack\Jetpack_Mu_Wpcom\WPCOM_Backup;
13use Automattic\Jetpack\Modules;
14use Automattic\Jetpack\Newsletter\Settings as Newsletter_Settings;
15use Automattic\Jetpack\Podcast\Admin_Page as Podcast_Admin_Page;
16use Automattic\Jetpack\Redirect;
17
18require_once __DIR__ . '/../../common/wpcom-callout.php';
19require_once __DIR__ . '/../../common/launchpad-no-guidance.php';
20
21/**
22 * Feature flag gating the native Activity Log page on Simple sites.
23 */
24const WPCOM_NATIVE_ACTIVITY_LOG_FLAG = 'wpcom-native-activity-log';
25
26/**
27 * Registers the feature flag.
28 *
29 * Runs as this file loads, so the flag is listed wherever flags are read or toggled.
30 *
31 * @return void
32 */
33function wpcom_register_native_activity_log_flag() {
34    Feature_Flags::register(
35        WPCOM_NATIVE_ACTIVITY_LOG_FLAG,
36        array(
37            'default'     => true,
38            'description' => 'Show the native wp-admin Activity Log page on Simple sites instead of linking to Calypso.',
39            'owner'       => 'jetpack-mu-wpcom',
40        )
41    );
42}
43wpcom_register_native_activity_log_flag();
44
45/**
46 * Feature flag showing My Jetpack on Atomic Personal and Premium plans.
47 */
48const WPCOM_MY_JETPACK_ALL_ATOMIC_PLANS_FLAG = 'wpcom-my-jetpack-all-atomic-plans';
49
50/**
51 * Registers the feature flag for My Jetpack on Atomic Personal and Premium plans as this file loads.
52 *
53 * @since $$next-version$$
54 *
55 * @return void
56 */
57function wpcom_register_my_jetpack_all_atomic_plans_flag() {
58    Feature_Flags::register(
59        WPCOM_MY_JETPACK_ALL_ATOMIC_PLANS_FLAG,
60        array(
61            'default'     => false,
62            'description' => 'Show My Jetpack and Jetpack Settings on Atomic Personal and Premium plans and drop the Calypso Traffic menu item, instead of redirecting My Jetpack to Stats.',
63            'owner'       => 'jetpack-mu-wpcom',
64        )
65    );
66}
67wpcom_register_my_jetpack_all_atomic_plans_flag();
68
69/**
70 * Checks if the current user has a WordPress.com account connected.
71 *
72 * @return bool
73 */
74function current_user_has_wpcom_account() {
75    $user_id = get_current_user_id();
76
77    if ( function_exists( '\A8C\Billingdaddy\Users\get_wpcom_user' ) ) {
78        // On Simple sites, use get_wpcom_user function to check if the user has a WordPress.com account.
79        $user        = \A8C\Billingdaddy\Users\get_wpcom_user( $user_id );
80        $has_account = isset( $user->ID );
81    } else {
82        // On Atomic sites, use the Connection Manager to check if the user has a WordPress.com account.
83        $connection_manager = new Connection_Manager();
84        $wpcom_user_data    = $connection_manager->get_connected_user_data( $user_id );
85        $has_account        = isset( $wpcom_user_data['ID'] );
86    }
87
88    return $has_account;
89}
90
91/**
92 * Adds the Dashboard > Updates menu on Simple sites
93 */
94function wpcom_add_dashboard_updates_menu() {
95    $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
96    if ( ! $is_simple_site || ( function_exists( 'wpcom_is_vip' ) && wpcom_is_vip() ) ) {
97        return;
98    }
99
100    add_submenu_page(
101        'index.php',
102        __( 'WordPress Updates', 'jetpack-mu-wpcom' ),
103        __( 'Updates', 'jetpack-mu-wpcom' ),
104        'manage_options',
105        'wpcom-dashboard-updates',
106        'wpcom_display_dashboard_updates_page'
107    );
108}
109add_action( 'admin_menu', 'wpcom_add_dashboard_updates_menu' );
110
111/**
112 * Displays a WordPress Updates page for Simple sites.
113 */
114function wpcom_display_dashboard_updates_page() {
115    ?>
116    <div class="wrap">
117        <h1><?php esc_html_e( 'WordPress Updates', 'jetpack-mu-wpcom' ); ?></h1>
118        <p><?php esc_html_e( "WordPress.com automatically keeps your site's plugins, themes, and WordPress version up to date.", 'jetpack-mu-wpcom' ); ?></p>
119        <h2><?php esc_html_e( 'WordPress', 'jetpack-mu-wpcom' ); ?></h2>
120        <p><?php esc_html_e( 'Your version of WordPress is up to date.', 'jetpack-mu-wpcom' ); ?></p>
121        <h2><?php esc_html_e( 'Plugins', 'jetpack-mu-wpcom' ); ?></h2>
122        <p><?php esc_html_e( 'Your plugins are all up to date.', 'jetpack-mu-wpcom' ); ?>
123        <h2><?php esc_html_e( 'Themes', 'jetpack-mu-wpcom' ); ?></h2>
124        <p><?php esc_html_e( 'Your themes are all up to date.', 'jetpack-mu-wpcom' ); ?>
125    </div>
126    <?php
127}
128
129/**
130 * Checks if menu items can link to Calypso.
131 *
132 * This way we can avoid a broken nav experience for super admins who are not members of the current site,
133 * since Calypso doesn't support this flow.
134 */
135function wpcom_can_link_to_calypso() {
136    return is_user_member_of_blog();
137}
138
139/**
140 * Adds a My Home menu.
141 */
142function wpcom_add_my_home_menu() {
143    if ( ! wpcom_can_link_to_calypso() ) {
144        return;
145    }
146
147    // My Home only goes with the legacy launchpad: AI Launchpad and no-guidance sites drop it for every user.
148    // Removing it here also drops it from the Calypso sidebar.
149    if ( get_option( 'wpcom_ai_launchpad_enabled' ) || wpcom_launchpad_is_no_guidance() ) {
150        return;
151    }
152
153    $domain = wp_parse_url( home_url(), PHP_URL_HOST );
154    // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
155    add_menu_page( __( 'My Home', 'jetpack-mu-wpcom' ), __( 'My Home', 'jetpack-mu-wpcom' ), 'read', 'https://wordpress.com/home/' . $domain, null, 'dashicons-admin-home', 2.01 ); // The 2.01 position is to ensure it's above the VIP menu on P2 sites.'
156}
157add_action( 'admin_menu', 'wpcom_add_my_home_menu' );
158
159/**
160 * Adds a Hosting menu.
161 */
162function wpcom_add_hosting_menu() {
163    $domain = wp_parse_url( home_url(), PHP_URL_HOST );
164
165    $menu_title = sprintf(
166        '%1$s<span class="inline-icon dashicons dashicons-external"></span>',
167        __( 'Hosting', 'jetpack-mu-wpcom' )
168    );
169
170    add_menu_page(
171        __( 'Hosting', 'jetpack-mu-wpcom' ),
172        $menu_title,
173        'manage_options',
174        esc_url( "https://my.wordpress.com/sites/$domain" ),
175        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
176        'dashicons-cloud',
177        2.98
178    );
179}
180add_action( 'admin_menu', 'wpcom_add_hosting_menu' );
181
182/**
183 * Enqueues admin menu styles.
184 */
185function wpcom_admin_menu_enqueue_styles() {
186    wp_enqueue_style(
187        'wpcom-admin-menu',
188        plugins_url( 'wpcom-admin-menu.css', __FILE__ ),
189        array(),
190        filemtime( __DIR__ . '/wpcom-admin-menu.css' )
191    );
192}
193add_action( 'admin_enqueue_scripts', 'wpcom_admin_menu_enqueue_styles' );
194
195/**
196 * Adds an Upgrades menu.
197 *
198 * This centralizes the Upgrades menu registration for all admin interfaces (Calypso and wp-admin).
199 * The masterbar classes defer to this function instead of registering their own Upgrades menu.
200 */
201function wpcom_add_upgrades_menu() {
202    // Don't show Upgrades on staging sites.
203    if ( get_option( 'wpcom_is_staging_site' ) ) {
204        return;
205    }
206
207    $domain      = wp_parse_url( home_url(), PHP_URL_HOST );
208    $parent_slug = 'paid-upgrades.php';
209
210    // Build the menu title, optionally with the plan label.
211    $plan = wpcom_get_current_plan_name();
212    if ( $plan ) {
213        // Add display:none as a default for cases when CSS is not loaded.
214        // Calypso and the masterbar CSS override this to show the plan label.
215        $menu_title = sprintf(
216            '%1$s<span class="inline-text" style="display:none">%2$s</span>',
217            __( 'Upgrades', 'jetpack-mu-wpcom' ),
218            esc_html( $plan )
219        );
220    } else {
221        $menu_title = __( 'Upgrades', 'jetpack-mu-wpcom' );
222    }
223
224    add_menu_page(
225        __( 'Upgrades', 'jetpack-mu-wpcom' ),
226        $menu_title,
227        'manage_options',
228        $parent_slug,
229        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
230        'dashicons-cart',
231        2.99
232    );
233
234    add_submenu_page(
235        $parent_slug,
236        __( 'Plans', 'jetpack-mu-wpcom' ),
237        __( 'Plans', 'jetpack-mu-wpcom' ),
238        'manage_options',
239        esc_url( "https://wordpress.com/plans/$domain" ),
240        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
241        1
242    );
243
244    add_submenu_page(
245        $parent_slug,
246        __( 'Add-ons', 'jetpack-mu-wpcom' ),
247        __( 'Add-ons', 'jetpack-mu-wpcom' ),
248        'manage_options',
249        esc_url( "https://wordpress.com/add-ons/$domain" ),
250        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
251        2
252    );
253
254    add_submenu_page(
255        $parent_slug,
256        __( 'Domains', 'jetpack-mu-wpcom' ),
257        __( 'Domains', 'jetpack-mu-wpcom' ),
258        'manage_options',
259        esc_url( "https://wordpress.com/domains/manage/$domain" ),
260        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
261        3
262    );
263
264    add_submenu_page(
265        $parent_slug,
266        __( 'Emails', 'jetpack-mu-wpcom' ),
267        __( 'Emails', 'jetpack-mu-wpcom' ),
268        'manage_options',
269        esc_url( "https://wordpress.com/email/$domain" ),
270        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
271        4
272    );
273
274    add_submenu_page(
275        $parent_slug,
276        __( 'Purchases', 'jetpack-mu-wpcom' ),
277        __( 'Purchases', 'jetpack-mu-wpcom' ),
278        'manage_options',
279        esc_url( "https://wordpress.com/purchases/subscriptions/$domain" ),
280        null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
281        5
282    );
283
284    // By default, WordPress adds a submenu item for the parent menu item, which we don't want.
285    remove_submenu_page( $parent_slug, $parent_slug );
286
287    // Remove legacy Upgrades submenus registered elsewhere on WP.com.
288    remove_submenu_page( $parent_slug, 'premium-themes' );
289    remove_submenu_page( $parent_slug, 'domains' );
290    remove_submenu_page( $parent_slug, 'my-upgrades' );
291    remove_submenu_page( $parent_slug, 'billing-history' );
292}
293add_action( 'admin_menu', 'wpcom_add_upgrades_menu', 140 ); // After hookpress hook at 130, needed to ensure the legacy submenus are removed.
294
295/**
296 * Gets the current plan's short name.
297 *
298 * @return string|null The plan name, or null if unavailable.
299 */
300function wpcom_get_current_plan_name() {
301    // Simple sites: use WPCOM_Store_API.
302    if ( class_exists( 'WPCOM_Store_API' ) ) {
303        $current_plan = \WPCOM_Store_API::get_current_plan( get_current_blog_id() );
304        if ( ! empty( $current_plan['product_name_short'] ) ) {
305            return $current_plan['product_name_short'];
306        }
307    }
308
309    // Atomic sites: use Jetpack Current_Plan.
310    if ( class_exists( 'Automattic\Jetpack\Current_Plan' ) ) {
311        $products = \Automattic\Jetpack\Current_Plan::get();
312        if ( array_key_exists( 'product_name_short', $products ) ) {
313            return $products['product_name_short'];
314        }
315    }
316
317    return null;
318}
319
320/**
321 * Re-order the submenu items of the given menu slug according to a sorted array of submenu slugs.
322 *
323 * @param string $menu_slug The menu slug.
324 * @param array  $desired_order A list of the submenu slugs in the desired order.
325 */
326function wpcom_reorder_submenu( $menu_slug, $desired_order ) {
327    // Re-order menu.
328    global $submenu;
329    if ( ! isset( $submenu[ $menu_slug ] ) ) {
330        return;
331    }
332
333    $domain          = wp_parse_url( home_url(), PHP_URL_HOST );
334    $ordered_submenu = array();
335
336    // Re-add submenu items in the desired order. Dedupe because a slug in
337    // $desired_order can be a substring of another item's URL, which would
338    // otherwise match the same item twice.
339    foreach ( $desired_order as $submenu_slug ) {
340        foreach ( $submenu[ $menu_slug ] as $item ) {
341            $clean_url = str_replace( $domain, '', $item[2] );
342            if ( str_contains( $clean_url, $submenu_slug ) && ! in_array( $item, $ordered_submenu, true ) ) {
343                $ordered_submenu[] = $item;
344            }
345        }
346    }
347
348    // Add any remaining submenu items.
349    foreach ( $submenu[ $menu_slug ] as $item ) {
350        if ( ! in_array( $item, $ordered_submenu, true ) ) {
351            $ordered_submenu[] = $item;
352        }
353    }
354
355    // phpcs:ignore WordPress.WP.GlobalVariablesOverride
356    $submenu[ $menu_slug ] = $ordered_submenu;
357}
358
359/**
360 * Whether the host replaces My Jetpack with Stats.
361 *
362 * @return bool
363 */
364function jetpack_mu_wpcom_redirects_my_jetpack_to_stats() {
365    if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) || ! class_exists( '\\Automattic\\Jetpack\\Current_Plan' ) ) {
366        return false;
367    }
368    $plan = \Automattic\Jetpack\Current_Plan::get();
369    // Plan first: whatever answers the flag must only be asked on the plans it can affect.
370    return in_array( $plan['class'] ?? '', array( 'personal', 'premium' ), true ) && ! Feature_Flags::is_enabled( WPCOM_MY_JETPACK_ALL_ATOMIC_PLANS_FLAG );
371}
372add_filter(
373    'jetpack_my_jetpack_modules_management_available',
374    static function ( $available ) {
375        return $available && ! jetpack_mu_wpcom_redirects_my_jetpack_to_stats();
376    }
377);
378
379/**
380 * Whether the Jetpack menu has a My Jetpack entry, whichever page registered it.
381 *
382 * @return bool
383 */
384function wpcom_jetpack_menu_has_my_jetpack() {
385    global $submenu;
386    return in_array( 'my-jetpack', array_column( $submenu['jetpack'] ?? array(), 2 ), true );
387}
388
389/**
390 * Whether Jetpack > Backup opens the wp-admin Backup page rather than Calypso.
391 *
392 * Only meaningful once whatever serves the page has registered it; see WPCOM_WP_Build_Page::REGISTER_PRIORITY.
393 *
394 * @return bool
395 */
396function wpcom_backup_opens_in_wp_admin() {
397    return class_exists( WPCOM_Backup::class ) && WPCOM_Backup::slug_is_claimed() && WPCOM_Backup::is_modernized();
398}
399
400/**
401 * Adds WordPress.com submenu items related to Jetpack under the Jetpack admin menu.
402 */
403function wpcom_add_jetpack_submenu() {
404    $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
405
406    $blog_id = Connection_Manager::get_site_id();
407    if ( is_wp_error( $blog_id ) ) {
408        return;
409    }
410
411    $domain = wp_parse_url( home_url(), PHP_URL_HOST );
412
413    // @codeCoverageIgnoreStart
414    // Hide certain Jetpack submenus for Atomic sites on Personal or Premium plans.
415    if ( jetpack_mu_wpcom_redirects_my_jetpack_to_stats() ) {
416        // Jetpack > My Jetpack.
417        wpcom_hide_submenu_page( 'jetpack', 'my-jetpack' );
418
419        // Jetpack > Settings; WoA can pair this with a Jetpack serving either address.
420        wpcom_hide_submenu_page( 'jetpack', admin_url( 'admin.php?page=jetpack#/settings' ) );
421        wpcom_hide_submenu_page( 'jetpack', 'jetpack-settings' );
422
423        // Redirect My Jetpack page to Stats for Atomic sites on Personal or Premium plans.
424        add_action(
425            'admin_init',
426            function () {
427                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action taken, just checking page.
428                if ( isset( $_GET['page'] ) && 'my-jetpack' === $_GET['page'] ) {
429                    /** This filter is documented in projects/packages/stats-admin/src/class-admin-bar.php */
430                    wp_safe_redirect( apply_filters( 'jetpack_stats_url', admin_url( 'admin.php?page=stats' ), array( 'view' => 'dashboard' ) ) );
431                    exit;
432                }
433            }
434        );
435
436        // Jetpack > Traffic (Calypso).
437        add_submenu_page(
438            'jetpack',
439            esc_attr__( 'Traffic', 'jetpack-mu-wpcom' ),
440            __( 'Traffic', 'jetpack-mu-wpcom' ),
441            'manage_options',
442            'https://wordpress.com/marketing/traffic/' . $domain,
443            null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
444        );
445
446    }
447    // @codeCoverageIgnoreEnd
448
449    // Jetpack > Scan, beside Protect until Protect replaces it.
450    wpcom_hide_submenu_page( 'jetpack', esc_url( Redirect::get_url( 'cloud-scan-history-wp-menu' ) ) );
451    wpcom_hide_submenu_page( 'jetpack', esc_url( Redirect::get_url( 'calypso-scanner' ) ) );
452    add_submenu_page(
453        'jetpack',
454        /** "Scan" is a product name, do not translate. */
455        'Scan',
456        'Scan',
457        'manage_options',
458        'https://wordpress.com/scan/' . $domain,
459        null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
460    );
461
462    // Jetpack > Backup. Until the wp-admin page takes over, Calypso owns the nav and `jetpack-backup`
463    // is hidden rather than removed, so links into it keep working.
464    wpcom_hide_submenu_page( 'jetpack', esc_url( Redirect::get_url( 'calypso-backups' ) ) );
465    if ( ! wpcom_backup_opens_in_wp_admin() ) {
466        wpcom_hide_submenu_page( 'jetpack', 'jetpack-backup' );
467        add_submenu_page(
468            'jetpack',
469            /** "Backup" is a product name, do not translate. */
470            'Backup',
471            'Backup',
472            'manage_options',
473            'https://wordpress.com/backup/' . $domain,
474            null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
475        );
476    }
477
478    // Jetpack > Monetize.
479    add_submenu_page(
480        'jetpack',
481        esc_attr__( 'Monetize', 'jetpack-mu-wpcom' ),
482        __( 'Monetize', 'jetpack-mu-wpcom' ),
483        'manage_options',
484        'https://wordpress.com/earn/' . $domain,
485        null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
486    );
487
488    // Jetpack > Subscribers. Always hide the auto-added Calypso redirect link.
489    wpcom_hide_submenu_page( 'jetpack', esc_url( Redirect::get_url( 'jetpack-menu-jetpack-manage-subscribers', array( 'site' => $blog_id ) ) ) );
490
491    // The unified Newsletter page owns the Subscribers tab on every site, so the legacy
492    // Calypso "Subscribers" submenu is retired. add_filter( 'rsm_jetpack_ui_modernization_newsletter',
493    // '__return_false' ) brings it back â€” the Calypso link only, not a wp-admin dashboard.
494    if ( ! apply_filters( 'rsm_jetpack_ui_modernization_newsletter', true ) ) {
495        add_submenu_page(
496            'jetpack',
497            __( 'Subscribers', 'jetpack-mu-wpcom' ),
498            __( 'Subscribers', 'jetpack-mu-wpcom' ),
499            'manage_options',
500            'https://wordpress.com/subscribers/' . $domain,
501            null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
502        );
503    }
504
505    // Atomic loads Podcast through the Jetpack module, which the owner can switch
506    // off, and this builder runs either way. is_active() is always true on Simple,
507    // where the package loads unconditionally. The package ships with Jetpack, not this one.
508    if ( class_exists( Podcast_Admin_Page::class ) && ( new Modules() )->is_active( 'podcast' ) ) {
509        Podcast_Admin_Page::add_wp_admin_submenu();
510    }
511
512    if ( $is_simple_site ) {
513        // Jetpack > Newsletter.
514        // Register the in-admin Newsletter settings page (with its own render callback
515        // and admin hooks). This must be done here (at priority 999999) because the
516        // Jetpack menu is created by this function and doesn't exist at earlier priorities.
517        if ( class_exists( '\Automattic\Jetpack\Newsletter\Settings' ) ) {
518            // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader.
519            $newsletter_settings = new Newsletter_Settings();
520            // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader.
521            $newsletter_settings->add_wp_admin_submenu();
522        }
523
524        // Jetpack > VideoPress.
525        // Register the in-admin VideoPress dashboard page. Like Newsletter above, this
526        // must run here (priority 999999) because the Jetpack parent menu is created by
527        // this function and doesn't exist at earlier priorities. Gated on the VideoPress
528        // site feature so it only surfaces for VideoPress-enabled Simple sites during dev.
529        if (
530            class_exists( '\Automattic\Jetpack\VideoPress\Admin_UI' ) &&
531            function_exists( 'wpcom_site_has_feature' ) &&
532            class_exists( '\WPCOM_Features' ) &&
533            wpcom_site_has_feature( \WPCOM_Features::VIDEOPRESS )
534        ) {
535            \Automattic\Jetpack\VideoPress\Admin_UI::add_wp_admin_submenu();
536        }
537
538        // Jetpack > Traffic
539        add_submenu_page(
540            'jetpack',
541            __( 'Traffic', 'jetpack-mu-wpcom' ),
542            __( 'Traffic', 'jetpack-mu-wpcom' ),
543            'manage_options',
544            'https://wordpress.com/marketing/traffic/' . $domain,
545            null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
546        );
547    }
548
549    // Jetpack > Activity Log.
550    // Atomic sites use the native Activity Log page that the `jetpack-activity-log`
551    // package registers at `admin.php?page=jetpack-activity-log`, whichever admin
552    // interface the site uses, and behave like a self-hosted site when that page is
553    // not available: the Calypso Activity Log screen is being retired. Simple sites
554    // get the native page too unless its flag is off, and link to wordpress.com/activity-log otherwise.
555    if ( $is_simple_site && ! wpcom_add_native_activity_log_submenu() ) {
556        wpcom_hide_submenu_page( 'jetpack', 'jetpack-activity-log' );
557        add_submenu_page(
558            'jetpack',
559            /** "Activity Log" is a product name, do not translate. */
560            'Activity Log',
561            'Activity Log',
562            'manage_options',
563            'https://wordpress.com/activity-log/' . $domain,
564            null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
565        );
566    }
567
568    wpcom_sort_jetpack_submenu();
569}
570add_action( 'admin_menu', 'wpcom_add_jetpack_submenu', 999999 );
571
572/**
573 * Sorts the Jetpack submenu A to Z by title, with My Jetpack first; Beta Tester, Settings and the
574 * upgrade link go at the bottom, as on self-hosted.
575 *
576 * WordPress points the top-level Jetpack link at the first item, so a `hide-if-js` item sorts after the visible
577 * ones in its tier. Items admin-ui hides only leave on admin_head, so they sort as visible here.
578 */
579function wpcom_sort_jetpack_submenu() {
580    global $submenu;
581    if ( empty( $submenu['jetpack'] ) ) {
582        return;
583    }
584
585    // Admin_Menu::POSITION_* values, as this package doesn't depend on admin-ui. There is no
586    // POSITION_EXTERNAL tier: links that leave wp-admin sort in with everything else.
587    $named_tiers = array(
588        'my-jetpack'                                    => -10,
589        'jetpack_modules'                               => -5,
590        'jetpack-beta'                                  => 998,
591        'jetpack-settings'                              => 998,
592        admin_url( 'admin.php?page=jetpack#/settings' ) => 998,
593    );
594
595    // Without a My Jetpack page, pin Activity Log rather than let the translated A to Z order pick the top link.
596    if ( defined( 'IS_WPCOM' ) && IS_WPCOM && ! wpcom_jetpack_menu_has_my_jetpack() ) {
597        $named_tiers['jetpack-activity-log'] = -5;
598        $named_tiers[ 'https://wordpress.com/activity-log/' . wp_parse_url( home_url(), PHP_URL_HOST ) ] = -5;
599    }
600
601    $keyed = array();
602    foreach ( $submenu['jetpack'] as $item ) {
603        // Drop exact duplicates: Simple can register Akismet twice.
604        if ( in_array( $item, array_column( $keyed, 'item' ), true ) ) {
605            continue;
606        }
607
608        if ( isset( $named_tiers[ $item[2] ] ) ) {
609            $tier = $named_tiers[ $item[2] ];
610        } elseif ( str_contains( $item[2], 'jetpack-wpadmin-sidebar-free-plan-upsell-menu-item' ) ) {
611            // Admin_Menu::UPGRADE_MENU_SLUG, sent through a jetpack.com redirect; admin-ui never adds it on WordPress.com.
612            $tier = 999;
613        } else {
614            $tier = 0;
615        }
616
617        $keyed[] = array(
618            'tier'   => $tier,
619            'hidden' => str_contains( $item[4] ?? '', 'hide-if-js' ),
620            'title'  => wp_strip_all_tags( $item[0] ),
621            'item'   => $item,
622        );
623    }
624
625    usort(
626        $keyed,
627        function ( $a, $b ) {
628            $result = array( $a['tier'], $a['hidden'] ) <=> array( $b['tier'], $b['hidden'] );
629            return 0 !== $result ? $result : strnatcasecmp( $a['title'], $b['title'] );
630        }
631    );
632
633    // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
634    $submenu['jetpack'] = array_column( $keyed, 'item' );
635}
636
637/**
638 * Registers the native Activity Log page under Jetpack on a Simple site.
639 *
640 * @return bool Whether the page was registered.
641 */
642function wpcom_add_native_activity_log_submenu() {
643    if ( ! Feature_Flags::is_enabled( WPCOM_NATIVE_ACTIVITY_LOG_FLAG ) ) {
644        return false;
645    }
646
647    // The package ships with Jetpack, which deploys separately from this one.
648    if ( ! class_exists( '\Automattic\Jetpack\Activity_Log\Jetpack_Activity_Log' ) ) {
649        return false;
650    }
651
652    // A package predating Simple support returns null, which keeps the Calypso link.
653    // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader.
654    return null !== \Automattic\Jetpack\Activity_Log\Jetpack_Activity_Log::add_wp_admin_submenu();
655}
656
657/*
658 * Prevents the Jetpack menu from being overridden on Simple sites.
659 *
660 * TODO: After deploying https://github.com/Automattic/jetpack/pull/39393, we can remove the `add_jetpack_submenu` function and this `remove_action` call.
661 */
662remove_action( 'admin_menu', 'add_jetpack_submenu', 999999 );
663
664/**
665 * Ensures customizer menu and admin bar items are not visible on a block theme.
666 */
667function wpcom_hide_customizer_submenu_on_block_theme() {
668    if ( wp_is_block_theme() && ! is_customize_preview() ) {
669        remove_action( 'customize_register', 'add_logotool_button', 20 );
670        remove_action( 'customize_register', 'footercredits_register', 99 );
671        remove_action( 'customize_register', 'wpcom_disable_customizer_site_icon', 20 );
672
673        if ( class_exists( '\Jetpack_Fonts' ) ) {
674            $jetpack_fonts_instance = \Jetpack_Fonts::get_instance();
675            remove_action( 'customize_register', array( $jetpack_fonts_instance, 'register_controls' ) );
676            remove_action( 'customize_register', array( $jetpack_fonts_instance, 'maybe_prepopulate_option' ), 0 );
677        }
678
679        remove_action( 'customize_register', array( 'Jetpack_Fonts_Typekit', 'maybe_override_for_advanced_mode' ), 20 );
680
681        remove_action( 'customize_register', 'Automattic\Jetpack\Masterbar\register_css_nudge_control' );
682
683        remove_action( 'customize_register', array( 'Jetpack_Custom_CSS_Customizer', 'customize_register' ) );
684
685        remove_action( 'customize_register', array( 'Jetpack_Custom_CSS_Enhancements', 'customize_register' ) );
686    }
687}
688
689$customizer_removal_hook = defined( 'REST_API_REQUEST' ) && REST_API_REQUEST ? 'rest_pre_dispatch' : 'init';
690add_action( $customizer_removal_hook, 'wpcom_hide_customizer_submenu_on_block_theme' );
691
692/**
693 * Links were removed in 3.5 core, but we've kept them active on dotcom.
694 *
695 * This function will check to see if Links should be enabled based on the number of links in the database
696 * and then set an option to minimize repeat queries later. The Links menu is visible when the Link Manager is enabled.
697 *
698 * @return void
699 */
700function wpcom_maybe_enable_link_manager() {
701    if ( get_option( 'link_manager_check' ) ) {
702        return;
703    }
704
705    // The max ID number of the auto-generated links.
706    // See /wp-content/mu-plugins/wpcom-wp-install-defaults.php in WP.com.
707    $max_default_id = 10;
708
709    // We are only checking the latest entry link_id so are limiting the query to 1.
710    $link_manager_links = get_bookmarks(
711        array(
712            'orderby'        => 'link_id',
713            'order'          => 'DESC',
714            'limit'          => 1,
715            'hide_invisible' => 0,
716        )
717    );
718
719    $has_links = is_countable( $link_manager_links ) && count( $link_manager_links ) > 0 && $link_manager_links[0]->link_id > $max_default_id;
720
721    update_option( 'link_manager_enabled', intval( $has_links ) );
722    update_option( 'link_manager_check', time() );
723}
724add_action( 'init', 'wpcom_maybe_enable_link_manager' );
725
726/**
727 * Hides a submenu item.
728 *
729 * Useful in cases where we cannot remove a submenu item because there is external logic
730 * that depends on the route registered by that submenu.
731 *
732 * @param string $menu_slug The slug of the parent menu.
733 * @param string $submenu_slug The slug of the submenu that should be hidden.
734 */
735function wpcom_hide_submenu_page( string $menu_slug, string $submenu_slug ) {
736    global $submenu;
737
738    if ( ! isset( $submenu[ $menu_slug ] ) ) {
739        return;
740    }
741
742    foreach ( $submenu[ $menu_slug ] as $i => $item ) {
743        if ( $submenu_slug !== $item[2] ) {
744            continue;
745        }
746
747        $css_hide_class = 'hide-if-js';
748        $css_classes    = empty( $item[4] ) ? $css_hide_class : $item[4] . ' ' . $css_hide_class;
749
750        // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
751        $submenu[ $menu_slug ][ $i ][4] = $css_classes;
752        return;
753    }
754}
755
756/**
757 * Handles the Plugins menu.
758 */
759function wpcom_add_plugins_menu() {
760    global $menu;
761    $is_simple_site          = defined( 'IS_WPCOM' ) && IS_WPCOM;
762    $is_atomic_site          = ! $is_simple_site;
763    $uses_wp_admin_interface = get_option( 'wpcom_admin_interface' ) === 'wp-admin';
764
765    if ( $is_simple_site ) {
766        $has_plugins_menu = false;
767        foreach ( $menu as &$menu_item ) {
768            if ( 'plugins.php' === $menu_item[2] ) {
769                $has_plugins_menu = true;
770                break;
771            }
772        }
773
774        if ( ! $has_plugins_menu ) {
775            // TODO: Remove `remove_menu_page('plugins.php');` from `/wp-content/admin-plugins/wpcom-misc.php`.
776            add_menu_page(
777                __( 'Plugins', 'jetpack-mu-wpcom' ),
778                __( 'Plugins', 'jetpack-mu-wpcom' ),
779                'manage_options', // Roughly means "is a site admin"
780                'plugins.php',
781                null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
782                'dashicons-admin-plugins',
783                65
784            );
785        }
786
787        if ( function_exists( 'wpcom_plugins_display_marketplace' ) ) {
788            add_submenu_page(
789                'plugins.php',
790                __( 'Add Plugin', 'jetpack-mu-wpcom' ),
791                __( 'Add Plugin', 'jetpack-mu-wpcom' ),
792                'manage_options', // Roughly means "is a site admin"
793                'wpcom-install-plugin',
794                'wpcom_plugins_display_marketplace'
795            );
796
797            if ( ! $uses_wp_admin_interface ) {
798                wpcom_hide_submenu_page( 'plugins.php', 'wpcom-install-plugin' );
799            }
800        }
801    }
802
803    $domain = wp_parse_url( home_url(), PHP_URL_HOST );
804    if ( $uses_wp_admin_interface ) {
805        add_submenu_page(
806            'plugins.php',
807            /* translators: Name of the Plugins submenu that links to the Plugins Marketplace */
808                __( 'Marketplace', 'jetpack-mu-wpcom' ),
809            /* translators: Name of the Plugins submenu that links to the Plugins Marketplace */
810                __( 'Marketplace', 'jetpack-mu-wpcom' ),
811            'manage_options', // Roughly means "is a site admin"
812            'https://wordpress.com/plugins/' . $domain,
813            null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
814        );
815    }
816
817    if ( $is_atomic_site ) {
818        if (
819            ! get_option( 'wpcom_is_staging_site' ) &&
820            function_exists( 'wpcom_site_has_feature' ) &&
821            wpcom_site_has_feature( \WPCOM_Features::SCHEDULED_UPDATES )
822        ) {
823            add_submenu_page(
824                'plugins.php',
825                esc_attr__( 'Scheduled Updates', 'jetpack-mu-wpcom' ),
826                __( 'Scheduled Updates', 'jetpack-mu-wpcom' ),
827                'update_plugins',
828                esc_url( "https://wordpress.com/plugins/scheduled-updates/$domain" ),
829                null // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
830            );
831        }
832    }
833}
834add_action( 'admin_menu', 'wpcom_add_plugins_menu' );
835
836/**
837 * Adds some Tools menus that are missing on Simple sites.
838 */
839function wpcom_add_tools_menu() {
840    $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
841    if ( $is_simple_site ) {
842        add_submenu_page(
843            'tools.php',
844            __( 'Export Personal Data', 'jetpack-mu-wpcom' ),
845            __( 'Export Personal Data', 'jetpack-mu-wpcom' ),
846            'manage_options',
847            'wpcom-export-personal-data',
848            'wpcom_display_export_erase_personal_data_page'
849        );
850
851        add_submenu_page(
852            'tools.php',
853            __( 'Erase Personal Data', 'jetpack-mu-wpcom' ),
854            __( 'Erase Personal Data', 'jetpack-mu-wpcom' ),
855            'manage_options',
856            'wpcom-erase-personal-data',
857            'wpcom_display_export_erase_personal_data_page'
858        );
859
860        add_submenu_page(
861            'tools.php',
862            __( 'Site Health', 'jetpack-mu-wpcom' ),
863            __( 'Site Health', 'jetpack-mu-wpcom' ),
864            'manage_options',
865            'wpcom-site-health',
866            'wpcom_display_site_health_page'
867        );
868    }
869
870    wpcom_reorder_submenu(
871        'tools.php',
872        array(
873            'tools.php',
874            'monetize',
875            'import',
876            'export.php',
877            'export-media-files',
878            'site-health',
879            'export-personal-data',
880            'erase-personal-data',
881            'theme-editor',
882            'plugin-editor',
883        )
884    );
885}
886add_action( 'admin_menu', 'wpcom_add_tools_menu', 999999 );
887
888/**
889 * Sends the retired Tools > Marketing URL to the dashboard.
890 *
891 * The page was removed in DOTCOM-18531. Nothing links to it any more, but the
892 * Calypso sidebar pointed at this exact URL until the removal shipped, so it is
893 * still in plenty of browser histories and bookmarks. Left alone, WordPress
894 * answers an unregistered page slug with a bare "Cannot load
895 * wpcom-marketing-tools.", which reads like a broken install rather than a page
896 * that went away. The dashboard mirrors where the Calypso URL now lands.
897 *
898 * This runs on admin_init, which fires before the point in wp-admin/admin.php
899 * where core gives up on the slug.
900 *
901 * Tombstone: delete this function and its hook by 2027-09-10. A year is long
902 * enough for the stale bookmarks to age out, and after that the redirect is
903 * just a puzzle for whoever reads this next.
904 */
905function wpcom_redirect_retired_marketing_page() {
906    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading a menu slug from a GET request, no state changes.
907    if ( ! isset( $_GET['page'] ) ) {
908        return;
909    }
910
911    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- As above.
912    if ( 'wpcom-marketing-tools' !== sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
913        return;
914    }
915
916    wp_safe_redirect( admin_url() );
917    exit; // @codeCoverageIgnore -- the tests unwind from the wp_redirect filter before this line.
918}
919add_action( 'admin_init', 'wpcom_redirect_retired_marketing_page' ); // @codeCoverageIgnore
920
921/**
922 * Displays an Export/Erase Personal Date page for Simple sites.
923 */
924function wpcom_display_export_erase_personal_data_page() {
925    if ( str_contains( get_current_screen()->id, 'export-personal-data' ) ) {
926        $page_title = __( 'Export Personal Data', 'jetpack-mu-wpcom' );
927    } else {
928        $page_title = __( 'Erase Personal Data', 'jetpack-mu-wpcom' );
929    }
930
931    wpcom_display_callout(
932        'dashicons-id-alt',
933        $page_title,
934        array(
935            __( 'WordPress.com gives you the tools to manage personal data from your dashboard, like viewing or deleting comments tied to a visitor.', 'jetpack-mu-wpcom' ),
936            __( 'To support privacy requests, make sure people can reach you easily, whether through a contact form or an email in your Privacy Policy.', 'jetpack-mu-wpcom' ),
937        ),
938        localized_wpcom_url( 'https://wordpress.com/support/your-site-and-the-gdpr/' ),
939        __( 'Learn more', 'jetpack-mu-wpcom' ),
940        plugins_url( 'images/performance.svg', __FILE__ )
941    );
942}
943
944/**
945 * Displays a callout on Simple Sites for Tools > Site Health menu.
946 *
947 * @return void
948 */
949function wpcom_display_site_health_page() {
950    wpcom_display_callout(
951        'dashicons-admin-site-alt3',
952        __( 'Your site\'s in good hands', 'jetpack-mu-wpcom' ),
953        array(
954            __( 'No need to stress over performance or security checks, WordPress.com handles that for you behind the scenes.', 'jetpack-mu-wpcom' ),
955            __( 'That way, your site stays fast, safe, and reliable, without any extra effort from you.', 'jetpack-mu-wpcom' ),
956        ),
957        localized_wpcom_url( 'https://wordpress.com/support/choose-a-host/#frequently-asked-questions-about-managed-hosting-with-word-press-com' ),
958        __( 'Learn more', 'jetpack-mu-wpcom' ),
959        plugins_url( 'images/cloud.svg', __FILE__ )
960    );
961}
962
963/**
964 * Adjust the Settings submenus so they are sorted consistently.
965 */
966function wpcom_add_settings_menu() {
967    wpcom_reorder_submenu(
968        'options-general.php',
969        array(
970            'general',
971            'writing',
972            'reading',
973            'discussion',
974            'media',
975            'permalink',
976            'privacy',
977            'sharing',
978            'optimize',
979            'crowdsignal',
980            'rating',
981            'newsletter',
982        )
983    );
984}
985add_action( 'admin_menu', 'wpcom_add_settings_menu', 999999 );
986
987if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
988    require_once __DIR__ . '/p2-admin-menu.php';
989}