Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.20% covered (warning)
64.20%
165 / 257
31.82% covered (danger)
31.82%
7 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Admin
64.17% covered (warning)
64.17%
163 / 254
31.82% covered (danger)
31.82%
7 / 22
559.86
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 add_no_store_header
n/a
0 / 0
n/a
0 / 0
1
 __construct
86.49% covered (warning)
86.49%
32 / 37
0.00% covered (danger)
0.00%
0 / 1
3.02
 additional_css_menu
50.00% covered (danger)
50.00%
6 / 12
0.00% covered (danger)
0.00%
0 / 1
19.12
 customizer_redirect
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 customizer_link
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
 sort_requires_connection_last
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_modules
90.20% covered (success)
90.20%
46 / 51
0.00% covered (danger)
0.00%
0 / 1
14.18
 is_module_available
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
12.04
 get_module_unavailable_reason
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
15.22
 get_protect_page_module_urls
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 handle_unrecognized_action
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
110
 fix_redirect
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 admin_menu_debugger
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 wrap_debugger_page
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 debugger_page
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 should_display_jitms_on_screen
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
2.00
 is_jetpack_admin_page
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
7.04
 add_jetpack_admin_body_class
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 add_footer_removal_styles
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_enqueue_design_tokens
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 maybe_remove_admin_footer_text
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 maybe_remove_admin_footer_version
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Build the Jetpack admin menu as a whole.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Admin_UI\Admin_Menu;
9use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
10use Automattic\Jetpack\Partner_Coupon as Jetpack_Partner_Coupon;
11use Automattic\Jetpack\Protect\Dashboard as Protect_Dashboard;
12use Automattic\Jetpack\Status;
13use Automattic\Jetpack\Status\Host;
14
15if ( ! defined( 'ABSPATH' ) ) {
16    exit( 0 );
17}
18
19/**
20 * Build the Jetpack admin menu as a whole.
21 */
22class Jetpack_Admin {
23
24    /**
25     * Static instance.
26     *
27     * @var Jetpack_Admin
28     */
29    private static $instance = null;
30
31    /**
32     * Initialize and fetch the static instance.
33     *
34     * @return self
35     */
36    public static function init() {
37        if ( self::$instance === null ) {
38            self::$instance = new Jetpack_Admin();
39        }
40        return self::$instance;
41    }
42
43    /**
44     * Filter callback to add `no-store` to the `Cache-Control` header.
45     *
46     * @deprecated 14.9
47     * @param array $headers Headers array.
48     * @return array Modified headers array.
49     */
50    public static function add_no_store_header( $headers ) {
51        _deprecated_function( __METHOD__, '14.9' );
52        $headers['Cache-Control'] .= ', no-store';
53        return $headers;
54    }
55
56    /** Constructor. */
57    private function __construct() {
58        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php';
59        $jetpack_react = new Jetpack_React_Page();
60
61        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-jetpack-settings-react-page.php';
62        $jetpack_settings = new Jetpack_Settings_React_Page();
63
64        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-settings-page.php';
65        $fallback_page = new Jetpack_Settings_Page();
66
67        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-jetpack-about-page.php';
68        $jetpack_about = new Jetpack_About_Page();
69
70        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-jetpack-ai-page.php';
71        $jetpack_ai = new Jetpack_AI_Page();
72
73        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-jetpack-wp-admin-spa.php';
74
75        add_action( 'admin_init', array( $jetpack_react, 'react_redirects' ), 0 );
76        add_action( 'admin_menu', array( $jetpack_react, 'add_actions' ), 998 );
77        add_action( 'admin_menu', array( $jetpack_react, 'remove_jetpack_menu' ), 2000 );
78        add_action( 'admin_menu', array( $jetpack_settings, 'maybe_load_wp_build' ), 1 );
79        add_action( 'jetpack_admin_menu', array( $jetpack_settings, 'add_actions' ) );
80        add_action( 'jetpack_admin_menu', array( $this, 'admin_menu_debugger' ) );
81        add_action( 'jetpack_admin_menu', array( $fallback_page, 'add_actions' ) );
82        add_action( 'jetpack_admin_menu', array( $jetpack_about, 'add_actions' ) );
83        add_action( 'jetpack_admin_menu', array( $jetpack_ai, 'add_actions' ) );
84
85        // Add redirect to current page for activation/deactivation of modules.
86        add_action( 'jetpack_pre_activate_module', array( $this, 'fix_redirect' ), 10, 2 );
87        add_action( 'jetpack_pre_deactivate_module', array( $this, 'fix_redirect' ), 10, 2 );
88
89        // Add module bulk actions handler.
90        add_action( 'jetpack_unrecognized_action', array( $this, 'handle_unrecognized_action' ) );
91
92        if ( class_exists( 'Akismet_Admin' ) ) {
93            // Network Admin never fires admin_menu, so starting Admin_Menu there would only add its upgrade item.
94            if ( ! is_network_admin() ) {
95                Admin_Menu::init();
96            }
97
98            // Render the unified Jetpack header/footer chrome on Akismet's admin pages by
99            // consuming Akismet's `akismet_header` / `akismet_footer` action hooks. This does
100            // not modify the Akismet plugin; it only registers callbacks on its own hooks.
101            require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-akismet-admin-chrome.php';
102            $akismet_admin_chrome = new Akismet_Admin_Chrome();
103            $akismet_admin_chrome->init_hooks();
104        }
105
106        // Ensure an Additional CSS menu item is added to the Appearance menu whenever Jetpack is connected.
107        add_action( 'admin_menu', array( $this, 'additional_css_menu' ) );
108
109        add_filter( 'jetpack_display_jitms_on_screen', array( $this, 'should_display_jitms_on_screen' ), 10, 2 );
110
111        // Register Jetpack partner coupon hooks.
112        Jetpack_Partner_Coupon::register_coupon_admin_hooks( 'jetpack', Jetpack::admin_url() );
113
114        // Remove default WordPress admin footer on Jetpack pages only.
115        add_filter( 'admin_footer_text', array( $this, 'maybe_remove_admin_footer_text' ) );
116        add_filter( 'update_footer', array( $this, 'maybe_remove_admin_footer_version' ), 11 );
117        add_filter( 'admin_body_class', array( $this, 'add_jetpack_admin_body_class' ) );
118        add_action( 'admin_head', array( $this, 'add_footer_removal_styles' ) );
119
120        // Make WPDS design tokens resolve at runtime on the legacy/wrap_ui Jetpack
121        // admin pages (Dashboard, Settings, Debugger) that don't ship their own
122        // `:root{--wpds-*}` source. Delegates to Admin_Menu's shared enqueue API.
123        add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_design_tokens' ) );
124    }
125
126    /**
127     * Handle our Additional CSS menu item and legacy page declaration.
128     *
129     * @since 11.0 . Prior to that, this function was located in custom-css-4.7.php (now custom-css.php).
130     */
131    public static function additional_css_menu() {
132        /*
133         * Custom CSS for the Customizer is deprecated for block themes as of WP 6.1, so we only expose it with a menu
134         * if the site already has existing CSS code.
135         */
136        if ( wp_is_block_theme() ) {
137            $styles = wp_get_custom_css();
138            if ( ! $styles ) {
139                return;
140            }
141        }
142
143        // If the site is a WoA site and the custom-css feature is not available, return.
144        // See https://github.com/Automattic/jetpack/pull/19965 for more on how this menu item is dealt with on WoA sites.
145        if ( ( new Host() )->is_woa_site() && ! ( in_array( 'custom-css', Jetpack::get_available_modules(), true ) ) ) {
146            return;
147        } elseif (
148            class_exists( 'Jetpack' ) && (
149                Jetpack::is_module_active( 'custom-css' ) || // If the Custom CSS module is enabled, add the Additional CSS menu item and link to the Customizer.
150                ( wp_is_block_theme() && ! empty( wp_get_custom_css() ) ) // Do the same if the theme is block-based but has existing custom CSS.
151            )
152        ) {
153            // Add in our legacy page to support old bookmarks and such.
154            add_submenu_page( '', __( 'CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'edit_theme_options', 'editcss', array( __CLASS__, 'customizer_redirect' ) );
155
156            // Add in our new page slug that will redirect to the customizer.
157            $hook = add_theme_page( __( 'CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'edit_theme_options', 'editcss-customizer-redirect', array( __CLASS__, 'customizer_redirect' ) );
158            add_action( "load-{$hook}", array( __CLASS__, 'customizer_redirect' ) );
159        }
160    }
161
162    /**
163     * Handle the redirect for the customizer.  This is necessary because
164     * we can't directly add customizer links to the admin menu.
165     *
166     * @since 11.0 . Prior to that, this function was located in custom-css-4.7.php (now custom-css.php).
167     *
168     * There is a core patch in trac that would make this unnecessary.
169     *
170     * @link https://core.trac.wordpress.org/ticket/39050
171     *
172     * @return never
173     */
174    public static function customizer_redirect() {
175        wp_safe_redirect(
176            self::customizer_link(
177                array(
178                    'return_url' => wp_get_referer(),
179                )
180            )
181        );
182        exit( 0 );
183    }
184
185    /**
186     * Build the URL to deep link to the Customizer.
187     *
188     * You can modify the return url via $args.
189     *
190     * @since 11.0 in this file. This method is also located in custom-css-4.7.php to cover legacy scenarios.
191     *
192     * @param array $args Array of parameters.
193     * @return string
194     */
195    public static function customizer_link( $args = array() ) {
196        if ( isset( $_SERVER['REQUEST_URI'] ) ) {
197            $args = wp_parse_args(
198                $args,
199                array(
200                    'return_url' => rawurlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
201                )
202            );
203        }
204
205        return add_query_arg(
206            array(
207                array(
208                    'autofocus' => array(
209                        'section' => 'custom_css',
210                    ),
211                ),
212                'return' => $args['return_url'],
213            ),
214            admin_url( 'customize.php' )
215        );
216    }
217
218    /**
219     * Sort callback to put modules with `requires_connection` last.
220     *
221     * @param array $module1 Module data.
222     * @param array $module2 Module data.
223     * @return int Indicating the relative ordering of module1 and module2.
224     */
225    public static function sort_requires_connection_last( $module1, $module2 ) {
226        return ( (bool) $module1['requires_connection'] ) <=> ( (bool) $module2['requires_connection'] );
227    }
228
229    /**
230     * Produce JS understandable objects of modules containing information for
231     * presentation like description, name, configuration url, etc.
232     */
233    public function get_modules() {
234        include_once JETPACK__PLUGIN_DIR . 'modules/module-info.php';
235        $available_modules = Jetpack::get_available_modules();
236        $active_modules    = Jetpack::get_active_modules();
237        $modules           = array();
238        $jetpack_active    = Jetpack::is_connection_ready() || ( new Status() )->is_offline_mode();
239        $overrides         = Jetpack_Modules_Overrides::instance();
240        $protect_page_urls = self::get_protect_page_module_urls();
241        foreach ( $available_modules as $module ) {
242            $module_array = Jetpack::get_module( $module );
243            if ( $module_array ) {
244                /**
245                 * Filters each module's short description.
246                 *
247                 * @since 3.0.0
248                 *
249                 * @param string $module_array['description'] Module description.
250                 * @param string $module Module slug.
251                 */
252                $short_desc = apply_filters( 'jetpack_short_module_description', $module_array['description'], $module );
253                // Fix: correct multibyte strings truncate with checking for mbstring extension.
254                $short_desc_trunc = ( function_exists( 'mb_strlen' ) )
255                            ? ( ( mb_strlen( $short_desc ) > 143 )
256                                ? mb_substr( $short_desc, 0, 140 ) . '...'
257                                : $short_desc )
258                            : ( ( strlen( $short_desc ) > 143 )
259                                ? substr( $short_desc, 0, 140 ) . '...'
260                                : $short_desc );
261
262                $module_array['module'] = $module;
263
264                $is_available = self::is_module_available( $module_array );
265
266                $module_array['activated']          = ( $jetpack_active ? in_array( $module, $active_modules, true ) : false );
267                $module_array['deactivate_nonce']   = wp_create_nonce( 'jetpack_deactivate-' . $module );
268                $module_array['activate_nonce']     = wp_create_nonce( 'jetpack_activate-' . $module );
269                $module_array['available']          = $is_available;
270                $module_array['unavailable_reason'] = $is_available ? false : self::get_module_unavailable_reason( $module_array );
271                $module_array['short_description']  = $short_desc_trunc;
272                $module_array['configure_url']      = Jetpack::module_configuration_url( $module );
273                $module_array['override']           = $overrides->get_module_override( $module );
274                $module_array['disabled']           = $is_available ? '' : 'disabled="disabled"';
275                $module_array['deactivation_note']  = Jetpack::get_module_deactivation_note( $module );
276
277                ob_start();
278                /**
279                 * Allow the display of a "Learn More" button.
280                 * The dynamic part of the action, $module, is the module slug.
281                 *
282                 * @since 3.0.0
283                 */
284                do_action( 'jetpack_learn_more_button_' . $module );
285                $module_array['learn_more_button'] = ob_get_clean();
286
287                ob_start();
288                /**
289                 * Allow the display of information text when Jetpack is connected to WordPress.com.
290                 * The dynamic part of the action, $module, is the module slug.
291                 *
292                 * @since 3.0.0
293                 */
294                do_action( 'jetpack_module_more_info_' . $module );
295
296                /**
297                * Filter the long description of a module.
298                *
299                * @since 3.5.0
300                *
301                * @param string ob_get_clean() The module long description.
302                * @param string $module The module name.
303                */
304                $module_array['long_description'] = apply_filters( 'jetpack_long_module_description', ob_get_clean(), $module );
305
306                ob_start();
307                /**
308                 * Filter the search terms for a module
309                 *
310                 * Search terms are typically added to the module headers, under "Additional Search Queries".
311                 *
312                 * Use syntax:
313                 * function jetpack_$module_search_terms( $terms ) {
314                 *  $terms = _x( 'term 1, term 2', 'search terms', 'jetpack' );
315                 *  return $terms;
316                 * }
317                 * add_filter( 'jetpack_search_terms_$module', 'jetpack_$module_search_terms' );
318                 *
319                 * @since 3.5.0
320                 *
321                 * @param string The search terms (comma-separated).
322                 */
323                echo apply_filters( 'jetpack_search_terms_' . $module, $module_array['additional_search_queries'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
324                $module_array['search_terms'] = ob_get_clean();
325
326                $module_array['configurable'] = false;
327                if (
328                    current_user_can( 'manage_options' ) &&
329                    /**
330                     * Allow the display of a configuration link in the Jetpack Settings screen.
331                     *
332                     * @since 3.0.0
333                     *
334                     * @param string $module Module name.
335                     * @param bool false Should the Configure module link be displayed? Default to false.
336                     */
337                    apply_filters( 'jetpack_module_configurable_' . $module, false )
338                ) {
339                    $module_array['configurable'] = sprintf( '<a href="%1$s">%2$s</a>', esc_url( $module_array['configure_url'] ), __( 'Configure', 'jetpack' ) );
340                }
341
342                // The Protect page's link replaces both the switch and Configure.
343                $module_array['protect_page_url'] = $protect_page_urls[ $module ] ?? '';
344                if ( $module_array['protect_page_url'] ) {
345                    $module_array['configurable'] = false;
346                }
347
348                $modules[ $module ] = $module_array;
349            }
350        }
351
352        uasort( $modules, array( 'Jetpack', 'sort_modules' ) );
353
354        if ( ! Jetpack::is_connection_ready() ) {
355            uasort( $modules, array( __CLASS__, 'sort_requires_connection_last' ) );
356        }
357
358        return $modules;
359    }
360
361    /**
362     * Check if a module is available.
363     *
364     * @param array $module Module data.
365     */
366    public static function is_module_available( $module ) {
367        if ( ! is_array( $module ) || empty( $module ) ) {
368            return false;
369        }
370
371        /**
372         * We never want to show VaultPress as activatable through Jetpack.
373         */
374        if ( 'vaultpress' === $module['module'] ) {
375            return false;
376        }
377
378        /*
379         * WooCommerce Analytics should only be available
380         * when running WooCommerce 3+
381         */
382        if (
383            'woocommerce-analytics' === $module['module']
384            && (
385                ! class_exists( 'WooCommerce' )
386                || version_compare( WC_VERSION, '3.0', '<' )
387            )
388        ) {
389            return false;
390        }
391
392        /*
393         * In Offline mode, modules that require a site or user
394         * level connection should be unavailable.
395         */
396        if ( ( new Status() )->is_offline_mode() ) {
397            return ! ( $module['requires_connection'] || $module['requires_user_connection'] );
398        }
399
400        /*
401         * Jetpack not connected.
402         */
403        if ( ! Jetpack::is_connection_ready() ) {
404            return false;
405        }
406
407        /*
408         * Jetpack connected at a site level only. Make sure to make
409         * modules that require a user connection unavailable.
410         */
411        if ( ! Jetpack::connection()->has_connected_owner() && $module['requires_user_connection'] ) {
412            return false;
413        }
414
415        return Jetpack_Plan::supports( $module['module'] );
416    }
417
418    /**
419     * Returns why a module is unavailable.
420     *
421     * @param  array $module The module.
422     * @return string|false A string stating why the module is not available or false if the module is available.
423     */
424    public static function get_module_unavailable_reason( $module ) {
425        if ( ! is_array( $module ) || empty( $module ) ) {
426            return false;
427        }
428
429        if ( self::is_module_available( $module ) ) {
430            return false;
431        }
432
433        /**
434         * We never want to show VaultPress as activatable through Jetpack so return an empty string.
435         */
436        if ( 'vaultpress' === $module['module'] ) {
437            return '';
438        }
439
440        /*
441         * WooCommerce Analytics should only be available
442         * when running WooCommerce 3+
443         */
444        if (
445            'woocommerce-analytics' === $module['module']
446            && (
447                    ! class_exists( 'WooCommerce' )
448                    || version_compare( WC_VERSION, '3.0', '<' )
449                )
450            ) {
451            return __( 'Requires WooCommerce 3+ plugin', 'jetpack' );
452        }
453
454        /*
455         * In Offline mode, modules that require a site or user
456         * level connection should be unavailable.
457         */
458        if ( ( new Status() )->is_offline_mode() ) {
459            if ( $module['requires_connection'] || $module['requires_user_connection'] ) {
460                return __( 'Unavailable in Offline Mode', 'jetpack' );
461            }
462        }
463
464        /*
465         * Jetpack not connected.
466         */
467        if ( ! Jetpack::is_connection_ready() ) {
468            return __( 'Jetpack is not connected', 'jetpack' );
469        }
470
471        /*
472         * Jetpack connected at a site level only and module requires a user connection.
473         */
474        if ( ! Jetpack::connection()->has_connected_owner() && $module['requires_user_connection'] ) {
475            return __( 'Requires a connected WordPress.com account', 'jetpack' );
476        }
477
478        /*
479         * Plan restrictions.
480         */
481        if ( ! Jetpack_Plan::supports( $module['module'] ) ) {
482            return __( 'Not supported by current plan', 'jetpack' );
483        }
484
485        return '';
486    }
487
488    /**
489     * Where each security module's settings live while the Protect page owns them, keyed by module slug.
490     *
491     * @since 16.4
492     *
493     * @return array<string, string> Empty while the Protect page is off.
494     */
495    public static function get_protect_page_module_urls() {
496        // method_exists, not class_exists: another plugin's older copy of the package can win the autoloader.
497        if ( ! did_action( 'jetpack_protect_dashboard_initialized' ) || ! method_exists( Protect_Dashboard::class, 'get_module_settings_urls' ) ) {
498            return array();
499        }
500
501        return Protect_Dashboard::get_module_settings_urls();
502    }
503
504    /**
505     * Handle an unrecognized action.
506     *
507     * @param string $action Action.
508     */
509    public function handle_unrecognized_action( $action ) {
510        switch ( $action ) {
511            case 'bulk-activate':
512                check_admin_referer( 'bulk-jetpack_page_jetpack_modules' );
513                if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
514                    break;
515                }
516
517                $modules = isset( $_GET['modules'] ) ? array_map( 'sanitize_key', wp_unslash( (array) $_GET['modules'] ) ) : array();
518                $modules = array_diff( $modules, array_keys( self::get_protect_page_module_urls() ) );
519                foreach ( $modules as $module ) {
520                    Jetpack::log( 'activate', $module );
521                    Jetpack::activate_module( $module, false );
522                }
523                // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
524                wp_safe_redirect( wp_get_referer() );
525                exit( 0 );
526            case 'bulk-deactivate':
527                check_admin_referer( 'bulk-jetpack_page_jetpack_modules' );
528                if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
529                    break;
530                }
531
532                $modules = isset( $_GET['modules'] ) ? array_map( 'sanitize_key', wp_unslash( (array) $_GET['modules'] ) ) : array();
533                $modules = array_diff( $modules, array_keys( self::get_protect_page_module_urls() ) );
534                foreach ( $modules as $module ) {
535                    Jetpack::log( 'deactivate', $module );
536                    Jetpack::deactivate_module( $module );
537                    Jetpack::state( 'message', 'module_deactivated' );
538                }
539                Jetpack::state( 'module', $modules );
540                wp_safe_redirect( wp_get_referer() );
541                exit( 0 );
542            default:
543                return;
544        }
545    }
546
547    /**
548     * Fix redirect.
549     *
550     * Apparently we redirect to the referrer instead of whatever WordPress
551     * wants to redirect to when activating and deactivating modules.
552     *
553     * @param string $module Module slug.
554     * @param bool   $redirect Should we exit after the module has been activated. Default to true.
555     */
556    public function fix_redirect( $module, $redirect = true ) {
557        if ( ! $redirect ) {
558            return;
559        }
560        if ( wp_get_referer() ) {
561            add_filter( 'wp_redirect', 'wp_get_referer' );
562        }
563    }
564
565    /**
566     * Add debugger admin menu.
567     */
568    public function admin_menu_debugger() {
569        require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger.php';
570        Jetpack_Debugger::disconnect_and_redirect();
571        $debugger_hook = add_submenu_page(
572            '',
573            __( 'Debugging Center', 'jetpack' ),
574            '',
575            'manage_options',
576            'jetpack-debugger',
577            array( $this, 'wrap_debugger_page' )
578        );
579        add_action( "admin_head-$debugger_hook", array( 'Jetpack_Debugger', 'jetpack_debug_admin_head' ) );
580    }
581
582    /**
583     * Wrap debugger page.
584     */
585    public function wrap_debugger_page() {
586        nocache_headers();
587        if ( ! current_user_can( 'manage_options' ) ) {
588            die( '-1' );
589        }
590        Jetpack_Admin_Page::wrap_ui(
591            array( $this, 'debugger_page' ),
592            array(
593                'is-wide'  => true,
594                'show-nav' => false,
595            )
596        );
597    }
598
599    /**
600     * Display debugger page.
601     */
602    public function debugger_page() {
603        require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger.php';
604        Jetpack_Debugger::jetpack_debug_display_handler();
605    }
606
607    /**
608     * Determines if JITMs should display on a particular screen.
609     *
610     * @param bool   $value The default value of the filter.
611     * @param string $screen_id The ID of the screen being tested for JITM display.
612     *
613     * @return bool True if JITMs should display, false otherwise.
614     */
615    public function should_display_jitms_on_screen( $value, $screen_id ) {
616        // Disable all JITMs on these pages.
617        if (
618        in_array(
619            $screen_id,
620            array(
621                'jetpack_page_akismet-key-config',
622                'admin_page_jetpack_modules',
623            ),
624            true
625        ) ) {
626            return false;
627        }
628
629        return $value;
630    }
631
632    /**
633     * Check if we're on a Jetpack admin page.
634     *
635     * Similar to how WooCommerce checks for its admin pages by comparing
636     * against known screen ID patterns.
637     *
638     * @return bool True if on a Jetpack admin page, false otherwise.
639     */
640    private function is_jetpack_admin_page() {
641        $screen = get_current_screen();
642        if ( ! $screen ) {
643            return false;
644        }
645
646        // Check for Jetpack admin pages:
647        // - toplevel_page_jetpack (main Jetpack menu page)
648        // - toplevel_page_jetpack-network (Jetpack Network Admin menu page)
649        // - jetpack_page_* (Jetpack submenu pages)
650        // - admin_page_jetpack* (legacy/special Jetpack pages)
651        // Or check if parent_base is 'jetpack' or 'jetpack-network' (submenu pages)
652        return (
653        $screen->id === 'toplevel_page_jetpack' ||
654        $screen->id === 'toplevel_page_jetpack-network' ||
655        str_starts_with( $screen->id, 'jetpack_page_' ) ||
656        str_starts_with( $screen->id, 'admin_page_jetpack' ) ||
657        $screen->parent_base === 'jetpack' ||
658        $screen->parent_base === 'jetpack-network'
659        );
660    }
661
662    /**
663     * Add a body class to Jetpack admin pages.
664     *
665     * @param string $classes Space-separated list of CSS classes.
666     * @return string Modified class list.
667     */
668    public function add_jetpack_admin_body_class( $classes ) {
669        if ( $this->is_jetpack_admin_page() ) {
670            return ltrim( trim( $classes ) . ' jetpack-admin-page ' );
671        }
672        return $classes;
673    }
674
675    /**
676     * Add inline styles to remove footer padding on Jetpack pages.
677     *
678     * This needs to be inline because jetpack-admin.css is not loaded on
679     * React-powered admin pages (they use load_wrapper_styles instead).
680     */
681    public function add_footer_removal_styles() {
682        if ( ! $this->is_jetpack_admin_page() ) {
683            return;
684        }
685        echo '<style>.jetpack-admin-page #wpbody-content { padding-bottom: 0; } .jetpack-admin-page #wpfooter { display: none; }</style>';
686    }
687
688    /**
689     * Enqueues the shared WPDS design-tokens stylesheet on the legacy/wrap_ui pages.
690     *
691     * This is the admin_enqueue_scripts callback for the legacy Jetpack admin
692     * pages. The admin-ui package owns the handle and enqueues it on the
693     * modernized dashboards it registers; the legacy/wrap_ui pages (Dashboard,
694     * Settings, Debugger) aren't registered through Admin_Menu, so we cover them
695     * here via the central is_jetpack_admin_page() gate. The actual enqueue is
696     * delegated to the reusable Admin_Menu::enqueue_design_tokens() API so there
697     * is a single owner of the handle and no duplicated register/enqueue logic.
698     *
699     * @return void
700     */
701    public function maybe_enqueue_design_tokens() {
702        if ( ! $this->is_jetpack_admin_page() ) {
703            return;
704        }
705
706        // Guard against an older admin-ui being loaded ahead of this one by the
707        // package autoloader's version-precedence resolution.
708        if ( ! method_exists( Admin_Menu::class, 'enqueue_design_tokens' ) ) {
709            return;
710        }
711
712        Admin_Menu::enqueue_design_tokens();
713    }
714
715    /**
716     * Remove the admin footer text on Jetpack pages.
717     *
718     * @param string $content The default footer text.
719     * @return string Empty string on Jetpack pages, original content otherwise.
720     */
721    public function maybe_remove_admin_footer_text( $content ) {
722        return $this->is_jetpack_admin_page() ? '' : $content;
723    }
724
725    /**
726     * Remove the admin footer version on Jetpack pages.
727     *
728     * @param string $content The default footer version text.
729     * @return string Empty string on Jetpack pages, original content otherwise.
730     */
731    public function maybe_remove_admin_footer_version( $content ) {
732        return $this->is_jetpack_admin_page() ? '' : $content;
733    }
734}
735Jetpack_Admin::init();