Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.63% covered (warning)
77.63%
118 / 152
58.82% covered (warning)
58.82%
10 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Settings_React_Page
77.18% covered (warning)
77.18%
115 / 149
58.82% covered (warning)
58.82%
10 / 17
153.15
0.00% covered (danger)
0.00%
0 / 1
 should_load_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 maybe_load_wp_build
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
42
 load_as_admin_shell_guest
91.30% covered (success)
91.30%
21 / 23
0.00% covered (danger)
0.00%
0 / 1
7.03
 is_admin_shell_guest_request
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 should_render_wp_build
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_wp_build_script_dependencies
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 get_page_hook
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
4
 hide_menu_item
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_remaining_tabs
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
19
 add_page_actions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_fallback_redirects
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 can_access_settings
83.33% covered (warning)
83.33%
15 / 18
0.00% covered (danger)
0.00%
0 / 1
12.67
 are_settings_moving_out
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 page_render
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
2.06
 additional_styles
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 page_admin_scripts
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
8
1<?php
2/**
3 * The Jetpack Settings admin page.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Admin_UI\Admin_Menu;
9use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\My_Jetpack\Google_Analytics_Settings;
12use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
13use Automattic\Jetpack\PremiumAnalytics\Analytics;
14use Automattic\Jetpack\SEO\Initializer as SEO_Initializer;
15use Automattic\Jetpack\Stats\Options as Stats_Options;
16use Automattic\Jetpack\Status;
17use Automattic\Jetpack\Status\Host;
18
19require_once __DIR__ . '/class.jetpack-admin-page.php';
20require_once __DIR__ . '/class-jetpack-redux-state-helper.php';
21require_once __DIR__ . '/class-jetpack-wp-build-page.php';
22
23/**
24 * Renders the Settings app, whose connection screens also serve unconnected sites.
25 *
26 * @since 16.3
27 */
28class Jetpack_Settings_React_Page extends Jetpack_Admin_Page {
29    /**
30     * Register the page before the site connects, for the connection screen.
31     *
32     * @var bool
33     */
34    protected $dont_show_if_not_active = false;
35
36    /**
37     * Whether the REST API is off and the page falls back to the modules list.
38     *
39     * @var bool
40     */
41    protected $is_redirecting = false;
42
43    /**
44     * The wp-build route's page id, which must not be the `jetpack-settings` menu slug.
45     *
46     * @var string
47     */
48    const WP_BUILD_PAGE_ID = 'jetpack-settings-dashboard';
49
50    /**
51     * Whether this request loaded the wp-build route.
52     *
53     * @var bool
54     */
55    private $is_wp_build_loaded = false;
56
57    /**
58     * Whether this request should load wp-build.
59     *
60     * An IDC-blocked page shows only the IDC banner, which the wp-build template would hide.
61     *
62     * @since 16.3
63     *
64     * @return bool
65     */
66    public function should_load_wp_build() {
67        if ( ! is_admin() ) {
68            return false;
69        }
70
71        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
72        if ( ! isset( $_GET['page'] ) || 'jetpack-settings' !== sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
73            return false;
74        }
75
76        return ! $this->block_page_rendering_for_idc();
77    }
78
79    /**
80     * Load wp-build before the admin menu is built, on the Settings request only.
81     *
82     * @since 16.3
83     *
84     * @return void
85     */
86    public function maybe_load_wp_build() {
87        if ( $this->should_load_wp_build() ) {
88            $this->is_wp_build_loaded = Jetpack_WP_Build_Page::load( self::WP_BUILD_PAGE_ID );
89        }
90    }
91
92    /**
93     * Register Settings with the admin shell, which switches between Jetpack dashboards without a page load.
94     *
95     * @since 16.5
96     *
97     * @param array $members Shell members keyed by admin page slug.
98     * @return array
99     */
100    public function add_admin_shell_member( $members ) {
101        // During IDC the page shows only the IDC banner.
102        if (
103            ( new Host() )->is_wpcom_simple()
104            || ! file_exists( JETPACK__PLUGIN_DIR . 'build/build.php' )
105            || ! $this->should_add_page()
106            || ! $this->can_access_settings()
107            || $this->block_page_rendering_for_idc()
108        ) {
109            return $members;
110        }
111
112        $members['jetpack-settings'] = array(
113            'build_prefix' => 'jetpack_plugin',
114            'build_page'   => self::WP_BUILD_PAGE_ID,
115            'init_modules' => array( '@jetpack-plugin/init' ),
116            'title'        => __( 'Settings', 'jetpack' ),
117            // The landing tab, and so its subtitle, is picked in the browser from modules, plan and pages.
118            'header'       => array(
119                'title'    => __( 'Settings', 'jetpack' ),
120                'subtitle' => null,
121            ),
122            'capability'   => 'jetpack_admin_page',
123            'handles'      => array( 'react-plugin', 'jetpack-script-data', 'jp-tracks', 'wp-jp-i18n-loader' ),
124            'load'         => array( $this, 'load_as_admin_shell_guest' ),
125        );
126        return $members;
127    }
128
129    /**
130     * Ready the Settings routes and page data while another dashboard's page is open, without the screen ID alias.
131     *
132     * @since 16.5
133     *
134     * @return void
135     */
136    public function load_as_admin_shell_guest() {
137        // A menu hover builds the page state, which saves module defaults and copies of per-user values; the page's own load saves them.
138        if ( self::is_admin_shell_guest_request() ) {
139            $user_id     = get_current_user_id();
140            $keep_stored = static function ( $value, $old_value ) {
141                return $old_value;
142            };
143            foreach ( array( 'sharing-options', 'monitor_receive_notifications' . $user_id, 'post_by_email_address' . $user_id ) as $option ) {
144                add_filter( 'pre_update_option_' . $option, $keep_stored, 10, 2 );
145            }
146            // The purchase token lives among the connection tokens, so hold back only that key.
147            add_filter(
148                'pre_update_option_jetpack_private_options',
149                static function ( $value, $old_value ) {
150                    if ( ! is_array( $value ) ) {
151                        return $value;
152                    }
153                    if ( is_array( $old_value ) && isset( $old_value['purchase_token'] ) ) {
154                        $value['purchase_token'] = $old_value['purchase_token'];
155                    } else {
156                        unset( $value['purchase_token'] );
157                    }
158                    return $value;
159                },
160                10,
161                2
162            );
163        }
164
165        $this->is_wp_build_loaded = Jetpack_WP_Build_Page::load( self::WP_BUILD_PAGE_ID, false );
166        if ( $this->is_wp_build_loaded ) {
167            add_action( 'admin_enqueue_scripts', array( $this, 'page_admin_scripts' ) );
168        }
169    }
170
171    /**
172     * Whether this is the admin shell's hover request, not another dashboard's page readying Settings for a switch.
173     *
174     * @return bool
175     */
176    private static function is_admin_shell_guest_request() {
177        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Compared only; the shell checks the nonce.
178        return wp_doing_ajax() && isset( $_GET['action'] ) && \Automattic\Jetpack\Admin_UI\Admin_Shell::GUEST_ACTION === wp_unslash( $_GET['action'] );
179    }
180
181    /**
182     * Whether this request renders through wp-build.
183     *
184     * @since 16.3
185     *
186     * @return bool
187     */
188    public function should_render_wp_build() {
189        return $this->is_wp_build_loaded && function_exists( 'jetpack_plugin_jetpack_settings_dashboard_wp_admin_render_page' );
190    }
191
192    /**
193     * The route bundle's classic script dependencies (e.g. `lodash`), which wp-build registers
194     * as a script module without them, leaving globals like `window.lodash` undefined.
195     *
196     * @since 16.3
197     *
198     * @return string[]
199     */
200    protected function get_wp_build_script_dependencies() {
201        $asset_path = JETPACK__PLUGIN_DIR . 'build/routes/settings/content.min.asset.php';
202        if ( ! file_exists( $asset_path ) ) {
203            return array();
204        }
205
206        $asset = include $asset_path;
207        return $asset['dependencies'] ?? array();
208    }
209
210    /**
211     * Register the page; only its sidebar entry keeps the Settings access gate.
212     *
213     * Shares the bottom tier with Beta Tester so it lands below the alphabetical run;
214     * the upsell still renders underneath because Admin_Menu appends it after sorting.
215     *
216     * @return string The page hook.
217     */
218    public function get_page_hook() {
219        if ( ! $this->can_access_settings() || array() === self::get_remaining_tabs() ) {
220            add_filter( 'jetpack_admin_menu_visibility', array( __CLASS__, 'hide_menu_item' ) );
221        }
222
223        $position = defined( Admin_Menu::class . '::POSITION_LAST' ) ? Admin_Menu::POSITION_LAST : 998;
224
225        $hook = Admin_Menu::add_menu(
226            __( 'Settings', 'jetpack' ),
227            __( 'Settings', 'jetpack' ),
228            'jetpack_admin_page',
229            'jetpack-settings',
230            array( $this, 'render' ),
231            $position,
232            array( 'key' => 'jetpack-settings' )
233        );
234
235        // The IDC banner is a core-style notice, and during IDC it is all this page shows.
236        remove_action( "load-$hook", array( Admin_Menu::class, 'hide_core_admin_notices' ) );
237
238        return $hook;
239    }
240
241    /**
242     * Hide the sidebar entry from users who cannot use Settings, or who have no tab left on it.
243     *
244     * @param array $states Menu item key to visibility state.
245     * @return array
246     */
247    public static function hide_menu_item( $states ) {
248        $states['jetpack-settings'] = 'hidden';
249        return $states;
250    }
251
252    /**
253     * The tabs Settings still shows this user once settings move to My Jetpack, which the sidebar entry and the nav both follow.
254     *
255     * @since 16.5
256     *
257     * @return string[]|null Tab routes without the slash, or null while settings stay here: consolidation is off, or the user cannot manage modules.
258     */
259    public static function get_remaining_tabs() {
260        if ( ! current_user_can( 'jetpack_manage_modules' ) || ! self::are_settings_moving_out() ) {
261            return null;
262        }
263
264        $available = Jetpack::get_available_modules();
265        $has_any   = static function ( array $modules ) use ( $available ) {
266            return array() !== array_intersect( $modules, $available );
267        };
268
269        if ( ! function_exists( 'is_plugin_active' ) ) {
270            require_once ABSPATH . 'wp-admin/includes/plugin.php';
271        }
272
273        $tabs = array();
274
275        if (
276            ! did_action( 'jetpack_protect_dashboard_initialized' )
277            && ( $has_any( array( 'protect', 'sso', 'vaultpress' ) ) || is_plugin_active( 'akismet/akismet.php' ) )
278        ) {
279            $tabs[] = 'security';
280        }
281
282        $has_seo_page        = method_exists( SEO_Initializer::class, 'is_seo_surface_visible' ) && SEO_Initializer::is_seo_surface_visible();
283        $has_analytics_panel = method_exists( Google_Analytics_Settings::class, 'is_available' ) && Google_Analytics_Settings::is_available();
284        // Stats v2 counts wherever it booted, the Premium Analytics plugin included.
285        $has_stats_v2   = method_exists( Analytics::class, 'is_initialized' ) ? Analytics::is_initialized() : Jetpack::is_premium_analytics_enabled();
286        $has_stats_page = Stats_Options::get_option( 'enable_odyssey_stats' ) || $has_stats_v2;
287        if (
288            ( ! $has_seo_page && $has_any( array( 'seo-tools', 'canonical-urls', 'verification-tools', 'sitemaps' ) ) )
289            || ( ( new Host() )->is_woa_site() && ! $has_analytics_panel )
290            || ( ! $has_stats_page && $has_any( array( 'stats' ) ) )
291        ) {
292            $tabs[] = 'traffic';
293        }
294
295        if ( $has_any( array( 'wordads' ) ) && ! Jetpack_Ads_Settings_Home::is_moved_off_settings() ) {
296            $tabs[] = 'earn';
297        }
298
299        return $tabs;
300    }
301
302    /**
303     * Add page actions.
304     *
305     * @param string $hook Hook of current page.
306     * @return void
307     */
308    public function add_page_actions( $hook ) {
309        add_action( "load-$hook", array( $this, 'add_fallback_redirects' ) );
310    }
311
312    /**
313     * Send browsers that cannot run the app to the modules list.
314     *
315     * @return void
316     */
317    public function add_fallback_redirects() {
318        if ( ! $this->is_rest_api_enabled() ) {
319            $this->is_redirecting = true;
320            add_action( 'admin_head', array( $this, 'add_fallback_head_meta' ) );
321        }
322
323        add_action( 'admin_head', array( $this, 'add_noscript_head_meta' ) );
324    }
325
326    /**
327     * Determine whether a user can access the Jetpack Settings page.
328     *
329     * Rules are:
330     * - user is allowed to see the Jetpack Admin
331     * - site is connected or in offline mode
332     * - non-admins only need access to the settings when there are modules they can manage.
333     *
334     * @return bool $can_access_settings Can the user access settings.
335     */
336    private function can_access_settings() {
337        $connection = new Connection_Manager( 'jetpack' );
338        $status     = new Status();
339
340        // User must have the necessary permissions to see the Jetpack settings pages.
341        if ( ! current_user_can( 'edit_posts' ) ) {
342            return false;
343        }
344
345        // In offline mode, allow access to admins.
346        if ( $status->is_offline_mode() && current_user_can( 'manage_options' ) ) {
347            return true;
348        }
349
350        // If not in offline mode but site is not connected, bail.
351        if ( ! Jetpack::is_connection_ready() ) {
352            return false;
353        }
354
355        /*
356         * Additional checks for non-admins.
357        */
358        if ( ! current_user_can( 'manage_options' ) ) {
359            // If the site isn't connected at all, bail.
360            if ( ! $connection->has_connected_owner() ) {
361                return false;
362            }
363
364            /*
365             * If they haven't connected their own account yet,
366             * they have no use for the settings page.
367             * They will not be able to manage any settings.
368             */
369            if ( ! $connection->is_user_connected() ) {
370                return false;
371            }
372
373            /*
374             * Non-admins only have access to settings
375             * for the following modules:
376             * - Publicize
377             * - Post By Email, until it lives only on their Profile page
378             * If those modules are not available, bail.
379             */
380            if (
381                ( ! Jetpack::is_module_active( 'post-by-email' ) || self::are_settings_moving_out() )
382                    && (
383                        ! Jetpack::is_module_active( 'publicize' ) ||
384                        ! current_user_can( 'publish_posts' )
385                    )
386            ) {
387                return false;
388            }
389        }
390
391        // fallback.
392        return true;
393    }
394
395    /**
396     * Whether settings move to My Jetpack, which leaves Post by Email for non-admins only on their Profile page.
397     *
398     * Uses the check that needs no admin menu, since this runs while the menu is built.
399     *
400     * @return bool
401     */
402    private static function are_settings_moving_out() {
403        return method_exists( My_Jetpack_Initializer::class, 'is_settings_consolidation_on_for_site' )
404            && My_Jetpack_Initializer::is_settings_consolidation_on_for_site();
405    }
406
407    /**
408     * Add action to render page specific HTML.
409     *
410     * @return void
411     */
412    public function page_render() {
413        /** This action is already documented in class.jetpack-admin-page.php */
414        do_action( 'jetpack_notices' );
415
416        if ( $this->should_render_wp_build() ) {
417            jetpack_plugin_jetpack_settings_dashboard_wp_admin_render_page(); // @phan-suppress-current-line PhanUndeclaredFunction -- should_render_wp_build() checks function_exists(); defined in the generated build/pages/, which Phan excludes.
418            return;
419        }
420
421        echo '<p class="jp-settings-build-error">';
422        esc_html_e( 'Jetpack Settings could not load. Try running: ', 'jetpack' );
423        echo '<code>pnpm jetpack build plugins/jetpack</code>';
424        echo '</p>';
425    }
426
427    /**
428     * Load styles for static page.
429     */
430    public function additional_styles() {
431        // The route bundle carries these styles.
432        if ( $this->should_render_wp_build() ) {
433            return;
434        }
435
436        Jetpack_Admin_Page::load_wrapper_styles();
437    }
438
439    /**
440     * Load admin page scripts.
441     */
442    public function page_admin_scripts() {
443        // A fallback page, or one without the route (IDC-blocked or unbuilt), renders no app to feed.
444        if ( $this->is_redirecting || ! $this->should_render_wp_build() ) {
445            return;
446        }
447
448        $status          = new Status();
449        $is_offline_mode = $status->is_offline_mode();
450        $site_suffix     = $status->get_site_suffix();
451
452        // wp-build enqueues the route bundle; this handle carries the inline state and classic dependencies.
453        wp_register_script( 'react-plugin', false, $this->get_wp_build_script_dependencies(), JETPACK__VERSION, true );
454        wp_enqueue_script( 'react-plugin' );
455
456        $blog_id_prop = '';
457        if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
458            $blog_id = Connection_Manager::get_site_id( true );
459            if ( $blog_id ) {
460                $blog_id_prop = ', currentBlogID: "' . (int) $blog_id . '"';
461            }
462        }
463
464        if ( ! $is_offline_mode && Jetpack::is_connection_ready() ) {
465            // Required for Analytics.
466            wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
467        }
468
469        // Add objects to be passed to the initial state of the app.
470        // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
471        wp_add_inline_script( 'react-plugin', 'var Initial_State=' . wp_json_encode( Jetpack_Redux_State_Helper::get_initial_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';', 'before' );
472
473        // This will set the default URL of the jp_redirects lib.
474        wp_add_inline_script( 'react-plugin', 'var jetpack_redirects = { currentSiteRawUrl: "' . $site_suffix . '"' . $blog_id_prop . ' };', 'before' );
475
476        // Adds Connection package initial state.
477        Connection_Initial_State::render_script( 'react-plugin' );
478    }
479}