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-requests-hooks.php b/src/wp-includes/class-wp-http-requests-hooks.php index aac172892f293..be6341ec27ebb 100644 --- a/src/wp-includes/class-wp-http-requests-hooks.php +++ b/src/wp-includes/class-wp-http-requests-hooks.php @@ -53,7 +53,12 @@ public function dispatch( $hook, $parameters = array() ) { // Handle back-compat actions. switch ( $hook ) { + /** + * Requests fires 'curl.before_multi_add' instead of 'curl.before_send' for the + * requests of a batch, see {@see WP_Http::request_multiple()}. + */ case 'curl.before_send': + case 'curl.before_multi_add': /** This action is documented in wp-includes/class-wp-http-curl.php */ do_action_ref_array( 'http_api_curl', array( &$parameters[0], $this->request, $this->url ) ); break; diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index de53011d11983..681b501a37aff 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,234 @@ 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, exactly 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. The requests that were not short-circuited are then sent side by + * side, at most $concurrency at a time. + * + * 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. + * @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 { + foreach ( $batch as $id => $prepared ) { + $request_url = $prepared['url']; + $request_headers = $prepared['headers']; + $request_data = $prepared['data']; + $request_type = $prepared['type']; + $request_options = $prepared['options']; + + /* + * Requests::request() fires this hook for a single request, but + * Requests::request_multiple() does not, so fire it here to treat + * the requests of a batch like requests sent on their own. + */ + $request_options['hooks']->dispatch( + 'requests.before_request', + array( &$request_url, &$request_headers, &$request_data, &$request_type, &$request_options ) + ); + + /* + * Requests::request_multiple() throws for the whole batch if one of its URLs + * is not an HTTP(S) URL. Reject such a request on its own instead, with the + * same error that Requests::request() would throw for it. + */ + if ( ! preg_match( '/^http(s)?:\/\//i', $request_url ) ) { + $results[ $id ] = new WpOrg\Requests\Exception( 'Only HTTP(S) requests are handled.', 'nonhttp', $request_url ); + continue; + } + + $batch_requests[ $id ] = array( + 'url' => $request_url, + 'headers' => $request_headers, + 'data' => $request_data, + 'type' => $request_type, + 'options' => $request_options, + ); + } + + 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; + } + } 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(); + } + + 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 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 + */ + protected function prepare_request( $url, array $args = array() ) { $defaults = array( 'method' => 'GET', /** @@ -244,9 +518,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 +556,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 +695,46 @@ 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 + */ + protected function finalize_response( $response, array $parsed_args, string $url ) { + if ( $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..5796edb36176d 100644 --- a/src/wp-includes/http.php +++ b/src/wp-includes/http.php @@ -178,6 +178,56 @@ 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. + * @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 +353,46 @@ function wp_remote_head( $url, $args = array() ) { return $http->head( $url, $args ); } +/** + * Performs multiple HTTP requests concurrently and returns their responses. + * + * The requests are sent side by side rather than one after the other, so a batch of + * requests takes about as long as its slowest request instead of the sum of all of them. + * + * Each request is filtered, and its response processed, individually and exactly 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. + * @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..7e68683a0f7dc --- /dev/null +++ b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php @@ -0,0 +1,566 @@ +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 ); + } + + /** + * 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 ); + } + + /** + * 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.' ); + } + } +}