Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.70% covered (warning)
80.70%
347 / 430
33.33% covered (danger)
33.33%
6 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
Client
80.70% covered (warning)
80.70%
347 / 430
33.33% covered (danger)
33.33%
6 / 18
257.31
0.00% covered (danger)
0.00%
0 / 1
 remote_request
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 sign_remote_request
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 report_remote_response
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 remote_request_error_type
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 build_signed_request
90.38% covered (success)
90.38%
94 / 104
0.00% covered (danger)
0.00%
0 / 1
17.26
 is_safe_url_path
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 add_query_args
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
5.07
 _wp_remote_request
69.23% covered (warning)
69.23%
18 / 26
0.00% covered (danger)
0.00%
0 / 1
19.71
 set_time_diff
40.00% covered (danger)
40.00%
6 / 15
0.00% covered (danger)
0.00%
0 / 1
31.60
 validate_args_for_wpcom_json_api_request
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
2
 wpcom_json_api_request_as_user
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
6.84
 wpcom_json_api_request_as_blog
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
3.71
 wpcom_json_api_get_multiple_as_blog
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
5.03
 supports_parallel_requests
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
7.33
 send_multiple
86.36% covered (warning)
86.36%
38 / 44
0.00% covered (danger)
0.00%
0 / 1
14.50
 prepare_http_request
