Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.74% covered (warning)
81.74%
94 / 115
64.29% covered (warning)
64.29%
9 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_React_Page
81.58% covered (warning)
81.58%
93 / 114
64.29% covered (warning)
64.29%
9 / 14
62.40
0.00% covered (danger)
0.00%
0 / 1
 get_page_hook
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 add_page_actions
64.29% covered (warning)
64.29%
9 / 14
0.00% covered (danger)
0.00%
0 / 1
7.64
 remove_jetpack_menu
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 get_legacy_route_redirects
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
7
 should_redirect_legacy_routes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 my_jetpack_shows_settings_notices
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 print_legacy_route_redirect
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 render_redirect_document
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 print_redirect_document
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 can_use_my_jetpack
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
6
 get_partner_coupon_redirect
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 jetpack_add_settings_sub_nav_item
n/a
0 / 0
n/a
0 / 0
1
 page_render
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 react_redirects
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 page_admin_scripts
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3use Automattic\Jetpack\Assets\Logo;
4use Automattic\Jetpack\Redirect;
5use Automattic\Jetpack\Status;
6
7require_once __DIR__ . '/class.jetpack-admin-page.php';
8
9/**
10 * Registers the Jetpack menu parent, whose page only redirects.
11 */
12class Jetpack_React_Page extends Jetpack_Admin_Page {
13    /**
14     * Register the menu parent before the site connects too.
15     *
16     * @var bool
17     */
18    protected $dont_show_if_not_active = false;
19
20    /**
21     * Legacy hashes the Settings page renders; they forward there with their hash.
22     *
23     * Mirrors `settingsRoutes` in `_inc/client/main.jsx`, plus the connection screens.
24     *
25     * @since 16.3
26     * @var string[]
27     */
28    const SETTINGS_ROUTES = array(
29        '/settings',
30        '/security',
31        '/performance',
32        '/writing',
33        '/sharing',
34        '/discussion',
35        '/earn',
36        '/reader',
37        '/traffic',
38        '/privacy',
39        '/setup',
40        '/connect-user',
41        '/connect-user-setup',
42    );
43
44    /**
45     * Forwards Settings hashes with their hash, maps known routes, and falls back for the rest.
46     *
47     * @var string
48     */
49    const LEGACY_ROUTE_REDIRECT_SCRIPT = <<<'JS'
50function ( settings, forward, routes, fallback ) {
51    var hash = window.location.hash;
52    var path = hash.replace( /^#\/?/, '/' ).split( '?' )[ 0 ] || '/';
53    var target = fallback;
54    if ( forward.indexOf( path ) !== -1 ) {
55        target = settings + hash;
56    } else if ( Object.prototype.hasOwnProperty.call( routes, path ) ) {
57        target = routes[ path ];
58    }
59    window.location.replace( target );
60}
61JS;
62
63    /**
64     * Add the main admin Jetpack menu.
65     *
66     * @return string|false Return value from WordPress's `add_menu_page()`.
67     */
68    public function get_page_hook() {
69        $logo = new Logo();
70        // Keep this fallback in sync with Jetpack_Network::add_network_admin_menu().
71        $icon = method_exists( $logo, 'get_base64_admin_menu_logo' ) ? $logo->get_base64_admin_menu_logo() : $logo->get_base64_logo();
72        return add_menu_page( 'Jetpack', 'Jetpack', 'jetpack_admin_page', 'jetpack', array( $this, 'render' ), $icon, 3 );
73    }
74
75    /**
76     * Add page action.
77     *
78     * @param string $hook Hook of current page.
79     * @return void
80     */
81    public function add_page_actions( $hook ) {
82        /** This action is documented in class.jetpack-admin.php */
83        do_action( 'jetpack_admin_menu', $hook );
84
85        if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
86            return;
87        }
88        $page = sanitize_text_field( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
89        if ( 'jetpack' !== $page ) {
90            if ( strpos( $page, 'jetpack/' ) === 0 ) {
91                $section = substr( $page, 8 );
92                wp_safe_redirect( admin_url( 'admin.php?page=jetpack#/' . $section ) );
93                exit( 0 );
94            }
95            return; // No need to handle the fallback redirection if we are not on the Jetpack page.
96        }
97
98        // After the action handlers and the connection controller, which exit when they act.
99        add_action( "load-$hook", array( $this, 'render_redirect_document' ), PHP_INT_MAX );
100
101        // If this is the first time the user is viewing the admin, don't show JITMs.
102        // This filter is added just in time because this function is called on admin_menu
103        // and JITMs are initialized on admin_init.
104        if ( Jetpack::is_connection_ready() && ! Jetpack_Options::get_option( 'first_admin_view', false ) ) {
105            Jetpack_Options::update_option( 'first_admin_view', true );
106            add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
107        }
108    }
109
110    /**
111     * Remove the main Jetpack submenu if a site is in offline mode or connected
112     * or if My Jetpack is available.
113     * At that point, admins can access the Jetpack Dashboard instead.
114     *
115     * @since 13.8
116     */
117    public function remove_jetpack_menu() {
118        $is_offline_mode = ( new Status() )->is_offline_mode();
119        $has_my_jetpack  = (
120            class_exists( 'Automattic\Jetpack\My_Jetpack\Initializer' ) &&
121            method_exists( 'Automattic\Jetpack\My_Jetpack\Initializer', 'should_initialize' ) &&
122            \Automattic\Jetpack\My_Jetpack\Initializer::should_initialize()
123        );
124
125        if ( $is_offline_mode || $has_my_jetpack || Jetpack::is_connection_ready() ) {
126            remove_submenu_page( 'jetpack', 'jetpack' );
127        }
128    }
129
130    /**
131     * Where links into page=jetpack land.
132     *
133     * Settings hashes keep their hash on the Settings page. Admins go to My Jetpack
134     * wherever it runs; everyone else lands on Settings, and so does a request with a
135     * pending error unless My Jetpack shows Settings' notices. While the partner coupon
136     * screen applies, every route goes there.
137     *
138     * @return array{settings: string, forward: string[], routes: array<string, string>, fallback: string}
139     */
140    public static function get_legacy_route_redirects() {
141        $settings_url  = admin_url( 'admin.php?page=jetpack-settings' );
142        $coupon_screen = self::get_partner_coupon_redirect();
143        if ( $coupon_screen ) {
144            return array(
145                'settings' => $settings_url,
146                'forward'  => array(),
147                'routes'   => array(),
148                'fallback' => $coupon_screen,
149            );
150        }
151
152        $table = array(
153            'settings' => $settings_url,
154            'forward'  => self::SETTINGS_ROUTES,
155            'routes'   => array(),
156            'fallback' => $settings_url,
157        );
158
159        if ( ! self::should_redirect_legacy_routes() ) {
160            if ( self::my_jetpack_shows_settings_notices() ) {
161                $table['fallback'] = admin_url( 'admin.php?page=my-jetpack' );
162            }
163            return $table;
164        }
165
166        $pricing_url     = Redirect::get_url( 'jetpack-plans' );
167        $table['routes'] = array(
168            '/plans'        => $pricing_url,
169            '/plans-prompt' => $pricing_url,
170            '/newsletter'   => admin_url( 'admin.php?page=jetpack-newsletter' ),
171        );
172
173        if ( self::can_use_my_jetpack() ) {
174            $my_jetpack = admin_url( 'admin.php?page=my-jetpack' );
175
176            foreach ( array( 'akismet', 'backup', 'scan', 'search', 'security', 'videopress' ) as $product ) {
177                $table['routes'][ '/product/' . $product ] = $my_jetpack . '#/add-' . $product;
178            }
179
180            $table['routes']['/license/activation'] = $my_jetpack . '#/add-license';
181
182            foreach ( array( '/reconnect', '/disconnect', '/woo-setup' ) as $route ) {
183                $table['routes'][ $route ] = $my_jetpack . '#/connection';
184            }
185
186            $table['fallback'] = $my_jetpack;
187        }
188
189        return $table;
190    }
191
192    /**
193     * Whether this request may follow the forwarder's routes; a pending error must land where its notice shows.
194     *
195     * @return bool
196     */
197    public static function should_redirect_legacy_routes() {
198        return ! Jetpack::state( 'error' );
199    }
200
201    /**
202     * Whether My Jetpack shows the notices Settings used to, this request's `Jetpack::state()` included.
203     *
204     * @return bool
205     */
206    private static function my_jetpack_shows_settings_notices() {
207        return self::can_use_my_jetpack()
208            && method_exists( 'Automattic\Jetpack\My_Jetpack\Initializer', 'shows_settings_notices' )
209            && \Automattic\Jetpack\My_Jetpack\Initializer::shows_settings_notices();
210    }
211
212    /**
213     * Print the legacy route redirect; it runs in the browser because the server never sees the hash.
214     */
215    public function print_legacy_route_redirect() {
216        $table = self::get_legacy_route_redirects();
217        $flags = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP;
218
219        wp_print_inline_script_tag(
220            sprintf(
221                '( %s )( %s, %s, %s, %s );',
222                self::LEGACY_ROUTE_REDIRECT_SCRIPT,
223                wp_json_encode( $table['settings'], $flags ),
224                wp_json_encode( $table['forward'], $flags ),
225                wp_json_encode( (object) $table['routes'], $flags ),
226                wp_json_encode( $table['fallback'], $flags )
227            )
228        );
229    }
230
231    /**
232     * Replace page=jetpack with the redirect document; nothing else renders here.
233     *
234     * @since 16.3
235     *
236     * @return never
237     */
238    public function render_redirect_document() {
239        $table = self::get_legacy_route_redirects();
240        if ( $table['settings'] === $table['fallback'] || self::my_jetpack_shows_settings_notices() ) {
241            // The landing page renders this request's notices, so its state must survive the hop.
242            Jetpack::restate();
243        }
244
245        $this->print_redirect_document();
246        exit( 0 );
247    }
248
249    /**
250     * Print a bare document that only redirects.
251     *
252     * @since 16.3
253     */
254    public function print_redirect_document() {
255        ?>
256<!DOCTYPE html>
257<html <?php language_attributes(); ?>>
258<head>
259<meta charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
260<title>Jetpack</title><?php // "Jetpack" is a product name, do not translate. ?>
261        <?php
262        if ( $this->is_rest_api_enabled() ) {
263            $this->print_legacy_route_redirect();
264            $this->add_noscript_head_meta();
265        } else {
266            $this->add_fallback_head_meta();
267        }
268        ?>
269</head>
270<body></body>
271</html>
272        <?php
273    }
274
275    /**
276     * Whether My Jetpack can take over for the current user.
277     *
278     * @return bool
279     */
280    private static function can_use_my_jetpack() {
281        return current_user_can( 'manage_options' )
282            && class_exists( 'Automattic\Jetpack\My_Jetpack\Initializer' )
283            && method_exists( 'Automattic\Jetpack\My_Jetpack\Initializer', 'should_initialize' )
284            && \Automattic\Jetpack\My_Jetpack\Initializer::should_initialize()
285            && ( ! method_exists( 'Automattic\Jetpack\My_Jetpack\Initializer', 'current_user_can_access_page' )
286                || \Automattic\Jetpack\My_Jetpack\Initializer::current_user_can_access_page() );
287    }
288
289    /**
290     * The My Jetpack coupon screen, while it should replace this page.
291     *
292     * An older My Jetpack bounces showCouponRedemption back here, so only forward to one that renders it.
293     *
294     * @return string|null
295     */
296    private static function get_partner_coupon_redirect() {
297        if (
298            ! class_exists( 'Automattic\Jetpack\My_Jetpack\Initializer' )
299            || ! method_exists( 'Automattic\Jetpack\My_Jetpack\Initializer', 'get_partner_coupon_screen' )
300            || null === \Automattic\Jetpack\My_Jetpack\Initializer::get_partner_coupon_screen()
301        ) {
302            return null;
303        }
304
305        return admin_url( 'admin.php?page=my-jetpack&showCouponRedemption=1' );
306    }
307
308    /**
309     * Formerly added the Settings sub-link.
310     *
311     * @since 4.3.0
312     * @deprecated 16.3 Jetpack_Settings_React_Page registers the Settings page.
313     */
314    public function jetpack_add_settings_sub_nav_item() {
315        _deprecated_function( __METHOD__, 'jetpack-16.3' );
316    }
317
318    /**
319     * Nothing renders here: render_redirect_document() exits on load.
320     *
321     * @return void
322     */
323    public function page_render() {}
324    /**
325     * Allow robust deep links to React.
326     *
327     * The Jetpack dashboard requires fragments/hash values to make
328     * a deep link to it but passing fragments as part of a return URL
329     * will most often be discarded throughout the process.
330     * This logic aims to bridge this gap and reduce the chance of React
331     * specific links being broken while passing them along.
332     */
333    public function react_redirects() {
334        global $pagenow;
335
336        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
337        if ( 'admin.php' !== $pagenow || ! isset( $_GET['jp-react-redirect'] ) ) {
338            return;
339        }
340
341        $allowed_paths = array(
342            'product-purchased' => admin_url( 'admin.php?page=jetpack' ),
343        );
344
345        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
346        $target = sanitize_text_field( wp_unslash( $_GET['jp-react-redirect'] ) );
347        if ( isset( $allowed_paths[ $target ] ) ) {
348            wp_safe_redirect( $allowed_paths[ $target ] );
349            exit( 0 );
350        }
351    }
352
353    /**
354     * Nothing loads here: render_redirect_document() exits on load.
355     */
356    public function page_admin_scripts() {}
357}