Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.06% covered (success)
92.06%
348 / 378
80.00% covered (warning)
80.00%
28 / 35
CRAP
0.00% covered (danger)
0.00%
0 / 1
Api_Proxy_Controller
92.06% covered (success)
92.06%
348 / 378
80.00% covered (warning)
80.00%
28 / 35
137.32
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 add_batch_script_data
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 register_transient_cleanup_prefix
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_routes
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
1
 handle_batch_request
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
9
 build_batch_item_request
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
5.00
 prepare_batched_read
86.96% covered (warning)
86.96%
20 / 23
0.00% covered (danger)
0.00%
0 / 1
6.08
 fetch_batched_reads
83.33% covered (warning)
83.33%
20 / 24
0.00% covered (danger)
0.00%
0 / 1
5.12
 batch_item_result
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 allowed_endpoint_pattern
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 config_for
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 check_data_permission
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 validate_data_endpoint
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
8
 validate_version
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle_data_request
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
4
 base_for_version
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 build_data_path
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 is_write_allowed
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 inject_user_email
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
 busts_cache
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 cache_scope_for
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 invalidate_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 cache_generations
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 cache_generation
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 bump_cache_generation
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 forward
80.36% covered (warning)
80.36%
45 / 56
0.00% covered (danger)
0.00%
0 / 1
15.49
 request_unauthenticated
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 maybe_bust_read_cache
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 cache_and_build_response
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
 build_response
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 extract_forwarded_headers
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
5.58
 append_forwarded_params
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 get_forwarded_params
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 cache_key_for
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * REST controller that proxies dashboard data-layer requests to the WPCOM analytics API.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics\REST;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager;
12use Automattic\Jetpack\Constants;
13use Jetpack_Options;
14use WP_Error;
15use WP_REST_Controller;
16use WP_REST_Request;
17use WP_REST_Response;
18use WP_REST_Server;
19
20/**
21 * Forwards an authenticated dashboard request to the WPCOM endpoint for the connected
22 * site's blog ID, caches the successful response in a short-lived transient, and returns
23 * it. Lets the extracted frontend's data layer talk to WPCOM without each call leaving the
24 * WordPress origin.
25 *
26 * One agnostic route serves the whole pass-through surface (analytics + the re-exposed
27 * `stats-admin` endpoints), minus the blog ID in the URL:
28 *
29 *     proxy/v<version>/<prefix>/<subpath>   e.g. proxy/v1.1/wordads/earnings
30 *
31 * The `proxy/` segment marks a transparent WPCOM forward (future local endpoints live
32 * elsewhere under the namespace). Rather than registering each endpoint, it accepts any
33 * sub-path under an allowed top-level prefix (see {@see PREFIX_CONFIG}); the caller picks the
34 * WPCOM API `version` in the path (the base is derived: v2 → wpcom, v1.x → rest). The proxy
35 * stays endpoint-agnostic while the prefix allowlist + write-method policy keep the blast
36 * radius of the blog token bounded.
37 */
38class Api_Proxy_Controller extends WP_REST_Controller {
39
40    /**
41     * Package slug. Also the cache-key prefix (see SLUG-derived CACHE_PREFIX) — the only
42     * piece the source pulled from its dropped Utilities trait.
43     */
44    private const SLUG = 'jetpack-premium-analytics';
45
46    /**
47     * Transient key prefix, derived from the package slug.
48     *
49     * @var string
50     */
51    private const CACHE_PREFIX = self::SLUG . '_proxy_';
52
53    /**
54     * How long a successful response stays cached.
55     *
56     * @var int
57     */
58    private const CACHE_TTL = 5 * MINUTE_IN_SECONDS;
59
60    /**
61     * Option holding a counter per `invalidates` scope; each value is part of that scope's cache keys.
62     *
63     * @var string
64     */
65    private const CACHE_GENERATIONS_OPTION = 'jetpack_premium_analytics_proxy_cache_generations';
66
67    /**
68     * The generations entry that every cached read is keyed under, whatever its scope.
69     *
70     * @var string
71     */
72    private const ALL_SCOPES = '*';
73
74    /**
75     * Timeout for the outbound WPCOM request, in seconds.
76     *
77     * @var int
78     */
79    private const API_TIMEOUT = 20;
80
81    /**
82     * Most reads one batch request may carry.
83     *
84     * @var int
85     */
86    private const BATCH_MAX_ITEMS = 20;
87
88    /**
89     * Response headers worth forwarding back to the dashboard.
90     *
91     * @var string[]
92     */
93    private const FORWARDED_HEADERS = array( 'x-wp-total', 'x-wp-totalpages' );
94
95    /**
96     * Per-prefix configuration — the single source of truth for every proxied endpoint group.
97     * The route regex, permission check, write gate, cache-busting, and path builder all read
98     * from this table, so an endpoint group is defined here and nowhere else.
99     *
100     * The keys double as the security boundary: a request is only routed (and the blog token only
101     * forwarded) if its first path segment is a key here — so the proxy can never be driven
102     * against the whole WPCOM site API. Keep keys lowercase; they are matched case-insensitively.
103     *
104     * A request maps to `proxy/v<version>/<key>/<sub-path>` →
105     * `/sites/<blog-id>/<key>/<sub-path>` (the caller chooses `<version>`; the base is derived).
106     *
107     * Fields per entry:
108     *  - `capability` (string, required) Capability granting access. `manage_options` is always
109     *                  also accepted, so a value of `manage_options` means "admins only". A
110     *                  missing/unknown value fails closed (denies).
111     *  - `writes`     (string[], optional) Sub-paths reachable with POST (the only write verb).
112     *                  Each matcher: trailing `/` = that sub-path and anything under it; no
113     *                  trailing `/` = that exact endpoint only. Omit for a read-only group.
114     *  - `cache_bust` (bool, optional) If true, a successful POST clears the matching read cache.
115     *                  Only meaningful alongside `writes`.
116     *  - `invalidates` (string[], optional) Sub-paths whose cached reads, at any params or version,
117     *                  a successful POST in this group makes stale. Each covers that sub-path and
118     *                  everything under it, and must lie inside this group, since a read only
119     *                  consults its own group's entries. Only meaningful alongside `writes`.
120     *  - `path`       (string, optional) printf template (`%d` = blog id) for groups NOT under
121     *                  `/sites/<id>/` (e.g. `upgrades` → `/upgrades?site=%d`). A group with a
122     *                  fixed `path` takes no sub-path. Omit for the normal `/sites/<id>/<key>/…`.
123     *  - `pattern`    (string, optional) Regex the sub-path (after `<key>/`) must fully match,
124     *                  for groups where only specific endpoints are safe to expose (e.g. `posts`
125     *                  → only `<id>/likes` and `<id>/replies`, never post content). Anchored on both ends and
126     *                  enforced in the route regex AND in `validate_data_endpoint()` (the route
127     *                  capture can be shadowed with `?endpoint=`). Omit to allow the whole group.
128     *  - `inject_user_email` (bool, optional) Add the local user's email to the forwarded write body
129     *                  as `user_email`. The blog token carries no user, so a WPCOM endpoint that
130     *                  attributes a submission to a person cannot resolve one on its own (it falls
131     *                  back to the site's first administrator). The only body rewrite this proxy
132     *                  does; see `inject_user_email()`.
133     *  - `unauthenticated` (bool, optional) Forward reads WITHOUT signing (plain HTTP, like
134     *                  stats-admin's Odyssey proxy does for post likes). For WPCOM endpoints
135     *                  that reject blog-token auth but serve public data without credentials.
136     *                  Reads only; the group's `capability` still gates the local request.
137     *
138     * Maintaining endpoints (this table is the only edit needed for a pass-through endpoint):
139     *  - ADD a group:   add a key with at least `capability`. Reads work immediately at
140     *                   `proxy/v<version>/<key>/<sub-path>`. The frontend picks the WPCOM version.
141     *  - ALLOW writes:  add `writes` (and `cache_bust` if a write should freshen a cached read).
142     *  - CHANGE access: edit `capability` (e.g. tighten a group to `manage_options`).
143     *  - REMOVE a group: delete its key — the route stops matching it and it 404s.
144     *  - Cover it with a row in `data_endpoint_matrix()` (capability / writable / WPCOM path).
145     *  - NOTE: this is for transparent WPCOM forwards only. Endpoints needing local processing
146     *    (DB reads, the Notices class, …) are NOT proxied — they get their own routes outside
147     *    `proxy/`; do not add them here. `inject_user_email` is the one exception, and stays one:
148     *    a rewrite that cannot be expressed as a flag on this table belongs in its own route.
149     *
150     * @var array<string, array<string, mixed>>
151     */
152    private const PREFIX_CONFIG = array(
153        // Gated like WooCommerce's own Analytics screens, which shop managers can read;
154        // woocommerce-analytics made the same move away from manage_options (WOOA7S-551).
155        'analytics'                     => array( 'capability' => 'view_woocommerce_reports' ),
156        'stats'                         => array(
157            'capability'  => 'view_stats',
158            'writes'      => array( 'stats/referrers/spam/' ),
159            // Marking a referrer as spam removes it from every referrers read.
160            'invalidates' => array( 'stats/referrers' ),
161        ),
162        'wordads'                       => array( 'capability' => 'activate_wordads' ),
163        'subscribers'                   => array( 'capability' => 'view_stats' ),
164        'site-has-never-published-post' => array( 'capability' => 'view_stats' ),
165        'jetpack-stats'                 => array(
166            'capability'        => 'view_stats',
167            'writes'            => array( 'jetpack-stats/user-feedback' ),
168            'inject_user_email' => true,
169        ),
170        'jetpack-stats-dashboard'       => array(
171            'capability' => 'view_stats',
172            'writes'     => array( 'jetpack-stats-dashboard/' ),
173            'cache_bust' => true,
174        ),
175        'commercial-classification'     => array(
176            'capability' => 'view_stats',
177            'writes'     => array( 'commercial-classification' ),
178        ),
179        'upgrades'                      => array(
180            'capability' => 'view_stats',
181            'path'       => '/upgrades?site=%d',
182        ),
183        'posts'                         => array(
184            'capability'      => 'view_stats',
185            // Only a post's public likers and approved replies — never post content
186            // (the blog token could otherwise read private posts for any view_stats user).
187            'pattern'         => '[0-9]+/(?:likes|replies)',
188            // Both endpoints serve public data without credentials, while likes
189            // rejects blog-token auth; forward the constrained group unsigned,
190            // mirroring stats-admin's Odyssey proxy for likes.
191            'unauthenticated' => true,
192        ),
193    );
194
195    /**
196     * Constructor.
197     */
198    public function __construct() {
199        $this->namespace = self::SLUG . '/v1';
200    }
201
202    /**
203     * Hook the controller's routes onto rest_api_init, and register its cache prefix with the
204     * stats package's transient cleanup cron.
205     *
206     * @return void
207     */
208    public static function register(): void {
209        $controller = new self();
210        add_action( 'rest_api_init', array( $controller, 'register_routes' ) );
211        add_filter( 'jetpack_stats_transient_cleanup_prefixes', array( $controller, 'register_transient_cleanup_prefix' ) );
212        add_filter( 'jetpack_admin_js_script_data', array( $controller, 'add_batch_script_data' ), 20 );
213    }
214
215    /**
216     * Tell the dashboard whether `proxy/batch` can fetch in parallel here; where it cannot, separate reads are faster.
217     *
218     * @param array $data The script data.
219     *
220     * @return array
221     */
222    public function add_batch_script_data( $data ) {
223        if ( ! is_array( $data ) ) {
224            return $data;
225        }
226        if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) {
227            $data['premium_analytics'] = array();
228        }
229        // An older Connection package loaded by another plugin has no parallel client.
230        $data['premium_analytics']['proxy_batch'] = method_exists( Client::class, 'supports_parallel_requests' )
231            && method_exists( Client::class, 'wpcom_json_api_get_multiple_as_blog' )
232            && Client::supports_parallel_requests();
233
234        return $data;
235    }
236
237    /**
238     * Register the proxy cache prefix with the stats package's transient cleanup cron, so expired
239     * proxy transients are swept on sites without a persistent object cache (where WordPress's lazy
240     * GC never reaches the rarely re-read, param-keyed entries). The coupling is loose: the filter
241     * is just a hook name, so if the stats package isn't loaded it never fires and nothing breaks.
242     *
243     * Appends only when handed a valid array; a non-array (from a misbehaving upstream filter) is
244     * returned untouched so the stats consumer's own fall-back-to-defaults normalization still runs
245     * instead of being masked into dropping the default stats prefix.
246     *
247     * @param mixed $prefixes Transient prefixes the stats cleanup cron will sweep.
248     *
249     * @return mixed
250     */
251    public function register_transient_cleanup_prefix( $prefixes ) {
252        if ( is_array( $prefixes ) ) {
253            $prefixes[] = self::CACHE_PREFIX;
254        }
255
256        return $prefixes;
257    }
258
259    /**
260     * Register the agnostic data proxy route.
261     *
262     * @return void
263     */
264    public function register_routes(): void {
265        // proxy/v<version>/<prefix>/<subpath> — the `proxy/` segment marks a transparent WPCOM
266        // pass-through (local endpoints live elsewhere under the namespace), the version is part
267        // of the path (matching WPCOM's own `rest/v1.1` / `wpcom/v2` structure), and the prefix
268        // allowlist is anchored into the route.
269        register_rest_route(
270            $this->namespace,
271            '/proxy/v(?P<version>[0-9]+(?:\.[0-9]+)?)/(?P<endpoint>' . $this->allowed_endpoint_pattern() . ')',
272            array(
273                'methods'             => WP_REST_Server::READABLE . ',' . WP_REST_Server::EDITABLE,
274                'callback'            => array( $this, 'handle_data_request' ),
275                'permission_callback' => array( $this, 'check_data_permission' ),
276                'args'                => array(
277                    'endpoint' => array(
278                        'type'              => 'string',
279                        'required'          => true,
280                        'validate_callback' => array( $this, 'validate_data_endpoint' ),
281                    ),
282                    'version'  => array(
283                        'description'       => __( 'WPCOM API version to forward to (e.g. 1.1, 1.2, 2).', 'jetpack-premium-analytics-pkg' ),
284                        'type'              => 'string',
285                        'required'          => true,
286                        'validate_callback' => array( $this, 'validate_version' ),
287                    ),
288                ),
289            )
290        );
291
292        // proxy/batch — several reads in one local request, so HTTP/1.1 connections and PHP workers aren't held one per read.
293        register_rest_route(
294            $this->namespace,
295            '/proxy/batch',
296            array(
297                'methods'             => WP_REST_Server::CREATABLE,
298                'callback'            => array( $this, 'handle_batch_request' ),
299                // Each item runs its own prefix capability check in the callback.
300                'permission_callback' => 'is_user_logged_in',
301                'args'                => array(
302                    'requests' => array(
303                        'type'     => 'array',
304                        'required' => true,
305                        'minItems' => 1,
306                        'maxItems' => self::BATCH_MAX_ITEMS,
307                        'items'    => array( 'type' => 'string' ),
308                    ),
309                ),
310            )
311        );
312    }
313
314    /**
315     * Serve a batch of proxy reads: cache hits and errors locally, the misses through one parallel fan-out to WPCOM.
316     *
317     * @param WP_REST_Request $request Request object.
318     *
319     * @return WP_REST_Response
320     */
321    public function handle_batch_request( WP_REST_Request $request ): WP_REST_Response {
322        $force_refresh = null !== $request->get_param( 'force_refresh' );
323        $results       = array();
324        $pending       = array();
325
326        foreach ( array_values( (array) $request->get_param( 'requests' ) ) as $index => $item ) {
327            $sub = $this->build_batch_item_request( (string) $item, $force_refresh );
328            if ( ! is_wp_error( $sub ) ) {
329                // Each item answers to what would gate it as a request of its own.
330                /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
331                $pre = apply_filters( 'rest_pre_dispatch', null, rest_get_server(), $sub );
332                if ( null !== $pre ) {
333                    $results[ $index ] = $this->batch_item_result( $pre );
334                    continue;
335                }
336            }
337            if ( ! is_wp_error( $sub ) && ! $this->check_data_permission( $sub ) ) {
338                $sub = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.', 'jetpack-premium-analytics-pkg' ), array( 'status' => rest_authorization_required_code() ) );
339            }
340
341            $prepared = is_wp_error( $sub ) ? $sub : $this->prepare_batched_read( $sub );
342            if ( is_array( $prepared ) ) {
343                $pending[ $index ] = $prepared;
344            } else {
345                $results[ $index ] = $this->batch_item_result( $prepared );
346            }
347        }
348
349        foreach ( $this->fetch_batched_reads( $pending ) as $index => $response ) {
350            $results[ $index ] = $this->batch_item_result( $response );
351        }
352
353        ksort( $results );
354
355        return new WP_REST_Response( array_values( $results ), 200 );
356    }
357
358    /**
359     * Turn one batch item (`/v<version>/<endpoint>?<query>`) into the GET request the single route would see.
360     *
361     * @param string $item          The item path.
362     * @param bool   $force_refresh Whether the batch asked to bypass the cache.
363     *
364     * @return WP_REST_Request|WP_Error
365     */
366    private function build_batch_item_request( string $item, bool $force_refresh ) {
367        $path = (string) wp_parse_url( $item, PHP_URL_PATH );
368        if ( ! preg_match( '#^/v([0-9]+(?:\.[0-9]+)?)/(.+)$#', $path, $matches )
369            || ! $this->validate_version( $matches[1] )
370            || ! $this->validate_data_endpoint( $matches[2] )
371        ) {
372            return new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method.', 'jetpack-premium-analytics-pkg' ), array( 'status' => 404 ) );
373        }
374
375        parse_str( (string) wp_parse_url( $item, PHP_URL_QUERY ), $query );
376        // A real request's `get_param()` would let these shadow the route captures; here the route wins.
377        unset( $query['endpoint'], $query['version'] );
378        if ( $force_refresh ) {
379            $query['force_refresh'] = '1';
380        }
381
382        $sub = new WP_REST_Request( 'GET', '/' . $this->namespace . '/proxy' . $path );
383        $sub->set_url_params(
384            array(
385                'version'  => $matches[1],
386                'endpoint' => $matches[2],
387            )
388        );
389        $sub->set_query_params( $query );
390
391        return $sub;
392    }
393
394    /**
395     * Run a batched read up to its WPCOM call: a cache hit or error is the answer, a miss what to fetch.
396     *
397     * Unsigned groups take the single-request path instead.
398     *
399     * @param WP_REST_Request $sub The item's GET request.
400     *
401     * @return WP_REST_Response|WP_Error|array{request: WP_REST_Request, path: string, version: string, base: string, cache_key: string|null}
402     */
403    private function prepare_batched_read( WP_REST_Request $sub ) {
404        $endpoint = (string) $sub->get_param( 'endpoint' );
405        $config   = $this->config_for( $endpoint );
406        if ( ! empty( $config['unauthenticated'] ) ) {
407            return $this->handle_data_request( $sub );
408        }
409
410        $version    = (string) $sub->get_param( 'version' );
411        $base       = $this->base_for_version( $version );
412        $wpcom_path = $this->build_data_path( $endpoint );
413        $cache_key  = null === $sub->get_param( 'force_refresh' )
414            ? $this->cache_key_for( $wpcom_path, $version, $base, $this->get_forwarded_params( $sub, $wpcom_path ), $this->cache_scope_for( $endpoint ) )
415            : null;
416
417        if ( null !== $cache_key ) {
418            $cached = get_transient( $cache_key );
419            if ( false !== $cached ) {
420                return $this->build_response( $cached );
421            }
422        }
423
424        if ( ! ( new Manager( self::SLUG ) )->is_connected() ) {
425            return new WP_Error( 'no_connection', __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics-pkg' ), array( 'status' => 403 ) );
426        }
427
428        return array(
429            'request'   => $sub,
430            'path'      => $this->append_forwarded_params( $sub, $wpcom_path ),
431            'version'   => $version,
432            'base'      => $base,
433            'cache_key' => $cache_key,
434        );
435    }
436
437    /**
438     * Fetch the batch's cache misses from WPCOM in parallel, caching each success as the single route would.
439     *
440     * @param array<int, array> $pending Reads from `prepare_batched_read()`, keyed by batch index.
441     *
442     * @return array<int, WP_REST_Response|WP_Error> Keyed like `$pending`.
443     */
444    private function fetch_batched_reads( array $pending ): array {
445        $results = array();
446
447        // An older Connection package loaded by another plugin lacks the parallel client: answer one by one.
448        if ( ! method_exists( Client::class, 'wpcom_json_api_get_multiple_as_blog' ) ) {
449            foreach ( $pending as $index => $read ) {
450                $results[ $index ] = $this->handle_data_request( $read['request'] );
451            }
452            return $results;
453        }
454
455        $responses = Client::wpcom_json_api_get_multiple_as_blog(
456            array_map(
457                static function ( $read ) {
458                    return array(
459                        'path'          => $read['path'],
460                        'version'       => $read['version'],
461                        'base_api_path' => $read['base'],
462                        'args'          => array( 'timeout' => self::API_TIMEOUT ),
463                    );
464                },
465                $pending
466            )
467        );
468
469        foreach ( $pending as $index => $read ) {
470            $response          = $responses[ $index ] ?? null;
471            $results[ $index ] = is_array( $response )
472                ? $this->cache_and_build_response( $response, $read['cache_key'] )
473                : new WP_Error( 'api_error', __( 'Error communicating with the data service.', 'jetpack-premium-analytics-pkg' ), array( 'status' => 500 ) );
474        }
475
476        return $results;
477    }
478
479    /**
480     * One batch item as the client reads it: the status, body and headers the single route would have sent.
481     *
482     * @param WP_REST_Response|WP_Error $response The item's outcome.
483     *
484     * @return array{status: int, body: mixed, headers: array}
485     */
486    private function batch_item_result( $response ): array {
487        $response = is_wp_error( $response ) ? rest_convert_error_to_response( $response ) : rest_ensure_response( $response );
488
489        return array(
490            'status'  => $response->get_status(),
491            'body'    => $response->get_data(),
492            'headers' => $response->get_headers(),
493        );
494    }
495
496    /**
497     * Regex alternation of the allowed endpoints, used to anchor the data route: each
498     * {@see PREFIX_CONFIG} key followed by its `pattern`-constrained sub-path when set, or any
499     * sub-path otherwise.
500     *
501     * @return string
502     */
503    private function allowed_endpoint_pattern(): string {
504        $alternatives = array();
505
506        foreach ( self::PREFIX_CONFIG as $prefix => $config ) {
507            $suffix         = isset( $config['pattern'] ) ? '/' . $config['pattern'] : '(?:/.*)?';
508            $alternatives[] = preg_quote( $prefix, '#' ) . $suffix;
509        }
510
511        return '(?:' . implode( '|', $alternatives ) . ')';
512    }
513
514    /**
515     * The {@see PREFIX_CONFIG} entry for an endpoint's top-level prefix, or null if not allowed.
516     *
517     * @param string $endpoint The endpoint value (`get_param('endpoint')`).
518     *
519     * @return array<string, mixed>|null
520     */
521    private function config_for( string $endpoint ): ?array {
522        $prefix = strtolower( explode( '/', $endpoint )[0] );
523
524        return self::PREFIX_CONFIG[ $prefix ] ?? null;
525    }
526
527    /**
528     * Permission for the data proxy: the prefix's configured capability grants access, and
529     * `manage_options` always does (so `wordads`, whose `activate_wordads` no role holds, stays
530     * admin-only). The capability comes from {@see PREFIX_CONFIG}.
531     *
532     * @param WP_REST_Request $request Request object.
533     *
534     * @return bool
535     */
536    public function check_data_permission( WP_REST_Request $request ): bool {
537        $config = $this->config_for( (string) $request->get_param( 'endpoint' ) );
538        if ( null === $config ) {
539            return false;
540        }
541
542        // Fall back to `do_not_allow` so a config entry missing `capability` fails closed.
543        $capability = $config['capability'] ?? 'do_not_allow';
544
545        // phpcs:ignore WordPress.WP.Capabilities.Unknown -- capability is from the PREFIX_CONFIG allowlist.
546        return current_user_can( 'manage_options' ) || current_user_can( $capability );
547    }
548
549    /**
550     * Confine a data endpoint to a relative sub-path under an allowed prefix, rejecting traversal
551     * (`..`) and schemes (`:`). Commas are permitted since stats sub-paths legitimately contain
552     * them (UTM params).
553     *
554     * The prefix is re-checked here, not just in the route regex: WP's `get_param()` prefers
555     * GET/JSON/POST over the URL route capture, so a caller could otherwise shadow the matched
556     * `endpoint` with `?endpoint=…` and escape the allowlist. This runs against the same
557     * `get_param()` value the handler forwards, so it closes the hole whichever source wins.
558     *
559     * @param mixed $value Raw endpoint param.
560     *
561     * @return bool
562     */
563    public function validate_data_endpoint( $value ): bool {
564        $value = (string) $value;
565
566        if ( str_contains( $value, '..' ) ) {
567            return false;
568        }
569
570        if ( ! preg_match( '#^[\w.,/-]+$#', $value ) ) {
571            return false;
572        }
573
574        $config = $this->config_for( $value );
575        if ( null === $config ) {
576            return false;
577        }
578
579        // A prefix with a fixed `path` (e.g. site-less `upgrades`) takes no sub-path, so reject
580        // `<prefix>/<anything>` — build_data_path() ignores sub-paths there and would mis-route.
581        if ( isset( $config['path'] ) ) {
582            $prefix = strtolower( explode( '/', $value )[0] );
583            if ( $prefix !== rtrim( strtolower( $value ), '/' ) ) {
584                return false;
585            }
586        }
587
588        // A `pattern`-constrained prefix only exposes matching sub-paths. Re-checked here, not
589        // just in the route regex, because `get_param()` can be shadowed with `?endpoint=`.
590        if ( isset( $config['pattern'] ) ) {
591            $prefix = strtolower( explode( '/', $value )[0] );
592            if ( ! preg_match( '#^' . preg_quote( $prefix, '#' ) . '/' . $config['pattern'] . '$#i', rtrim( $value, '/' ) ) ) {
593                return false;
594            }
595        }
596
597        return true;
598    }
599
600    /**
601     * A WPCOM API version is one or two dot-separated numbers (e.g. `2`, `1.1`).
602     *
603     * @param mixed $value Raw version param.
604     *
605     * @return bool
606     */
607    public function validate_version( $value ): bool {
608        return (bool) preg_match( '#^[0-9]+(\.[0-9]+)?$#', (string) $value );
609    }
610
611    /**
612     * Proxy a data request to its WPCOM endpoint, at the caller-chosen API version.
613     *
614     * @param WP_REST_Request $request Request object.
615     *
616     * @return WP_REST_Response|WP_Error
617     */
618    public function handle_data_request( WP_REST_Request $request ) {
619        $endpoint = (string) $request->get_param( 'endpoint' );
620        $method   = strtoupper( $request->get_method() );
621
622        // Reads are open across the allowed prefixes; only POST may mutate, and only the
623        // few endpoints on the write allowlist. Everything else is rejected locally.
624        if ( 'GET' !== $method && ! ( 'POST' === $method && $this->is_write_allowed( $endpoint ) ) ) {
625            return new WP_Error(
626                'rest_read_only',
627                __( 'This endpoint is read-only.', 'jetpack-premium-analytics-pkg' ),
628                array( 'status' => 405 )
629            );
630        }
631
632        $version = (string) $request->get_param( 'version' );
633
634        $config = $this->config_for( $endpoint );
635
636        return $this->forward(
637            $request,
638            $this->build_data_path( $endpoint ),
639            array(
640                'version'           => $version,
641                'base'              => $this->base_for_version( $version ),
642                'bust_on_write'     => $this->busts_cache( $endpoint ),
643                'invalidates'       => $config['invalidates'] ?? array(),
644                'cache_scope'       => $this->cache_scope_for( $endpoint ),
645                'unauthenticated'   => ! empty( $config['unauthenticated'] ),
646                'inject_user_email' => ! empty( $config['inject_user_email'] ),
647            )
648        );
649    }
650
651    /**
652     * The WPCOM API base for a version: v2 lives under `wpcom`, v1.x under `rest`. Derived from
653     * the major component so dotted forms (e.g. `2.0`) map correctly.
654     *
655     * @param string $version WPCOM API version.
656     *
657     * @return string
658     */
659    private function base_for_version( string $version ): string {
660        return 2 === (int) $version ? 'wpcom' : 'rest';
661    }
662
663    /**
664     * Build the WPCOM path for a data endpoint.
665     *
666     * @param string $endpoint The validated, allowed sub-path.
667     *
668     * @return string
669     */
670    private function build_data_path( string $endpoint ): string {
671        $site_id = (int) Jetpack_Options::get_option( 'id' );
672
673        // A prefix with a fixed `path` (e.g. site-less `upgrades`) is not scoped under /sites/<id>/.
674        $config = $this->config_for( $endpoint );
675        if ( null !== $config && isset( $config['path'] ) ) {
676            return sprintf( $config['path'], $site_id );
677        }
678
679        return sprintf( '/sites/%d/%s', $site_id, $endpoint );
680    }
681
682    /**
683     * Whether a non-GET method may be forwarded for this endpoint, per the prefix's `writes`.
684     * A `writes` entry ending in `/` matches that sub-path prefix; otherwise it matches exactly.
685     *
686     * @param string $endpoint The validated sub-path.
687     *
688     * @return bool
689     */
690    private function is_write_allowed( string $endpoint ): bool {
691        $endpoint = strtolower( $endpoint );
692        $config   = $this->config_for( $endpoint );
693
694        foreach ( $config['writes'] ?? array() as $matcher ) {
695            $matcher = strtolower( $matcher );
696            $matches = str_ends_with( $matcher, '/' )
697                ? str_starts_with( $endpoint, $matcher )
698                : $endpoint === $matcher;
699            if ( $matches ) {
700                return true;
701            }
702        }
703
704        return false;
705    }
706
707    /**
708     * Add the local user's email to a forwarded write body, for a group declaring
709     * `inject_user_email`.
710     *
711     * Mirrors what stats-admin's own `post_user_feedback()` does: the request is signed with the
712     * blog token, so WPCOM sees no user and would attribute the submission to whichever
713     * administrator it finds first. A body that is neither empty nor a JSON object is returned
714     * untouched rather than replaced, so a malformed request still fails at WPCOM's own validation.
715     *
716     * @param string               $body The request body to forward.
717     * @param array<string, mixed> $opts The matched prefix config.
718     *
719     * @return string
720     */
721    private function inject_user_email( string $body, array $opts ): string {
722        if ( empty( $opts['inject_user_email'] ) ) {
723            return $body;
724        }
725
726        $email = wp_get_current_user()->user_email;
727        if ( ! $email ) {
728            return $body;
729        }
730
731        $decoded = '' === $body ? array() : json_decode( $body, true );
732        if ( ! is_array( $decoded ) ) {
733            return $body;
734        }
735
736        // A JSON list is not a param bag, and adding a string key would reshape it into an object.
737        if ( array() !== $decoded && array_keys( $decoded ) === range( 0, count( $decoded ) - 1 ) ) {
738            return $body;
739        }
740
741        $decoded['user_email'] = $email;
742
743        return (string) wp_json_encode( $decoded, JSON_UNESCAPED_SLASHES );
744    }
745
746    /**
747     * Whether a successful write to this endpoint should invalidate the matching read cache.
748     *
749     * @param string $endpoint The validated sub-path.
750     *
751     * @return bool
752     */
753    private function busts_cache( string $endpoint ): bool {
754        $config = $this->config_for( $endpoint );
755
756        return ! empty( $config['cache_bust'] );
757    }
758
759    /**
760     * The `invalidates` entry of the endpoint's group that covers this endpoint, if any.
761     *
762     * @param string $endpoint The validated sub-path.
763     *
764     * @return string|null
765     */
766    private function cache_scope_for( string $endpoint ): ?string {
767        $endpoint = strtolower( $endpoint );
768        $config   = $this->config_for( $endpoint );
769
770        foreach ( $config['invalidates'] ?? array() as $scope ) {
771            $scope = strtolower( $scope );
772            if ( $endpoint === $scope || str_starts_with( $endpoint, $scope . '/' ) ) {
773                return $scope;
774            }
775        }
776
777        return null;
778    }
779
780    /**
781     * Make every cached read stale, as when a purchase changes what WPCOM returns.
782     *
783     * @since 0.13.0
784     *
785     * @return void
786     */
787    public static function invalidate_cache(): void {
788        self::bump_cache_generation( self::ALL_SCOPES );
789    }
790
791    /**
792     * The stored generation of each cache scope, keyed by scope.
793     *
794     * @return array<string, int>
795     */
796    private static function cache_generations(): array {
797        $generations = get_option( self::CACHE_GENERATIONS_OPTION, array() );
798
799        return is_array( $generations ) ? $generations : array();
800    }
801
802    /**
803     * The cache-key suffix: the all-scopes generation once bumped, then the read's scope generation, or '' when neither applies.
804     *
805     * @param string|null $scope The `invalidates` entry covering the read.
806     *
807     * @return string
808     */
809    private function cache_generation( ?string $scope ): string {
810        $generations = self::cache_generations();
811
812        $parts = array();
813        // Left out until first bumped, so keys cached before it existed stay valid.
814        if ( ! empty( $generations[ self::ALL_SCOPES ] ) ) {
815            $parts[] = self::ALL_SCOPES . ':' . (int) $generations[ self::ALL_SCOPES ];
816        }
817        if ( null !== $scope ) {
818            $parts[] = $scope . ':' . (int) ( $generations[ $scope ] ?? 0 );
819        }
820
821        return implode( '|', $parts );
822    }
823
824    /**
825     * Move a cache scope to a new generation, so every read cached under the old one is skipped.
826     *
827     * @param string $scope The `invalidates` entry to advance.
828     *
829     * @return void
830     */
831    private static function bump_cache_generation( string $scope ): void {
832        $scope       = strtolower( $scope );
833        $generations = self::cache_generations();
834
835        $generations[ $scope ] = (int) ( $generations[ $scope ] ?? 0 ) + 1;
836        update_option( self::CACHE_GENERATIONS_OPTION, $generations, false );
837    }
838
839    /**
840     * Serve a cached payload when available, otherwise forward to WPCOM and cache the result.
841     *
842     * @param WP_REST_Request      $request    Request object.
843     * @param string               $wpcom_path WPCOM path without the forwarded query string.
844     * @param array<string, mixed> $opts       version | base | bust_on_write | invalidates | cache_scope | cache overrides.
845     *
846     * @return WP_REST_Response|WP_Error
847     */
848    private function forward( WP_REST_Request $request, string $wpcom_path, array $opts ) {
849        $version   = $opts['version'] ?? '2';
850        $base      = $opts['base'] ?? 'wpcom';
851        $method    = strtoupper( $request->get_method() );
852        $is_read   = 'GET' === $method;
853        $cacheable = $is_read
854            && ( $opts['cache'] ?? true )
855            && null === $request->get_param( 'force_refresh' );
856
857        $cache_key = $cacheable
858            ? $this->cache_key_for( $wpcom_path, $version, $base, $this->get_forwarded_params( $request, $wpcom_path ), $opts['cache_scope'] ?? null )
859            : null;
860        if ( null !== $cache_key ) {
861            $cached = get_transient( $cache_key );
862            if ( false !== $cached ) {
863                return $this->build_response( $cached );
864            }
865        }
866
867        // Unsigned forwards need no tokens — only the blog id baked into the path —
868        // so they skip the connection gate (its blog-token requirement) entirely.
869        if ( ! empty( $opts['unauthenticated'] ) && $is_read ) {
870            $response = $this->request_unauthenticated( $request, $wpcom_path, $version, $base );
871            if ( is_wp_error( $response ) ) {
872                return $response;
873            }
874
875            return $this->cache_and_build_response( $response, $cache_key );
876        }
877
878        if ( ! ( new Manager( self::SLUG ) )->is_connected() ) {
879            return new WP_Error(
880                'no_connection',
881                __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics-pkg' ),
882                array( 'status' => 403 )
883            );
884        }
885
886        $args = array(
887            'method'  => $method,
888            'timeout' => self::API_TIMEOUT,
889        );
890        $body = null;
891        if ( ! $is_read ) {
892            $body            = $this->inject_user_email( (string) $request->get_body(), $opts );
893            $args['headers'] = array( 'Content-Type' => 'application/json' );
894        }
895
896        // The signer hashes '' like any body, then refuses to sign a hash on an empty one.
897        if ( '' === $body ) {
898            $body = null;
899        }
900
901        try {
902            $response = Client::wpcom_json_api_request_as_blog(
903                $this->append_forwarded_params( $request, $wpcom_path ),
904                $version,
905                $args,
906                $body,
907                $base
908            );
909        } catch ( \Exception $e ) {
910            return new WP_Error(
911                'api_error',
912                __( 'Error processing the request.', 'jetpack-premium-analytics-pkg' ),
913                array( 'status' => 500 )
914            );
915        }
916
917        if ( is_wp_error( $response ) ) {
918            return new WP_Error(
919                'api_error',
920                __( 'Error communicating with the data service.', 'jetpack-premium-analytics-pkg' ),
921                array( 'status' => 500 )
922            );
923        }
924
925        $this->maybe_bust_read_cache( $response, ! $is_read, $opts, $wpcom_path, $version, $base );
926
927        return $this->cache_and_build_response( $response, $cache_key );
928    }
929
930    /**
931     * Forward a read to WPCOM without signing, for `unauthenticated` endpoint groups. Mirrors
932     * stats-admin's Odyssey proxy (`get_single_post_likes()`): the target endpoint rejects
933     * blog-token auth but serves public data to credential-less requests. Private posts/sites
934     * return WPCOM's own restricted error — the same limitation Odyssey has.
935     *
936     * @param WP_REST_Request $request    Request object.
937     * @param string          $wpcom_path WPCOM path without the forwarded query string.
938     * @param string          $version    WPCOM API version.
939     * @param string          $base       WPCOM API base (`rest` or `wpcom`).
940     *
941     * @return array|WP_Error Raw HTTP response, or an error.
942     */
943    private function request_unauthenticated( WP_REST_Request $request, string $wpcom_path, string $version, string $base ) {
944        // The path embeds the blog id; without one the request would target site 0.
945        if ( ! (int) Jetpack_Options::get_option( 'id' ) ) {
946            return new WP_Error(
947                'no_connection',
948                __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics-pkg' ),
949                array( 'status' => 403 )
950            );
951        }
952
953        $api_base = Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' );
954        if ( empty( $api_base ) ) {
955            $api_base = 'https://public-api.wordpress.com';
956        }
957
958        $response = wp_remote_get(
959            sprintf( '%s/%s/v%s%s', $api_base, $base, $version, $this->append_forwarded_params( $request, $wpcom_path ) ),
960            array( 'timeout' => self::API_TIMEOUT )
961        );
962
963        if ( is_wp_error( $response ) ) {
964            return new WP_Error(
965                'api_error',
966                __( 'Error communicating with the data service.', 'jetpack-premium-analytics-pkg' ),
967                array( 'status' => 500 )
968            );
969        }
970
971        return $response;
972    }
973
974    /**
975     * Mirror stats-admin: a successful write invalidates the matching (param-less) read cache, so
976     * the next GET reflects the change instead of serving the cached pre-write value. It busts only
977     * when the request was a write, the prefix opted in (`bust_on_write`), and WPCOM returned 200.
978     * The same successful write also advances every `invalidates` scope of the prefix.
979     *
980     * This is a pure function of the response and route context — it takes the raw client response
981     * rather than reaching out to WPCOM itself, so the full bust decision is unit-testable without
982     * a live connection.
983     *
984     * @param array                $http_response Raw response from the Jetpack client.
985     * @param bool                 $is_write      Whether the request used a write (non-GET) method.
986     * @param array<string, mixed> $opts          Forwarding opts (reads `bust_on_write`, `invalidates`).
987     * @param string               $wpcom_path    WPCOM path without the forwarded query string.
988     * @param string               $version       WPCOM API version.
989     * @param string               $base          WPCOM API base.
990     *
991     * @return void
992     */
993    private function maybe_bust_read_cache( array $http_response, bool $is_write, array $opts, string $wpcom_path, string $version, string $base ): void {
994        if ( ! $is_write || 200 !== (int) wp_remote_retrieve_response_code( $http_response ) ) {
995            return;
996        }
997
998        if ( ! empty( $opts['bust_on_write'] ) ) {
999            delete_transient( $this->cache_key_for( $wpcom_path, $version, $base, array() ) );
1000        }
1001
1002        foreach ( $opts['invalidates'] ?? array() as $scope ) {
1003            self::bump_cache_generation( $scope );
1004        }
1005    }
1006
1007    /**
1008     * Cache a successful (200) response when a cache key is given, and return it to the caller.
1009     *
1010     * @param array       $http_response Raw response from the Jetpack client.
1011     * @param string|null $cache_key     Transient key, or null to skip caching.
1012     *
1013     * @return WP_REST_Response|WP_Error
1014     */
1015    private function cache_and_build_response( array $http_response, ?string $cache_key ) {
1016        $status = (int) wp_remote_retrieve_response_code( $http_response );
1017        $data   = json_decode( wp_remote_retrieve_body( $http_response ), false );
1018
1019        // A 200 with an undecodable body means the upstream is degraded; don't cache garbage.
1020        if ( 200 === $status && null === $data && JSON_ERROR_NONE !== json_last_error() ) {
1021            return new WP_Error(
1022                'api_error',
1023                __( 'The data service returned an unreadable response.', 'jetpack-premium-analytics-pkg' ),
1024                array( 'status' => 502 )
1025            );
1026        }
1027
1028        $payload = array(
1029            'data'    => $data,
1030            'status'  => $status,
1031            'headers' => $this->extract_forwarded_headers( wp_remote_retrieve_headers( $http_response ) ),
1032        );
1033
1034        if ( null !== $cache_key && 200 === $status ) {
1035            set_transient( $cache_key, $payload, self::CACHE_TTL );
1036        }
1037
1038        return $this->build_response( $payload );
1039    }
1040
1041    /**
1042     * Rebuild a WP_REST_Response from a cached or freshly fetched payload.
1043     *
1044     * @param array $payload Stored payload with data, status, and headers.
1045     *
1046     * @return WP_REST_Response
1047     */
1048    private function build_response( array $payload ): WP_REST_Response {
1049        $response = new WP_REST_Response( $payload['data'], (int) $payload['status'] );
1050
1051        foreach ( (array) $payload['headers'] as $name => $value ) {
1052            $response->header( $name, $value );
1053        }
1054
1055        return $response;
1056    }
1057
1058    /**
1059     * Keep only the response headers the dashboard needs (pagination totals).
1060     *
1061     * @param mixed $headers Response headers as returned by the HTTP API.
1062     *
1063     * @return array<string, string>
1064     */
1065    private function extract_forwarded_headers( $headers ): array {
1066        if ( $headers instanceof \ArrayAccess || is_array( $headers ) ) {
1067            $forwarded = array();
1068            foreach ( self::FORWARDED_HEADERS as $name ) {
1069                if ( isset( $headers[ $name ] ) ) {
1070                    $forwarded[ $name ] = (string) $headers[ $name ];
1071                }
1072            }
1073            return $forwarded;
1074        }
1075
1076        return array();
1077    }
1078
1079    /**
1080     * Append the forwarded query params to a WPCOM path, choosing the right separator.
1081     *
1082     * @param WP_REST_Request $request    Request object.
1083     * @param string          $wpcom_path WPCOM path that may already carry a query string.
1084     *
1085     * @return string
1086     */
1087    private function append_forwarded_params( WP_REST_Request $request, string $wpcom_path ): string {
1088        $params = $this->get_forwarded_params( $request, $wpcom_path );
1089        if ( empty( $params ) ) {
1090            return $wpcom_path;
1091        }
1092
1093        $separator = str_contains( $wpcom_path, '?' ) ? '&' : '?';
1094
1095        return $wpcom_path . $separator . http_build_query( $params );
1096    }
1097
1098    /**
1099     * Query params to forward to WPCOM, minus the WordPress routing params, the proxy's own
1100     * control params (`endpoint`, `version`, `force_refresh` — which a caller could also pass as
1101     * query params since `get_param()` prefers GET), and any arg the WPCOM path already sets (a
1102     * fixed `path` such as `products?type=jetpack` or `upgrades?site=<id>` owns its args, and a
1103     * repeated arg would override it). Dropping the control params also keeps them out of the cache key.
1104     *
1105     * @param WP_REST_Request $request    Request object.
1106     * @param string          $wpcom_path WPCOM path that may already carry a query string.
1107     *
1108     * @return array
1109     */
1110    private function get_forwarded_params( WP_REST_Request $request, string $wpcom_path ): array {
1111        $params = $request->get_query_params();
1112        if ( ! is_array( $params ) ) {
1113            return array();
1114        }
1115        // `_method` too: WPCOM would honour it as the HTTP method, turning a forwarded read into a write.
1116        unset( $params['rest_route'], $params['_locale'], $params['_method'], $params['endpoint'], $params['version'], $params['force_refresh'] );
1117
1118        parse_str( (string) wp_parse_url( $wpcom_path, PHP_URL_QUERY ), $fixed );
1119
1120        return array_diff_key( $params, $fixed );
1121    }
1122
1123    /**
1124     * Transient key for a target path + API version/base + forwarded params (order-independent) + cache generations.
1125     * Version and base are part of the key so the same path at different versions doesn't collide.
1126     *
1127     * @param string      $wpcom_path WPCOM path without the forwarded query string.
1128     * @param string      $version    WPCOM API version.
1129     * @param string      $base       WPCOM API base.
1130     * @param array       $params     Forwarded query params.
1131     * @param string|null $scope      The `invalidates` entry covering the read, if any.
1132     *
1133     * @return string
1134     */
1135    private function cache_key_for( string $wpcom_path, string $version, string $base, array $params, ?string $scope = null ): string {
1136        ksort( $params );
1137        $generation = $this->cache_generation( $scope );
1138        $parts      = array( $wpcom_path, $version, $base, (string) wp_json_encode( $params, JSON_UNESCAPED_SLASHES ) );
1139        if ( '' !== $generation ) {
1140            $parts[] = $generation;
1141        }
1142        $signature = implode( '|', $parts );
1143
1144        return self::CACHE_PREFIX . md5( $signature );
1145    }
1146}