Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
16.67% covered (danger)
16.67%
18 / 108
9.09% covered (danger)
9.09%
1 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_React_Page
15.09% covered (danger)
15.09%
16 / 106
9.09% covered (danger)
9.09%
1 / 11
1228.99
0.00% covered (danger)
0.00%
0 / 1
 get_page_hook
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 add_page_actions
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
56
 remove_jetpack_menu
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 can_access_settings
38.89% covered (danger)
38.89%
7 / 18
0.00% covered (danger)
0.00%
0 / 1
38.62
 jetpack_add_settings_sub_nav_item
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 add_fallback_head_meta
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add_noscript_head_meta
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 page_render
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 react_redirects
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 additional_styles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 page_admin_scripts
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
72
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3use Automattic\Jetpack\Admin_UI\Admin_Menu;
4use Automattic\Jetpack\Assets\Logo;
5use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
6use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7use Automattic\Jetpack\Status;
8
9require_once __DIR__ . '/class.jetpack-admin-page.php';
10require_once __DIR__ . '/class-jetpack-redux-state-helper.php';
11
12/**
13 * Builds the landing page and its menu.
14 */
15class Jetpack_React_Page extends Jetpack_Admin_Page {
16    /**
17     * Show the landing page only when Jetpack is connected.
18     *
19     * @var bool
20     */
21    protected $dont_show_if_not_active = false;
22
23    /**
24     * Used for fallback when REST API is disabled.
25     *
26     * @var bool
27     */
28    protected $is_redirecting = false;
29
30    /**
31     * Add the main admin Jetpack menu.
32     *
33     * @return string|false Return value from WordPress's `add_menu_page()`.
34     */
35    public function get_page_hook() {
36        $icon = ( new Logo() )->get_base64_admin_menu_logo();
37        return add_menu_page( 'Jetpack', 'Jetpack', 'jetpack_admin_page', 'jetpack', array( $this, 'render' ), $icon, 3 );
38    }
39
40    /**
41     * Add page action.
42     *
43     * @param string $hook Hook of current page.
44     * @return void
45     */
46    public function add_page_actions( $hook ) {
47        /** This action is documented in class.jetpack-admin.php */
48        do_action( 'jetpack_admin_menu', $hook );
49
50        if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
51            return;
52        }
53        $page = sanitize_text_field( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
54        if ( 'jetpack' !== $page ) {
55            if ( strpos( $page, 'jetpack/' ) === 0 ) {
56                $section = substr( $page, 8 );
57                wp_safe_redirect( admin_url( 'admin.php?page=jetpack#/' . $section ) );
58                exit( 0 );
59            }
60            return; // No need to handle the fallback redirection if we are not on the Jetpack page.
61        }
62
63        // Adding a redirect meta tag if the REST API is disabled.
64        if ( ! $this->is_rest_api_enabled() ) {
65            $this->is_redirecting = true;
66            add_action( 'admin_head', array( $this, 'add_fallback_head_meta' ) );
67        }
68
69        // Adding a redirect meta tag wrapped in noscript tags for all browsers in case they have JavaScript disabled.
70        add_action( 'admin_head', array( $this, 'add_noscript_head_meta' ) );
71
72        // If this is the first time the user is viewing the admin, don't show JITMs.
73        // This filter is added just in time because this function is called on admin_menu
74        // and JITMs are initialized on admin_init.
75        if ( Jetpack::is_connection_ready() && ! Jetpack_Options::get_option( 'first_admin_view', false ) ) {
76            Jetpack_Options::update_option( 'first_admin_view', true );
77            add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
78        }
79    }
80
81    /**
82     * Remove the main Jetpack submenu if a site is in offline mode or connected
83     * or if My Jetpack is available.
84     * At that point, admins can access the Jetpack Dashboard instead.
85     *
86     * @since 13.8
87     */
88    public function remove_jetpack_menu() {
89        $is_offline_mode = ( new Status() )->is_offline_mode();
90        $has_my_jetpack  = (
91            class_exists( 'Automattic\Jetpack\My_Jetpack\Initializer' ) &&
92            method_exists( 'Automattic\Jetpack\My_Jetpack\Initializer', 'should_initialize' ) &&
93            \Automattic\Jetpack\My_Jetpack\Initializer::should_initialize()
94        );
95
96        if ( $is_offline_mode || $has_my_jetpack || Jetpack::is_connection_ready() ) {
97            remove_submenu_page( 'jetpack', 'jetpack' );
98        }
99    }
100
101    /**
102     * Determine whether a user can access the Jetpack Settings page.
103     *
104     * Rules are:
105     * - user is allowed to see the Jetpack Admin
106     * - site is connected or in offline mode
107     * - non-admins only need access to the settings when there are modules they can manage.
108     *
109     * @return bool $can_access_settings Can the user access settings.
110     */
111    private function can_access_settings() {
112        $connection = new Connection_Manager( 'jetpack' );
113        $status     = new Status();
114
115        // User must have the necessary permissions to see the Jetpack settings pages.
116        if ( ! current_user_can( 'edit_posts' ) ) {
117            return false;
118        }
119
120        // In offline mode, allow access to admins.
121        if ( $status->is_offline_mode() && current_user_can( 'manage_options' ) ) {
122            return true;
123        }
124
125        // If not in offline mode but site is not connected, bail.
126        if ( ! Jetpack::is_connection_ready() ) {
127            return false;
128        }
129
130        /*
131         * Additional checks for non-admins.
132        */
133        if ( ! current_user_can( 'manage_options' ) ) {
134            // If the site isn't connected at all, bail.
135            if ( ! $connection->has_connected_owner() ) {
136                return false;
137            }
138
139            /*
140             * If they haven't connected their own account yet,
141             * they have no use for the settings page.
142             * They will not be able to manage any settings.
143             */
144            if ( ! $connection->is_user_connected() ) {
145                return false;
146            }
147
148            /*
149             * Non-admins only have access to settings
150             * for the following modules:
151             * - Publicize
152             * - Post By Email
153             * If those modules are not available, bail.
154             */
155            if (
156                ! Jetpack::is_module_active( 'post-by-email' )
157                    && (
158                        ! Jetpack::is_module_active( 'publicize' ) ||
159                        ! current_user_can( 'publish_posts' )
160                    )
161            ) {
162                return false;
163            }
164        }
165
166        // fallback.
167        return true;
168    }
169
170    /**
171     * Jetpack Settings sub-link.
172     *
173     * Shares the bottom tier with Beta Tester so it lands below the alphabetical run
174     * rather than inside it; the two sort by title within the tier. The upsell still
175     * renders underneath — Admin_Menu appends that one after sorting, so it never
176     * competes on position.
177     *
178     * @since 4.3.0
179     * @since 9.7.0 If Connection does not have an owner, restrict it to admins
180     */
181    public function jetpack_add_settings_sub_nav_item() {
182        if ( $this->can_access_settings() ) {
183            Admin_Menu::add_menu(
184                __( 'Settings', 'jetpack' ),
185                __( 'Settings', 'jetpack' ),
186                'jetpack_admin_page',
187                Jetpack::admin_url( array( 'page' => 'jetpack#/settings' ) ),
188                null,
189                998
190            );
191        }
192    }
193
194    /**
195     * Fallback redirect meta tag if the REST API is disabled.
196     *
197     * @return void
198     */
199    public function add_fallback_head_meta() {
200        echo '<meta http-equiv="refresh" content="0; url=?page=jetpack_modules">';
201    }
202
203    /**
204     * Fallback meta tag wrapped in noscript tags for all browsers in case they have JavaScript disabled.
205     *
206     * @return void
207     */
208    public function add_noscript_head_meta() {
209        echo '<noscript>';
210        $this->add_fallback_head_meta();
211        echo '</noscript>';
212    }
213
214    /**
215     * Add action to render page specific HTML.
216     *
217     * @return void
218     */
219    public function page_render() {
220        /** This action is already documented in class.jetpack-admin-page.php */
221        do_action( 'jetpack_notices' );
222
223        // Fetch static.html.
224        $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.
225
226        if ( false === $static_html ) {
227
228            // If we still have nothing, display an error.
229            echo '<p>';
230            esc_html_e( 'Error fetching static.html. Try running: ', 'jetpack' );
231            echo '<code>pnpm run distclean && pnpm jetpack build plugins/jetpack</code>';
232            echo '</p>';
233        } else {
234            // We got the static.html so let's display it.
235            echo $static_html; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
236        }
237    }
238    /**
239     * Allow robust deep links to React.
240     *
241     * The Jetpack dashboard requires fragments/hash values to make
242     * a deep link to it but passing fragments as part of a return URL
243     * will most often be discarded throughout the process.
244     * This logic aims to bridge this gap and reduce the chance of React
245     * specific links being broken while passing them along.
246     */
247    public function react_redirects() {
248        global $pagenow;
249
250        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
251        if ( 'admin.php' !== $pagenow || ! isset( $_GET['jp-react-redirect'] ) ) {
252            return;
253        }
254
255        $allowed_paths = array(
256            'product-purchased' => admin_url( '/admin.php?page=jetpack#/recommendations/product-purchased' ),
257        );
258
259        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
260        $target = sanitize_text_field( wp_unslash( $_GET['jp-react-redirect'] ) );
261        if ( isset( $allowed_paths[ $target ] ) ) {
262            wp_safe_redirect( $allowed_paths[ $target ] );
263            exit( 0 );
264        }
265    }
266
267    /**
268     * Load styles for static page.
269     */
270    public function additional_styles() {
271        Jetpack_Admin_Page::load_wrapper_styles();
272    }
273
274    /**
275     * Load admin page scripts.
276     */
277    public function page_admin_scripts() {
278        if ( $this->is_redirecting ) {
279            return; // No need for scripts on a fallback page.
280        }
281
282        $status              = new Status();
283        $is_offline_mode     = $status->is_offline_mode();
284        $site_suffix         = $status->get_site_suffix();
285        $script_deps_path    = JETPACK__PLUGIN_DIR . '_inc/build/admin.asset.php';
286        $script_dependencies = array( 'jquery', 'wp-polyfill' );
287        $version             = JETPACK__VERSION;
288        if ( file_exists( $script_deps_path ) ) {
289            $asset_manifest      = include $script_deps_path;
290            $script_dependencies = $asset_manifest['dependencies'];
291            $version             = $asset_manifest['version'];
292        }
293
294        $blog_id_prop = '';
295        if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
296            $blog_id = Connection_Manager::get_site_id( true );
297            if ( $blog_id ) {
298                $blog_id_prop = ', currentBlogID: "' . (int) $blog_id . '"';
299            }
300        }
301
302        wp_enqueue_script(
303            'react-plugin',
304            plugins_url( '_inc/build/admin.js', JETPACK__PLUGIN_FILE ),
305            $script_dependencies,
306            $version,
307            true
308        );
309
310        if ( ! $is_offline_mode && Jetpack::is_connection_ready() ) {
311            // Required for Analytics.
312            wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
313        }
314
315        wp_set_script_translations( 'react-plugin', 'jetpack' );
316
317        // Add objects to be passed to the initial state of the app.
318        // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
319        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' );
320
321        // This will set the default URL of the jp_redirects lib.
322        wp_add_inline_script( 'react-plugin', 'var jetpack_redirects = { currentSiteRawUrl: "' . $site_suffix . '"' . $blog_id_prop . ' };', 'before' );
323
324        // Adds Connection package initial state.
325        Connection_Initial_State::render_script( 'react-plugin' );
326    }
327}