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