75.96% covered (warning)
75.96%
79 / 104
0.00% covered (danger)
0.00%
0 / 1
30.35
 wait_for_multi_handle
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 _stringify_data
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2/**
3 * The Connection Client class file.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\Constants;
11use WP_Error;
12
13// `wp_remote_request` returns an array with a particular format.
14'@phan-type _WP_Remote_Response_Array = array{headers:\WpOrg\Requests\Utility\CaseInsensitiveDictionary,body:string,response:array{code:int,message:string},cookies:\WP_HTTP_Cookie[],filename:?string,http_response:WP_HTTP_Requests_Response}';
15
16/**
17 * The Client class that is used to connect to WordPress.com Jetpack API.
18 */
19class Client {
20    const WPCOM_JSON_API_VERSION = '1.1';
21
22    /**
23     * Makes an authorized remote request using Jetpack_Signature
24     *
25     * @param array             $args the arguments for the remote request.
26     * @param array|string|null $body the request body.
27     * @return array|WP_Error WP HTTP response on success
28     * @phan-return _WP_Remote_Response_Array|WP_Error
29     */
30    public static function remote_request( $args, $body = null ) {
31        $result = self::sign_remote_request( $args, $body );
32        if ( is_wp_error( $result ) ) {
33            return $result;
34        }
35
36        $response = self::_wp_remote_request( $result['url'], $result['request'] );
37
38        self::report_remote_response( $response, $result );
39
40        return $response;
41    }
42
43    /**
44     * Sign a remote request, reporting a signing failure to the Error_Handler.
45     *
46     * @param array             $args the arguments for the remote request.
47     * @param array|string|null $body the request body.
48     * @return WP_Error|array{url:string,request:array,auth:array,args:array} The signed request, with the filtered `$args` it was built from.
49     */
50    private static function sign_remote_request( $args, $body = null ) {
51        if ( isset( $args['url'] ) ) {
52            /**
53             * Filters the remote request url.
54             *
55             * @since 1.30.12
56             *
57             * @param string The remote request url.
58             */
59            $args['url'] = apply_filters( 'jetpack_remote_request_url', $args['url'] );
60        }
61
62        $result = self::build_signed_request( $args, $body );
63        if ( is_wp_error( $result ) ) {
64            // The request was never made, so it has no response to check. Report the signing
65            // failure; attribution comes from the error itself â€” see
66            // `Error_Handler::check_signed_request_for_errors()`.
67            // Reporting is best-effort and must never fatal a request running mid-plugin-update:
68            // skip it when the already-loaded Error_Handler is a stale version predating this method.
69            if ( method_exists( Error_Handler::class, 'check_signed_request_for_errors' ) ) {
70                Error_Handler::get_instance()->check_signed_request_for_errors(
71                    $result,
72                    empty( $args['url'] ) ? '' : $args['url'],
73                    empty( $args['method'] ) ? 'POST' : $args['method'],
74                    self::remote_request_error_type( $args )
75                );
76            }
77
78            return $result;
79        }
80
81        $result['args'] = $args;
82
83        return $result;
84    }
85
86    /**
87     * Feed a remote response into the outgoing-request error flow and announce it.
88     *
89     * @param array|WP_Error $response The HTTP response.
90     * @param array          $signed   The signed request, from `sign_remote_request()`.
91     * @phan-param _WP_Remote_Response_Array|WP_Error $response
92     */
93    private static function report_remote_response( $response, $signed ) {
94        $args = $signed['args'];
95        $url  = empty( $args['url'] ) ? '' : $args['url'];
96
97        // Feed failures into the outgoing-request error flow of Error_Handler: any known
98        // connection error is stored and surfaced to the user. See the Error_Handler
99        // class docblock for the full picture of both error-handling flows.
100        Error_Handler::get_instance()->check_api_response_for_errors(
101            $response,
102            $signed['auth'],
103            $url,
104            empty( $args['method'] ) ? 'POST' : $args['method'],
105            self::remote_request_error_type( $args )
106        );
107
108        /**
109         * Fired when the remote request response has been received.
110         *
111         * @since 1.30.8
112         *
113         * @param array|WP_Error The HTTP response.
114         */
115        do_action( 'jetpack_received_remote_request_response', $response );
116    }
117
118    /**
119     * Which Error_Handler flow a request belongs to: XML-RPC calls (Jetpack_IXR_Client) go through `remote_request()` too.
120     *
121     * The literals match Error_Handler::ERROR_TYPE_XMLRPC / ERROR_TYPE_REST. Referencing the constants
122     * would fatal mid-update against a stale Error_Handler that predates them.
123     *
124     * @param array $args the arguments for the remote request.
125     * @return string
126     */
127    private static function remote_request_error_type( $args ) {
128        $request_path = (string) wp_parse_url( empty( $args['url'] ) ? '' : $args['url'], PHP_URL_PATH );
129
130        return '/xmlrpc.php' === substr( $request_path, -strlen( '/xmlrpc.php' ) ) ? 'xmlrpc' : 'rest';
131    }
132
133    /**
134     * Adds authorization signature to a remote request using Jetpack_Signature
135     *
136     * @param array             $args the arguments for the remote request.
137     * @param array|string|null $body the request body.
138     * @return WP_Error|array{url:string,request:array,auth:array} {
139     *     An array containing URL and request items.
140     *
141     *     @type string $url     The request URL.
142     *     @type array  $request Request arguments.
143     *     @type array  $auth    Authorization data.
144     * }
145     */
146    public static function build_signed_request( $args, $body = null ) {
147        add_filter(
148            'jetpack_constant_default_value',
149            __NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
150            10,
151            2
152        );
153
154        $defaults = array(
155            'url'           => '',
156            'user_id'       => 0,
157            'blog_id'       => 0,
158            'auth_location' => Constants::get_constant( 'JETPACK_CLIENT__AUTH_LOCATION' ),
159            'method'        => 'POST',
160            'format'        => 'json',
161            'timeout'       => 10,
162            'redirection'   => 0,
163            'headers'       => array(),
164            'stream'        => false,
165            'filename'      => null,
166            'sslverify'     => true,
167        );
168
169        $args = wp_parse_args( $args, $defaults );
170
171        $args['blog_id'] = (int) $args['blog_id'];
172
173        if ( ! self::is_safe_url_path( $args['url'] ) ) {
174            return new WP_Error( 'invalid_request_path', 'The request path contains a dot segment, a fragment or whitespace.' );
175        }
176
177        if ( 'header' !== $args['auth_location'] ) {
178            $args['auth_location'] = 'query_string';
179        }
180
181        // Return the specific reason the token could not be loaded instead of a bare `false`.
182        // Note the returned `WP_Error` is truthy, so this must not be tested with `! $token`.
183        $token = ( new Tokens() )->get_access_token(
184            $args['user_id'],
185            false, // token_key
186            false  // suppress_errors
187        );
188        if ( is_wp_error( $token ) ) {
189            return $token;
190        }
191        if ( ! $token ) {
192            // `get_access_token()` explains itself for every case but one: it returns a bare
193            // `false` when the tokens are locked. That lock is one-shot and self-healing.
194            return new WP_Error( 'tokens_locked' );
195        }
196
197        $method = strtoupper( $args['method'] );
198
199        $timeout = (int) $args['timeout'];
200
201        $redirection = $args['redirection'];
202        $stream      = $args['stream'];
203        $filename    = $args['filename'];
204        $sslverify   = $args['sslverify'];
205
206        $request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
207
208        @list( $token_key, $secret ) = explode( '.', $token->secret ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
209        if ( ! $secret ) {
210            return new WP_Error( 'malformed_token' );
211        }
212
213        $token_key = sprintf(
214            '%s:%d:%d',
215            $token_key,
216            Constants::get_constant( 'JETPACK__API_VERSION' ),
217            $token->external_user_id
218        );
219
220        $time_diff         = (int) \Jetpack_Options::get_option( 'time_diff' );
221        $jetpack_signature = new \Jetpack_Signature( $token->secret, $time_diff );
222
223        $timestamp = time() + $time_diff;
224
225        if ( function_exists( 'wp_generate_password' ) ) {
226            $nonce = wp_generate_password( 10, false );
227        } else {
228            $nonce = substr( sha1( (string) wp_rand( 0, 1000000 ) ), 0, 10 );
229        }
230
231        // Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing.
232        if ( $body === null ) {
233            $body_hash = '';
234
235        } else {
236            // Allow arrays to be used in passing data.
237            $body_to_hash = $body;
238
239            if ( $args['format'] === 'jsonl' ) {
240                parse_str( $body, $body_to_hash );
241            }
242            if ( is_array( $body_to_hash ) ) {
243                // We cast this to a new variable, because the array form of $body needs to be
244                // maintained so it can be passed into the request later on in the code.
245                if ( array() !== $body_to_hash ) {
246                    $body_to_hash = wp_json_encode(
247                        self::_stringify_data( $body_to_hash ),
248                        0 // phpcs:ignore Jetpack.Functions.JsonEncodeFlags.ZeroFound -- No `json_encode()` flags because this needs to match whatever is calculating the hash on the other end.
249                    );
250                } else {
251                    $body_to_hash = '';
252                }
253            }
254
255            if ( ! is_string( $body_to_hash ) ) {
256                return new WP_Error( 'invalid_body', 'Body is malformed.' );
257            }
258            $body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
259        }
260
261        $auth = array(
262            'token'     => $token_key,
263            'timestamp' => $timestamp,
264            'nonce'     => $nonce,
265            'body-hash' => $body_hash,
266        );
267
268        if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
269            $url_args = array(
270                'for'           => 'jetpack',
271                'wpcom_blog_id' => \Jetpack_Options::get_option( 'id' ),
272            );
273        } else {
274            $url_args = array();
275        }
276
277        if ( 'header' !== $args['auth_location'] ) {
278            $url_args += $auth;
279        }
280
281        $url = self::add_query_args( $url_args, $args['url'] );
282
283        $signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
284
285        if ( is_wp_error( $signature ) ) {
286            return $signature;
287        }
288
289        // Send an Authorization header so various caches/proxies do the right thing.
290        $auth['signature'] = $signature;
291        $auth['version']   = Constants::get_constant( 'JETPACK__VERSION' );
292        $header_pieces     = array();
293        foreach ( $auth as $key => $value ) {
294            $header_pieces[] = sprintf( '%s="%s"', $key, $value );
295        }
296        $request['headers'] = array_merge(
297            $args['headers'],
298            array(
299                'Authorization' => 'X_JETPACK ' . implode( ' ', $header_pieces ),
300            )
301        );
302
303        if ( 'header' !== $args['auth_location'] ) {
304            $url = self::add_query_args( array( 'signature' => $signature ), $url );
305        }
306
307        return compact( 'url', 'request', 'auth' );
308    }
309
310    /**
311     * Checks that the part of a URL before its query names one resource, so the transport cannot resolve it to another.
312     *
313     * The HTTP transport removes `.` and `..` segments before it sends the request, and the receiving server can decode `%2e` and `%2f` into them.
314     *
315     * @param string $url The URL.
316     * @return bool False when the path holds a dot segment, literal or encoded, a fragment, or whitespace.
317     */
318    private static function is_safe_url_path( $url ) {
319        $position = strpos( $url, '?' );
320        $path     = false === $position ? $url : substr( $url, 0, $position );
321
322        if ( preg_match( '#[\#\s\x00-\x1f\x7f]#', $path ) ) {
323            return false;
324        }
325
326        return ! preg_match( '#(^|/)\.\.?(/|$)#', rawurldecode( $path ) );
327    }
328
329    /**
330     * Adds arguments to the query string of a URL, keeping each existing key and value with the meaning the caller gave it.
331     *
332     * @param array  $args Unencoded scalar arguments to add. They replace existing arguments with the same name.
333     * @param string $url  The URL.
334     * @return string The URL with the arguments added and every key and value encoded.
335     */
336    private static function add_query_args( $args, $url ) {
337        $fragment = '';
338        $position = strpos( $url, '#' );
339        if ( false !== $position ) {
340            $fragment = substr( $url, $position );
341            $url      = substr( $url, 0, $position );
342        }
343
344        $params   = array();
345        $position = strpos( $url, '?' );
346        if ( false !== $position ) {
347            parse_str( substr( $url, $position + 1 ), $params );
348            $url = substr( $url, 0, $position );
349        }
350
351        foreach ( $args as $key => $value ) {
352            $params[ $key ] = (string) $value;
353        }
354
355        $query = http_build_query( $params, '', '&' );
356
357        return $url . ( '' === $query ? '' : '?' . $query ) . $fragment;
358    }
359
360    /**
361     * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
362     * This is lame, but many, many, many hosts have misconfigured SSL.
363     *
364     * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
365     * 1. a certificate error is found AND
366     * 2. not verifying the certificate works around the problem.
367     *
368     * The option is checked on each request.
369     *
370     * @internal
371     *
372     * @param string  $url the request URL.
373     * @param array   $args request arguments.
374     * @param boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
375     * @return array|WP_Error WP HTTP response on success
376     * @phan-return _WP_Remote_Response_Array|WP_Error
377     */
378    public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
379        $fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
380        if ( false === $fallback ) {
381            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
382        }
383
384        /**
385         * SSL verification (`sslverify`) for the JetpackClient remote request
386         * defaults to off, use this filter to force it on.
387         *
388         * Return `true` to ENABLE SSL verification, return `false`
389         * to DISABLE SSL verification.
390         *
391         * @since 1.7.0
392         * @since-jetpack 3.6.0
393         *
394         * @param bool Whether to force `sslverify` or not.
395         */
396        if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
397            return wp_remote_request( $url, $args );
398        }
399
400        if ( (int) $fallback ) {
401            // We're flagged to fallback.
402            $args['sslverify'] = false;
403        }
404
405        $response = wp_remote_request( $url, $args );
406
407        if (
408            ! $set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens.
409            ||
410            isset( $args['sslverify'] ) && ! $args['sslverify'] // No verification - no point in doing it again.
411            ||
412            ! is_wp_error( $response )                          // Let it ride.
413        ) {
414            self::set_time_diff( $response, $set_fallback );
415            return $response;
416        }
417
418        // At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
419
420        $message = $response->get_error_message();
421
422        // Is it an SSL Certificate verification error?
423        if (
424            false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error.
425            &&
426            false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error.
427            &&
428            false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found.
429            &&
430            false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
431            // Different versions of curl have different error messages
432            // this string should catch them all.
433            &&
434            false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights.
435        ) {
436            // No, it is not.
437            return $response;
438        }
439
440        // Redo the request without SSL certificate verification.
441        $args['sslverify'] = false;
442        $response          = wp_remote_request( $url, $args );
443
444        if ( ! is_wp_error( $response ) ) {
445            // The request went through this time, flag for future fallbacks.
446            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
447            self::set_time_diff( $response, $set_fallback );
448        }
449
450        return $response;
451    }
452
453    /**
454     * Sets the time difference for correct signature computation.
455     *
456     * @param array|WP_Error $response Response array from `wp_remote_request`, or WP_Error on error.
457     * @param bool           $force_set whether to force setting the time difference.
458     * @phan-param _WP_Remote_Response_Array|WP_Error $response
459     */
460    public static function set_time_diff( &$response, $force_set = false ) {
461        $code = wp_remote_retrieve_response_code( $response );
462
463        // Only trust the Date header on some responses.
464        if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) { // phpcs:ignore  Universal.Operators.StrictComparisons.LooseNotEqual
465            return;
466        }
467
468        $date = wp_remote_retrieve_header( $response, 'date' );
469        if ( ! $date ) {
470            return;
471        }
472
473        $time = (int) strtotime( $date );
474        if ( 0 >= $time ) {
475            return;
476        }
477
478        $time_diff = $time - time();
479
480        if ( $force_set ) { // During register.
481            \Jetpack_Options::update_option( 'time_diff', $time_diff );
482        } else { // Otherwise.
483            $old_diff = \Jetpack_Options::get_option( 'time_diff' );
484            if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
485                \Jetpack_Options::update_option( 'time_diff', $time_diff );
486            }
487        }
488    }
489
490    /**
491     * Validate and build arguments for a WordPress.com REST API request.
492     *
493     * @param  string $path             REST API path.
494     * @param  string $version          REST API version. Default is `2`.
495     * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
496     * @param  string $base_api_path    REST API root. Default is `wpcom`.
497     *
498     * @return array Validated arguments.
499     */
500    public static function validate_args_for_wpcom_json_api_request(
501        $path,
502        $version = '2',
503        $args = array(),
504        $base_api_path = 'wpcom'
505    ) {
506        $base_api_path = trim( $base_api_path, '/' );
507        $version       = ltrim( $version, 'v' );
508        $path          = ltrim( $path, '/' );
509
510        $filtered_args = array_intersect_key(
511            $args,
512            array(
513                'headers'     => 'array',
514                'method'      => 'string',
515                'format'      => 'string',
516                'timeout'     => 'int',
517                'redirection' => 'int',
518                'stream'      => 'boolean',
519                'filename'    => 'string',
520                'sslverify'   => 'boolean',
521            )
522        );
523
524        // Use GET by default whereas `remote_request` uses POST.
525        $request_method = isset( $filtered_args['method'] ) ? strtoupper( $filtered_args['method'] ) : 'GET';
526
527        $url = sprintf(
528            '%s/%s/v%s/%s',
529            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
530            $base_api_path,
531            $version,
532            $path
533        );
534
535        $validated_args = array_merge(
536            $filtered_args,
537            array(
538                'url'    => $url,
539                'method' => $request_method,
540            )
541        );
542
543        return $validated_args;
544    }
545
546    /**
547     * Queries the WordPress.com REST API with a user token.
548     *
549     * @param string            $path             REST API path.
550     * @param string            $version          REST API version. Default is `2`.
551     * @param array             $args             Arguments to {@see WP_Http}. Default is `array()`.
552     * @param null|string|array $body             Body passed to {@see WP_Http}. Default is `null`.
553     * @param string            $base_api_path    REST API root. Default is `wpcom`.
554     *
555     * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
556     * @phan-return _WP_Remote_Response_Array|WP_Error
557     */
558    public static function wpcom_json_api_request_as_user(
559        $path,
560        $version = '2',
561        $args = array(),
562        $body = null,
563        $base_api_path = 'wpcom'
564    ) {
565        $args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
566        $args['user_id'] = get_current_user_id();
567
568        if ( isset( $body ) && ! isset( $args['headers'] ) && in_array( $args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
569            $args['headers'] = array( 'Content-Type' => 'application/json' );
570        }
571
572        if ( isset( $body ) && ! is_string( $body ) ) {
573            $body = wp_json_encode( $body, JSON_UNESCAPED_SLASHES );
574        }
575
576        return self::remote_request( $args, $body );
577    }
578
579    /**
580     * Query the WordPress.com REST API using the blog token
581     *
582     * @param string            $path The API endpoint relative path.
583     * @param string            $version The API version.
584     * @param array             $args Request arguments.
585     * @param array|string|null $body Request body.
586     * @param string            $base_api_path (optional) the API base path override, defaults to 'rest'.
587     * @return array|WP_Error $response Data.
588     * @phan-return _WP_Remote_Response_Array|WP_Error
589     */
590    public static function wpcom_json_api_request_as_blog(
591        $path,
592        $version = self::WPCOM_JSON_API_VERSION,
593        $args = array(),
594        $body = null,
595        $base_api_path = 'rest'
596    ) {
597        $validated_args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
598        $validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
599
600        // For Simple sites get the response directly without any HTTP requests.
601        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
602            add_filter( 'is_jetpack_authorized_for_site', '__return_true' );
603            require_lib( 'wpcom-api-direct' );
604            return \WPCOM_API_Direct::do_request( $validated_args, $body );
605        }
606
607        return self::remote_request( $validated_args, $body );
608    }
609
610    /**
611     * Query several WordPress.com REST API endpoints at once using the blog token, sending the GETs in parallel.
612     *
613     * Each request is signed, filtered, proxied and reported like one sent through `wpcom_json_api_request_as_blog()`.
614     *
615     * @since $$next-version$$
616     *
617     * @param array $requests Requests keyed by the caller: `path`, and optionally `version`, `args` and `base_api_path`
618     *                        as `wpcom_json_api_request_as_blog()` takes them. The method is always GET.
619     * @return array Responses (array or WP_Error) keyed like `$requests`.
620     * @phan-param array<array-key,array{path:string,version?:string,args?:array,base_api_path?:string}> $requests
621     * @phan-return array<array-key,_WP_Remote_Response_Array|WP_Error>
622     */
623    public static function wpcom_json_api_get_multiple_as_blog( array $requests ) {
624        $responses = array();
625        $serial    = ! self::supports_parallel_requests();
626
627        $signed = array();
628        foreach ( $requests as $key => $request ) {
629            $version = $request['version'] ?? self::WPCOM_JSON_API_VERSION;
630            $base    = $request['base_api_path'] ?? 'rest';
631            $args    = array_merge( $request['args'] ?? array(), array( 'method' => 'GET' ) );
632
633            if ( $serial ) {
634                $responses[ $key ] = self::wpcom_json_api_request_as_blog( $request['path'], $version, $args, null, $base );
635                continue;
636            }
637
638            $validated_args            = self::validate_args_for_wpcom_json_api_request( $request['path'], $version, $args, $base );
639            $validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
640
641            $result = self::sign_remote_request( $validated_args );
642            if ( is_wp_error( $result ) ) {
643                $responses[ $key ] = $result;
644            } else {
645                $signed[ $key ] = $result;
646            }
647        }
648
649        foreach ( self::send_multiple( $signed ) as $key => $response ) {
650            self::report_remote_response( $response, $signed[ $key ] );
651            $responses[ $key ] = $response;
652        }
653
654        // Callers read results by key, but keep the order they asked in too.
655        return array_replace( array_intersect_key( $requests, $responses ), $responses );
656    }
657
658    /**
659     * Whether `wpcom_json_api_get_multiple_as_blog()` sends its requests in parallel here, rather than one by one.
660     *
661     * @since $$next-version$$
662     *
663     * @return bool
664     */
665    public static function supports_parallel_requests() {
666        if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) || ! class_exists( \WpOrg\Requests\Transport\Curl::class ) ) {
667            return false;
668        }
669
670        // Hosts disable these individually, and Requests picks cURL on `curl_exec` alone.
671        foreach ( array( 'curl_multi_init', 'curl_multi_exec', 'curl_multi_select', 'curl_multi_info_read' ) as $function ) {
672            if ( ! function_exists( $function ) ) {
673                return false;
674            }
675        }
676
677        return \WpOrg\Requests\Transport\Curl::test( array( 'ssl' => true ) );
678    }
679
680    /**
681     * Send signed requests at once, as `_wp_remote_request()` and `WP_Http::request()` would send each of them.
682     *
683     * @param array $signed Signed requests from `sign_remote_request()`, keyed by the caller.
684     * @return array Responses (array or WP_Error) keyed like `$signed`.
685     * @phan-return array<array-key,_WP_Remote_Response_Array|WP_Error>
686     */
687    private static function send_multiple( array $signed ) {
688        if ( ! $signed ) {
689            return array();
690        }
691
692        $fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
693        if ( false === $fallback ) {
694            \Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
695        }
696        /** This filter is documented in `_wp_remote_request()` above. */
697        $force_verify = apply_filters( 'jetpack_client_verify_ssl_certs', false );
698
699        $responses = array();
700        $queued    = array();
701        foreach ( $signed as $key => $request ) {
702            $args = $request['request'];
703            if ( ! $force_verify && (int) $fallback ) {
704                $args['sslverify'] = false;
705            }
706
707            $prepared = self::prepare_http_request( $request['url'], $args );
708            if ( isset( $prepared['response'] ) ) {
709                $responses[ $key ] = $prepared['response'];
710            } elseif ( ! empty( $prepared['serial'] ) ) {
711                // Arguments the parallel path cannot honour; the filters run again on this rare path.
712                $responses[ $key ] = self::_wp_remote_request( $request['url'], $args );
713            } else {
714                $queued[ $key ] = $prepared;
715            }
716        }
717
718        if ( $queued ) {
719            mbstring_binary_safe_encoding();
720            try {
721                $results = \WpOrg\Requests\Requests::request_multiple(
722                    array_map(
723                        static function ( $prepared ) {
724                            return $prepared['request'];
725                        },
726                        $queued
727                    )
728                );
729            } catch ( \WpOrg\Requests\Exception $e ) {
730                // As `WP_Http::request()` does; here every request in the call fails with it.
731                $results = array_fill_keys( array_keys( $queued ), $e );
732            } finally {
733                reset_mbstring_encoding();
734            }
735
736            foreach ( $queued as $key => $prepared ) {
737                $result = $results[ $key ] ?? null;
738                if ( $result instanceof \WpOrg\Requests\Response ) {
739                    $http_response             = new \WP_HTTP_Requests_Response( $result );
740                    $response                  = $http_response->to_array();
741                    $response['http_response'] = $http_response;
742                } else {
743                    $response = new WP_Error( 'http_request_failed', $result instanceof \Exception ? $result->getMessage() : '' );
744                }
745
746                /** This action is documented in wp-includes/class-wp-http.php */
747                do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $prepared['parsed_args'], $prepared['url'] );
748                if ( ! is_wp_error( $response ) ) {
749                    /** This filter is documented in wp-includes/class-wp-http.php */
750                    $response = apply_filters( 'http_response', $response, $prepared['parsed_args'], $prepared['url'] );
751                }
752
753                self::set_time_diff( $response );
754                $responses[ $key ] = $response;
755            }
756        }
757
758        return array_replace( array_intersect_key( $signed, $responses ), $responses );
759    }
760
761    /**
762     * Run a GET through `WP_Http::request()`'s preparation: its defaults and filters, the URL and
763     * external-request checks, SSL and proxy settings.
764     *
765     * @param string $url  The signed request URL.
766     * @param array  $args The signed request arguments.
767     * @return array Either `response` (a short-circuited response or error), or the Requests `request` to send
768     *               with the `url` and `parsed_args` the WordPress HTTP hooks receive.
769     */
770    private static function prepare_http_request( $url, array $args ) {
771        $defaults = array(
772            'method'              => 'GET',
773            /** This filter is documented in wp-includes/class-wp-http.php */
774            'timeout'             => apply_filters( 'http_request_timeout', 5, $url ),
775            /** This filter is documented in wp-includes/class-wp-http.php */
776            'redirection'         => apply_filters( 'http_request_redirection_count', 5, $url ),
777            /** This filter is documented in wp-includes/class-wp-http.php */
778            'httpversion'         => apply_filters( 'http_request_version', '1.0', $url ),
779            /** This filter is documented in wp-includes/class-wp-http.php */
780            'user-agent'          => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $url ),
781            /** This filter is documented in wp-includes/class-wp-http.php */
782            'reject_unsafe_urls'  => apply_filters( 'http_request_reject_unsafe_urls', false, $url ),
783            'blocking'            => true,
784            'headers'             => array(),
785            'cookies'             => array(),
786            'compress'            => false,
787            'decompress'          => true,
788            'stream'              => false,
789            'filename'            => null,
790            'sslverify'           => true,
791            'sslcertificates'     => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
792            'limit_response_size' => null,
793        );
794
795        $parsed_args = wp_parse_args( $args, $defaults );
796        /** This filter is documented in wp-includes/class-wp-http.php */
797        $parsed_args = apply_filters( 'http_request_args', $parsed_args, $url );
798        if ( ! isset( $parsed_args['_redirection'] ) ) {
799            $parsed_args['_redirection'] = $parsed_args['redirection'];
800        }
801
802        /** This filter is documented in wp-includes/class-wp-http.php */
803        $pre = apply_filters( 'pre_http_request', false, $parsed_args, $url );
804        if ( false !== $pre ) {
805            return array( 'response' => $pre );
806        }
807
808        if ( $parsed_args['reject_unsafe_urls'] ) {
809            $url = wp_http_validate_url( $url );
810        }
811        if ( $url ) {
812            $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
813        }
814
815        $error = null;
816        if ( empty( $url ) || ! wp_parse_url( $url, PHP_URL_SCHEME ) ) {
817            $error = new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.', 'jetpack-connection' ) );
818        } elseif ( _wp_http_get_object()->block_request( $url ) ) {
819            /* translators: %s: URL to which the HTTP request was blocked. */
820            $error = new WP_Error( 'http_request_not_executed', sprintf( __( 'User has blocked requests through HTTP to the URL: %s.', 'jetpack-connection' ), $url ) );
821        }
822        if ( $error ) {
823            /** This action is documented in wp-includes/class-wp-http.php */
824            do_action( 'http_api_debug', $error, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url );
825            return array( 'response' => $error );
826        }
827
828        if ( $parsed_args['stream'] || ! $parsed_args['blocking'] || ! empty( $parsed_args['cookies'] ) ) {
829            return array( 'serial' => true );
830        }
831        if ( ! is_array( $parsed_args['headers'] ) ) {
832            $parsed_args['headers'] = \WP_Http::processHeaders( (string) $parsed_args['headers'] )['headers'];
833        }
834
835        $hooks   = new \WP_HTTP_Requests_Hooks( $url, $parsed_args );
836        $options = array(
837            'timeout'   => $parsed_args['timeout'],
838            'useragent' => $parsed_args['user-agent'],
839            'blocking'  => true,
840            'hooks'     => $hooks,
841        );
842        if ( empty( $parsed_args['redirection'] ) ) {
843            $options['follow_redirects'] = false;
844        } else {
845            $options['redirects'] = $parsed_args['redirection'];
846            $hooks->register( 'requests.before_redirect', array( \WP_Http::class, 'browser_redirect_compatibility' ) );
847            if ( $parsed_args['reject_unsafe_urls'] ) {
848                $hooks->register( 'requests.before_redirect', array( \WP_Http::class, 'validate_redirects' ) );
849            }
850        }
851        if ( isset( $parsed_args['limit_response_size'] ) ) {
852            $options['max_bytes'] = $parsed_args['limit_response_size'];
853        }
854        if ( ! $parsed_args['sslverify'] ) {
855            $options['verify']     = false;
856            $options['verifyname'] = false;
857        } else {
858            $options['verify'] = $parsed_args['sslcertificates'];
859        }
860        /** This filter is documented in wp-includes/class-wp-http.php */
861        $options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url );
862
863        $proxy = new \WP_HTTP_Proxy();
864        if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
865            $options['proxy'] = new \WpOrg\Requests\Proxy\Http( $proxy->host() . ':' . $proxy->port() );
866            if ( $proxy->use_authentication() ) {
867                $options['proxy']->use_authentication = true;
868                $options['proxy']->user               = $proxy->username();
869                $options['proxy']->pass               = $proxy->password();
870            }
871        }
872
873        // cURL's multi path skips `curl.before_send`, where Requests applies the proxy and WordPress fires
874        // `http_api_curl`, and the SSL options its single path sets; apply both per handle.
875        $verify     = $options['verify'];
876        $verifyname = $options['verifyname'] ?? true;
877        $hooks->register(
878            'curl.before_multi_add',
879            static function ( &$handle ) use ( $hooks, $verify, $verifyname ) {
880                if ( false === $verify ) {
881                    curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, 0 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
882                    curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, 0 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
883                } elseif ( is_string( $verify ) ) {
884                    curl_setopt( $handle, CURLOPT_CAINFO, $verify ); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
885                }
886                if ( ! $verifyname ) {
887                    curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, 0 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
888                }
889                $hooks->dispatch( 'curl.before_send', array( &$handle ) );
890            }
891        );
892
893        // Requests' own multi loop spins on `curl_multi_exec()`; wait on the sockets first, leaving the
894        // finished transfers for that loop to collect. Only the last request's hooks see this event.
895        $hooks->register(
896            'curl.before_multi_exec',
897            static function ( &$multihandle ) {
898                self::wait_for_multi_handle( $multihandle );
899            }
900        );
901
902        // Fired by `Requests::request()` but not by `request_multiple()`; Server_Sandbox reroutes here.
903        $headers = (array) ( $parsed_args['headers'] ?? array() );
904        $data    = array();
905        $type    = 'GET';
906        $hooks->dispatch( 'requests.before_request', array( &$url, &$headers, &$data, &$type, &$options ) );
907
908        return array(
909            'url'         => $url,
910            'parsed_args' => $parsed_args,
911            'request'     => array(
912                'url'     => $url,
913                'headers' => $headers,
914                'data'    => $data,
915                'type'    => $type,
916                'options' => $options,
917            ),
918        );
919    }
920
921    /**
922     * Run a cURL multi handle until its transfers finish, sleeping on the sockets between bursts.
923     *
924     * @param resource|\CurlMultiHandle $multihandle The multi handle.
925     */
926    private static function wait_for_multi_handle( $multihandle ) {
927        do {
928            do {
929                $status = curl_multi_exec( $multihandle, $active ); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_multi_exec
930            } while ( CURLM_CALL_MULTI_PERFORM === $status );
931
932            // `curl_multi_select()` returns -1 on some builds instead of waiting.
933            if ( $active && -1 === curl_multi_select( $multihandle, 1.0 ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_multi_select
934                usleep( 10000 );
935            }
936        } while ( $active && CURLM_OK === $status );
937    }
938
939    /**
940     * Takes an array or similar structure and recursively turns all values into strings. This is used to
941     * make sure that body hashes are made ith the string version, which is what will be seen after a
942     * server pulls up the data in the $_POST array.
943     *
944     * @param mixed $data the data that needs to be stringified.
945     *
946     * @return array|string
947     */
948    public static function _stringify_data( $data ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
949
950        // Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
951        if ( is_bool( $data ) ) {
952            return $data ? '1' : '0';
953        }
954
955        // Cast objects into arrays.
956        if ( is_object( $data ) ) {
957            $data = (array) $data;
958        }
959
960        // Non arrays at this point should be just converted to strings.
961        if ( ! is_array( $data ) ) {
962            return (string) $data;
963        }
964
965        foreach ( $data as &$value ) {
966            $value = self::_stringify_data( $value );
967        }
968
969        return $data;
970    }
971}