Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
71.54% covered (warning)
71.54%
88 / 123
54.55% covered (warning)
54.55%
12 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_WP_Build_Page
72.13% covered (warning)
72.13%
88 / 122
54.55% covered (warning)
54.55%
12 / 22
137.92
0.00% covered (danger)
0.00%
0 / 1
 get_page_title
n/a
0 / 0
n/a
0 / 0
0
 get_menu_title
n/a
0 / 0
n/a
0 / 0
0
 get_initial_state
n/a
0 / 0
n/a
0 / 0
0
 should_register
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
5.02
 build_dir
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_build
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_routes
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
6.07
 get_render_callback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_page_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_page_request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 register_page
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
4.00
 owns_page
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_screen_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 slug_is_claimed
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 load_wp_build
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 alias_screen_id
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 restore_screen_id
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 enqueue_page_data
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
7.03
 get_initial_state_script
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 get_translations_script
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
2.50
 add_admin_shell_member
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
5
 load_as_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 get_admin_shell_guest_data
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
1<?php
2/**
3 * Shared plumbing for mu-wpcom's wp-build admin pages.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8// @phan-file-suppress PhanAbstractStaticMethodCallInStatic -- static:: dispatches to the concrete page; the base is never booted itself.
9
10namespace Automattic\Jetpack\Jetpack_Mu_Wpcom;
11
12use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
13use Automattic\Jetpack\Status\Host;
14use Automattic\Jetpack\Tracking;
15use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
16
17require_once __DIR__ . '/wp-build-script-translations.php';
18
19/**
20 * Serves a wp-build page under a wp-admin menu slug of the subclass's choosing.
21 *
22 * Subclasses are static and boot with `add_action( 'init', array( Subclass::class, 'init' ) )`.
23 */
24abstract class WPCOM_WP_Build_Page {
25
26    /**
27     * Admin page slug, which stays in the page URL.
28     */
29    const MENU_SLUG = '';
30
31    /**
32     * Page name for wp-build, as declared in the page's routes/<route>/package.json.
33     *
34     * Must differ from the menu slug, or wp-build's generated standalone page takes the slug over.
35     */
36    const WP_BUILD_PAGE = '';
37
38    /**
39     * Menu the page sits under.
40     */
41    const PARENT_SLUG = 'jetpack';
42
43    /**
44     * Capability for the page, and for receiving its initial state.
45     */
46    const CAPABILITY = 'manage_options';
47
48    /**
49     * `admin_menu` priority for register_page().
50     *
51     * After Jetpack's Admin_Menu (1000), so a slug it claimed is visible, and before
52     * wpcom_add_jetpack_submenu() (999999), which reads whether the slug is claimed.
53     */
54    const REGISTER_PRIORITY = 999998;
55
56    /**
57     * Global the page's boot script reads get_initial_state() from.
58     */
59    const INITIAL_STATE_VAR = '';
60
61    /**
62     * Whether the page loads WordPress.com Tracks.
63     */
64    const ENQUEUE_TRACKS = false;
65
66    /**
67     * Whether the admin shell builds the admin menu before reading the page's data on its guest endpoint,
68     * which runs on admin-ajax and so has no menu otherwise.
69     */
70    const ADMIN_SHELL_NEEDS_MENU = false;
71
72    /**
73     * Whether each page registered its slug on this request, keyed by class.
74     *
75     * @var bool[]
76     */
77    private static $owns_page = array();
78
79    /**
80     * The screen ID displaced by alias_screen_id(), keyed by class.
81     *
82     * @var string[]
83     */
84    private static $displaced_screen_id = array();
85
86    /**
87     * The hook suffix add_submenu_page() returned, which is the page's screen ID, keyed by class.
88     *
89     * @var string[]
90     */
91    private static $screen_id = array();
92
93    /**
94     * The page title.
95     *
96     * @return string
97     */
98    abstract public static function get_page_title();
99
100    /**
101     * The menu entry's label.
102     *
103     * @return string
104     */
105    abstract public static function get_menu_title();
106
107    /**
108     * The state the page's boot script reads from INITIAL_STATE_VAR.
109     *
110     * @return array
111     */
112    abstract public static function get_initial_state();
113
114    /**
115     * Whether this page should claim its slug on this site.
116     *
117     * @return bool
118     */
119    public static function should_register() {
120        return true;
121    }
122
123    /**
124     * Boot the page, loading the wp-build assets only on its own request.
125     *
126     * @return void
127     */
128    public static function init() {
129        // Without a build the page would render blank, so leave the slug to whatever serves it otherwise.
130        if ( ! static::should_register() || ! static::has_build() ) {
131            return;
132        }
133
134        add_action( 'admin_menu', array( static::class, 'register_page' ), static::REGISTER_PRIORITY );
135
136        // After the Jetpack packages at 10, so a package that serves the same slug keeps it.
137        add_filter( 'jetpack_admin_shell_members', array( static::class, 'add_admin_shell_member' ), 20 );
138
139        if ( ! static::is_page_request() ) {
140            return;
141        }
142
143        static::load_wp_build();
144
145        // wp-build's generated enqueue runs at the default priority 10; the alias is
146        // scoped to that one pass so nothing else sees the rewritten screen.
147        add_action( 'admin_enqueue_scripts', array( static::class, 'alias_screen_id' ), 9 );
148        add_action( 'admin_enqueue_scripts', array( static::class, 'restore_screen_id' ), 11 );
149        add_action( 'admin_enqueue_scripts', array( static::class, 'enqueue_page_data' ), 20 );
150    }
151
152    /**
153     * The wp-build output directory, produced at release time and absent from an unbuilt checkout.
154     *
155     * @return string
156     */
157    public static function build_dir() {
158        return dirname( __DIR__, 2 ) . '/build';
159    }
160
161    /**
162     * Whether the wp-build output the page renders from exists.
163     *
164     * @return bool
165     */
166    public static function has_build() {
167        return file_exists( static::build_dir() . '/build.php' );
168    }
169
170    /**
171     * The page's wp-build route directories, read from the build's route registry.
172     *
173     * @return string[]
174     */
175    public static function get_routes() {
176        $registry = static::build_dir() . '/routes/registry.php';
177
178        if ( ! file_exists( $registry ) ) {
179            return array();
180        }
181
182        $routes = array();
183        foreach ( (array) require $registry as $route ) {
184            if ( is_array( $route ) && static::WP_BUILD_PAGE === ( $route['page'] ?? null ) && isset( $route['name'] ) ) {
185                $routes[] = $route['name'];
186            }
187        }
188
189        return $routes;
190    }
191
192    /**
193     * Render callback wp-build generates in build/pages/<page>/page-wp-admin.php.
194     *
195     * @return string
196     */
197    public static function get_render_callback() {
198        return 'jetpack_mu_wpcom_' . str_replace( '-', '_', static::WP_BUILD_PAGE ) . '_wp_admin_render_page';
199    }
200
201    /**
202     * The page's own address.
203     *
204     * @return string
205     */
206    public static function get_page_url() {
207        return admin_url( 'admin.php?page=' . static::MENU_SLUG );
208    }
209
210    /**
211     * Whether the current request targets this page.
212     *
213     * @return bool
214     */
215    public static function is_page_request() {
216        // admin-ajax.php is also `is_admin()`, and has no menu, screen or enqueue pass to set up.
217        if ( ! is_admin() || 'admin.php' !== ( $GLOBALS['pagenow'] ?? '' ) ) {
218            return false;
219        }
220
221        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only routing check; no form data is processed.
222        return isset( $_GET['page'] ) && static::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
223    }
224
225    /**
226     * Register the page, unless something else already serves the slug.
227     *
228     * @return void
229     */
230    public static function register_page() {
231        // A second entry under a slug someone else owns would leave two.
232        if ( static::slug_is_claimed() ) {
233            return;
234        }
235
236        self::$owns_page[ static::class ] = true;
237
238        // build/build.php defines the render callback but only loads on this page's
239        // own request; elsewhere the callback never runs, so any callable will do.
240        $callback = function_exists( static::get_render_callback() )
241            ? static::get_render_callback()
242            : '__return_empty_string';
243
244        $hook = add_submenu_page(
245            static::PARENT_SLUG,
246            static::get_page_title(),
247            static::get_menu_title(),
248            static::CAPABILITY,
249            static::MENU_SLUG,
250            $callback
251        );
252
253        if ( $hook ) {
254            self::$screen_id[ static::class ] = $hook;
255        }
256    }
257
258    /**
259     * Whether this page registered its slug on this request.
260     *
261     * @return bool
262     */
263    public static function owns_page() {
264        return ! empty( self::$owns_page[ static::class ] );
265    }
266
267    /**
268     * The page's screen ID, or null when it did not register on this request.
269     *
270     * @return string|null
271     */
272    public static function get_screen_id() {
273        return self::$screen_id[ static::class ] ?? null;
274    }
275
276    /**
277     * Reset the registration state. Test seam; production sets this once per request.
278     *
279     * @return void
280     */
281    public static function reset() {
282        unset( self::$owns_page[ static::class ], self::$displaced_screen_id[ static::class ], self::$screen_id[ static::class ] );
283    }
284
285    /**
286     * Whether something has already registered this page's slug.
287     *
288     * @return bool
289     */
290    public static function slug_is_claimed() {
291        global $submenu;
292
293        foreach ( $submenu[ static::PARENT_SLUG ] ?? array() as $item ) {
294            if ( is_array( $item ) && static::MENU_SLUG === ( $item[2] ?? null ) ) {
295                return true;
296            }
297        }
298
299        return false;
300    }
301
302    /**
303     * Load the wp-build generated asset registrations and the boot polyfills.
304     *
305     * @return void
306     */
307    public static function load_wp_build() {
308        $wp_build_index = static::build_dir() . '/build.php';
309        require_once $wp_build_index;
310
311        // Register polyfills for WP < 7.0 (must run before enqueue).
312        WP_Build_Polyfills::register(
313            'jetpack-mu-wpcom',
314            array_merge(
315                WP_Build_Polyfills::SCRIPT_HANDLES,
316                WP_Build_Polyfills::MODULE_IDS
317            ),
318            null,
319            array(
320                array(
321                    'prefix' => 'jetpack_mu_wpcom',
322                    'slug'   => static::WP_BUILD_PAGE,
323                ),
324            )
325        );
326    }
327
328    /**
329     * Make wp-build's enqueue check, which wants a screen ID of WP_BUILD_PAGE, pass without changing the URL.
330     *
331     * Paired with restore_screen_id() so the body class and page-view tracker keep reading the real ID.
332     *
333     * @return void
334     */
335    public static function alias_screen_id() {
336        $screen = get_current_screen();
337
338        if ( ! static::owns_page() || ! is_object( $screen ) ) {
339            return;
340        }
341
342        self::$displaced_screen_id[ static::class ] = $screen->id;
343        $screen->id                                 = static::WP_BUILD_PAGE;
344    }
345
346    /**
347     * Put back the screen ID displaced by alias_screen_id().
348     *
349     * @return void
350     */
351    public static function restore_screen_id() {
352        $screen = get_current_screen();
353
354        if ( ! isset( self::$displaced_screen_id[ static::class ] ) || ! is_object( $screen ) ) {
355            return;
356        }
357
358        $screen->id = self::$displaced_screen_id[ static::class ];
359        unset( self::$displaced_screen_id[ static::class ] );
360    }
361
362    /**
363     * Hand the page its initial state, Tracks and translation catalogs.
364     *
365     * All of it lands on the prerequisites script, which runs before the boot module.
366     *
367     * @return void
368     */
369    public static function enqueue_page_data() {
370        $handle = static::WP_BUILD_PAGE . '-wp-admin-prerequisites';
371
372        // The menu's capability gate already keeps others off the page; restated because
373        // subclasses build the state from direct calls rather than gated endpoints.
374        if ( ! static::owns_page() || ! wp_script_is( $handle, 'registered' ) || ! current_user_can( static::CAPABILITY ) ) {
375            return;
376        }
377
378        // wp-build has no `jetpackConfig` external, so @automattic/jetpack-config reads this global.
379        wp_add_inline_script( $handle, 'window.jetpackConfig = ' . wp_json_encode( array( 'consumer_slug' => 'jetpack-mu-wpcom' ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES ) . ';', 'before' );
380
381        // Every `before` script shares one tag, so a bare `= ;` would also break the translations.
382        $state = static::get_initial_state_script();
383        if ( '' !== $state ) {
384            wp_add_inline_script( $handle, $state, 'before' );
385        }
386
387        if ( static::ENQUEUE_TRACKS ) {
388            Common\wpcom_enqueue_tracking_scripts( $handle );
389        }
390
391        $translations = static::get_translations_script();
392        if ( '' !== $translations ) {
393            wp_add_inline_script( $handle, $translations, 'before' );
394        }
395    }
396
397    /**
398     * The script that sets INITIAL_STATE_VAR, or '' for none.
399     *
400     * @return string
401     */
402    public static function get_initial_state_script() {
403        if ( '' === static::INITIAL_STATE_VAR ) {
404            return '';
405        }
406
407        // Inline JSON rather than wp_localize_script(), which stringifies top-level scalars.
408        $state = wp_json_encode( static::get_initial_state(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES );
409
410        return false === $state ? '' : 'window.' . static::INITIAL_STATE_VAR . ' = ' . $state . ';';
411    }
412
413    /**
414     * The script that loads the page's translation catalogs, or '' for none.
415     *
416     * @return string
417     */
418    public static function get_translations_script() {
419        $constants = static::build_dir() . '/constants.php';
420        if ( ! file_exists( $constants ) ) {
421            return '';
422        }
423
424        $build_constants = require $constants;
425        $translations    = wpcom_wp_build_script_translations( static::build_dir() . '/i18n-manifest.json', $build_constants['build_url'], static::get_routes() );
426
427        return $translations ?? '';
428    }
429
430    /**
431     * Add the page to the dashboards that share the Jetpack admin shell, on Simple only.
432     *
433     * Elsewhere the Jetpack plugin can claim the slug, which admin-ajax, where the shell loads guests,
434     * can't tell, as it never builds the menu.
435     *
436     * @param array $members Member definitions keyed by admin page slug.
437     * @return array
438     */
439    public static function add_admin_shell_member( $members ) {
440        if ( ! is_array( $members ) || isset( $members[ static::MENU_SLUG ] ) || ! ( new Host() )->is_wpcom_simple() ) {
441            return $members;
442        }
443
444        $handles = array( 'wp-jp-i18n-loader' );
445        if ( static::ENQUEUE_TRACKS ) {
446            $handles[] = 'jp-tracks-functions';
447        }
448
449        $members[ static::MENU_SLUG ] = array(
450            'build_prefix' => 'jetpack_mu_wpcom',
451            'build_page'   => static::WP_BUILD_PAGE,
452            'title'        => static::get_page_title(),
453            'capability'   => static::CAPABILITY,
454            'handles'      => $handles,
455            'load'         => array( static::class, 'load_as_admin_shell_guest' ),
456            'data'         => array( static::class, 'get_admin_shell_guest_data' ),
457            'admin_menu'   => static::ADMIN_SHELL_NEEDS_MENU,
458        );
459
460        return $members;
461    }
462
463    /**
464     * Ready the page's routes while another dashboard's page is open.
465     *
466     * Safe to run twice, and on a host page built from this package too: the build loads once.
467     *
468     * @return void
469     */
470    public static function load_as_admin_shell_guest() {
471        static::load_wp_build();
472
473        // wp-build registers its modules on wp_default_scripts, which has fired by the time the shell loads a guest.
474        if ( function_exists( 'jetpack_mu_wpcom_register_script_modules' ) ) {
475            jetpack_mu_wpcom_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php.
476        }
477
478        if ( static::ENQUEUE_TRACKS ) {
479            Tracking::register_tracks_functions_scripts( true );
480        }
481    }
482
483    /**
484     * The page data enqueue_page_data() adds on the page's own request, for the shell's guest endpoint.
485     *
486     * Leaves out `window.jetpackConfig`, which belongs to the host page.
487     *
488     * @return string
489     */
490    public static function get_admin_shell_guest_data() {
491        $scripts = array( static::get_initial_state_script(), static::get_translations_script() );
492        if ( static::ENQUEUE_TRACKS && class_exists( Connection_Initial_State::class ) ) {
493            $scripts[] = Connection_Initial_State::render();
494        }
495
496        return implode( "\n", array_filter( $scripts ) );
497    }
498}