Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.16% covered (success)
94.16%
129 / 137
71.43% covered (warning)
71.43%
15 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin_Page
94.16% covered (success)
94.16%
129 / 137
71.43% covered (warning)
71.43%
15 / 21
48.46
0.00% covered (danger)
0.00%
0 / 1
 wp_build_index_path
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_menu_item
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 maybe_load_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 register_page_data
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 add_admin_shell_member
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
4
 load_as_admin_shell_guest
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_tracks_transport
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 can_use_analytics
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_tracks_context
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
7
 enqueue_runtime_config
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 load_wp_build_with_screen_alias
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
2.06
 load_wp_build
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 alias_screen_id_for_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 restore_screen_id_after_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 opt_out_of_jitms
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 hide_jitms_on_wp_build_dashboard
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 inject_script_data
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
3.00
 inject_tracks_context
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 render_fallback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_seo_admin_request
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
1<?php
2/**
3 * The Jetpack SEO wp-admin page shell.
4 *
5 * Registers the `admin.php?page=jetpack-seo` screen via Admin_Menu so it is
6 * reachable on self-hosted, Atomic/WoA, and Simple sites alike, loads the
7 * `@wordpress/build` (wp-build) dashboard bundle that renders it, and
8 * bootstraps the React app's initial state onto the page.
9 *
10 * @package automattic/jetpack-seo-package
11 */
12
13namespace Automattic\Jetpack\SEO;
14
15use Automattic\Jetpack\Admin_UI\Admin_Menu;
16use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17use Automattic\Jetpack\Constants;
18use Automattic\Jetpack\Modules;
19use Automattic\Jetpack\Status;
20use Automattic\Jetpack\Status\Host;
21use Automattic\Jetpack\Terms_Of_Service;
22use Automattic\Jetpack\Tracking;
23use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
24use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
25
26/**
27 * Registers the SEO admin menu and loads the wp-build dashboard bundle.
28 */
29class Admin_Page {
30
31    /**
32     * URL-facing menu slug (`admin.php?page=jetpack-seo`).
33     */
34    const MENU_SLUG = 'jetpack-seo';
35
36    /**
37     * Slug emitted by `@wordpress/build` (`wpPlugin.pages[0]`). wp-build's
38     * auto-generated enqueue callback only fires when `$screen->id` matches
39     * this value, so we alias the screen id to it around that check without
40     * changing the user-facing URL.
41     */
42    const WP_BUILD_SLUG = 'jetpack-seo-dashboard';
43
44    /**
45     * Render function generated by `@wordpress/build` into
46     * `build/pages/jetpack-seo-dashboard/page-wp-admin.php`. Naming convention:
47     * `{wpPlugin.name}_{page-with-underscores}_wp_admin_render_page`.
48     */
49    const WP_BUILD_RENDER_FN = 'jetpack_seo_jetpack_seo_dashboard_wp_admin_render_page';
50
51    /**
52     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
53     *
54     * @var string|null
55     */
56    private static $wp_build_original_screen_id = null;
57
58    /**
59     * The dashboard screen hide_jitms_on_wp_build_dashboard() opts out of JITMs.
60     *
61     * @var string|null
62     */
63    private static $jitm_opt_out_screen_id = null;
64
65    /**
66     * Overrides the generated entry point path. Test seam, null in production.
67     *
68     * @var string|null
69     */
70    private static $wp_build_index = null;
71
72    /**
73     * Absolute path to the entry point generated by the WP build script.
74     *
75     * @return string
76     */
77    private static function wp_build_index_path() {
78        return self::$wp_build_index ?? dirname( __DIR__ ) . '/build/build.php';
79    }
80
81    /**
82     * The SEO page's wp-admin URL.
83     *
84     * @return string
85     */
86    public static function get_url() {
87        return admin_url( 'admin.php?page=' . self::MENU_SLUG );
88    }
89
90    /**
91     * Register the admin menu item.
92     *
93     * Uses Admin_Menu so the page is reachable on wp-admin across all site
94     * types. The render callback is wp-build's generated render function when
95     * the bundle is loaded (i.e. on the SEO page itself, after
96     * `maybe_load_wp_build()` ran at priority 1); otherwise it falls back to a
97     * bare mount node so the page never fatals on an unbuilt checkout.
98     *
99     * @return void
100     */
101    public static function add_menu_item() {
102        $callback = function_exists( self::WP_BUILD_RENDER_FN )
103            ? self::WP_BUILD_RENDER_FN
104            : array( __CLASS__, 'render_fallback' );
105
106        $page_suffix = Admin_Menu::add_menu(
107            'SEO',
108            'SEO',
109            'manage_options',
110            self::MENU_SLUG,
111            $callback,
112            null,
113            // Hidden while seo-tools is off, like other Jetpack modules; My Jetpack turns it back on.
114            array(
115                'module' => 'seo-tools',
116                'key'    => 'jetpack-seo',
117            )
118        );
119
120        if ( $page_suffix ) {
121            self::opt_out_of_jitms( $page_suffix );
122        }
123    }
124
125    /**
126     * On the SEO admin page, load the wp-build bundle, alias the screen id so
127     * wp-build enqueues its assets, and bootstrap the app's initial state.
128     *
129     * Hooked at `admin_menu` priority 1 so polyfills register and the render
130     * function is defined before `add_menu_item()` runs at priority 10.
131     *
132     * @return void
133     */
134    public static function maybe_load_wp_build() {
135        if ( ! self::is_seo_admin_request() ) {
136            return;
137        }
138
139        wp_enqueue_media();
140        self::load_wp_build_with_screen_alias();
141        self::register_page_data();
142    }
143
144    /**
145     * Hook the app's initial state and, when the site allows tracking, its Tracks transport and context.
146     *
147     * @since 0.12.0
148     *
149     * @return void
150     */
151    public static function register_page_data() {
152        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_script_data' ) );
153        self::enqueue_runtime_config();
154
155        // Without the context the client records nothing, so another script's Tracks transport can't send our events.
156        if ( self::can_use_analytics() ) {
157            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_tracks_transport' ) );
158            add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_tracks_context' ) );
159        }
160    }
161
162    /**
163     * Register SEO with the admin shell, which switches between Jetpack dashboards without a page load.
164     *
165     * Only hooked once Initializer::init() has passed the checks that register the page itself.
166     *
167     * @since 0.12.0
168     *
169     * @param array $members Shell members keyed by admin page slug.
170     * @return array
171     */
172    public static function add_admin_shell_member( $members ) {
173        if ( ( new Host() )->is_wpcom_simple() || ! file_exists( self::wp_build_index_path() ) ) {
174            return $members;
175        }
176
177        // The menu item hides while seo-tools is off, so there is no link to switch to.
178        if ( ! ( new Modules() )->is_active( 'seo-tools' ) ) {
179            return $members;
180        }
181
182        $members[ self::MENU_SLUG ] = array(
183            'build_prefix' => 'jetpack_seo',
184            'build_page'   => self::WP_BUILD_SLUG,
185            'title'        => 'SEO',
186            'header'       => array(
187                'title'    => 'SEO',
188                'subtitle' => __( 'Make your site discoverable in search and social, and control AI access.', 'jetpack-seo' ),
189            ),
190            'capability'   => 'manage_options',
191            'handles'      => array( 'jetpack-script-data', 'jetpack-seo-config', 'jp-tracks', 'wp-jp-i18n-loader' ),
192            'load'         => array( __CLASS__, 'load_as_admin_shell_guest' ),
193        );
194        return $members;
195    }
196
197    /**
198     * Ready the SEO routes and page data while another dashboard's page is open, without the screen ID alias.
199     *
200     * @since 0.12.0
201     *
202     * @return void
203     */
204    public static function load_as_admin_shell_guest() {
205        self::load_wp_build();
206        // The shell runs this hook only when it prints SEO's assets, so other pages skip the tracking check.
207        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'register_page_data' ), 0 );
208    }
209
210    /**
211     * Load the Tracks transport, without which `recordSeoEvent()` only queues into `window._tkq`.
212     *
213     * Skipped on Simple, where stats.php already prints w.js; a second copy re-sends the queue.
214     *
215     * @return void
216     */
217    public static function enqueue_tracks_transport() {
218        if ( ( new Host() )->is_wpcom_simple() ) {
219            return;
220        }
221
222        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
223    }
224
225    /**
226     * Whether the site has opted into Tracks, as `Jetpack::initialize_tracking()` checks.
227     *
228     * WordPress.com's own terms cover Simple and Atomic, which `should_enable_tracking()` misreads.
229     *
230     * @return bool
231     */
232    public static function can_use_analytics() {
233        if ( ( new Host() )->is_wpcom_platform() ) {
234            return true;
235        }
236
237        $tracking = new Tracking( 'jetpack', new Connection_Manager() );
238
239        return $tracking->should_enable_tracking( new Terms_Of_Service(), new Status() );
240    }
241
242    /**
243     * Identifiers the client attaches to every SEO Tracks event.
244     *
245     * `blog_id` is the WordPress.com id, or 0 before connecting, so a local id never collides with one.
246     *
247     * @return array{blog_id:int, site_type:string, is_a11n:bool, is_test:bool, product_version:string}
248     */
249    public static function get_tracks_context() {
250        $host = new Host();
251        if ( $host->is_wpcom_simple() ) {
252            $site_type = 'simple';
253        } elseif ( $host->is_woa_site() ) {
254            $site_type = 'atomic';
255        } else {
256            $site_type = 'jetpack';
257        }
258
259        $blog_id = (int) $host->get_wpcom_site_id();
260
261        // `is_automattician()` exists on Simple only; on Atomic, the a8c proxy is what identifies us.
262        $is_a11n = ( function_exists( 'is_automattician' ) && (bool) is_automattician() )
263            || Constants::is_true( 'AT_PROXIED_REQUEST' );
264
265        // `Status::is_staging_site()` would cover this, but it is deprecated.
266        $is_test = (bool) get_option( 'wpcom_is_staging_site' )
267            || 'production' !== wp_get_environment_type()
268            || ( new Status() )->is_local_site();
269
270        return array(
271            'blog_id'         => $blog_id,
272            'site_type'       => $site_type,
273            'is_a11n'         => $is_a11n,
274            'is_test'         => $is_test,
275            'product_version' => Initializer::PACKAGE_VERSION,
276        );
277    }
278
279    /**
280     * Supply the consumer identity used by wp-build's shared AdminPage dependencies.
281     *
282     * @return void
283     */
284    private static function enqueue_runtime_config() {
285        wp_register_script( 'jetpack-seo-config', false, array(), Initializer::PACKAGE_VERSION, true );
286        wp_enqueue_script( 'jetpack-seo-config' );
287        $config = wp_json_encode( array( 'consumer_slug' => 'jetpack-seo' ), JSON_HEX_TAG | JSON_HEX_AMP );
288        wp_add_inline_script( 'jetpack-seo-config', 'window.jetpackConfig = Object.assign(' . $config . ', window.jetpackConfig || {});', 'before' );
289    }
290
291    /**
292     * Load wp-build with the screen ID aliased across its generated enqueue check.
293     *
294     * @see WP_Build_Screen_Id::load_with_alias()
295     * @return void
296     */
297    private static function load_wp_build_with_screen_alias() {
298        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
299        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
300            WP_Build_Screen_Id::load_with_alias(
301                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
302                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
303                function () {
304                    self::load_wp_build();
305                }
306            );
307            return;
308        }
309
310        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
311        self::load_wp_build();
312        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
313    }
314
315    /**
316     * Load wp-build's generated registration file and register the polyfills
317     * the bundle depends on. No-op on a fresh checkout before `pnpm build`, in
318     * which case `add_menu_item()` falls back to {@see self::render_fallback()}.
319     *
320     * @return void
321     */
322    private static function load_wp_build() {
323        $build_index = self::wp_build_index_path();
324
325        if ( ! file_exists( $build_index ) ) {
326            return;
327        }
328
329        require_once $build_index;
330
331        WP_Build_Polyfills::register(
332            'jetpack-seo',
333            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
334        );
335    }
336
337    /**
338     * Alias the current screen id to wp-build's expected slug so its
339     * auto-generated enqueue callback fires for our user-facing page.
340     *
341     * @since 0.9.5 Takes no argument; hooked on `admin_enqueue_scripts`.
342     *
343     * @return void
344     */
345    public static function alias_screen_id_for_wp_build() {
346        $screen = get_current_screen();
347        if ( ! $screen ) {
348            return;
349        }
350
351        self::$wp_build_original_screen_id = $screen->id;
352        $screen->id                        = self::WP_BUILD_SLUG;
353    }
354
355    /**
356     * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
357     *
358     * @since 0.9.5
359     *
360     * @return void
361     */
362    public static function restore_screen_id_after_wp_build() {
363        $screen = get_current_screen();
364        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
365            return;
366        }
367
368        $screen->id                        = self::$wp_build_original_screen_id;
369        self::$wp_build_original_screen_id = null;
370    }
371
372    /**
373     * Opt the dashboard's screen out of JITMs.
374     *
375     * @param string $screen_id The hook suffix the page was registered under, which is its screen ID.
376     * @return void
377     */
378    private static function opt_out_of_jitms( $screen_id ) {
379        self::$jitm_opt_out_screen_id = $screen_id;
380        add_filter( 'jetpack_display_jitms_on_screen', array( __CLASS__, 'hide_jitms_on_wp_build_dashboard' ), 10, 2 );
381    }
382
383    /**
384     * Keep JITMs off the wp-build dashboard, which has no `#jp-admin-notices` to show them in.
385     *
386     * Fetching a JITM records a view, so one the page hides would still be counted.
387     *
388     * @since 0.9.5
389     *
390     * @param bool   $show      Whether to show JITMs on the screen.
391     * @param string $screen_id The screen ID.
392     * @return bool
393     */
394    public static function hide_jitms_on_wp_build_dashboard( $show, $screen_id ) {
395        if ( null !== self::$jitm_opt_out_screen_id && self::$jitm_opt_out_screen_id === $screen_id ) {
396            return false;
397        }
398
399        return $show;
400    }
401
402    /**
403     * Bootstrap the React app's initial state onto `window.JetpackScriptData.seo`.
404     *
405     * Because wp-build pages load as ES modules, `wp_localize_script` can't
406     * attach data to them; the shared `jetpack_admin_js_script_data` filter
407     * (printed by the Script_Data package onto the `jetpack-script-data` handle
408     * the bundle already depends on) is the supported channel. The per-tab state
409     * is provided as an apiFetch *preload* (mirrors Podcast) so the app resolves
410     * it with no request on a normal load yet can re-fetch when the preload is
411     * missing or stale, rather than dead-ending on a one-shot read.
412     *
413     * @param array $data Script data being injected onto the page.
414     * @return array
415     */
416    public static function inject_script_data( $data ) {
417        if ( ! is_array( $data ) ) {
418            $data = array();
419        }
420
421        // Preload the dashboard's REST reads into the page so the app resolves them from
422        // cache on first paint with no network request — while still being able to
423        // re-fetch if that preload is ever missing or stale. This replaces injecting the
424        // raw payloads, which the app read synchronously once and couldn't recover from
425        // when momentarily absent (the load-error dead-end). See Dashboard_Data::register_rest_reads()
426        // and the client readers `_inc/data/get-preloaded.ts` + `_inc/data/use-ensure-tab-data.ts`.
427        $data[ Initializer::SCRIPT_DATA_KEY ]['preload'] = array_reduce(
428            Dashboard_Data::rest_read_paths(),
429            'rest_preload_api_request',
430            array()
431        );
432
433        // Small synchronous reads used outside the per-tab data stores, and not part of
434        // the load-error path.
435        $data[ Initializer::SCRIPT_DATA_KEY ]['google_verify'] = Dashboard_Data::get_google_verify_data();
436        $data[ Initializer::SCRIPT_DATA_KEY ]['site']          = Dashboard_Data::get_site_data();
437        $data[ Initializer::SCRIPT_DATA_KEY ]['output']        = Dashboard_Data::get_output_data();
438
439        // Plan-gating signal for below-Premium WordPress.com sites: when gated, the
440        // dashboard reduces to a free subset and surfaces the upsell banner. Self-hosted
441        // is never gated (see Initializer::is_gated()). The upsell URL is only meaningful
442        // when gated, so it's built only then — every ungated and self-hosted admin load
443        // otherwise pays for a site-suffix lookup it never uses.
444        $is_gated                                       = Initializer::is_gated();
445        $data[ Initializer::SCRIPT_DATA_KEY ]['gating'] = array(
446            'is_gated'   => $is_gated,
447            'upsell_url' => $is_gated ? Initializer::get_upsell_url() : '',
448        );
449
450        return $data;
451    }
452
453    /**
454     * Add the Tracks context to the SEO script data.
455     *
456     * @param array $data Script data being injected onto the page.
457     * @return array
458     */
459    public static function inject_tracks_context( $data ) {
460        if ( ! is_array( $data ) ) {
461            $data = array();
462        }
463
464        $data[ Initializer::SCRIPT_DATA_KEY ]['tracks'] = self::get_tracks_context();
465
466        return $data;
467    }
468
469    /**
470     * Fallback render used when the wp-build artifact is missing (unbuilt
471     * checkout). Renders a bare wrapper so the page loads without the app.
472     *
473     * @return void
474     */
475    public static function render_fallback() {
476        echo '<div class="wrap"><h1>SEO</h1></div>';
477    }
478
479    /**
480     * Whether the current request targets the SEO admin page.
481     *
482     * @return bool
483     */
484    private static function is_seo_admin_request() {
485        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
486        if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
487            return false;
488        }
489
490        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
491        return self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
492    }
493}