Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.01% covered (warning)
77.01%
67 / 87
71.43% covered (warning)
71.43%
5 / 7
CRAP
n/a
0 / 0
Automattic\Jetpack\PremiumAnalytics\register_widget_modules_rest_route
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\ensure_widget_registry_ready
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
Automattic\Jetpack\PremiumAnalytics\get_widget_modules_response
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\PremiumAnalytics\add_widget_modules_to_boot_deps
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
Automattic\Jetpack\PremiumAnalytics\preload_requested_route_content
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
10.60
Automattic\Jetpack\PremiumAnalytics\get_requested_route_content_module
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
11
Automattic\Jetpack\PremiumAnalytics\preload_dashboard_rest_responses
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Dashboard widget modules: REST exposure, import-map wiring and the page's boot preloads.
4 *
5 * Reads get_available_widget_types() and exposes it two ways: the `/wpcom/v2/widget-modules`
6 * REST list, and the page import map, for dynamic `import()`.
7 *
8 * @package automattic/jetpack-premium-analytics
9 */
10
11namespace Automattic\Jetpack\PremiumAnalytics;
12
13use Automattic\Jetpack\Status\Host;
14
15require_once __DIR__ . '/rest-namespace.php';
16require_once __DIR__ . '/dashboard-layout.php';
17
18/**
19 * Register the `/wpcom/v2/widget-modules` REST route.
20 *
21 * @return void
22 */
23function register_widget_modules_rest_route() {
24    register_rest_route(
25        DASHBOARD_REST_NAMESPACE,
26        '/widget-modules',
27        array(
28            'methods'             => \WP_REST_Server::READABLE,
29            'callback'            => __NAMESPACE__ . '\\get_widget_modules_response',
30            'permission_callback' => array( Capabilities::class, 'current_user_can_view_analytics' ),
31        )
32    );
33}
34
35/**
36 * Load the widget type API and the build manifest, once, ahead of the registry's first read.
37 *
38 * Deferred to the registry's only two readers rather than run at boot: on Simple this file's
39 * registration runs on every WPCOM public-api request, and most never read the registry. The
40 * registry hydrates itself on that read, from the registration action.
41 *
42 * @return void
43 */
44function ensure_widget_registry_ready() {
45    static $ready = false;
46    if ( $ready ) {
47        return;
48    }
49    $ready = true;
50
51    require_once __DIR__ . '/widget-types.php';
52    require_once __DIR__ . '/widget-availability.php';
53
54    // REST does not load the admin build, so this require is the manifest's only route in
55    // (WOOA7S-1804). Drop it and every widget renders "Widget is no longer available" (#49961).
56    $widgets_manifest = Analytics::widget_manifest_path();
57    if ( file_exists( $widgets_manifest ) ) {
58        require_once $widgets_manifest;
59    }
60}
61
62/**
63 * Build the REST response: one record per available widget type.
64 *
65 * @return \WP_REST_Response
66 */
67function get_widget_modules_response() {
68    ensure_widget_registry_ready();
69
70    $records = array();
71
72    foreach ( get_available_widget_types() as $widget_type ) {
73        $records[] = array(
74            'name'          => $widget_type->name,
75            'render_module' => $widget_type->render_module,
76            'widget_module' => $widget_type->widget_module,
77            'presentation'  => $widget_type->presentation,
78            'category'      => $widget_type->category,
79            'title'         => $widget_type->title,
80            'description'   => $widget_type->description,
81            'help'          => $widget_type->help,
82            'icon'          => $widget_type->icon,
83            'actions'       => $widget_type->actions,
84            'attributes'    => $widget_type->attributes,
85            'keywords'      => $widget_type->keywords,
86            'textdomain'    => $widget_type->textdomain,
87            'i18n_manifest' => $widget_type->i18n_manifest,
88            'former_names'  => $widget_type->former_names,
89        );
90    }
91
92    return rest_ensure_response( $records );
93}
94
95/**
96 * Add available widget modules to the page import map as dynamic dependencies,
97 * so the client can `import()` them on demand.
98 *
99 * @param array $boot_dependencies Boot dependencies for the page.
100 * @return array Updated boot dependencies.
101 */
102function add_widget_modules_to_boot_deps( $boot_dependencies ) {
103    ensure_widget_registry_ready();
104
105    foreach ( get_available_widget_types() as $widget_type ) {
106        if ( ! empty( $widget_type->render_module ) ) {
107            $boot_dependencies[] = array(
108                'import' => 'dynamic',
109                'id'     => $widget_type->render_module,
110            );
111        }
112
113        if ( ! empty( $widget_type->widget_module ) ) {
114            $boot_dependencies[] = array(
115                'import' => 'dynamic',
116                'id'     => $widget_type->widget_module,
117            );
118        }
119    }
120
121    return $boot_dependencies;
122}
123add_filter( 'jetpack-premium-analytics-wp-admin_boot_dependencies', __NAMESPACE__ . '\\add_widget_modules_to_boot_deps' );
124
125/**
126 * Make the requested route's content module static, so core modulepreloads it with the page.
127 *
128 * The page's loader module is empty, so this only fetches and compiles it early; boot still runs it.
129 * Widget modules stay dynamic: preloading them too delayed the first widget on slow connections.
130 *
131 * @param array      $boot_dependencies Boot dependencies for the page.
132 * @param array|null $routes            The page's registered routes. Defaults to the generated page's.
133 * @return array Updated boot dependencies.
134 */
135function preload_requested_route_content( $boot_dependencies, $routes = null ) {
136    // Generated by wp-build into the page file; filled before this filter runs.
137    if ( null === $routes && function_exists( 'jpa_get_jetpack_premium_analytics_wp_admin_routes' ) ) {
138        // @phan-suppress-next-line PhanUndeclaredFunction -- Declared in build/, which Phan excludes.
139        $routes = jpa_get_jetpack_premium_analytics_wp_admin_routes();
140    }
141    if ( ! is_array( $boot_dependencies ) || ! is_array( $routes ) ) {
142        return $boot_dependencies;
143    }
144
145    $content_module = get_requested_route_content_module( $routes );
146    if ( null === $content_module ) {
147        return $boot_dependencies;
148    }
149
150    foreach ( $boot_dependencies as $index => $dependency ) {
151        if ( is_array( $dependency ) && isset( $dependency['id'] ) && $content_module === $dependency['id'] ) {
152            $boot_dependencies[ $index ]['import'] = 'static';
153        }
154    }
155
156    return $boot_dependencies;
157}
158add_filter( 'jetpack-premium-analytics-wp-admin_boot_dependencies', __NAMESPACE__ . '\\preload_requested_route_content', 20 );
159
160/**
161 * The content module of the registered route the `p` query arg resolves to.
162 *
163 * @param array $routes The page's registered routes, each with `path` and an optional `content_module`.
164 * @return string|null Script module ID, or null when no route with content matches.
165 */
166function get_requested_route_content_module( $routes ) {
167    // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Read-only routing input, only compared against known route paths.
168    $location = isset( $_GET['p'] ) && is_string( $_GET['p'] ) ? wp_unslash( $_GET['p'] ) : '/';
169    $segments = array_values( array_filter( explode( '/', (string) wp_parse_url( $location, PHP_URL_PATH ) ), 'strlen' ) );
170
171    foreach ( $routes as $route ) {
172        if ( ! is_array( $route ) || empty( $route['content_module'] ) || ! isset( $route['path'] ) ) {
173            continue;
174        }
175
176        $pattern = array_values( array_filter( explode( '/', $route['path'] ), 'strlen' ) );
177        if ( count( $pattern ) !== count( $segments ) ) {
178            continue;
179        }
180
181        foreach ( $pattern as $position => $segment ) {
182            // `$postId`-style segments are params and match any value; the rest match as the
183            // client router does, decoded and case-insensitive.
184            if ( '$' !== $segment[0] && 0 !== strcasecmp( $segment, rawurldecode( $segments[ $position ] ) ) ) {
185                continue 2;
186            }
187        }
188
189        return $route['content_module'];
190    }
191
192    return null;
193}
194
195/**
196 * Add the REST responses the dashboard reads before it can place a widget to the page's preloads:
197 * the settings, then the sections and widget types, two round trips before the first widget mounts.
198 *
199 * Each path is the exact form the client requests, `_locale` included, or the preload goes unused.
200 * Not on Simple: there the client calls public-api, and wp-admin cannot answer these routes.
201 *
202 * @param array $preload_paths Paths the generated page preloads.
203 * @return array Updated paths.
204 */
205function preload_dashboard_rest_responses( $preload_paths ) {
206    if ( ! is_array( $preload_paths ) || ( new Host() )->is_wpcom_simple() ) {
207        return $preload_paths;
208    }
209
210    $preload_paths[] = '/wp/v2/settings';
211    $preload_paths[] = '/' . DASHBOARD_REST_NAMESPACE . '/dashboards/' . DASHBOARD_NAME . '/sections?per_page=100&_locale=user';
212    $preload_paths[] = '/' . DASHBOARD_REST_NAMESPACE . '/widget-modules?per_page=100&_locale=user';
213
214    return $preload_paths;
215}
216add_filter( 'jpa_jetpack_premium_analytics_wp_admin_preload_paths', __NAMESPACE__ . '\\preload_dashboard_rest_responses' );