From 4118d809c33b7b6eb6b01b819e3b8e637e85851a Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 22 Sep 2026 12:00:00 +0000 Subject: [PATCH 1/6] HTTP API: Add `wp_remote_request_multiple()` for concurrent requests. Introduce `WP_Http::request_multiple()`, `wp_remote_request_multiple()` and `wp_safe_remote_request_multiple()`, which send a batch of requests side by side and return their responses keyed and ordered like the requests. `WP_Http::request()` is split into `prepare_request()` and `finalize_response()`, so a batched request goes through the same steps as a single one: the `http_request_args`, `pre_http_request` and `http_response` filters, URL validation, blocked hosts, proxies and the `http_api_debug` action all apply to each request individually. Compared to the earlier patch on the ticket: * The single-request functions keep their signatures instead of accepting an array of requests, so `reject_unsafe_urls` can still be passed for a batch. * Batches are sent at most `concurrency` requests at a time (default 6, filterable with `http_request_multiple_concurrency`). * The `http_api_curl` action fires for batched requests too. Requests dispatches `curl.before_multi_add` instead of `curl.before_send` for them, which `WP_HTTP_Requests_Hooks` did not map. * When the Requests library rejects a batch as a whole, its requests are retried one by one so that each gets its own response or error. See #37459. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RvSBA4zz2vHphxunmJCV2G --- src/wp-includes/class-wp-http-curl.php | 1 + .../class-wp-http-requests-hooks.php | 5 + src/wp-includes/class-wp-http.php | 234 ++++++++- src/wp-includes/http.php | 59 +++ .../tests/http/wpRemoteRequestMultiple.php | 478 ++++++++++++++++++ 5 files changed, 767 insertions(+), 10 deletions(-) create mode 100644 tests/phpunit/tests/http/wpRemoteRequestMultiple.php diff --git a/src/wp-includes/class-wp-http-curl.php b/src/wp-includes/class-wp-http-curl.php index 4296bf42f2b00..d793fb7aed6a5 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.2.0 Also fires for each request sent by 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 f399acc860229..d40abebf956d6 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 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 13b82d95bfbd2..1a0c73f2deb06 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -168,6 +168,198 @@ class WP_Http { * } */ public function request( $url, $args = array() ) { + $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 ( isset( $prepared['response'] ) ) { + 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() ); + } + + 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.2.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: + * + * @type string $url The request URL. + * @type string|array $args Optional. Request arguments. See WP_Http::request(). + * } + * @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. + * } + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error + * on failure. See WP_Http::request() for the response format. + */ + public function request_multiple( array $requests, array $options = array() ) { + $responses = array(); + $pending = array(); + + foreach ( $requests as $id => $request ) { + if ( ! is_array( $request ) ) { + $request = array( 'url' => $request ); + } + + $url = isset( $request['url'] ) ? $request['url'] : ''; + $args = isset( $request['args'] ) ? wp_parse_args( $request['args'] ) : array(); + + // 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 ( isset( $prepared['response'] ) ) { + // The request was short-circuited by the 'pre_http_request' filter. + $responses[ $id ] = $prepared['response']; + } else { + $pending[ $id ] = $prepared; + } + } + + if ( ! empty( $pending ) ) { + $concurrency = isset( $options['concurrency'] ) ? (int) $options['concurrency'] : 6; + + /** + * Filters the maximum number of HTTP requests that WP_Http::request_multiple() sends at once. + * + * @since 7.2.0 + * + * @param int $concurrency Maximum number of requests to send at once. Default 6. + * @param array $requests The requests to send. See WP_Http::request_multiple(). + */ + $concurrency = (int) apply_filters( 'http_request_multiple_concurrency', $concurrency, $requests ); + $concurrency = max( 1, $concurrency ); + + foreach ( array_chunk( $pending, $concurrency, true ) as $batch ) { + $batch_requests = array(); + + foreach ( $batch as $id => $prepared ) { + $batch_requests[ $id ] = array( + 'url' => $prepared['url'], + 'headers' => $prepared['headers'], + 'data' => $prepared['data'], + 'type' => $prepared['type'], + 'options' => $prepared['options'], + ); + } + + // Avoid issues where mbstring.func_overload is enabled. + mbstring_binary_safe_encoding(); + + try { + $results = WpOrg\Requests\Requests::request_multiple( $batch_requests ); + } catch ( WpOrg\Requests\Exception $e ) { + /* + * The batch could not be sent at all, for example because one of the URLs + * is not an HTTP(S) URL. Send its requests one by one instead, so that each + * of them gets its own response or error. + */ + $results = array(); + + foreach ( $batch_requests as $id => $request ) { + try { + $results[ $id ] = WpOrg\Requests\Requests::request( + $request['url'], + $request['headers'], + $request['data'], + $request['type'], + $request['options'] + ); + } catch ( WpOrg\Requests\Exception $e ) { + $results[ $id ] = $e; + } + } + } + + 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.2.0 + * + * @param string $url The request URL. + * @param string|array $args Optional. Request arguments. 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 The response returned by the 'pre_http_request' filter, if any. + * } + */ + protected function prepare_request( $url, $args = array() ) { $defaults = array( 'method' => 'GET', /** @@ -278,7 +470,9 @@ public function request( $url, $args = array() ) { $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' ) ) { @@ -410,24 +604,44 @@ 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.2.0 + * + * @param \WpOrg\Requests\Response|\WpOrg\Requests\Exception|WP_Error $response The response, or the + * error the request failed with. + * @param array $parsed_args The parsed request arguments, + * as returned by WP_Http::prepare_request(). + * @param string $url The request URL. + * @return array|WP_Error The response array, or a WP_Error on failure. See WP_Http::request(). + */ + protected function finalize_response( $response, $parsed_args, $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 c2855a8d8d9c1..9668604fd26db 100644 --- a/src/wp-includes/http.php +++ b/src/wp-includes/http.php @@ -142,6 +142,38 @@ 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.2.0 + * + * @see wp_remote_request_multiple() For information on the request and response format. + * + * @param array $requests Requests to send. See wp_remote_request_multiple(). + * @param array $options Optional. Options that apply to the batch of requests. Default empty array. + * See WP_Http::request_multiple(). + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error on failure. + */ +function wp_safe_remote_request_multiple( $requests, $options = array() ) { + foreach ( $requests as $id => $request ) { + if ( ! is_array( $request ) ) { + $request = array( 'url' => $request ); + } + + $request['args'] = isset( $request['args'] ) ? wp_parse_args( $request['args'] ) : array(); + + $request['args']['reject_unsafe_urls'] = true; + + $requests[ $id ] = $request; + } + + $http = _wp_http_get_object(); + return $http->request_multiple( $requests, $options ); +} + /** * Performs an HTTP request and returns its response. * @@ -231,6 +263,33 @@ 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.2.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, such as + * 'concurrency'. Default empty array. See WP_Http::request_multiple(). + * @return array Responses keyed like $requests. Each is a response array, or a WP_Error on failure. + */ +function wp_remote_request_multiple( $requests, $options = 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..383b8d8414a33 --- /dev/null +++ b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php @@ -0,0 +1,478 @@ +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_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 + * @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.' ); + } + } +} From 077ed59d4c062bcdc81772adb444f48397fce147 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 22 Sep 2026 12:30:57 +0000 Subject: [PATCH 2/6] HTTP API: Address PHPStan findings in `WP_Http::request_multiple()`. * Catch `Exception` around `Requests::request_multiple()`. The Requests library only documents `InvalidArgument` on that method, although the URL validation and transport lookup it performs throw `WpOrg\Requests\Exception`, so PHPStan considered the narrower catch dead. * Document the two shapes `WP_Http::prepare_request()` returns with a `@phpstan-return`, as hash notation cannot express a union of shapes. * Describe the `$requests` parameter in prose. Its hash notation described a single request rather than the list of them. See #37459. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RvSBA4zz2vHphxunmJCV2G --- src/wp-includes/class-wp-http.php | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index 1a0c73f2deb06..ed56e5530087a 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -214,13 +214,11 @@ public function request( $url, $args = array() ) { * * @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: - * - * @type string $url The request URL. - * @type string|array $args Optional. Request arguments. See WP_Http::request(). - * } + * @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 WP_Http::request() for the accepted request arguments. * @param array $options { * Optional. Options that apply to the batch of requests. * @@ -288,11 +286,11 @@ public function request_multiple( array $requests, array $options = array() ) { try { $results = WpOrg\Requests\Requests::request_multiple( $batch_requests ); - } catch ( WpOrg\Requests\Exception $e ) { + } catch ( Exception $e ) { /* - * The batch could not be sent at all, for example because one of the URLs - * is not an HTTP(S) URL. Send its requests one by one instead, so that each - * of them gets its own response or error. + * The batch could not be sent at all, for example because the Requests + * library rejected one of the URLs while building it. Send its requests + * one by one instead, so that each of them gets its own response or error. */ $results = array(); @@ -356,8 +354,9 @@ public function request_multiple( array $requests, array $options = array() ) { * @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 The response returned by the 'pre_http_request' filter, if any. + * @type array|WP_Error $response Optional. The response returned by the 'pre_http_request' filter. * } + * @phpstan-return array{url: string, headers: array, data: mixed, type: string, options: array, args: array}|array{response: array|WP_Error}|WP_Error */ protected function prepare_request( $url, $args = array() ) { $defaults = array( From 40803fc110e17ea1dd2459b8075fae462bebfe3a Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 22 Sep 2026 12:36:06 +0000 Subject: [PATCH 3/6] HTTP API: Return a null `pre_http_request` value as is. `WP_Http::prepare_request()` signals a short-circuited request with the presence of the `response` key, but the callers checked it with `isset()`, which does not see a `null` value. A `pre_http_request` callback returning `null` therefore made `WP_Http::request()` read undefined keys and `WP_Http::request_multiple()` send a request without a URL, whereas `null` used to be returned to the caller unchanged. Check for the key with `array_key_exists()` instead, and add a test for it. See #37459. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01D8CZQKtzf87KYDehmhKnED --- src/wp-includes/class-wp-http.php | 4 ++-- tests/phpunit/tests/http/wpRemoteRequestMultiple.php | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index ed56e5530087a..a3984c71c2413 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -175,7 +175,7 @@ public function request( $url, $args = array() ) { } // The request was short-circuited by the 'pre_http_request' filter. - if ( isset( $prepared['response'] ) ) { + if ( array_key_exists( 'response', $prepared ) ) { return $prepared['response']; } @@ -246,7 +246,7 @@ public function request_multiple( array $requests, array $options = array() ) { if ( is_wp_error( $prepared ) ) { $responses[ $id ] = $prepared; - } elseif ( isset( $prepared['response'] ) ) { + } elseif ( array_key_exists( 'response', $prepared ) ) { // The request was short-circuited by the 'pre_http_request' filter. $responses[ $id ] = $prepared['response']; } else { diff --git a/tests/phpunit/tests/http/wpRemoteRequestMultiple.php b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php index 383b8d8414a33..29b48d26cb126 100644 --- a/tests/phpunit/tests/http/wpRemoteRequestMultiple.php +++ b/tests/phpunit/tests/http/wpRemoteRequestMultiple.php @@ -129,6 +129,18 @@ static function ( $response, $parsed_args ) use ( &$blocking ) { $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 */ From b9fbfe5891efcfcf3723baae9aba8691418d96a9 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Fri, 25 Sep 2026 20:39:50 +0000 Subject: [PATCH 4/6] HTTP API: Reference `WP_Http::request_multiple()` with `{@see}` in the `http_api_curl` docblock. See #37459. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01D8CZQKtzf87KYDehmhKnED --- src/wp-includes/class-wp-http-curl.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-http-curl.php b/src/wp-includes/class-wp-http-curl.php index d793fb7aed6a5..d7aef05849535 100644 --- a/src/wp-includes/class-wp-http-curl.php +++ b/src/wp-includes/class-wp-http-curl.php @@ -228,7 +228,7 @@ public function request( $url, $args = array() ) { * plugins to handle cookies themselves. * * @since 2.8.0 - * @since 7.2.0 Also fires for each request sent by WP_Http::request_multiple(). + * @since 7.2.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. From 000e9a1270475c12ae7921e59e7c90189a1f2149 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Fri, 25 Sep 2026 20:52:40 +0000 Subject: [PATCH 5/6] HTTP API: Type the batch request API for static analysis. * Declare the response array as a `Response` type on `WP_Http` and use it for the return value of `request()`, `finalize_response()` and the short-circuit value `prepare_request()` returns, rather than describing the shape in each place. * Declare the prepared request as a `Prepared_Request` type and give `request_multiple()`, `wp_remote_request_multiple()` and `wp_safe_remote_request_multiple()` value types for their requests, options and responses. * Type the results the Requests library returns for a batch. * Only parse request arguments given as a string, since arrays are passed on as they are. * Align the parameter descriptions of `finalize_response()` and reference methods with `{@see}`. See #37459. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01D8CZQKtzf87KYDehmhKnED --- src/wp-includes/class-wp-http.php | 51 +++++++++++++++++++++++-------- src/wp-includes/http.php | 31 ++++++++++++++----- 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/src/wp-includes/class-wp-http.php b/src/wp-includes/class-wp-http.php index a3984c71c2413..daf7dd606f314 100644 --- a/src/wp-includes/class-wp-http.php +++ b/src/wp-includes/class-wp-http.php @@ -29,6 +29,23 @@ * Debugging includes several actions, which pass different variables for debugging the HTTP API. * * @since 2.7.0 + * + * @phpstan-type Response array{ + * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|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, + * } + * @phpstan-type Prepared_Request array{ + * url: string, + * headers: array, + * data: mixed, + * type: string, + * options: array, + * args: array, + * } */ #[AllowDynamicProperties] class WP_Http { @@ -166,6 +183,7 @@ class WP_Http { * @type string|null $filename Optional. Filename of the response. * @type WP_HTTP_Requests_Response|null $http_response Response object. * } + * @phpstan-return Response|WP_Error */ public function request( $url, $args = array() ) { $prepared = $this->prepare_request( $url, $args ); @@ -218,14 +236,16 @@ public function request( $url, $args = array() ) { * 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 WP_Http::request() for the accepted request arguments. + * 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. * } * @return array Responses keyed like $requests. Each is a response array, or a WP_Error - * on failure. See WP_Http::request() for the response format. + * 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() ) { $responses = array(); @@ -237,7 +257,11 @@ public function request_multiple( array $requests, array $options = array() ) { } $url = isset( $request['url'] ) ? $request['url'] : ''; - $args = isset( $request['args'] ) ? wp_parse_args( $request['args'] ) : array(); + $args = isset( $request['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; @@ -285,6 +309,7 @@ public function request_multiple( array $requests, array $options = array() ) { mbstring_binary_safe_encoding(); try { + /** @var array $results */ $results = WpOrg\Requests\Requests::request_multiple( $batch_requests ); } catch ( Exception $e ) { /* @@ -342,8 +367,8 @@ public function request_multiple( array $requests, array $options = array() ) { * * @since 7.2.0 * - * @param string $url The request URL. - * @param string|array $args Optional. Request arguments. See WP_Http::request(). + * @param string $url The request URL. + * @param string|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. @@ -356,7 +381,8 @@ public function request_multiple( array $requests, array $options = array() ) { * @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-return array{url: string, headers: array, data: mixed, type: string, options: array, args: array}|array{response: array|WP_Error}|WP_Error + * @phpstan-param string|array $args + * @phpstan-return Prepared_Request|array{ response: Response|WP_Error }|WP_Error */ protected function prepare_request( $url, $args = array() ) { $defaults = array( @@ -620,12 +646,13 @@ protected function prepare_request( $url, $args = array() ) { * * @since 7.2.0 * - * @param \WpOrg\Requests\Response|\WpOrg\Requests\Exception|WP_Error $response The response, or the - * error the request failed with. - * @param array $parsed_args The parsed request arguments, - * as returned by WP_Http::prepare_request(). - * @param string $url The request URL. - * @return array|WP_Error The response array, or a WP_Error on failure. See WP_Http::request(). + * @param \WpOrg\Requests\Response|\WpOrg\Requests\Exception|WP_Error $response The response, or the error the + * request failed with. + * @param array $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-return Response|WP_Error */ protected function finalize_response( $response, $parsed_args, $url ) { if ( $response instanceof WpOrg\Requests\Exception ) { diff --git a/src/wp-includes/http.php b/src/wp-includes/http.php index 9668604fd26db..faecedafc0abe 100644 --- a/src/wp-includes/http.php +++ b/src/wp-includes/http.php @@ -152,10 +152,16 @@ function wp_safe_remote_head( $url, $args = array() ) { * * @see wp_remote_request_multiple() For information on the request and response format. * - * @param array $requests Requests to send. See wp_remote_request_multiple(). - * @param array $options Optional. Options that apply to the batch of requests. Default empty array. - * See WP_Http::request_multiple(). + * @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|WP_Error> */ function wp_safe_remote_request_multiple( $requests, $options = array() ) { foreach ( $requests as $id => $request ) { @@ -163,9 +169,14 @@ function wp_safe_remote_request_multiple( $requests, $options = array() ) { $request = array( 'url' => $request ); } - $request['args'] = isset( $request['args'] ) ? wp_parse_args( $request['args'] ) : array(); + $args = isset( $request['args'] ) ? $request['args'] : array(); + + if ( ! is_array( $args ) ) { + $args = wp_parse_args( $args ); + } - $request['args']['reject_unsafe_urls'] = true; + $args['reject_unsafe_urls'] = true; + $request['args'] = $args; $requests[ $id ] = $request; } @@ -281,9 +292,15 @@ function wp_remote_head( $url, $args = array() ) { * 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, such as - * 'concurrency'. Default empty array. See WP_Http::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|WP_Error> */ function wp_remote_request_multiple( $requests, $options = array() ) { $http = _wp_http_get_object(); From 39dc65f480233e3107b500c115c736604d4df29a Mon Sep 17 00:00:00 2001 From: robelsust Date: Wed, 7 Oct 2026 23:00:27 +0600 Subject: [PATCH 6/6] Upgrade/Install: Add concurrent package downloads via `download_url_multiple()`. Introduces `download_url_multiple()` to download multiple URLs concurrently using `wp_safe_remote_request_multiple()`. Refactors `download_url()` to share response handling with `_wp_handle_download_response()`, ensuring consistent MIME type detection, Content-Disposition extraction, checksum verification, and signature checking. Updates `Plugin_Upgrader::bulk_upgrade()` and `Theme_Upgrader::bulk_upgrade()` to pre-download compatible packages in parallel before iterating through the installation loop, significantly reducing bulk update wall-clock time and preventing timeouts on shared hosting. Includes dedicated unit tests in `downloadUrlMultiple.php` and integration tests in `bulkUpgrader.php`. See #37459. --- .../includes/class-plugin-upgrader.php | 41 ++- .../includes/class-theme-upgrader.php | 41 ++- src/wp-admin/includes/file.php | 108 +++++++ tests/phpunit/tests/admin/bulkUpgrader.php | 283 ++++++++++++++++ .../tests/admin/downloadUrlMultiple.php | 305 ++++++++++++++++++ 5 files changed, 776 insertions(+), 2 deletions(-) create mode 100644 tests/phpunit/tests/admin/bulkUpgrader.php create mode 100644 tests/phpunit/tests/admin/downloadUrlMultiple.php diff --git a/src/wp-admin/includes/class-plugin-upgrader.php b/src/wp-admin/includes/class-plugin-upgrader.php index 53e8f4af6b5a1..d0a02d28da06b 100644 --- a/src/wp-admin/includes/class-plugin-upgrader.php +++ b/src/wp-admin/includes/class-plugin-upgrader.php @@ -325,6 +325,32 @@ public function bulk_upgrade( $plugins, $args = array() ) { $results = array(); + $packages_to_download = array(); + foreach ( $plugins as $plugin ) { + if ( ! isset( $current->response[ $plugin ] ) ) { + continue; + } + + $upgrade_data = $current->response[ $plugin ]; + + if ( isset( $upgrade_data->requires ) && ! is_wp_version_compatible( $upgrade_data->requires ) ) { + continue; + } + + if ( isset( $upgrade_data->requires_php ) && ! is_php_version_compatible( $upgrade_data->requires_php ) ) { + continue; + } + + if ( ! empty( $upgrade_data->package ) ) { + $packages_to_download[ $plugin ] = $upgrade_data->package; + } + } + + $downloaded_packages = array(); + if ( ! empty( $packages_to_download ) ) { + $downloaded_packages = download_url_multiple( $packages_to_download ); + } + $this->update_count = count( $plugins ); $this->update_current = 0; foreach ( $plugins as $plugin ) { @@ -374,10 +400,16 @@ public function bulk_upgrade( $plugins, $args = array() ) { $this->skin->error( $result ); $this->skin->after(); } else { + $package = $upgrade_data->package; + if ( ! empty( $downloaded_packages[ $plugin ] ) && ! is_wp_error( $downloaded_packages[ $plugin ] ) ) { + $package = $downloaded_packages[ $plugin ]; + unset( $downloaded_packages[ $plugin ] ); + } + add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); $result = $this->run( array( - 'package' => $upgrade_data->package, + 'package' => $package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, @@ -403,6 +435,13 @@ public function bulk_upgrade( $plugins, $args = array() ) { } } // End foreach $plugins. + // Clean up any pre-downloaded packages that were not consumed. + foreach ( $downloaded_packages as $downloaded_package ) { + if ( is_string( $downloaded_package ) && file_exists( $downloaded_package ) ) { + unlink( $downloaded_package ); + } + } + $this->maintenance_mode( false ); // Force refresh of plugin update information. diff --git a/src/wp-admin/includes/class-theme-upgrader.php b/src/wp-admin/includes/class-theme-upgrader.php index c665ca063122a..a72b51c433b9a 100644 --- a/src/wp-admin/includes/class-theme-upgrader.php +++ b/src/wp-admin/includes/class-theme-upgrader.php @@ -424,6 +424,32 @@ public function bulk_upgrade( $themes, $args = array() ) { $results = array(); + $packages_to_download = array(); + foreach ( $themes as $theme ) { + if ( ! isset( $current->response[ $theme ] ) ) { + continue; + } + + $upgrade_data = $current->response[ $theme ]; + + if ( isset( $upgrade_data['requires'] ) && ! is_wp_version_compatible( $upgrade_data['requires'] ) ) { + continue; + } + + if ( isset( $upgrade_data['requires_php'] ) && ! is_php_version_compatible( $upgrade_data['requires_php'] ) ) { + continue; + } + + if ( ! empty( $upgrade_data['package'] ) ) { + $packages_to_download[ $theme ] = $upgrade_data['package']; + } + } + + $downloaded_packages = array(); + if ( ! empty( $packages_to_download ) ) { + $downloaded_packages = download_url_multiple( $packages_to_download ); + } + $this->update_count = count( $themes ); $this->update_current = 0; foreach ( $themes as $theme ) { @@ -472,10 +498,16 @@ public function bulk_upgrade( $themes, $args = array() ) { $this->skin->error( $result ); $this->skin->after(); } else { + $package = $upgrade_data['package']; + if ( ! empty( $downloaded_packages[ $theme ] ) && ! is_wp_error( $downloaded_packages[ $theme ] ) ) { + $package = $downloaded_packages[ $theme ]; + unset( $downloaded_packages[ $theme ] ); + } + add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); $result = $this->run( array( - 'package' => $upgrade_data['package'], + 'package' => $package, 'destination' => get_theme_root( $theme ), 'clear_destination' => true, 'clear_working' => true, @@ -501,6 +533,13 @@ public function bulk_upgrade( $themes, $args = array() ) { } } // End foreach $themes. + // Clean up any pre-downloaded packages that were not consumed. + foreach ( $downloaded_packages as $downloaded_package ) { + if ( is_string( $downloaded_package ) && file_exists( $downloaded_package ) ) { + unlink( $downloaded_package ); + } + } + $this->maintenance_mode( false ); // Refresh the Theme Update information. diff --git a/src/wp-admin/includes/file.php b/src/wp-admin/includes/file.php index 79a08bb2b9cba..03f8aba499a4b 100644 --- a/src/wp-admin/includes/file.php +++ b/src/wp-admin/includes/file.php @@ -1180,6 +1180,108 @@ function download_url( $url, $timeout = 300, $signature_verification = false ) { ) ); + return _wp_handle_download_response( $response, $tmpfname, $url, $signature_verification ); +} + +/** + * Downloads multiple URLs to local temporary files concurrently using the WordPress HTTP API. + * + * Please note that the calling function must delete or move the files. + * + * @since 7.2.0 + * + * @param string[] $urls An array of URLs to download, optionally keyed by an identifier. + * @param int $timeout Optional. The timeout for the requests to download the files. + * Default 300 seconds. + * @param bool $signature_verification Optional. Whether to perform Signature Verification. + * Default false. + * @return array An array of results keyed identically to $urls. Each element + * is the path to the downloaded temporary file on success, + * or a WP_Error on failure. + */ +function download_url_multiple( array $urls, $timeout = 300, $signature_verification = false ) { + if ( empty( $urls ) ) { + return array(); + } + + $results = array(); + $requests = array(); + $temp_files = array(); + + foreach ( $urls as $id => $url ) { + if ( ! $url ) { + $results[ $id ] = new WP_Error( 'http_no_url', __( 'No URL Provided.' ) ); + continue; + } + + $url_path = parse_url( $url, PHP_URL_PATH ); + $url_filename = ''; + if ( is_string( $url_path ) && '' !== $url_path ) { + $url_filename = basename( $url_path ); + } + + $tmpfname = wp_tempnam( $url_filename ); + if ( ! $tmpfname ) { + $results[ $id ] = new WP_Error( 'http_no_file', __( 'Could not create temporary file.' ) ); + continue; + } + + $temp_files[ $id ] = $tmpfname; + $requests[ $id ] = array( + 'url' => $url, + 'args' => array( + 'timeout' => $timeout, + 'stream' => true, + 'filename' => $tmpfname, + ), + ); + } + + if ( ! empty( $requests ) ) { + if ( function_exists( 'wp_safe_remote_request_multiple' ) ) { + $responses = wp_safe_remote_request_multiple( $requests ); + } else { + $responses = array(); + foreach ( $requests as $id => $request ) { + $responses[ $id ] = wp_safe_remote_get( $request['url'], $request['args'] ); + } + } + + foreach ( $responses as $id => $response ) { + $results[ $id ] = _wp_handle_download_response( + $response, + $temp_files[ $id ], + $urls[ $id ], + $signature_verification + ); + } + } + + // Preserve original key ordering. + $ordered_results = array(); + foreach ( array_keys( $urls ) as $id ) { + $ordered_results[ $id ] = $results[ $id ]; + } + + return $ordered_results; +} + +/** + * Processes a downloaded file response, handling HTTP status verification, + * content disposition renaming, MIME validation, and signature verification. + * + * For internal use by download_url() and download_url_multiple(). + * + * @access private + * @since 7.2.0 + * + * @param array|WP_Error $response The HTTP response or WP_Error. + * @param string $tmpfname The temporary file path where the stream was written. + * @param string $url The URL that was requested. + * @param bool $signature_verification Whether signature verification should be performed. + * @return string|WP_Error The path to the verified temporary file, or WP_Error on failure. + */ +function _wp_handle_download_response( $response, $tmpfname, $url, $signature_verification = false ) { if ( is_wp_error( $response ) ) { unlink( $tmpfname ); return $response; @@ -1288,6 +1390,12 @@ function download_url( $url, $timeout = 300, $signature_verification = false ) { // Perform signature validation if supported. if ( $signature_verification ) { + $url_path = parse_url( $url, PHP_URL_PATH ); + $url_filename = ''; + if ( is_string( $url_path ) && '' !== $url_path ) { + $url_filename = basename( $url_path ); + } + $signature = wp_remote_retrieve_header( $response, 'X-Content-Signature' ); if ( ! $signature ) { diff --git a/tests/phpunit/tests/admin/bulkUpgrader.php b/tests/phpunit/tests/admin/bulkUpgrader.php new file mode 100644 index 0000000000000..b7ffa34cd1a82 --- /dev/null +++ b/tests/phpunit/tests/admin/bulkUpgrader.php @@ -0,0 +1,283 @@ +run_calls[] = $options; + return true; + } +} + +/** + * Testable Theme_Upgrader that mocks fs_connect and captures run() arguments. + */ +class Testable_Theme_Upgrader extends Theme_Upgrader { + + /** + * Captured arguments passed to run(). + * + * @var array[] + */ + public $run_calls = array(); + + public function fs_connect( $directories = array(), $allow_relaxed_file_ownership = false ) { + return true; + } + + public function run( $options ) { + $this->run_calls[] = $options; + return true; + } +} + +/** + * Tests the concurrent bulk upgrade functionality. + * + * @group admin + * @group upgrade + * + * @covers Plugin_Upgrader::bulk_upgrade + * @covers Theme_Upgrader::bulk_upgrade + */ +class Tests_Admin_BulkUpgrader extends WP_UnitTestCase { + + /** + * Clean up filters and transients after each test. + */ + public function tear_down() { + remove_all_filters( 'pre_http_request' ); + delete_site_transient( 'update_plugins' ); + delete_site_transient( 'update_themes' ); + + parent::tear_down(); + } + + /** + * Tests that Plugin_Upgrader::bulk_upgrade() pre-downloads packages concurrently + * and supplies the local file path to run(). + * + * @ticket 37459 + */ + public function test_plugin_bulk_upgrade_uses_concurrent_pre_downloads() { + $downloaded_files = array(); + + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) use ( &$downloaded_files ) { + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'PK...' ); + $downloaded_files[] = $parsed_args['filename']; + } + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'content-type' => 'application/zip', + ), + ); + }, + 10, + 3 + ); + + $plugin_a = 'hello.php'; + $plugin_b = 'internationalized-plugin.php'; + + $update_plugins = new stdClass(); + $update_plugins->response = array( + $plugin_a => (object) array( + 'package' => 'https://downloads.wordpress.org/plugin/alpha.1.1.zip', + 'new_version' => '1.1', + ), + $plugin_b => (object) array( + 'package' => 'https://downloads.wordpress.org/plugin/beta.2.0.zip', + 'new_version' => '2.0', + ), + ); + set_site_transient( 'update_plugins', $update_plugins ); + + $skin = new Bulk_Upgrader_Test_Skin(); + $upgrader = new Testable_Plugin_Upgrader( $skin ); + + $results = $upgrader->bulk_upgrade( array( $plugin_a, $plugin_b ) ); + + $this->assertIsArray( $results ); + $this->assertCount( 2, $upgrader->run_calls ); + + // The packages passed to run() should be local file paths, not the remote URLs. + $package_a = $upgrader->run_calls[0]['package']; + $package_b = $upgrader->run_calls[1]['package']; + + $this->assertNotSame( 'https://downloads.wordpress.org/plugin/alpha.1.1.zip', $package_a ); + $this->assertNotSame( 'https://downloads.wordpress.org/plugin/beta.2.0.zip', $package_b ); + $this->assertFileExists( $package_a ); + $this->assertFileExists( $package_b ); + + // Clean up created files. + foreach ( $downloaded_files as $file ) { + if ( file_exists( $file ) ) { + unlink( $file ); + } + } + } + + /** + * Tests that Theme_Upgrader::bulk_upgrade() pre-downloads packages concurrently + * and supplies the local file path to run(). + * + * @ticket 37459 + */ + public function test_theme_bulk_upgrade_uses_concurrent_pre_downloads() { + $downloaded_files = array(); + + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) use ( &$downloaded_files ) { + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'PK...' ); + $downloaded_files[] = $parsed_args['filename']; + } + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'content-type' => 'application/zip', + ), + ); + }, + 10, + 3 + ); + + $theme_a = 'twentytwentyfive'; + $theme_b = 'twentytwentyfour'; + + $update_themes = new stdClass(); + $update_themes->response = array( + $theme_a => array( + 'package' => 'https://downloads.wordpress.org/theme/twentytwentyfive.1.1.zip', + 'new_version' => '1.1', + ), + $theme_b => array( + 'package' => 'https://downloads.wordpress.org/theme/twentytwentyfour.1.2.zip', + 'new_version' => '1.2', + ), + ); + set_site_transient( 'update_themes', $update_themes ); + + $skin = new Bulk_Upgrader_Test_Skin(); + $upgrader = new Testable_Theme_Upgrader( $skin ); + + $results = $upgrader->bulk_upgrade( array( $theme_a, $theme_b ) ); + + $this->assertIsArray( $results ); + $this->assertCount( 2, $upgrader->run_calls ); + + // The packages passed to run() should be local file paths, not the remote URLs. + $package_a = $upgrader->run_calls[0]['package']; + $package_b = $upgrader->run_calls[1]['package']; + + $this->assertNotSame( 'https://downloads.wordpress.org/theme/twentytwentyfive.1.1.zip', $package_a ); + $this->assertNotSame( 'https://downloads.wordpress.org/theme/twentytwentyfour.1.2.zip', $package_b ); + $this->assertFileExists( $package_a ); + $this->assertFileExists( $package_b ); + + // Clean up created files. + foreach ( $downloaded_files as $file ) { + if ( file_exists( $file ) ) { + unlink( $file ); + } + } + } + + /** + * Tests that when a batch download fails for an item, the upgrader falls back to the original package URL. + * + * @ticket 37459 + */ + public function test_plugin_bulk_upgrade_falls_back_to_url_on_download_failure() { + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) { + return array( + 'response' => array( + 'code' => 500, + 'message' => 'Internal Server Error', + ), + ); + }, + 10, + 3 + ); + + $plugin_slug = 'hello.php'; + $update_plugins = new stdClass(); + $update_plugins->response = array( + $plugin_slug => (object) array( + 'package' => 'https://downloads.wordpress.org/plugin/error-plugin.1.0.zip', + ), + ); + set_site_transient( 'update_plugins', $update_plugins ); + + $skin = new Bulk_Upgrader_Test_Skin(); + $upgrader = new Testable_Plugin_Upgrader( $skin ); + + $upgrader->bulk_upgrade( array( $plugin_slug ) ); + + $this->assertCount( 1, $upgrader->run_calls ); + // When batch download failed, it falls back to the remote URL for normal sequential handling. + $this->assertSame( + 'https://downloads.wordpress.org/plugin/error-plugin.1.0.zip', + $upgrader->run_calls[0]['package'] + ); + } +} diff --git a/tests/phpunit/tests/admin/downloadUrlMultiple.php b/tests/phpunit/tests/admin/downloadUrlMultiple.php new file mode 100644 index 0000000000000..a3564c6c9bee0 --- /dev/null +++ b/tests/phpunit/tests/admin/downloadUrlMultiple.php @@ -0,0 +1,305 @@ +test_files as $file ) { + if ( is_string( $file ) && file_exists( $file ) ) { + unlink( $file ); + } + } + $this->test_files = array(); + + remove_all_filters( 'pre_http_request' ); + remove_all_filters( 'download_url_error_max_body_size' ); + + parent::tear_down(); + } + + /** + * Tests that passing an empty array of URLs returns an empty array. + * + * @ticket 37459 + */ + public function test_download_url_multiple_empty_urls() { + $results = download_url_multiple( array() ); + + $this->assertSame( array(), $results ); + } + + /** + * Tests that invalid or empty URLs in the array produce WP_Error with code 'http_no_url'. + * + * @ticket 37459 + */ + public function test_download_url_multiple_empty_url_in_list() { + $urls = array( + 'first' => '', + 'second' => false, + ); + + $results = download_url_multiple( $urls ); + + $this->assertCount( 2, $results ); + $this->assertArrayHasKey( 'first', $results ); + $this->assertArrayHasKey( 'second', $results ); + $this->assertWPError( $results['first'] ); + $this->assertSame( 'http_no_url', $results['first']->get_error_code() ); + $this->assertWPError( $results['second'] ); + $this->assertSame( 'http_no_url', $results['second']->get_error_code() ); + } + + /** + * Tests that multiple concurrent downloads succeed, preserve array keys, and write content. + * + * @ticket 37459 + */ + public function test_download_url_multiple_success_and_preserves_keys() { + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) { + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'Payload for ' . $url ); + } + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'content-type' => 'application/zip', + ), + ); + }, + 10, + 3 + ); + + $urls = array( + 'plugin_alpha' => 'https://example.org/plugin-alpha.zip', + 'plugin_beta' => 'https://example.org/plugin-beta.zip', + 42 => 'https://example.org/plugin-numeric.zip', + ); + + $results = download_url_multiple( $urls ); + + $this->assertSame( array_keys( $urls ), array_keys( $results ) ); + + foreach ( $results as $key => $file_path ) { + $this->assertIsString( $file_path, "Result for key '$key' should be a file path string." ); + $this->assertFileExists( $file_path ); + $this->test_files[] = $file_path; + + $content = file_get_contents( $file_path ); + $this->assertSame( 'Payload for ' . $urls[ $key ], $content ); + } + } + + /** + * Tests partial batch failure where one URL succeeds and another fails with a 404 response. + * + * @ticket 37459 + */ + public function test_download_url_multiple_partial_failure() { + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) { + if ( 'https://example.org/failing.zip' === $url ) { + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'Not Found on server' ); + } + return array( + 'response' => array( + 'code' => 404, + 'message' => 'Not Found', + ), + 'headers' => array(), + ); + } + + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'Successful payload' ); + } + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'content-type' => 'application/zip', + ), + ); + }, + 10, + 3 + ); + + $urls = array( + 'ok' => 'https://example.org/successful.zip', + 'fail' => 'https://example.org/failing.zip', + ); + + $results = download_url_multiple( $urls ); + + $this->assertIsString( $results['ok'] ); + $this->assertFileExists( $results['ok'] ); + $this->test_files[] = $results['ok']; + + $this->assertWPError( $results['fail'] ); + $this->assertSame( 'http_404', $results['fail']->get_error_code() ); + $this->assertSame( 404, $results['fail']->get_error_data()['code'] ); + } + + /** + * Tests that Content-Disposition header filenames are respected across batch requests. + * + * @ticket 37459 + */ + public function test_download_url_multiple_respects_content_disposition() { + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) { + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'Disposed content' ); + } + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'Content-Disposition' => 'attachment; filename=custom-name.zip', + ), + ); + }, + 10, + 3 + ); + + $results = download_url_multiple( array( 'item' => 'https://example.org/generic-download' ) ); + + $this->assertIsString( $results['item'] ); + $this->assertFileExists( $results['item'] ); + $this->test_files[] = $results['item']; + $this->assertStringEndsWith( 'custom-name.zip', $results['item'] ); + } + + /** + * Tests that Content-Type header determines file extension when temporary file lacks one. + * + * @ticket 37459 + */ + public function test_download_url_multiple_respects_content_type() { + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) { + if ( ! empty( $parsed_args['filename'] ) ) { + file_put_contents( $parsed_args['filename'], 'Image content' ); + } + + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'content-type' => 'image/png', + ), + ); + }, + 10, + 3 + ); + + $results = download_url_multiple( array( 'image' => 'https://example.org/download-image' ) ); + + $this->assertIsString( $results['image'] ); + $this->assertFileExists( $results['image'] ); + $this->test_files[] = $results['image']; + $this->assertStringEndsWith( '.png', $results['image'] ); + } + + /** + * Tests Content-MD5 verification in batch downloads. + * + * @ticket 37459 + */ + public function test_download_url_multiple_md5_verification() { + $valid_content = 'Verified content payload'; + $valid_md5 = base64_encode( md5( $valid_content, true ) ); + $mismatched_md5 = base64_encode( md5( 'Other content', true ) ); + + add_filter( + 'pre_http_request', + static function ( $response, $parsed_args, $url ) use ( $valid_content, $valid_md5, $mismatched_md5 ) { + if ( 'https://example.org/good-md5.zip' === $url ) { + file_put_contents( $parsed_args['filename'], $valid_content ); + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'Content-MD5' => $valid_md5, + ), + ); + } + + file_put_contents( $parsed_args['filename'], $valid_content ); + return array( + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'headers' => array( + 'Content-MD5' => $mismatched_md5, + ), + ); + }, + 10, + 3 + ); + + $urls = array( + 'good' => 'https://example.org/good-md5.zip', + 'bad' => 'https://example.org/bad-md5.zip', + ); + + $results = download_url_multiple( $urls ); + + $this->assertIsString( $results['good'] ); + $this->assertFileExists( $results['good'] ); + $this->test_files[] = $results['good']; + + $this->assertWPError( $results['bad'] ); + $this->assertSame( 'md5_mismatch', $results['bad']->get_error_code() ); + } +}