diff --git a/src/wp-includes/class-wp-http-curl.php b/src/wp-includes/class-wp-http-curl.php index 4296bf42f2b00..cb6a9ac6056c4 100644 --- a/src/wp-includes/class-wp-http-curl.php +++ b/src/wp-includes/class-wp-http-curl.php @@ -228,6 +228,7 @@ public function request( $url, $args = array() ) { * plugins to handle cookies themselves. * * @since 2.8.0 + * @since 7.3.0 Also fires for each request sent by {@see WP_Http::request_multiple()}. * * @param resource $handle The cURL handle returned by curl_init() (passed by reference). * @param array $parsed_args The HTTP request arguments. diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index 39e9ecb99797d..d19532eb855ab 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -38,6 +38,55 @@ * filename?: string|null, * http_response?: WP_HTTP_Requests_Response|null, * } + * @phpstan-type HTTP_Request_Args array{ + * method?: string, + * timeout?: float|int, + * redirection?: int, + * httpversion?: string, + * 'user-agent'?: string, + * reject_unsafe_urls?: bool, + * blocking?: bool, + * headers?: string|mixed[]|null, + * cookies?: mixed[], + * body?: string|mixed[]|null, + * compress?: bool, + * decompress?: bool, + * sslverify?: bool, + * sslcertificates?: string, + * stream?: bool, + * filename?: string|null, + * limit_response_size?: int|null, + * ... + * } + * @phpstan-type Parsed_HTTP_Request_Args array{ + * method: string, + * timeout: float|int, + * redirection: int, + * httpversion: string, + * 'user-agent': string, + * reject_unsafe_urls: bool, + * blocking: bool, + * headers: string|mixed[]|null, + * cookies: mixed[], + * body: string|mixed[]|null, + * compress: bool, + * decompress: bool, + * sslverify: bool, + * sslcertificates: string, + * stream: bool, + * filename: string|null, + * limit_response_size: int|null, + * _redirection: int, + * ... + * } + * @phpstan-type Prepared_Request array{ + * url: string, + * headers: mixed[], + * data: mixed, + * type: mixed, + * options: array, + * args: Parsed_HTTP_Request_Args, + * } */ #[AllowDynamicProperties] class WP_Http { @@ -176,9 +225,506 @@ class WP_Http { * @type WP_HTTP_Requests_Response|null $http_response Response object. * } * + * @phpstan-param string|HTTP_Request_Args $args * @phpstan-return HTTP_Response|WP_Error */ public function request( $url, $args = array() ) { + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } + + $prepared = $this->prepare_request( $url, $args ); + + if ( is_wp_error( $prepared ) ) { + return $prepared; + } + + // The request was short-circuited by the 'pre_http_request' filter. + if ( array_key_exists( 'response', $prepared ) ) { + return $prepared['response']; + } + + // Avoid issues where mbstring.func_overload is enabled. + mbstring_binary_safe_encoding(); + + try { + $response = WpOrg\Requests\Requests::request( + $prepared['url'], + $prepared['headers'], + $prepared['data'], + $prepared['type'], + $prepared['options'] + ); + } catch ( WpOrg\Requests\Exception $e ) { + $response = new WP_Error( 'http_request_failed', $e->getMessage() ); + } finally { + reset_mbstring_encoding(); + } + + return $this->finalize_response( $response, $prepared['args'], $prepared['url'] ); + } + + /** + * Sends multiple HTTP requests concurrently and returns their responses. + * + * Every request is prepared, and its response processed, like a request sent through + * WP_Http::request(): the 'http_request_args', 'pre_http_request' and 'http_response' + * filters and the 'http_api_debug' action apply to each request individually, and a + * request that fails does not affect the others. + * + * The requests that were not short-circuited are then sent in groups of at most + * $concurrency requests. The requests of a group are sent side by side with the cURL + * transport, and the next group is sent once all requests of the group have finished. + * Without cURL, the requests are sent one after the other. + * + * Non-blocking requests are not supported: every request is performed in full. + * + * @since 7.3.0 + * + * @see WP_Http::request() For the accepted request arguments and the response format. + * + * @param array $requests Requests to send, keyed by an identifier of the caller's choosing. + * Each request is either a URL string, for a GET request with the + * default arguments, or an array with the request URL under 'url' + * and, optionally, the request arguments under 'args'. + * See {@see WP_Http::request()} for the accepted request arguments. + * @param array $options { + * Optional. Options that apply to the batch of requests. + * + * @type int $concurrency Maximum number of requests to send at once. Default 6. Minimum 1. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error + * on failure. See {@see WP_Http::request()} for the response format. + * A value returned by the {@see 'pre_http_request'} filter to short-circuit + * a request is passed through unchanged. + * @phpstan-param array $requests + * @phpstan-return array + */ + public function request_multiple( array $requests, array $options = array() ): array { + $responses = array(); + $pending = array(); + + foreach ( $requests as $id => $request ) { + if ( ! is_array( $request ) ) { + $request = array( 'url' => $request ); + } + + $url = $request['url'] ?? ''; + $args = $request['args'] ?? array(); + + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } + + // Batches cannot send non-blocking requests, each request is performed in full. + $args['blocking'] = true; + + $prepared = $this->prepare_request( $url, $args ); + + if ( is_wp_error( $prepared ) ) { + $responses[ $id ] = $prepared; + } elseif ( array_key_exists( 'response', $prepared ) ) { + // The request was short-circuited by the 'pre_http_request' filter. + $responses[ $id ] = $prepared['response']; + } else { + $pending[ $id ] = $prepared; + } + } + + if ( ! empty( $pending ) ) { + $concurrency = max( 1, (int) ( $options['concurrency'] ?? 6 ) ); + + /** + * Filters the maximum number of HTTP requests that WP_Http::request_multiple() sends at once. + * + * @since 7.3.0 + * + * @param int $concurrency Maximum number of requests to send at once. Default 6. Minimum 1. + * @param array $requests The requests to send. See WP_Http::request_multiple(). + * @phpstan-param positive-int $concurrency + * @phpstan-param array $requests + */ + $concurrency = (int) apply_filters( 'http_request_multiple_concurrency', $concurrency, $requests ); + $concurrency = max( 1, $concurrency ); + + foreach ( array_chunk( $pending, $concurrency, true ) as $batch ) { + $results = array(); + $batch_requests = array(); + + // Avoid issues where mbstring.func_overload is enabled. + mbstring_binary_safe_encoding(); + + try { + $stream_files = array(); + + foreach ( $batch as $id => $prepared ) { + try { + $batch_request = $this->prepare_batch_request( $prepared, $stream_files ); + } catch ( WpOrg\Requests\Exception $e ) { + // Fail this request only, as Requests::request() would. + $results[ $id ] = $e; + continue; + } + + $batch_requests[ $id ] = $batch_request; + } + + if ( ! empty( $batch_requests ) ) { + /** @var array<\WpOrg\Requests\Response|\WpOrg\Requests\Exception> $batch_results */ + $batch_results = WpOrg\Requests\Requests::request_multiple( $batch_requests ); + $results = $batch_results + $results; + + foreach ( $batch_results as $id => $result ) { + if ( self::should_retry_batch_request( $result ) ) { + $results[ $id ] = self::retry_batch_request( $batch_requests[ $id ] ); + } + } + } + } catch ( WpOrg\Requests\Exception $e ) { + /* + * The batch failed as a whole. Its requests may already have been sent, + * so do not send them again: report the error for each of them instead. + */ + foreach ( $batch as $id => $prepared ) { + if ( ! isset( $results[ $id ] ) ) { + $results[ $id ] = $e; + } + } + } finally { + reset_mbstring_encoding(); + + /* + * The cURL handles of a batch and the objects of the Requests library that + * own them reference each other, so they, and the files that failed requests + * were streaming to, are only released by the cycle collector. + */ + gc_collect_cycles(); + } + + foreach ( $batch as $id => $prepared ) { + if ( isset( $results[ $id ] ) ) { + $result = $results[ $id ]; + } else { + $result = new WP_Error( 'http_request_failed', __( 'No response was received.' ) ); + } + + $responses[ $id ] = $this->finalize_response( $result, $prepared['args'], $prepared['url'] ); + } + } + } + + // Return the responses in the order the requests were given. + $ordered = array(); + + foreach ( $requests as $id => $request ) { + $ordered[ $id ] = $responses[ $id ]; + } + + return $ordered; + } + + /** + * Prepares a request of a batch for Requests::request_multiple(). + * + * Requests::request() normalizes a single request, lets its cookie jar add the Cookie + * header and fires the 'requests.before_request' hook before sending it, but + * Requests::request_multiple() only normalizes the requests of a batch, all at once, + * and fails the whole batch if one of them cannot be. Do the same as Requests::request() + * here, for each request on its own, so that the requests of a batch are sent like + * requests sent on their own, and that a request that cannot be sent fails on its own. + * + * @since 7.3.0 + * + * @param array $prepared The prepared request, see {@see WP_Http::prepare_request()}. + * @param string[] $stream_files The files that other requests of the batch stream to. + * The file of this request is added to it. + * @return array { + * The request, for Requests::request_multiple(). + * + * @type string $url The request URL. + * @type array $headers Request headers. + * @type mixed $data Request body. + * @type string $type Request method. + * @type array $options Options for the Requests library. + * } + * @phpstan-param Prepared_Request $prepared + * @phpstan-return array{ url: string, headers: mixed[], data: mixed, type: string, options: array } + * + * @throws WpOrg\Requests\Exception When the request cannot be sent. + */ + private function prepare_batch_request( array $prepared, array &$stream_files ): array { + $url = $prepared['url']; + $headers = $prepared['headers']; + $data = $prepared['data']; + $type = (string) $prepared['type']; + $options = $prepared['options']; + + // Mirror WpOrg\Requests\Requests::request() and Requests::set_defaults(). + if ( empty( $options['type'] ) ) { + $options['type'] = $type; + } + + $options = array_merge( WpOrg\Requests\Requests::OPTION_DEFAULTS, $options ); + $url = self::normalize_batch_url( $url, $options ); + $type = strtoupper( $type ); + + if ( ! isset( $options['data_format'] ) ) { + $options['data_format'] = in_array( $type, array( WpOrg\Requests\Requests::HEAD, WpOrg\Requests\Requests::GET, WpOrg\Requests\Requests::DELETE ), true ) ? 'query' : 'body'; + } + + if ( $options['cookies'] instanceof WpOrg\Requests\Cookie\Jar ) { + $options['cookies']->before_request( $url, $headers, $data, $type, $options ); + } + + $options['hooks']->dispatch( 'requests.before_request', array( &$url, &$headers, &$data, &$type, &$options ) ); + + /* + * Requests::request_multiple() normalizes the URL again, and would fail the whole + * batch if the hook changed it into one that cannot be normalized. + */ + $url = self::normalize_batch_url( $url, $options ); + + if ( ! empty( $options['filename'] ) ) { + $filename = self::check_batch_stream_file( $options['filename'], $stream_files ); + + $stream_files[] = $filename; + } + + $this->register_batch_hooks( $options ); + + return array( + 'url' => $url, + 'headers' => $headers, + 'data' => $data, + 'type' => $type, + 'options' => $options, + ); + } + + /** + * Normalizes the URL of a request of a batch like Requests::set_defaults() does. + * + * @since 7.3.0 + * + * @param mixed $url The request URL. + * @param array $options Options for the Requests library. + * @return string The normalized URL. + * + * @throws WpOrg\Requests\Exception When the URL is not an HTTP(S) URL, or its host cannot be encoded. + */ + private static function normalize_batch_url( $url, array $options ): string { + if ( $url instanceof Stringable ) { + $url = (string) $url; + } + + if ( ! is_string( $url ) || ! preg_match( '/^http(s)?:\/\//i', $url ) ) { + throw new WpOrg\Requests\Exception( 'Only HTTP(S) requests are handled.', 'nonhttp', $url ); + } + + if ( false !== $options['idn'] ) { + $iri = new WpOrg\Requests\Iri( $url ); + $iri->host = WpOrg\Requests\IdnaEncoder::encode( $iri->ihost ); + $url = (string) $iri->uri; + } + + return $url; + } + + /** + * Checks that a request of a batch can stream its response to a file. + * + * The Requests library does not check whether it could open the file for the requests of + * a batch, and would report success without writing the file. Check it here instead, with + * the same error that Requests::request() would throw. Requests of the same batch that + * stream to the same file would also corrupt it, as they are written at the same time. + * + * @since 7.3.0 + * + * @param string $filename The file to stream the response to. + * @param string[] $stream_files The normalized paths of the files that other requests of the batch stream to. + * @return string The normalized path of the file. + * + * @throws WpOrg\Requests\Exception When the file cannot be used. + */ + private static function check_batch_stream_file( string $filename, array $stream_files ): string { + $directory = realpath( dirname( $filename ) ); + $normalized = ( false === $directory ) ? $filename : $directory . DIRECTORY_SEPARATOR . basename( $filename ); + + if ( in_array( $normalized, $stream_files, true ) ) { + throw new WpOrg\Requests\Exception( + sprintf( 'Another request of the batch streams to the same file: %s', $filename ), + 'fopen' + ); + } + + $existed = file_exists( $filename ); + + // Open the file without truncating it, as the request may still fail before it is sent. + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The error is thrown instead. + $handle = @fopen( $filename, 'ab' ); + + if ( false === $handle ) { + $error = error_get_last(); + + throw new WpOrg\Requests\Exception( $error['message'] ?? sprintf( 'Could not open %s for writing.', $filename ), 'fopen' ); + } + + fclose( $handle ); + + if ( ! $existed ) { + unlink( $filename ); + } + + return $normalized; + } + + /** + * Registers the hooks that make up for the differences between sending a request + * on its own and as part of a batch. + * + * For a single request, the cURL transport of the Requests library fires the + * 'curl.before_send' hook, through which the proxy settings are applied and the + * {@see 'http_api_curl'} action fires, applies the SSL verification settings, and + * fires the 'curl.after_send' hook. Requests::request() then fires the + * 'requests.before_parse' hook. For the requests of a batch, none of that happens. + * + * @since 7.3.0 + * + * @param array $options Options for the Requests library, see {@see WP_Http::prepare_request()}. + */ + private function register_batch_hooks( array $options ): void { + $hooks = $options['hooks']; + + if ( ! $hooks instanceof WpOrg\Requests\HookManager ) { + return; + } + + /* + * A later version of the Requests library may fire 'curl.before_send' for the requests + * of a batch, before 'curl.before_multi_add'. Only fire it here if it has not fired yet. + */ + $before_send_fired = false; + $sent_with_curl = false; + + $hooks->register( + 'curl.before_send', + static function () use ( &$before_send_fired ) { + $before_send_fired = true; + } + ); + + $hooks->register( + 'curl.before_multi_add', + static function ( &$handle ) use ( &$before_send_fired, &$sent_with_curl, $hooks, $options ) { + $sent_with_curl = true; + + if ( ! $before_send_fired ) { + $hooks->dispatch( 'curl.before_send', array( &$handle ) ); + } + + // Mirror WpOrg\Requests\Transport\Curl::request(). + if ( isset( $options['verify'] ) ) { + if ( false === $options['verify'] ) { + curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, 0 ); + curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, false ); + } elseif ( is_string( $options['verify'] ) ) { + curl_setopt( $handle, CURLOPT_CAINFO, $options['verify'] ); + } + } + + if ( isset( $options['verifyname'] ) && false === $options['verifyname'] ) { + curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, 0 ); + } + } + ); + + /* + * Requests::request_multiple() parses the response in this hook. Registered before it, + * at the same priority, this callback runs first, with the raw response. + */ + $hooks->register( + 'transport.internal.parse_response', + static function ( &$response, $request ) use ( &$sent_with_curl, $hooks ) { + if ( $sent_with_curl ) { + $hooks->dispatch( 'curl.after_send', array() ); + } + + $hooks->dispatch( + 'requests.before_parse', + array( &$response, $request['url'], $request['headers'], $request['data'], $request['type'], $request['options'] ) + ); + } + ); + } + + /** + * Determines whether a request of a batch should be sent again. + * + * For a single request, the cURL transport of the Requests library sends the request + * again without compression when the response cannot be decompressed or written, but + * not for the requests of a batch. + * + * @since 7.3.0 + * + * @param mixed $result The result of the request. + * @return bool Whether to send the request again. + */ + private static function should_retry_batch_request( $result ): bool { + return $result instanceof WpOrg\Requests\Exception\Transport\Curl + && WpOrg\Requests\Exception\Transport\Curl::EASY === $result->getType() + && in_array( $result->getCode(), array( CURLE_WRITE_ERROR, CURLE_BAD_CONTENT_ENCODING ), true ); + } + + /** + * Sends a request of a batch again, on its own. + * + * @since 7.3.0 + * + * @param array $request The request, as sent to Requests::request_multiple(). + * @return WpOrg\Requests\Response|WpOrg\Requests\Exception The response, or the error the request failed with. + * @phpstan-param array{ url: string, headers: mixed[], data: mixed, type: string, options: array } $request + */ + private static function retry_batch_request( array $request ) { + try { + return WpOrg\Requests\Requests::request( + $request['url'], + $request['headers'], + $request['data'], + $request['type'], + $request['options'] + ); + } catch ( WpOrg\Requests\Exception $e ) { + return $e; + } + } + + /** + * Prepares a request for the Requests library. + * + * Parses and filters the request arguments, lets the 'pre_http_request' filter + * short-circuit the request, validates the URL, checks whether the request is + * blocked, and translates the arguments into options for the Requests library. + * + * @since 7.3.0 + * + * @param string $url The request URL. + * @param array $args Optional. Request arguments. See {@see WP_Http::request()}. + * @return array|WP_Error { + * The prepared request, or a WP_Error if the request cannot be sent. If the request was + * short-circuited by the 'pre_http_request' filter, only the 'response' key is present. + * + * @type string $url The validated request URL. + * @type array $headers Request headers. + * @type mixed $data Request body. + * @type string $type Request method. + * @type array $options Options for the Requests library. + * @type array $args The parsed request arguments, after the 'http_request_args' filter. + * @type array|WP_Error $response Optional. The response returned by the 'pre_http_request' filter. + * } + * @phpstan-param HTTP_Request_Args $args + * @phpstan-return Prepared_Request|array{ response: HTTP_Response|WP_Error }|WP_Error + */ + private function prepare_request( $url, array $args = array() ) { $defaults = array( 'method' => 'GET', /** @@ -244,9 +790,6 @@ public function request( $url, $args = array() ) { 'limit_response_size' => null, ); - // Pre-parse for the HEAD checks. - $args = wp_parse_args( $args ); - // By default, HEAD requests do not cause redirections. if ( isset( $args['method'] ) && 'HEAD' === $args['method'] ) { $defaults['redirection'] = 0; @@ -285,11 +828,14 @@ public function request( $url, $args = array() ) { * @param false|array|WP_Error $response A preemptive return value of an HTTP request. Default false. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. + * @phpstan-param false|HTTP_Response|WP_Error $response */ $pre = apply_filters( 'pre_http_request', false, $parsed_args, $url ); if ( false !== $pre ) { - return $pre; + return array( + 'response' => $pre, + ); } if ( function_exists( 'wp_kses_bad_protocol' ) ) { @@ -421,24 +967,56 @@ public function request( $url, $args = array() ) { } } - // Avoid issues where mbstring.func_overload is enabled. - mbstring_binary_safe_encoding(); + return array( + 'url' => $url, + 'headers' => $headers, + 'data' => $data, + 'type' => $type, + 'options' => $options, + 'args' => $parsed_args, + ); + } - try { - $requests_response = WpOrg\Requests\Requests::request( $url, $headers, $data, $type, $options ); + /** + * Turns the result of a request into a WP_Http response array. + * + * Fires the 'http_api_debug' action and applies the 'http_response' filter. + * + * @since 7.3.0 + * + * @param \WpOrg\Requests\Response|\WpOrg\Requests\Exception|WP_Error $response The response, or the error the + * request failed with. + * @param mixed[] $parsed_args The parsed request arguments, as + * returned by {@see WP_Http::prepare_request()}. + * @param string $url The request URL. + * @return array|WP_Error The response array, or a WP_Error on failure. See {@see WP_Http::request()}. + * @phpstan-param Parsed_HTTP_Request_Args $parsed_args + * @phpstan-return HTTP_Response|WP_Error + */ + private function finalize_response( $response, array $parsed_args, string $url ) { + if ( $response instanceof WpOrg\Requests\Exception\Transport\Curl && WpOrg\Requests\Exception\Transport\Curl::EASY === $response->getType() ) { + /* + * The cURL transport reports the errors of the requests of a batch as + * "28 Operation timed out", but those of a single request as + * "cURL error 28: Operation timed out". Use the latter for both. + */ + $response = new WP_Error( + 'http_request_failed', + sprintf( 'cURL error %d: %s', $response->getCode(), $response->getReason() ) + ); + } elseif ( $response instanceof WpOrg\Requests\Exception ) { + $response = new WP_Error( 'http_request_failed', $response->getMessage() ); + } + if ( ! is_wp_error( $response ) ) { // Convert the response into an array. - $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] ); + $http_response = new WP_HTTP_Requests_Response( $response, $parsed_args['filename'] ); $response = $http_response->to_array(); // Add the original object to the array. $response['http_response'] = $http_response; - } catch ( WpOrg\Requests\Exception $e ) { - $response = new WP_Error( 'http_request_failed', $e->getMessage() ); } - reset_mbstring_encoding(); - /** * Fires after an HTTP API response is received and before the response is returned. * diff --git a/src/wp-includes/http.php b/src/wp-includes/http.php index ac589db1e91d3..e23fd223ec36b 100644 --- a/src/wp-includes/http.php +++ b/src/wp-includes/http.php @@ -178,6 +178,58 @@ function wp_safe_remote_head( $url, $args = array() ) { return $http->head( $url, $args ); } +/** + * Performs multiple HTTP requests concurrently using the safe variant of the HTTP API. + * + * Like wp_remote_request_multiple(), but every URL is validated to avoid redirection + * and request forgery attacks. See wp_safe_remote_request(). + * + * @since 7.3.0 + * + * @see wp_remote_request_multiple() For information on the request and response format. + * + * @param array $requests Requests to send. See {@see wp_remote_request_multiple()}. + * @param array $options { + * Optional. Options that apply to the batch of requests. See {@see WP_Http::request_multiple()}. + * Default empty array. + * + * @type int $concurrency Maximum number of requests to send at once. Default 6. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error on failure. + * A value returned by the {@see 'pre_http_request'} filter to short-circuit + * a request is passed through unchanged. + * @phpstan-param array $requests + * @phpstan-return array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error> + */ +function wp_safe_remote_request_multiple( array $requests, array $options = array() ): array { + foreach ( $requests as $id => $request ) { + if ( ! is_array( $request ) ) { + $request = array( 'url' => $request ); + } + + $args = $request['args'] ?? array(); + + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } + + $args['reject_unsafe_urls'] = true; + $request['args'] = $args; + + $requests[ $id ] = $request; + } + + $http = _wp_http_get_object(); + return $http->request_multiple( $requests, $options ); +} + /** * Performs an HTTP request and returns its response. * @@ -303,6 +355,49 @@ function wp_remote_head( $url, $args = array() ) { return $http->head( $url, $args ); } +/** + * Performs multiple HTTP requests concurrently and returns their responses. + * + * With the cURL transport, the requests are sent side by side rather than one after the + * other, so a group of requests takes about as long as its slowest request instead of the + * sum of all of them. See WP_Http::request_multiple() for how the requests are grouped. + * + * Each request is filtered, and its response processed, individually as if it had been + * sent with wp_remote_request(). + * + * @since 7.3.0 + * + * @see WP_Http::request_multiple() For information on the request format and the batch options. + * @see WP_Http::request() For information on accepted request arguments and the response format. + * + * @param array $requests Requests to send, keyed by an identifier of the caller's choosing. + * Each request is either a URL string, for a GET request with the + * default arguments, or an array with a 'url' key and an optional + * 'args' key holding the request arguments. + * @param array $options { + * Optional. Options that apply to the batch of requests. See {@see WP_Http::request_multiple()}. + * Default empty array. + * + * @type int $concurrency Maximum number of requests to send at once. Default 6. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error on failure. + * A value returned by the {@see 'pre_http_request'} filter to short-circuit + * a request is passed through unchanged. + * @phpstan-param array $requests + * @phpstan-return array, + * body: string, + * response: array{code: int|false, message: string|false}, + * cookies: WP_Http_Cookie[], + * filename?: string|null, + * http_response?: WP_HTTP_Requests_Response|null, + * }|WP_Error> + */ +function wp_remote_request_multiple( array $requests, array $options = array() ): array { + $http = _wp_http_get_object(); + return $http->request_multiple( $requests, $options ); +} + /** * Retrieves only the headers from the raw response. * diff --git a/tests/phpunit/tests/http/wpRemoteRequestMultiple.php b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php new file mode 100644 index 0000000000000..7a7c7bf7a28c3 --- /dev/null +++ b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php @@ -0,0 +1,834 @@ +assertSame( array(), wp_remote_request_multiple( array() ) ); + } + + /** + * @ticket 37459 + */ + public function test_should_key_and_order_the_responses_like_the_requests() { + $this->allow_requests_rejected_before_sending(); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + $responses = wp_remote_request_multiple( + array( + 'first' => 'https://example.org/first', + // This request is not short-circuited and is answered after the others, but must keep its place. + 'second' => 'ssl://example.org/second', + 7 => array( 'url' => 'https://example.org/third' ), + 'fourth' => array( + 'url' => 'https://example.org/fourth', + 'args' => array( 'method' => 'POST' ), + ), + ) + ); + + $this->assertSame( array( 'first', 'second', 7, 'fourth' ), array_keys( $responses ), 'The responses should be keyed and ordered like the requests.' ); + $this->assertSame( 'https://example.org/first', wp_remote_retrieve_response_message( $responses['first'] ) ); + $this->assertWPError( $responses['second'] ); + $this->assertSame( 'https://example.org/third', wp_remote_retrieve_response_message( $responses[7] ) ); + $this->assertSame( 'https://example.org/fourth', wp_remote_retrieve_response_message( $responses['fourth'] ) ); + } + + /** + * @ticket 37459 + */ + public function test_should_filter_each_request_individually() { + $methods = array(); + + add_filter( + 'http_request_args', + static function ( $parsed_args, $url ) use ( &$methods ) { + $methods[ $url ] = $parsed_args['method']; + return $parsed_args; + }, + 10, + 2 + ); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + wp_remote_request_multiple( + array( + 'https://example.org/get', + array( + 'url' => 'https://example.org/post', + 'args' => array( 'method' => 'POST' ), + ), + array( + 'url' => 'https://example.org/head', + 'args' => 'method=HEAD', + ), + ) + ); + + $this->assertSame( + array( + 'https://example.org/get' => 'GET', + 'https://example.org/post' => 'POST', + 'https://example.org/head' => 'HEAD', + ), + $methods + ); + } + + /** + * @ticket 37459 + */ + public function test_should_perform_each_request_in_full() { + $blocking = null; + + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args ) use ( &$blocking ) { + $blocking = $parsed_args['blocking']; + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + ); + }, + 10, + 2 + ); + + wp_remote_request_multiple( + array( + array( + 'url' => 'https://example.org/', + 'args' => array( 'blocking' => false ), + ), + ) + ); + + $this->assertTrue( $blocking, 'Batched requests should always be blocking.' ); + } + + /** + * @ticket 37459 + */ + public function test_should_return_a_null_short_circuit_value_as_is() { + add_filter( 'pre_http_request', '__return_null' ); + + $responses = wp_remote_request_multiple( array( 'first' => 'https://example.org/first' ) ); + + $this->assertSame( array( 'first' => null ), $responses, 'A null short-circuit value should be returned like any other.' ); + $this->assertNull( wp_remote_request( 'https://example.org/first' ), 'A single request should still return a null short-circuit value as is.' ); + } + + /** + * @ticket 37459 + */ + public function test_should_return_a_wp_error_for_a_request_that_cannot_be_prepared() { + $this->allow_requests_rejected_before_sending(); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + $responses = wp_remote_request_multiple( + array( + 'valid' => 'https://example.org/', + 'invalid' => 'not a url', + 'missing' => array( 'args' => array( 'method' => 'POST' ) ), + ) + ); + + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['valid'] ) ); + $this->assertWPError( $responses['invalid'] ); + $this->assertSame( 'http_request_failed', $responses['invalid']->get_error_code() ); + $this->assertWPError( $responses['missing'] ); + $this->assertSame( 'http_request_failed', $responses['missing']->get_error_code() ); + } + + /** + * @ticket 37459 + */ + public function test_should_return_a_wp_error_for_a_request_the_requests_library_rejects() { + $this->allow_requests_rejected_before_sending(); + + $responses = wp_remote_request_multiple( array( 'ssl' => 'ssl://example.org/' ) ); + + $this->assertWPError( $responses['ssl'] ); + $this->assertSame( 'http_request_failed', $responses['ssl']->get_error_code() ); + $this->assertSame( 'Only HTTP(S) requests are handled.', $responses['ssl']->get_error_message() ); + } + + /** + * @ticket 37459 + */ + public function test_safe_variant_should_reject_unsafe_urls_for_every_request() { + $reject_unsafe_urls = array(); + + add_filter( + 'http_request_args', + static function ( $parsed_args, $url ) use ( &$reject_unsafe_urls ) { + $reject_unsafe_urls[ $url ] = $parsed_args['reject_unsafe_urls']; + return $parsed_args; + }, + 10, + 2 + ); + add_filter( 'pre_http_request', array( $this, 'short_circuit_example_org' ), 10, 3 ); + + $responses = wp_safe_remote_request_multiple( + array( + 'https://example.org/string', + array( 'url' => 'https://example.org/no-args' ), + array( + 'url' => 'https://example.org/string-args', + 'args' => 'method=HEAD', + ), + array( + 'url' => 'https://example.org/array-args', + 'args' => array( 'reject_unsafe_urls' => false ), + ), + ) + ); + + $this->assertSame( + array( + 'https://example.org/string' => true, + 'https://example.org/no-args' => true, + 'https://example.org/string-args' => true, + 'https://example.org/array-args' => true, + ), + $reject_unsafe_urls + ); + + foreach ( $responses as $response ) { + $this->assertSame( 200, wp_remote_retrieve_response_code( $response ) ); + } + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_send_the_requests_and_return_their_responses() { + $file = $this->temp_filename(); + + $responses = wp_remote_request_multiple( + array( + 'redirected' => array( + 'url' => self::REDIRECTION_SCRIPT . '?code=301&rt=2', + 'args' => array( 'redirection' => 5 ), + ), + 'not_followed' => array( + 'url' => self::REDIRECTION_SCRIPT . '?code=302&rt=1', + 'args' => array( 'redirection' => 0 ), + ), + 'head' => array( + 'url' => self::FILE_URL, + 'args' => array( 'method' => 'HEAD' ), + ), + 'stream' => array( + 'url' => self::FILE_URL, + 'args' => array( + 'stream' => true, + 'filename' => $file, + 'timeout' => 30, + ), + ), + ) + ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( array( 'redirected', 'not_followed', 'head', 'stream' ), array_keys( $responses ) ); + + $this->assertNotWPError( $responses['redirected'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['redirected'] ) ); + + $this->assertNotWPError( $responses['not_followed'] ); + $this->assertSame( 302, wp_remote_retrieve_response_code( $responses['not_followed'] ) ); + + $this->assertNotWPError( $responses['head'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['head'] ) ); + $this->assertSame( 'image/png', wp_remote_retrieve_header( $responses['head'], 'Content-Type' ) ); + $this->assertSame( '', wp_remote_retrieve_body( $responses['head'] ) ); + + $this->assertNotWPError( $responses['stream'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['stream'] ) ); + $this->assertSame( $file, $responses['stream']['filename'] ); + $this->assertSame( 153204, filesize( $file ) ); + + unlink( $file ); + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_process_each_response_individually() { + $filtered = array(); + $debugged = array(); + + add_filter( + 'http_response', + static function ( $response, $parsed_args, $url ) use ( &$filtered ) { + $filtered[] = $url; + return $response; + }, + 10, + 3 + ); + add_action( + 'http_api_debug', + static function ( $response, $context, $transport, $parsed_args, $url ) use ( &$debugged ) { + $debugged[] = $url; + }, + 10, + 5 + ); + + $requests = $this->get_head_requests( 2 ); + $responses = wp_remote_request_multiple( $requests ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $urls = wp_list_pluck( $requests, 'url' ); + + $this->assertSame( $urls, $filtered, "The 'http_response' filter should be applied to each response." ); + $this->assertSame( $urls, $debugged, "The 'http_api_debug' action should fire for each response." ); + } + + /** + * @ticket 37459 + * + * @covers WP_HTTP_Requests_Hooks::dispatch + */ + public function test_should_fire_the_requests_before_request_hook_for_each_batched_request() { + $this->allow_requests_rejected_before_sending(); + + $urls = array(); + + add_action( + 'requests-requests.before_request', + static function ( &$url ) use ( &$urls ) { + $urls[] = $url; + // Rewrite the URL so that the Requests library rejects it before anything is sent. + $url = str_replace( 'https://', 'ftp://', $url ); + } + ); + + $responses = wp_remote_request_multiple( + array( + 'first' => 'https://example.org/first', + 'second' => 'https://example.org/second', + ) + ); + + $this->assertSame( array( 'https://example.org/first', 'https://example.org/second' ), $urls, 'The hook should fire once for each request.' ); + + foreach ( $responses as $response ) { + $this->assertWPError( $response ); + $this->assertSame( 'Only HTTP(S) requests are handled.', $response->get_error_message() ); + } + } + + /** + * @ticket 37459 + */ + public function test_should_not_send_the_requests_again_when_the_batch_fails() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + + $count = 0; + + add_action( + 'http_api_curl', + static function () use ( &$count ) { + ++$count; + } + ); + // Make the batch fail before the transfers start, so that nothing leaves the process. + add_action( + 'requests-curl.before_multi_exec', + static function () { + throw new WpOrg\Requests\Exception( 'Batch failed.', 'test' ); + } + ); + + $responses = wp_remote_request_multiple( + array( + 'first' => 'https://example.org/first', + 'second' => array( + 'url' => 'https://example.org/second', + 'args' => array( 'method' => 'POST' ), + ), + ) + ); + + $this->assertSame( 2, $count, 'Each request should only be prepared for sending once.' ); + + foreach ( $responses as $response ) { + $this->assertWPError( $response ); + $this->assertSame( 'http_request_failed', $response->get_error_code() ); + $this->assertSame( 'Batch failed.', $response->get_error_message() ); + } + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_send_the_other_requests_when_one_cannot_be_batched() { + $responses = wp_remote_request_multiple( + array( + 'ssl' => 'ssl://example.org/', + 'head' => array( + 'url' => self::FILE_URL, + 'args' => array( 'method' => 'HEAD' ), + ), + ) + ); + + $this->skipTestOnTimeout( $responses['head'] ); + + $this->assertWPError( $responses['ssl'] ); + $this->assertNotWPError( $responses['head'] ); + $this->assertSame( 200, wp_remote_retrieve_response_code( $responses['head'] ) ); + } + + /** + * @ticket 37459 + * @group external-http + * + * @covers WP_HTTP_Requests_Hooks::dispatch + */ + public function test_should_fire_http_api_curl_for_each_batched_request() { + $this->skip_without_curl(); + + $count = 0; + + add_action( + 'http_api_curl', + static function () use ( &$count ) { + ++$count; + } + ); + + $responses = wp_remote_request_multiple( $this->get_head_requests( 2 ) ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( 2, $count ); + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_send_at_most_concurrency_requests_at_once() { + $this->skip_without_curl(); + + $batches = 0; + + add_action( + 'requests-curl.before_multi_exec', + static function () use ( &$batches ) { + ++$batches; + } + ); + + $responses = wp_remote_request_multiple( $this->get_head_requests( 3 ), array( 'concurrency' => 2 ) ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( 2, $batches ); + } + + /** + * @ticket 37459 + * @group external-http + */ + public function test_should_apply_the_concurrency_filter() { + $this->skip_without_curl(); + + $batches = 0; + + add_action( + 'requests-curl.before_multi_exec', + static function () use ( &$batches ) { + ++$batches; + } + ); + add_filter( + 'http_request_multiple_concurrency', + static function () { + return 1; + } + ); + + $responses = wp_remote_request_multiple( $this->get_head_requests( 3 ) ); + + foreach ( $responses as $response ) { + $this->skipTestOnTimeout( $response ); + } + + $this->assertSame( 3, $batches ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_send_the_cookies_of_batched_requests() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + + $headers = array(); + + add_action( + 'requests-requests.before_request', + static function ( $url, $request_headers ) use ( &$headers ) { + $headers[ $url ] = $request_headers; + }, + 10, + 2 + ); + $this->fail_batches_before_sending(); + + wp_remote_request_multiple( + array( + array( + 'url' => 'https://example.org/first', + 'args' => array( 'cookies' => array( 'flavor' => 'oatmeal' ) ), + ), + 'https://example.org/second', + ) + ); + + $this->assertSame( 'flavor=oatmeal', $headers['https://example.org/first']['Cookie'] ?? null, 'The cookies of the request should be sent.' ); + $this->assertArrayNotHasKey( 'Cookie', $headers['https://example.org/second'], 'A request without cookies should not send any.' ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_fire_curl_before_send_once_for_each_batched_request() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + + $count = 0; + + // The proxy settings are applied to cURL handles through this hook. + add_action( + 'requests-curl.before_send', + static function () use ( &$count ) { + ++$count; + } + ); + $this->fail_batches_before_sending(); + + wp_remote_request_multiple( array( 'https://example.org/first', 'https://example.org/second' ) ); + + $this->assertSame( 2, $count ); + } + + /** + * @ticket 37459 + * + * @group external-http + * + * @covers WP_Http::request_multiple + */ + public function test_should_return_the_same_error_as_a_single_request_for_a_curl_error() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + + // Nothing listens on port 1, so the connection is refused without leaving the machine. + $url = 'http://127.0.0.1:1/'; + + $single = wp_remote_get( $url ); + $responses = wp_remote_request_multiple( array( $url ) ); + + $this->assertWPError( $single ); + $this->assertWPError( $responses[0] ); + // The messages end with the time the connection attempt took, which may differ. + $this->assertMatchesRegularExpression( '/^cURL error 7: /', $single->get_error_message() ); + $this->assertMatchesRegularExpression( '/^cURL error 7: /', $responses[0]->get_error_message() ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_return_a_wp_error_when_the_stream_file_cannot_be_opened() { + $this->allow_requests_rejected_before_sending(); + + // A directory cannot be opened as a file. + $directory = get_temp_dir() . 'request-multiple-' . uniqid(); + mkdir( $directory ); + + $args = array( + 'stream' => true, + 'filename' => $directory, + ); + + $responses = wp_remote_request_multiple( + array( + array( + 'url' => 'http://127.0.0.1:1/', + 'args' => $args, + ), + ) + ); + + rmdir( $directory ); + + $this->assertWPError( $responses[0] ); + $this->assertSame( 'http_request_failed', $responses[0]->get_error_code() ); + $this->assertStringContainsString( 'fopen(', $responses[0]->get_error_message() ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_not_stream_two_batched_requests_to_the_same_file() { + $this->allow_requests_rejected_before_sending(); + + $filename = get_temp_dir() . 'request-multiple-' . uniqid() . '.txt'; + $args = array( + 'stream' => true, + 'filename' => $filename, + ); + + $responses = wp_remote_request_multiple( + array( + 'first' => array( + 'url' => 'http://127.0.0.1:1/first', + 'args' => $args, + ), + 'second' => array( + 'url' => 'http://127.0.0.1:1/second', + 'args' => $args, + ), + ) + ); + + if ( file_exists( $filename ) ) { + unlink( $filename ); + } + + $this->assertWPError( $responses['second'] ); + $this->assertStringContainsString( 'same file', $responses['second']->get_error_message() ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_only_fail_the_request_whose_host_cannot_be_encoded() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + $this->fail_batches_before_sending(); + + $responses = wp_remote_request_multiple( + array( + 'good' => 'https://example.org/', + // The encoded host name is longer than the 63 characters allowed for a label. + 'bad' => 'https://' . str_repeat( 'ä', 70 ) . '.example/', + ) + ); + + $this->assertWPError( $responses['bad'] ); + $this->assertSame( 'Encoded string is too long', $responses['bad']->get_error_message(), 'The request whose host cannot be encoded should fail on its own.' ); + $this->assertWPError( $responses['good'] ); + $this->assertSame( 'Batch failed.', $responses['good']->get_error_message(), 'The other request should have been sent.' ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_fire_requests_before_request_with_the_same_arguments_as_for_a_single_request() { + $this->skip_without_curl(); + $this->allow_requests_rejected_before_sending(); + + $arguments = array(); + + add_action( + 'requests-requests.before_request', + static function ( $url, $headers, $data, $type, $options ) use ( &$arguments ) { + $arguments[] = array( $url, $type, array_keys( $options ) ); + + // Stop the request before it is sent. + throw new WpOrg\Requests\Exception( 'Stopped.', 'test' ); + }, + 10, + 5 + ); + + $url = 'https://xn--bcher-kva.example/'; + + wp_remote_request( 'https://bücher.example/', array( 'method' => 'post' ) ); + wp_remote_request_multiple( + array( + array( + 'url' => 'https://bücher.example/', + 'args' => array( 'method' => 'post' ), + ), + ) + ); + + $this->assertCount( 2, $arguments ); + $this->assertSame( array( $url, 'POST' ), array_slice( $arguments[0], 0, 2 ), 'The single request should be normalized.' ); + $this->assertSame( array( $url, 'POST' ), array_slice( $arguments[1], 0, 2 ), 'The batched request should be normalized like the single request.' ); + $this->assertSameSets( $arguments[0][2], $arguments[1][2], 'The batched request should have the same options as the single request.' ); + } + + /** + * @ticket 37459 + * + * @covers WP_Http::request_multiple + */ + public function test_should_detect_two_batched_requests_streaming_to_the_same_file_through_different_paths() { + $this->allow_requests_rejected_before_sending(); + + $name = 'request-multiple-' . uniqid() . '.txt'; + + $responses = wp_remote_request_multiple( + array( + 'first' => array( + 'url' => 'http://127.0.0.1:1/first', + 'args' => array( + 'stream' => true, + 'filename' => get_temp_dir() . $name, + ), + ), + 'second' => array( + 'url' => 'http://127.0.0.1:1/second', + 'args' => array( + 'stream' => true, + 'filename' => get_temp_dir() . './' . $name, + ), + ), + ) + ); + + if ( file_exists( get_temp_dir() . $name ) ) { + unlink( get_temp_dir() . $name ); + } + + $this->assertWPError( $responses['second'] ); + $this->assertStringContainsString( 'same file', $responses['second']->get_error_message() ); + } + + /** + * Short-circuits requests to example.org with a 200 response whose message is the request URL. + * + * @param false|array|WP_Error $response A preemptive return value of an HTTP request. + * @param array $parsed_args HTTP request arguments. + * @param string $url The request URL. + * @return false|array|WP_Error The short-circuited response for example.org, $response otherwise. + */ + public function short_circuit_example_org( $response, $parsed_args, $url ) { + if ( 0 !== strpos( $url, 'https://example.org/' ) ) { + return $response; + } + + return array( + 'headers' => array(), + 'body' => '', + 'response' => array( + 'code' => 200, + 'message' => $url, + ), + 'cookies' => array(), + 'filename' => null, + ); + } + + /** + * Returns HEAD requests for distinct URLs that are served with a direct 200 response. + * + * @param int $count Number of requests. + * @return array Requests, see wp_remote_request_multiple(). + */ + private function get_head_requests( $count ) { + $requests = array(); + + for ( $i = 1; $i <= $count; $i++ ) { + $requests[] = array( + 'url' => self::FILE_URL . '?' . $i, + 'args' => array( 'method' => 'HEAD' ), + ); + } + + return $requests; + } + + /** + * Lets requests reach WP_Http, for tests whose URLs are rejected before anything is sent. + * + * The test suite blocks external requests on the 'pre_http_request' filter, which runs + * before WP_Http validates the URL. The tests calling this only use URLs that WP_Http or + * the Requests library reject before a transport is used, so no request leaves the process. + */ + private function allow_requests_rejected_before_sending() { + remove_filter( 'pre_http_request', array( $this, 'block_external_http_request' ), PHP_INT_MAX ); + } + + /** + * Makes batches of requests fail before the cURL transport starts the transfers. + * + * Everything that happens before a request is sent still happens, but nothing leaves the process. + */ + private function fail_batches_before_sending() { + add_action( + 'requests-curl.before_multi_exec', + static function () { + throw new WpOrg\Requests\Exception( 'Batch failed.', 'test' ); + } + ); + } + + /** + * Skips the current test when the cURL transport of the Requests library is not available. + */ + private function skip_without_curl() { + if ( ! WpOrg\Requests\Transport\Curl::test() ) { + $this->markTestSkipped( 'This test requires the cURL transport.' ); + } + } +}