Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.64% covered (warning)
78.64%
81 / 103
53.85% covered (warning)
53.85%
7 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Settings_React_Page
77.78% covered (warning)
77.78%
77 / 99
53.85% covered (warning)
53.85%
7 / 13
65.25
0.00% covered (danger)
0.00%
0 / 1
 is_wp_build_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 should_load_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 maybe_load_wp_build
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 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%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 hide_menu_item
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 add_page_actions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add_fallback_redirects
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 can_access_settings
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
18.12
 page_render
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
3.18
 additional_styles
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 page_admin_scripts
87.88% covered (warning)
87.88%
29 / 33
0.00% covered (danger)
0.00%
0 / 1
9.14
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\Feature_Flags\Feature_Flags;
12use Automattic\Jetpack\Status;
13
14require_once __DIR__ . '/class.jetpack-admin-page.php';
15require_once __DIR__ . '/class-jetpack-redux-state-helper.php';
16require_once __DIR__ . '/class-jetpack-wp-build-page.php';
17require_once dirname( __DIR__ ) . '/class-jetpack-settings-feature-flags.php';
18
19/**
20 * Renders the Settings app, whose connection screens also serve unconnected sites.
21 *
22 * @since $$next-version$$
23 */
24class Jetpack_Settings_React_Page extends Jetpack_Admin_Page {
25    /**
26     * Register the page before the site connects, for the connection screen.
27     *
28     * @var bool
29     */
30    protected $dont_show_if_not_active = false;
31
32    /**
33     * Whether the REST API is off and the page falls back to the modules list.
34     *
35     * @var bool
36     */
37    protected $is_redirecting = false;
38
39    /**
40     * The wp-build route's page id, which must not be the `jetpack-settings` menu slug.
41     *
42     * @var string
43     */
44    const WP_BUILD_PAGE_ID = 'jetpack-settings-dashboard';
45
46    /**
47     * Whether this request loaded the wp-build route.
48     *
49     * @var bool
50     */
51    private $is_wp_build_loaded = false;
52
53    /**
54     * Whether Settings renders through wp-build; off serves the webpack page at the same address.
55     *
56     * @since $$next-version$$
57     *
58     * @return bool
59     */
60    public static function is_wp_build_enabled() {
61        return Feature_Flags::is_enabled( Jetpack_Settings_Feature_Flags::WP_BUILD );
62    }
63
64    /**
65     * Whether this request should load wp-build.
66     *
67     * An IDC-blocked page shows only the IDC banner, which the wp-build template would hide.
68     * RTL stays on webpack too: wp-build inlines the route CSS with no RTL variant.
69     *
70     * @since $$next-version$$
71     *
72     * @return bool
73     */
74    public function should_load_wp_build() {
75        if ( ! is_admin() || ! self::is_wp_build_enabled() || is_rtl() ) {
76            return false;
77        }
78
79        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
80        if ( ! isset( $_GET['page'] ) || 'jetpack-settings' !== sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
81            return false;
82        }
83
84        return ! $this->block_page_rendering_for_idc();
85    }
86
87    /**
88     * Load wp-build before the admin menu is built, on the Settings request only.
89     *
90     * @since $$next-version$$
91     *
92     * @return void
93     */
94    public function maybe_load_wp_build() {
95        if ( $this->should_load_wp_build() ) {
96            $this->is_wp_build_loaded = Jetpack_WP_Build_Page::load( self::WP_BUILD_PAGE_ID );
97        }
98    }
99
100    /**
101     * Whether this request renders through wp-build.
102     *
103     * @since $$next-version$$
104     *
105     * @return bool
106     */
107    public function should_render_wp_build() {
108        return $this->is_wp_build_loaded && function_exists( 'jetpack_plugin_jetpack_settings_dashboard_wp_admin_render_page' );
109    }
110
111    /**
112     * The route bundle's classic script dependencies (e.g. `lodash`), which wp-build registers
113     * as a script module without them, leaving globals like `window.lodash` undefined.
114     *
115     * @since $$next-version$$
116     *
117     * @return string[]
118     */
119    protected function get_wp_build_script_dependencies() {
120        $asset_path = JETPACK__PLUGIN_DIR . 'build/routes/settings/content.min.asset.php';
121        if ( ! file_exists( $asset_path ) ) {
122            return array();
123        }
124
125        $asset = include $asset_path;
126        return $asset['dependencies'] ?? array();
127    }
128
129    /**
130     * Register the page; only its sidebar entry keeps the Settings access gate.
131     *
132     * Shares the bottom tier with Beta Tester so it lands below the alphabetical run;
133     * the upsell still renders underneath because Admin_Menu appends it after sorting.
134     *
135     * @return string The page hook.
136     */
137    public function get_page_hook() {
138        if ( ! $this->can_access_settings() ) {
139            add_filter( 'jetpack_admin_menu_visibility', array( __CLASS__, 'hide_menu_item' ) );
140        }
141
142        $hook = Admin_Menu::add_menu(
143            __( 'Settings', 'jetpack' ),
144            __( 'Settings', 'jetpack' ),
145            'jetpack_admin_page',
146            'jetpack-settings',
147            array( $this, 'render' ),
148            Admin_Menu::POSITION_LAST,
149            array( 'key' => 'jetpack-settings' )
150        );
151
152        // The IDC banner is a core-style notice, and during IDC it is all this page shows.
153        remove_action( "load-$hook", array( Admin_Menu::class, 'hide_core_admin_notices' ) );
154
155        return $hook;
156    }
157
158    /**
159     * Hide the sidebar entry from users who cannot use Settings.
160     *
161     * @param array $states Menu item key to visibility state.
162     * @return array
163     */
164    public static function hide_menu_item( $states ) {
165        $states['jetpack-settings'] = 'hidden';
166        return $states;
167    }
168
169    /**
170     * Add page actions.
171     *
172     * @param string $hook Hook of current page.
173     * @return void
174     */
175    public function add_page_actions( $hook ) {
176        add_action( "load-$hook", array( $this, 'add_fallback_redirects' ) );
177    }
178
179    /**
180     * Send browsers that cannot run the app to the modules list.
181     *
182     * @return void
183     */
184    public function add_fallback_redirects() {
185        if ( ! $this->is_rest_api_enabled() ) {
186            $this->is_redirecting = true;
187            add_action( 'admin_head', array( $this, 'add_fallback_head_meta' ) );
188        }
189
190        add_action( 'admin_head', array( $this, 'add_noscript_head_meta' ) );
191    }
192
193    /**
194     * Determine whether a user can access the Jetpack Settings page.
195     *
196     * Rules are:
197     * - user is allowed to see the Jetpack Admin
198     * - site is connected or in offline mode
199     * - non-admins only need access to the settings when there are modules they can manage.
200     *
201     * @return bool $can_access_settings Can the user access settings.
202     */
203    private function can_access_settings() {
204        $connection = new Connection_Manager( 'jetpack' );
205        $status     = new Status();
206
207        // User must have the necessary permissions to see the Jetpack settings pages.
208        if ( ! current_user_can( 'edit_posts' ) ) {
209            return false;
210        }
211
212        // In offline mode, allow access to admins.
213        if ( $status->is_offline_mode() && current_user_can( 'manage_options' ) ) {
214            return true;
215        }
216
217        // If not in offline mode but site is not connected, bail.
218        if ( ! Jetpack::is_connection_ready() ) {
219            return false;
220        }
221
222        /*
223         * Additional checks for non-admins.
224        */
225        if ( ! current_user_can( 'manage_options' ) ) {
226            // If the site isn't connected at all, bail.
227            if ( ! $connection->has_connected_owner() ) {
228                return false;
229            }
230
231            /*
232             * If they haven't connected their own account yet,
233             * they have no use for the settings page.
234             * They will not be able to manage any settings.
235             */
236            if ( ! $connection->is_user_connected() ) {
237                return false;
238            }
239
240            /*
241             * Non-admins only have access to settings
242             * for the following modules:
243             * - Publicize
244             * - Post By Email
245             * If those modules are not available, bail.
246             */
247            if (
248                ! Jetpack::is_module_active( 'post-by-email' )
249                    && (
250                        ! Jetpack::is_module_active( 'publicize' ) ||
251                        ! current_user_can( 'publish_posts' )
252                    )
253            ) {
254                return false;
255            }
256        }
257
258        // fallback.
259        return true;
260    }
261
262    /**
263     * Add action to render page specific HTML.
264     *
265     * @return void
266     */
267    public function page_render() {
268        /** This action is already documented in class.jetpack-admin-page.php */
269        do_action( 'jetpack_notices' );
270
271        if ( $this->should_render_wp_build() ) {
272            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.
273            return;
274        }
275
276        // Fetch static.html.
277        $static_html = @file_get_contents( JETPACK__PLUGIN_DIR . '_inc/build/static.html' ); //phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents, Not fetching a remote file.
278
279        if ( false === $static_html ) {
280
281            // If we still have nothing, display an error.
282            echo '<p>';
283            esc_html_e( 'Error fetching static.html. Try running: ', 'jetpack' );
284            echo '<code>pnpm run distclean && pnpm jetpack build plugins/jetpack</code>';
285            echo '</p>';
286        } else {
287            // We got the static.html so let's display it.
288            echo $static_html; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
289        }
290    }
291
292    /**
293     * Load styles for static page.
294     */
295    public function additional_styles() {
296        // The route bundle carries these styles.
297        if ( $this->should_render_wp_build() ) {
298            return;
299        }
300
301        Jetpack_Admin_Page::load_wrapper_styles();
302    }
303
304    /**
305     * Load admin page scripts.
306     */
307    public function page_admin_scripts() {
308        if ( $this->is_redirecting ) {
309            return; // No need for scripts on a fallback page.
310        }
311
312        $status          = new Status();
313        $is_offline_mode = $status->is_offline_mode();
314        $site_suffix     = $status->get_site_suffix();
315
316        if ( $this->should_render_wp_build() ) {
317            // wp-build enqueues the route bundle; this handle carries the inline state and classic dependencies.
318            wp_register_script( 'react-plugin', false, $this->get_wp_build_script_dependencies(), JETPACK__VERSION, true );
319            wp_enqueue_script( 'react-plugin' );
320        } else {
321            $script_deps_path    = JETPACK__PLUGIN_DIR . '_inc/build/admin.asset.php';
322            $script_dependencies = array( 'jquery', 'wp-polyfill' );
323            $version             = JETPACK__VERSION;
324            if ( file_exists( $script_deps_path ) ) {
325                $asset_manifest      = include $script_deps_path;
326                $script_dependencies = $asset_manifest['dependencies'];
327                $version             = $asset_manifest['version'];
328            }
329
330            wp_enqueue_script(
331                'react-plugin',
332                plugins_url( '_inc/build/admin.js', JETPACK__PLUGIN_FILE ),
333                $script_dependencies,
334                $version,
335                true
336            );
337
338            wp_set_script_translations( 'react-plugin', 'jetpack' );
339        }
340
341        $blog_id_prop = '';
342        if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
343            $blog_id = Connection_Manager::get_site_id( true );
344            if ( $blog_id ) {
345                $blog_id_prop = ', currentBlogID: "' . (int) $blog_id . '"';
346            }
347        }
348
349        if ( ! $is_offline_mode && Jetpack::is_connection_ready() ) {
350            // Required for Analytics.
351            wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
352        }
353
354        // Add objects to be passed to the initial state of the app.
355        // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
356        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' );
357
358        // This will set the default URL of the jp_redirects lib.
359        wp_add_inline_script( 'react-plugin', 'var jetpack_redirects = { currentSiteRawUrl: "' . $site_suffix . '"' . $blog_id_prop . ' };', 'before' );
360
361        // Adds Connection package initial state.
362        Connection_Initial_State::render_script( 'react-plugin' );
363    }
364}