Make WordPress Core


Ignore:
Timestamp:
11/25/2021 01:10:30 AM (5 years ago)
Author:
SergeyBiryukov
Message:

External Libraries: Update the Requests library to version 2.0.0.

This is a major release and contains breaking changes.

Most important changes to be aware of for this release:

  • All code is now namespaced. Though there is a full backward compatibility layer available and the old class names are still supported, using them will generate a deprecation notice (which can be silenced by plugins if they'd need to support multiple WP versions). See the ​upgrade guide for more details.
  • A lot of classes have been marked final. This should generally not affect userland code as care has been taken to not apply the final keyword to classes which are known to be extended in userland code.
  • Extensive input validation has been added to Requests. When Requests is used as documented though, this will be unnoticable.
  • A new WpOrg\Requests\Requests::has_capabilities() method has been introduced which can be used to address #37708.
  • A new WpOrg\Requests\Response::decode_body() method has been introduced which may be usable to simplify some of the WP native wrapper code.
  • Remaining PHP 8.0 compatibility fixed (support for named parameters).
  • PHP 8.1 compatibility.

Release notes: ​https://github.com/WordPress/Requests/releases/tag/v2.0.0

For a full list of changes in this update, see the Requests GitHub:
​https://github.com/WordPress/Requests/compare/v1.8.1...v2.0.0

Follow-up to [50842], [51078].

Props jrf, schlessera, datagutten, wojsmol, dd32, dustinrue, soulseekah, costdev, szepeviktor.
Fixes #54504.

File:
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/Requests/Transport/Curl.php

    r52243 r52244  
    33 * cURL HTTP transport
    44 *
    5  * @package Requests
    6  * @subpackage Transport
     5 * @package Requests\Transport
    76 */
     7
     8namespace WpOrg\Requests\Transport;
     9
     10use RecursiveArrayIterator;
     11use RecursiveIteratorIterator;
     12use WpOrg\Requests\Capability;
     13use WpOrg\Requests\Exception;
     14use WpOrg\Requests\Exception\InvalidArgument;
     15use WpOrg\Requests\Exception\Transport\Curl as CurlException;
     16use WpOrg\Requests\Requests;
     17use WpOrg\Requests\Transport;
     18use WpOrg\Requests\Utility\InputValidator;
    819
    920/**
    1021 * cURL HTTP transport
    1122 *
    12  * @package Requests
    13  * @subpackage Transport
     23 * @package Requests\Transport
    1424 */
    15 class Requests_Transport_cURL implements Requests_Transport {
     25final class Curl implements Transport {
    1626        const CURL_7_10_5 = 0x070A05;
    1727        const CURL_7_16_2 = 0x071002;
    … …  
    3444         * Information on the current request
    3545         *
    36          * @var array cURL information array, see {@see https://secure.php.net/curl_getinfo}
     46         * @var array cURL information array, see {@link https://www.php.net/curl_getinfo}
    3747         */
    3848        public $info;
    … …  
    4858         * cURL handle
    4959         *
     60         * @var resource|\CurlHandle Resource in PHP < 8.0, Instance of CurlHandle in PHP >= 8.0.
     61         */
     62        private $handle;
     63
     64        /**
     65         * Hook dispatcher instance
     66         *
     67         * @var \WpOrg\Requests\Hooks
     68         */
     69        private $hooks;
     70
     71        /**
     72         * Have we finished the headers yet?
     73         *
     74         * @var boolean
     75         */
     76        private $done_headers = false;
     77
     78        /**
     79         * If streaming to a file, keep the file pointer
     80         *
    5081         * @var resource
    5182         */
    52         protected $handle;
    53 
    54         /**
    55          * Hook dispatcher instance
    56          *
    57          * @var Requests_Hooks
    58          */
    59         protected $hooks;
    60 
    61         /**
    62          * Have we finished the headers yet?
    63          *
    64          * @var boolean
    65          */
    66         protected $done_headers = false;
    67 
    68         /**
    69          * If streaming to a file, keep the file pointer
    70          *
    71          * @var resource
    72          */
    73         protected $stream_handle;
     83        private $stream_handle;
    7484
    7585        /**
    … …  
    7888         * @var int
    7989         */
    80         protected $response_bytes;
     90        private $response_bytes;
    8191
    8292        /**
    … …  
    8595         * @var int|bool Byte count, or false if no limit.
    8696         */
    87         protected $response_byte_limit;
     97        private $response_byte_limit;
    8898
    8999        /**
    … …  
    122132         * Perform a request
    123133         *
    124          * @throws Requests_Exception On a cURL error (`curlerror`)
    125          *
    126          * @param string $url URL to request
     134         * @param string|Stringable $url URL to request
    127135         * @param array $headers Associative array of request headers
    128136         * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
    129          * @param array $options Request options, see {@see Requests::response()} for documentation
     137         * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
    130138         * @return string Raw HTTP result
    131          */
    132         public function request($url, $headers = array(), $data = array(), $options = array()) {
     139         *
     140         * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string or Stringable.
     141         * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $headers argument is not an array.
     142         * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data parameter is not an array or string.
     143         * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
     144         * @throws \WpOrg\Requests\Exception       On a cURL error (`curlerror`)
     145         */
     146        public function request($url, $headers = [], $data = [], $options = []) {
     147                if (InputValidator::is_string_or_stringable($url) === false) {
     148                        throw InvalidArgument::create(1, '$url', 'string|Stringable', gettype($url));
     149                }
     150
     151                if (is_array($headers) === false) {
     152                        throw InvalidArgument::create(2, '$headers', 'array', gettype($headers));
     153                }
     154
     155                if (!is_array($data) && !is_string($data)) {
     156                        if ($data === null) {
     157                                $data = '';
     158                        } else {
     159                                throw InvalidArgument::create(3, '$data', 'array|string', gettype($data));
     160                        }
     161                }
     162
     163                if (is_array($options) === false) {
     164                        throw InvalidArgument::create(4, '$options', 'array', gettype($options));
     165                }
     166
    133167                $this->hooks = $options['hooks'];
    134168
    135169                $this->setup_handle($url, $headers, $data, $options);
    136170
    137                 $options['hooks']->dispatch('curl.before_send', array(&$this->handle));
     171                $options['hooks']->dispatch('curl.before_send', [&$this->handle]);
    138172
    139173                if ($options['filename'] !== false) {
    140                         $this->stream_handle = fopen($options['filename'], 'wb');
     174                        // phpcs:ignore WordPress.PHP.NoSilencedErrors -- Silenced the PHP native warning in favour of throwing an exception.
     175                        $this->stream_handle = @fopen($options['filename'], 'wb');
     176                        if ($this->stream_handle === false) {
     177                                $error = error_get_last();
     178                                throw new Exception($error['message'], 'fopen');
     179                        }
    141180                }
    142181
    … …  
    165204                $response = $this->response_data;
    166205
    167                 $options['hooks']->dispatch('curl.after_send', array());
    168 
    169                 if (curl_errno($this->handle) === 23 || curl_errno($this->handle) === 61) {
     206                $options['hooks']->dispatch('curl.after_send', []);
     207
     208                if (curl_errno($this->handle) === CURLE_WRITE_ERROR || curl_errno($this->handle) === CURLE_BAD_CONTENT_ENCODING) {
    170209                        // Reset encoding and try again
    171210                        curl_setopt($this->handle, CURLOPT_ENCODING, 'none');
    … …  
    180219
    181220                // Need to remove the $this reference from the curl handle.
    182                 // Otherwise Requests_Transport_cURL wont be garbage collected and the curl_close() will never be called.
     221                // Otherwise \WpOrg\Requests\Transport\Curl won't be garbage collected and the curl_close() will never be called.
    183222                curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null);
    184223                curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null);
    … …  
    192231         * @param array $requests Request data
    193232         * @param array $options Global options
    194          * @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well)
     233         * @return array Array of \WpOrg\Requests\Response objects (may contain \WpOrg\Requests\Exception or string responses as well)
     234         *
     235         * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access.
     236         * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
    195237         */
    196238        public function request_multiple($requests, $options) {
    197239                // If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
    198240                if (empty($requests)) {
    199                         return array();
     241                        return [];
     242                }
     243
     244                if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
     245                        throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests));
     246                }
     247
     248                if (is_array($options) === false) {
     249                        throw InvalidArgument::create(2, '$options', 'array', gettype($options));
    200250                }
    201251
    202252                $multihandle = curl_multi_init();
    203                 $subrequests = array();
    204                 $subhandles  = array();
     253                $subrequests = [];
     254                $subhandles  = [];
    205255
    206256                $class = get_class($this);
    … …  
    208258                        $subrequests[$id] = new $class();
    209259                        $subhandles[$id]  = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']);
    210                         $request['options']['hooks']->dispatch('curl.before_multi_add', array(&$subhandles[$id]));
     260                        $request['options']['hooks']->dispatch('curl.before_multi_add', [&$subhandles[$id]]);
    211261                        curl_multi_add_handle($multihandle, $subhandles[$id]);
    212262                }
    213263
    214264                $completed       = 0;
    215                 $responses       = array();
     265                $responses       = [];
    216266                $subrequestcount = count($subrequests);
    217267
    218                 $request['options']['hooks']->dispatch('curl.before_multi_exec', array(&$multihandle));
     268                $request['options']['hooks']->dispatch('curl.before_multi_exec', [&$multihandle]);
    219269
    220270                do {
    … …  
    226276                        while ($status === CURLM_CALL_MULTI_PERFORM);
    227277
    228                         $to_process = array();
     278                        $to_process = [];
    229279
    230280                        // Read the information as needed
    … …  
    242292                                        //get error string for handle.
    243293                                        $reason          = curl_error($done['handle']);
    244                                         $exception       = new Requests_Exception_Transport_cURL(
     294                                        $exception       = new CurlException(
    245295                                                $reason,
    246                                                 Requests_Exception_Transport_cURL::EASY,
     296                                                CurlException::EASY,
    247297                                                $done['handle'],
    248298                                                $done['result']
    249299                                        );
    250300                                        $responses[$key] = $exception;
    251                                         $options['hooks']->dispatch('transport.internal.parse_error', array(&$responses[$key], $requests[$key]));
     301                                        $options['hooks']->dispatch('transport.internal.parse_error', [&$responses[$key], $requests[$key]]);
    252302                                }
    253303                                else {
    254304                                        $responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options);
    255305
    256                                         $options['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$key], $requests[$key]));
     306                                        $options['hooks']->dispatch('transport.internal.parse_response', [&$responses[$key], $requests[$key]]);
    257307                                }
    258308
    … …  
    261311
    262312                                if (!is_string($responses[$key])) {
    263                                         $options['hooks']->dispatch('multiple.request.complete', array(&$responses[$key], $key));
     313                                        $options['hooks']->dispatch('multiple.request.complete', [&$responses[$key], $key]);
    264314                                }
    265315                                $completed++;
    … …  
    268318                while ($active || $completed < $subrequestcount);
    269319
    270                 $request['options']['hooks']->dispatch('curl.after_multi_exec', array(&$multihandle));
     320                $request['options']['hooks']->dispatch('curl.after_multi_exec', [&$multihandle]);
    271321
    272322                curl_multi_close($multihandle);
    … …  
    281331         * @param array $headers Associative array of request headers
    282332         * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
    283          * @param array $options Request options, see {@see Requests::response()} for documentation
    284          * @return resource Subrequest's cURL handle
     333         * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
     334         * @return resource|\CurlHandle Subrequest's cURL handle
    285335         */
    286336        public function &get_subrequest_handle($url, $headers, $data, $options) {
    … …  
    308358         * @param array $headers Associative array of request headers
    309359         * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
    310          * @param array $options Request options, see {@see Requests::response()} for documentation
    311          */
    312         protected function setup_handle($url, $headers, $data, $options) {
    313                 $options['hooks']->dispatch('curl.before_request', array(&$this->handle));
     360         * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
     361         */
     362        private function setup_handle($url, $headers, $data, $options) {
     363                $options['hooks']->dispatch('curl.before_request', [&$this->handle]);
    314364
    315365                // Force closing the connection for old versions of cURL (<7.22).
    … …  
    343393                        }
    344394                        elseif (!is_string($data)) {
    345                                 $data = http_build_query($data, null, '&');
     395                                $data = http_build_query($data, '', '&');
    346396                        }
    347397                }
    … …  
    394444                }
    395445                curl_setopt($this->handle, CURLOPT_URL, $url);
    396                 curl_setopt($this->handle, CURLOPT_REFERER, $url);
    397446                curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']);
    398447                if (!empty($headers)) {
    … …  
    407456
    408457                if ($options['blocking'] === true) {
    409                         curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array($this, 'stream_headers'));
    410                         curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, array($this, 'stream_body'));
     458                        curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, [$this, 'stream_headers']);
     459                        curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, [$this, 'stream_body']);
    411460                        curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE);
    412461                }
    … …  
    419468         * @param array $options Request options
    420469         * @return string|false HTTP response data including headers. False if non-blocking.
    421          * @throws Requests_Exception
     470         * @throws \WpOrg\Requests\Exception
    422471         */
    423472        public function process_response($response, $options) {
    424473                if ($options['blocking'] === false) {
    425474                        $fake_headers = '';
    426                         $options['hooks']->dispatch('curl.after_request', array(&$fake_headers));
     475                        $options['hooks']->dispatch('curl.after_request', [&$fake_headers]);
    427476                        return false;
    428477                }
    … …  
    441490                                curl_error($this->handle)
    442491                        );
    443                         throw new Requests_Exception($error, 'curlerror', $this->handle);
     492                        throw new Exception($error, 'curlerror', $this->handle);
    444493                }
    445494                $this->info = curl_getinfo($this->handle);
    446495
    447                 $options['hooks']->dispatch('curl.after_request', array(&$this->headers, &$this->info));
     496                $options['hooks']->dispatch('curl.after_request', [&$this->headers, &$this->info]);
    448497                return $this->headers;
    449498        }
    … …  
    452501         * Collect the headers as they are received
    453502         *
    454          * @param resource $handle cURL resource
     503         * @param resource|\CurlHandle $handle cURL handle
    455504         * @param string $headers Header string
    456505         * @return integer Length of provided header
    … …  
    477526         * @since 1.6.1
    478527         *
    479          * @param resource $handle cURL resource
     528         * @param resource|\CurlHandle $handle cURL handle
    480529         * @param string $data Body data
    481530         * @return integer Length of provided data
    482531         */
    483532        public function stream_body($handle, $data) {
    484                 $this->hooks->dispatch('request.progress', array($data, $this->response_bytes, $this->response_byte_limit));
     533                $this->hooks->dispatch('request.progress', [$data, $this->response_bytes, $this->response_byte_limit]);
    485534                $data_length = strlen($data);
    486535
    … …  
    514563         *
    515564         * @param string $url
    516          * @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query}
     565         * @param array|object $data Data to build query using, see {@link https://www.php.net/http_build_query}
    517566         * @return string URL with data
    518567         */
    519         protected static function format_get($url, $data) {
     568        private static function format_get($url, $data) {
    520569                if (!empty($data)) {
    521570                        $query     = '';
    … …  
    528577                        }
    529578
    530                         $query .= '&' . http_build_query($data, null, '&');
     579                        $query .= '&' . http_build_query($data, '', '&');
    531580                        $query  = trim($query, '&');
    532581
    … …  
    542591
    543592        /**
    544          * Whether this transport is valid
     593         * Self-test whether the transport can be used.
     594         *
     595         * The available capabilities to test for can be found in {@see \WpOrg\Requests\Capability}.
    545596         *
    546597         * @codeCoverageIgnore
    547          * @return boolean True if the transport is valid, false otherwise.
    548          */
    549         public static function test($capabilities = array()) {
     598         * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
     599         * @return bool Whether the transport can be used.
     600         */
     601        public static function test($capabilities = []) {
    550602                if (!function_exists('curl_init') || !function_exists('curl_exec')) {
    551603                        return false;
    … …  
    553605
    554606                // If needed, check that our installed curl version supports SSL
    555                 if (isset($capabilities['ssl']) && $capabilities['ssl']) {
     607                if (isset($capabilities[Capability::SSL]) && $capabilities[Capability::SSL]) {
    556608                        $curl_version = curl_version();
    557609                        if (!(CURL_VERSION_SSL & $curl_version['features'])) {
    … …  
    569621         * @return string The "Expect" header.
    570622         */
    571         protected function get_expect_header($data) {
     623        private function get_expect_header($data) {
    572624                if (!is_array($data)) {
    573625                        return strlen((string) $data) >= 1048576 ? '100-Continue' : '';
Note: See TracChangeset for help on using the changeset viewer.