[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/Requests/src/ -> Requests.php (source)

   1  <?php
   2  /**
   3   * Requests for PHP
   4   *
   5   * Inspired by Requests for Python.
   6   *
   7   * Based on concepts from SimplePie_File, RequestCore and WP_Http.
   8   *
   9   * @package Requests
  10   */
  11  
  12  namespace WpOrg\Requests;
  13  
  14  use WpOrg\Requests\Auth\Basic;
  15  use WpOrg\Requests\Capability;
  16  use WpOrg\Requests\Cookie\Jar;
  17  use WpOrg\Requests\Exception;
  18  use WpOrg\Requests\Exception\InvalidArgument;
  19  use WpOrg\Requests\Hooks;
  20  use WpOrg\Requests\IdnaEncoder;
  21  use WpOrg\Requests\Iri;
  22  use WpOrg\Requests\Proxy\Http;
  23  use WpOrg\Requests\Response;
  24  use WpOrg\Requests\Transport\Curl;
  25  use WpOrg\Requests\Transport\Fsockopen;
  26  use WpOrg\Requests\Utility\InputValidator;
  27  use WpOrg\Requests\Utility\Trim;
  28  
  29  /**
  30   * Requests for PHP
  31   *
  32   * Inspired by Requests for Python.
  33   *
  34   * Based on concepts from SimplePie_File, RequestCore and WP_Http.
  35   *
  36   * @package Requests
  37   */
  38  class Requests {
  39      /**
  40       * Current version of Requests
  41       *
  42       * @var string
  43       */
  44      const VERSION = '2.0.21';
  45  
  46      /**
  47       * POST method
  48       *
  49       * @var string
  50       */
  51      const POST = 'POST';
  52  
  53      /**
  54       * PUT method
  55       *
  56       * @var string
  57       */
  58      const PUT = 'PUT';
  59  
  60      /**
  61       * GET method
  62       *
  63       * @var string
  64       */
  65      const GET = 'GET';
  66  
  67      /**
  68       * HEAD method
  69       *
  70       * @var string
  71       */
  72      const HEAD = 'HEAD';
  73  
  74      /**
  75       * DELETE method
  76       *
  77       * @var string
  78       */
  79      const DELETE = 'DELETE';
  80  
  81      /**
  82       * OPTIONS method
  83       *
  84       * @var string
  85       */
  86      const OPTIONS = 'OPTIONS';
  87  
  88      /**
  89       * TRACE method
  90       *
  91       * @var string
  92       */
  93      const TRACE = 'TRACE';
  94  
  95      /**
  96       * PATCH method
  97       *
  98       * @link https://tools.ietf.org/html/rfc5789
  99       * @var string
 100       */
 101      const PATCH = 'PATCH';
 102  
 103      /**
 104       * Default size of buffer size to read streams
 105       *
 106       * @var integer
 107       */
 108      const BUFFER_SIZE = 1160;
 109  
 110      /**
 111       * Option defaults.
 112       *
 113       * @see \WpOrg\Requests\Requests::get_default_options()
 114       * @see \WpOrg\Requests\Requests::request() for values returned by this method
 115       *
 116       * @since 2.0.0
 117       *
 118       * @var array
 119       */
 120      const OPTION_DEFAULTS = [
 121          'timeout'          => 10,
 122          'connect_timeout'  => 10,
 123          'useragent'        => 'php-requests/' . self::VERSION,
 124          'protocol_version' => 1.1,
 125          'redirected'       => 0,
 126          'redirects'        => 10,
 127          'follow_redirects' => true,
 128          'blocking'         => true,
 129          'type'             => self::GET,
 130          'filename'         => false,
 131          'auth'             => false,
 132          'proxy'            => false,
 133          'cookies'          => false,
 134          'max_bytes'        => false,
 135          'idn'              => true,
 136          'hooks'            => null,
 137          'transport'        => null,
 138          'verify'           => null,
 139          'verifyname'       => true,
 140      ];
 141  
 142      /**
 143       * Default supported Transport classes.
 144       *
 145       * @since 2.0.0
 146       *
 147       * @var array
 148       */
 149      const DEFAULT_TRANSPORTS = [
 150          Curl::class      => Curl::class,
 151          Fsockopen::class => Fsockopen::class,
 152      ];
 153  
 154      /**
 155       * Selected transport name
 156       *
 157       * Use {@see \WpOrg\Requests\Requests::get_transport()} instead
 158       *
 159       * @var array
 160       */
 161      public static $transport = [];
 162  
 163      /**
 164       * Registered transport classes
 165       *
 166       * @var array
 167       */
 168      protected static $transports = [];
 169  
 170      /**
 171       * Default certificate path.
 172       *
 173       * @see \WpOrg\Requests\Requests::get_certificate_path()
 174       * @see \WpOrg\Requests\Requests::set_certificate_path()
 175       *
 176       * @var string
 177       */
 178      protected static $certificate_path = __DIR__ . '/../certificates/cacert.pem';
 179  
 180      /**
 181       * All (known) valid deflate, gzip header magic markers.
 182       *
 183       * These markers relate to different compression levels.
 184       *
 185       * @link https://stackoverflow.com/a/43170354/482864 Marker source.
 186       *
 187       * @since 2.0.0
 188       *
 189       * @var array
 190       */
 191      private static $magic_compression_headers = [
 192          "\x1f\x8b" => true, // Gzip marker.
 193          "\x78\x01" => true, // Zlib marker - level 1.
 194          "\x78\x5e" => true, // Zlib marker - level 2 to 5.
 195          "\x78\x9c" => true, // Zlib marker - level 6.
 196          "\x78\xda" => true, // Zlib marker - level 7 to 9.
 197      ];
 198  
 199      /**
 200       * This is a static class, do not instantiate it
 201       *
 202       * @codeCoverageIgnore
 203       */
 204  	private function __construct() {}
 205  
 206      /**
 207       * Register a transport
 208       *
 209       * @param string $transport Transport class to add, must support the \WpOrg\Requests\Transport interface
 210       */
 211  	public static function add_transport($transport) {
 212          if (empty(self::$transports)) {
 213              self::$transports = self::DEFAULT_TRANSPORTS;
 214          }
 215  
 216          self::$transports[$transport] = $transport;
 217      }
 218  
 219      /**
 220       * Get the fully qualified class name (FQCN) for a working transport.
 221       *
 222       * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
 223       * @return string FQCN of the transport to use, or an empty string if no transport was
 224       *                found which provided the requested capabilities.
 225       */
 226  	protected static function get_transport_class(array $capabilities = []) {
 227          // Caching code, don't bother testing coverage.
 228          // @codeCoverageIgnoreStart
 229          // Array of capabilities as a string to be used as an array key.
 230          ksort($capabilities);
 231          $cap_string = serialize($capabilities);
 232  
 233          // Don't search for a transport if it's already been done for these $capabilities.
 234          if (isset(self::$transport[$cap_string])) {
 235              return self::$transport[$cap_string];
 236          }
 237  
 238          // Ensure we will not run this same check again later on.
 239          self::$transport[$cap_string] = '';
 240          // @codeCoverageIgnoreEnd
 241  
 242          if (empty(self::$transports)) {
 243              self::$transports = self::DEFAULT_TRANSPORTS;
 244          }
 245  
 246          // Find us a working transport.
 247          foreach (self::$transports as $class) {
 248              if (!class_exists($class)) {
 249                  continue;
 250              }
 251  
 252              $result = $class::test($capabilities);
 253              if ($result === true) {
 254                  self::$transport[$cap_string] = $class;
 255                  break;
 256              }
 257          }
 258  
 259          return self::$transport[$cap_string];
 260      }
 261  
 262      /**
 263       * Get a working transport.
 264       *
 265       * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
 266       * @return \WpOrg\Requests\Transport
 267       * @throws \WpOrg\Requests\Exception If no valid transport is found (`notransport`).
 268       */
 269  	protected static function get_transport(array $capabilities = []) {
 270          $class = self::get_transport_class($capabilities);
 271  
 272          if ($class === '') {
 273              throw new Exception('No working transports found', 'notransport', self::$transports);
 274          }
 275  
 276          return new $class();
 277      }
 278  
 279      /**
 280       * Checks to see if we have a transport for the capabilities requested.
 281       *
 282       * Supported capabilities can be found in the {@see \WpOrg\Requests\Capability}
 283       * interface as constants.
 284       *
 285       * Example usage:
 286       * `Requests::has_capabilities([Capability::SSL => true])`.
 287       *
 288       * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
 289       * @return bool Whether the transport has the requested capabilities.
 290       */
 291  	public static function has_capabilities(array $capabilities = []) {
 292          return self::get_transport_class($capabilities) !== '';
 293      }
 294  
 295      /**#@+
 296       * @see \WpOrg\Requests\Requests::request()
 297       * @param string $url
 298       * @param array $headers
 299       * @param array $options
 300       * @return \WpOrg\Requests\Response
 301       */
 302      /**
 303       * Send a GET request
 304       */
 305  	public static function get($url, $headers = [], $options = []) {
 306          return self::request($url, $headers, null, self::GET, $options);
 307      }
 308  
 309      /**
 310       * Send a HEAD request
 311       */
 312  	public static function head($url, $headers = [], $options = []) {
 313          return self::request($url, $headers, null, self::HEAD, $options);
 314      }
 315  
 316      /**
 317       * Send a DELETE request
 318       */
 319  	public static function delete($url, $headers = [], $options = []) {
 320          return self::request($url, $headers, null, self::DELETE, $options);
 321      }
 322  
 323      /**
 324       * Send a TRACE request
 325       */
 326  	public static function trace($url, $headers = [], $options = []) {
 327          return self::request($url, $headers, null, self::TRACE, $options);
 328      }
 329      /**#@-*/
 330  
 331      /**#@+
 332       * @see \WpOrg\Requests\Requests::request()
 333       * @param string $url
 334       * @param array $headers
 335       * @param array $data
 336       * @param array $options
 337       * @return \WpOrg\Requests\Response
 338       */
 339      /**
 340       * Send a POST request
 341       */
 342  	public static function post($url, $headers = [], $data = [], $options = []) {
 343          return self::request($url, $headers, $data, self::POST, $options);
 344      }
 345      /**
 346       * Send a PUT request
 347       */
 348  	public static function put($url, $headers = [], $data = [], $options = []) {
 349          return self::request($url, $headers, $data, self::PUT, $options);
 350      }
 351  
 352      /**
 353       * Send an OPTIONS request
 354       */
 355  	public static function options($url, $headers = [], $data = [], $options = []) {
 356          return self::request($url, $headers, $data, self::OPTIONS, $options);
 357      }
 358  
 359      /**
 360       * Send a PATCH request
 361       *
 362       * Note: Unlike {@see \WpOrg\Requests\Requests::post()} and {@see \WpOrg\Requests\Requests::put()},
 363       * `$headers` is required, as the specification recommends that should send an ETag
 364       *
 365       * @link https://tools.ietf.org/html/rfc5789
 366       */
 367  	public static function patch($url, $headers, $data = [], $options = []) {
 368          return self::request($url, $headers, $data, self::PATCH, $options);
 369      }
 370      /**#@-*/
 371  
 372      /**
 373       * Main interface for HTTP requests
 374       *
 375       * This method initiates a request and sends it via a transport before
 376       * parsing.
 377       *
 378       * The `$options` parameter takes an associative array with the following
 379       * options:
 380       *
 381       * - `timeout`: How long should we wait for a response?
 382       *    Note: for cURL, a minimum of 1 second applies, as DNS resolution
 383       *    operates at second-resolution only.
 384       *    (float, seconds with a millisecond precision, default: 10, example: 0.01)
 385       * - `connect_timeout`: How long should we wait while trying to connect?
 386       *    (float, seconds with a millisecond precision, default: 10, example: 0.01)
 387       * - `useragent`: Useragent to send to the server
 388       *    (string, default: php-requests/$version)
 389       * - `follow_redirects`: Should we follow 3xx redirects?
 390       *    (boolean, default: true)
 391       * - `redirects`: How many times should we redirect before erroring?
 392       *    (integer, default: 10)
 393       * - `blocking`: Should we block processing on this request?
 394       *    (boolean, default: true)
 395       * - `filename`: File to stream the body to instead.
 396       *    (string|boolean, default: false)
 397       * - `auth`: Authentication handler or array of user/password details to use
 398       *    for Basic authentication
 399       *    (\WpOrg\Requests\Auth|array|boolean, default: false)
 400       * - `proxy`: Proxy details to use for proxy by-passing and authentication
 401       *    (\WpOrg\Requests\Proxy|array|string|boolean, default: false)
 402       * - `max_bytes`: Limit for the response body size.
 403       *    (integer|boolean, default: false)
 404       * - `idn`: Enable IDN parsing
 405       *    (boolean, default: true)
 406       * - `transport`: Custom transport. Either a class name, or a
 407       *    transport object. Defaults to the first working transport from
 408       *    {@see \WpOrg\Requests\Requests::getTransport()}
 409       *    (string|\WpOrg\Requests\Transport, default: {@see \WpOrg\Requests\Requests::getTransport()})
 410       * - `hooks`: Hooks handler.
 411       *    (\WpOrg\Requests\HookManager, default: new WpOrg\Requests\Hooks())
 412       * - `verify`: Should we verify SSL certificates? Allows passing in a custom
 413       *    certificate file as a string. (Using true uses the system-wide root
 414       *    certificate store instead, but this may have different behaviour
 415       *    across transports.)
 416       *    (string|boolean, default: certificates/cacert.pem)
 417       * - `verifyname`: Should we verify the common name in the SSL certificate?
 418       *    (boolean, default: true)
 419       * - `data_format`: How should we send the `$data` parameter?
 420       *    (string, one of 'query' or 'body', default: 'query' for
 421       *    HEAD/GET/DELETE, 'body' for POST/PUT/OPTIONS/PATCH)
 422       *
 423       * @param string|Stringable $url URL to request
 424       * @param array $headers Extra headers to send with the request
 425       * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
 426       * @param string $type HTTP request type (use Requests constants)
 427       * @param array $options Options for the request (see description for more information)
 428       * @return \WpOrg\Requests\Response
 429       *
 430       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string or Stringable.
 431       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $type argument is not a string.
 432       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
 433       * @throws \WpOrg\Requests\Exception On invalid URLs (`nonhttp`)
 434       */
 435  	public static function request($url, $headers = [], $data = [], $type = self::GET, $options = []) {
 436          if (InputValidator::is_string_or_stringable($url) === false) {
 437              throw InvalidArgument::create(1, '$url', 'string|Stringable', gettype($url));
 438          }
 439  
 440          if (is_string($type) === false) {
 441              throw InvalidArgument::create(4, '$type', 'string', gettype($type));
 442          }
 443  
 444          if (is_array($options) === false) {
 445              throw InvalidArgument::create(5, '$options', 'array', gettype($options));
 446          }
 447  
 448          if (empty($options['type'])) {
 449              $options['type'] = $type;
 450          }
 451  
 452          $options = array_merge(self::get_default_options(), $options);
 453  
 454          self::set_defaults($url, $headers, $data, $type, $options);
 455  
 456          $options['hooks']->dispatch('requests.before_request', [&$url, &$headers, &$data, &$type, &$options]);
 457  
 458          if (!empty($options['transport'])) {
 459              $transport = $options['transport'];
 460  
 461              if (is_string($options['transport'])) {
 462                  $transport = new $transport();
 463              }
 464          } else {
 465              $need_ssl     = (stripos($url, 'https://') === 0);
 466              $capabilities = [Capability::SSL => $need_ssl];
 467              $transport    = self::get_transport($capabilities);
 468          }
 469  
 470          $response = $transport->request($url, $headers, $data, $options);
 471  
 472          $options['hooks']->dispatch('requests.before_parse', [&$response, $url, $headers, $data, $type, $options]);
 473  
 474          return self::parse_response($response, $url, $headers, $data, $options);
 475      }
 476  
 477      /**
 478       * Send multiple HTTP requests simultaneously
 479       *
 480       * The `$requests` parameter takes an associative or indexed array of
 481       * request fields. The key of each request can be used to match up the
 482       * request with the returned data, or with the request passed into your
 483       * `multiple.request.complete` callback.
 484       *
 485       * The request fields value is an associative array with the following keys:
 486       *
 487       * - `url`: Request URL Same as the `$url` parameter to
 488       *    {@see \WpOrg\Requests\Requests::request()}
 489       *    (string, required)
 490       * - `headers`: Associative array of header fields. Same as the `$headers`
 491       *    parameter to {@see \WpOrg\Requests\Requests::request()}
 492       *    (array, default: `array()`)
 493       * - `data`: Associative array of data fields or a string. Same as the
 494       *    `$data` parameter to {@see \WpOrg\Requests\Requests::request()}
 495       *    (array|string, default: `array()`)
 496       * - `type`: HTTP request type (use \WpOrg\Requests\Requests constants). Same as the `$type`
 497       *    parameter to {@see \WpOrg\Requests\Requests::request()}
 498       *    (string, default: `\WpOrg\Requests\Requests::GET`)
 499       * - `cookies`: Associative array of cookie name to value, or cookie jar.
 500       *    (array|\WpOrg\Requests\Cookie\Jar)
 501       *
 502       * If the `$options` parameter is specified, individual requests will
 503       * inherit options from it. This can be used to use a single hooking system,
 504       * or set all the types to `\WpOrg\Requests\Requests::POST`, for example.
 505       *
 506       * In addition, the `$options` parameter takes the following global options:
 507       *
 508       * - `complete`: A callback for when a request is complete. Takes two
 509       *    parameters, a \WpOrg\Requests\Response/\WpOrg\Requests\Exception reference, and the
 510       *    ID from the request array (Note: this can also be overridden on a
 511       *    per-request basis, although that's a little silly)
 512       *    (callback)
 513       *
 514       * @param array $requests Requests data (see description for more information)
 515       * @param array $options Global and default options (see {@see \WpOrg\Requests\Requests::request()})
 516       * @return array Responses (either \WpOrg\Requests\Response or a \WpOrg\Requests\Exception object)
 517       *
 518       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access.
 519       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
 520       */
 521  	public static function request_multiple($requests, $options = []) {
 522          if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
 523              throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests));
 524          }
 525  
 526          if (is_array($options) === false) {
 527              throw InvalidArgument::create(2, '$options', 'array', gettype($options));
 528          }
 529  
 530          $options = array_merge(self::get_default_options(true), $options);
 531  
 532          if (!empty($options['hooks'])) {
 533              $options['hooks']->register('transport.internal.parse_response', [static::class, 'parse_multiple']);
 534              if (!empty($options['complete'])) {
 535                  $options['hooks']->register('multiple.request.complete', $options['complete']);
 536              }
 537          }
 538  
 539          foreach ($requests as $id => &$request) {
 540              if (!isset($request['headers'])) {
 541                  $request['headers'] = [];
 542              }
 543  
 544              if (!isset($request['data'])) {
 545                  $request['data'] = [];
 546              }
 547  
 548              if (!isset($request['type'])) {
 549                  $request['type'] = self::GET;
 550              }
 551  
 552              if (!isset($request['options'])) {
 553                  $request['options']         = $options;
 554                  $request['options']['type'] = $request['type'];
 555              } else {
 556                  if (empty($request['options']['type'])) {
 557                      $request['options']['type'] = $request['type'];
 558                  }
 559  
 560                  $request['options'] = array_merge($options, $request['options']);
 561              }
 562  
 563              self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
 564  
 565              // Ensure we only hook in once
 566              if ($request['options']['hooks'] !== $options['hooks']) {
 567                  $request['options']['hooks']->register('transport.internal.parse_response', [static::class, 'parse_multiple']);
 568                  if (!empty($request['options']['complete'])) {
 569                      $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
 570                  }
 571              }
 572          }
 573  
 574          unset($request);
 575  
 576          if (!empty($options['transport'])) {
 577              $transport = $options['transport'];
 578  
 579              if (is_string($options['transport'])) {
 580                  $transport = new $transport();
 581              }
 582          } else {
 583              $transport = self::get_transport();
 584          }
 585  
 586          $responses = $transport->request_multiple($requests, $options);
 587  
 588          foreach ($responses as $id => &$response) {
 589              // If our hook got messed with somehow, ensure we end up with the
 590              // correct response
 591              if (is_string($response)) {
 592                  $request = $requests[$id];
 593                  self::parse_multiple($response, $request);
 594                  $request['options']['hooks']->dispatch('multiple.request.complete', [&$response, $id]);
 595              }
 596          }
 597  
 598          return $responses;
 599      }
 600  
 601      /**
 602       * Get the default options
 603       *
 604       * @see \WpOrg\Requests\Requests::request() for values returned by this method
 605       * @param boolean $multirequest Is this a multirequest?
 606       * @return array Default option values
 607       */
 608  	protected static function get_default_options($multirequest = false) {
 609          $defaults           = static::OPTION_DEFAULTS;
 610          $defaults['verify'] = self::$certificate_path;
 611  
 612          if ($multirequest !== false) {
 613              $defaults['complete'] = null;
 614          }
 615  
 616          return $defaults;
 617      }
 618  
 619      /**
 620       * Get default certificate path.
 621       *
 622       * @return string Default certificate path.
 623       */
 624  	public static function get_certificate_path() {
 625          return self::$certificate_path;
 626      }
 627  
 628      /**
 629       * Set default certificate path.
 630       *
 631       * @param string|Stringable|bool $path Certificate path, pointing to a PEM file.
 632       *
 633       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string, Stringable or boolean.
 634       */
 635  	public static function set_certificate_path($path) {
 636          if (InputValidator::is_string_or_stringable($path) === false && is_bool($path) === false) {
 637              throw InvalidArgument::create(1, '$path', 'string|Stringable|bool', gettype($path));
 638          }
 639  
 640          self::$certificate_path = $path;
 641      }
 642  
 643      /**
 644       * Set the default values
 645       *
 646       * The $options parameter is updated with the results.
 647       *
 648       * @param string $url URL to request
 649       * @param array $headers Extra headers to send with the request
 650       * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
 651       * @param string $type HTTP request type
 652       * @param array $options Options for the request
 653       * @return void
 654       *
 655       * @throws \WpOrg\Requests\Exception When the $url is not an http(s) URL.
 656       */
 657  	protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
 658          if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
 659              throw new Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url);
 660          }
 661  
 662          if (empty($options['hooks'])) {
 663              $options['hooks'] = new Hooks();
 664          }
 665  
 666          if (is_array($options['auth'])) {
 667              $options['auth'] = new Basic($options['auth']);
 668          }
 669  
 670          if ($options['auth'] !== false) {
 671              $options['auth']->register($options['hooks']);
 672          }
 673  
 674          if (is_string($options['proxy']) || is_array($options['proxy'])) {
 675              $options['proxy'] = new Http($options['proxy']);
 676          }
 677  
 678          if ($options['proxy'] !== false) {
 679              $options['proxy']->register($options['hooks']);
 680          }
 681  
 682          if (is_array($options['cookies'])) {
 683              $options['cookies'] = new Jar($options['cookies']);
 684          } elseif (empty($options['cookies'])) {
 685              $options['cookies'] = new Jar();
 686          }
 687  
 688          if ($options['cookies'] !== false) {
 689              $options['cookies']->register($options['hooks']);
 690          }
 691  
 692          if ($options['idn'] !== false) {
 693              $iri       = new Iri($url);
 694              $iri->host = IdnaEncoder::encode($iri->ihost);
 695              $url       = $iri->uri;
 696          }
 697  
 698          // Massage the type to ensure we support it.
 699          $type = strtoupper($type);
 700  
 701          if (!isset($options['data_format'])) {
 702              if (in_array($type, [self::HEAD, self::GET, self::DELETE], true)) {
 703                  $options['data_format'] = 'query';
 704              } else {
 705                  $options['data_format'] = 'body';
 706              }
 707          }
 708      }
 709  
 710      /**
 711       * HTTP response parser
 712       *
 713       * @param string $headers Full response text including headers and body
 714       * @param string $url Original request URL
 715       * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
 716       * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
 717       * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
 718       * @return \WpOrg\Requests\Response
 719       *
 720       * @throws \WpOrg\Requests\Exception On missing head/body separator (`requests.no_crlf_separator`)
 721       * @throws \WpOrg\Requests\Exception On missing head/body separator (`noversion`)
 722       * @throws \WpOrg\Requests\Exception On missing head/body separator (`toomanyredirects`)
 723       */
 724  	protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
 725          $return = new Response();
 726          if (!$options['blocking']) {
 727              return $return;
 728          }
 729  
 730          $return->raw  = $headers;
 731          $return->url  = (string) $url;
 732          $return->body = '';
 733  
 734          if (!$options['filename']) {
 735              $pos = strpos($headers, "\r\n\r\n");
 736              if ($pos === false) {
 737                  // Crap!
 738                  throw new Exception('Missing header/body separator', 'requests.no_crlf_separator');
 739              }
 740  
 741              $headers = substr($return->raw, 0, $pos);
 742              // Headers will always be separated from the body by two new lines - `\n\r\n\r`.
 743              $body = substr($return->raw, $pos + 4);
 744              if (!empty($body)) {
 745                  $return->body = $body;
 746              }
 747          }
 748  
 749          // Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
 750          $headers = str_replace("\r\n", "\n", $headers);
 751          // Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
 752          $headers = preg_replace('/\n[ \t]/', ' ', $headers);
 753          $headers = explode("\n", $headers);
 754          preg_match('#^HTTP/(1\.\d)[ \t]+(\d+)#i', array_shift($headers), $matches);
 755          if (empty($matches)) {
 756              throw new Exception('Response could not be parsed', 'noversion', $headers);
 757          }
 758  
 759          $return->protocol_version = (float) $matches[1];
 760          $return->status_code      = (int) $matches[2];
 761          if ($return->status_code >= 200 && $return->status_code < 300) {
 762              $return->success = true;
 763          }
 764  
 765          foreach ($headers as $header) {
 766              list($key, $value) = explode(':', $header, 2);
 767              $value             = trim($value, Trim::WHITESPACE_CHARS_NO_FF);
 768              preg_replace('#(\s+)#i', ' ', $value);
 769              $return->headers[$key] = $value;
 770          }
 771  
 772          if (isset($return->headers['transfer-encoding'])) {
 773              $return->body = self::decode_chunked($return->body);
 774              unset($return->headers['transfer-encoding']);
 775          }
 776  
 777          if (isset($return->headers['content-encoding'])) {
 778              $return->body = self::decompress($return->body);
 779          }
 780  
 781          //fsockopen and cURL compatibility
 782          if (isset($return->headers['connection'])) {
 783              unset($return->headers['connection']);
 784          }
 785  
 786          $options['hooks']->dispatch('requests.before_redirect_check', [&$return, $req_headers, $req_data, $options]);
 787  
 788          if ($return->is_redirect() && $options['follow_redirects'] === true) {
 789              if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
 790                  if ($return->status_code === 303) {
 791                      $options['type'] = self::GET;
 792                  }
 793  
 794                  ++$options['redirected'];
 795                  $location = $return->headers['location'];
 796                  if (strpos($location, 'http://') !== 0 && strpos($location, 'https://') !== 0) {
 797                      // relative redirect, for compatibility make it absolute
 798                      $location = Iri::absolutize($url, $location);
 799                      $location = $location->uri;
 800                  }
 801  
 802                  $hook_args = [
 803                      &$location,
 804                      &$req_headers,
 805                      &$req_data,
 806                      &$options,
 807                      $return,
 808                  ];
 809                  $options['hooks']->dispatch('requests.before_redirect', $hook_args);
 810                  $redirected            = self::request($location, $req_headers, $req_data, $options['type'], $options);
 811                  $redirected->history[] = $return;
 812                  return $redirected;
 813              } elseif ($options['redirected'] >= $options['redirects']) {
 814                  throw new Exception('Too many redirects', 'toomanyredirects', $return);
 815              }
 816          }
 817  
 818          $return->redirects = $options['redirected'];
 819  
 820          $options['hooks']->dispatch('requests.after_request', [&$return, $req_headers, $req_data, $options]);
 821          return $return;
 822      }
 823  
 824      /**
 825       * Callback for `transport.internal.parse_response`
 826       *
 827       * Internal use only. Converts a raw HTTP response to a \WpOrg\Requests\Response
 828       * while still executing a multiple request.
 829       *
 830       * `$response` is either set to a \WpOrg\Requests\Response instance, or a \WpOrg\Requests\Exception object
 831       *
 832       * @param string $response Full response text including headers and body (will be overwritten with Response instance)
 833       * @param array $request Request data as passed into {@see \WpOrg\Requests\Requests::request_multiple()}
 834       * @return void
 835       */
 836  	public static function parse_multiple(&$response, $request) {
 837          try {
 838              $url      = $request['url'];
 839              $headers  = $request['headers'];
 840              $data     = $request['data'];
 841              $options  = $request['options'];
 842              $response = self::parse_response($response, $url, $headers, $data, $options);
 843          } catch (Exception $e) {
 844              $response = $e;
 845          }
 846      }
 847  
 848      /**
 849       * Decoded a chunked body as per RFC 2616
 850       *
 851       * @link https://tools.ietf.org/html/rfc2616#section-3.6.1
 852       * @param string $data Chunked body
 853       * @return string Decoded body
 854       */
 855  	protected static function decode_chunked($data) {
 856          if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data, Trim::WHITESPACE_CHARS_NO_FF))) {
 857              return $data;
 858          }
 859  
 860          $decoded = '';
 861          $encoded = $data;
 862  
 863          while (true) {
 864              $is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches);
 865              if (!$is_chunked) {
 866                  // Looks like it's not chunked after all
 867                  return $data;
 868              }
 869  
 870              $length = hexdec(trim($matches[1], Trim::WHITESPACE_CHARS_NO_FF));
 871              if ($length === 0) {
 872                  // Ignore trailer headers
 873                  return $decoded;
 874              }
 875  
 876              $chunk_length = strlen($matches[0]);
 877              $decoded     .= substr($encoded, $chunk_length, $length);
 878              $encoded      = substr($encoded, $chunk_length + $length + 2);
 879  
 880              if (trim($encoded, Trim::WHITESPACE_CHARS_NO_FF) === '0' || empty($encoded)) {
 881                  return $decoded;
 882              }
 883          }
 884  
 885          // We'll never actually get down here
 886          // @codeCoverageIgnoreStart
 887      }
 888      // @codeCoverageIgnoreEnd
 889  
 890      /**
 891       * Convert a key => value array to a 'key: value' array for headers
 892       *
 893       * @param iterable $dictionary Dictionary of header values
 894       * @return array List of headers
 895       *
 896       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not iterable.
 897       */
 898  	public static function flatten($dictionary) {
 899          if (InputValidator::is_iterable($dictionary) === false) {
 900              throw InvalidArgument::create(1, '$dictionary', 'iterable', gettype($dictionary));
 901          }
 902  
 903          $return = [];
 904          foreach ($dictionary as $key => $value) {
 905              $return[] = sprintf('%s: %s', $key, $value);
 906          }
 907  
 908          return $return;
 909      }
 910  
 911      /**
 912       * Decompress an encoded body
 913       *
 914       * Implements gzip, compress and deflate. Guesses which it is by attempting
 915       * to decode.
 916       *
 917       * @param string $data Compressed data in one of the above formats
 918       * @return string Decompressed string
 919       *
 920       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string.
 921       */
 922  	public static function decompress($data) {
 923          if (is_string($data) === false) {
 924              throw InvalidArgument::create(1, '$data', 'string', gettype($data));
 925          }
 926  
 927          if (trim($data, Trim::WHITESPACE_CHARS_NO_FF) === '') {
 928              // Empty body does not need further processing.
 929              return $data;
 930          }
 931  
 932          $marker = substr($data, 0, 2);
 933          if (!isset(self::$magic_compression_headers[$marker])) {
 934              // Not actually compressed. Probably cURL ruining this for us.
 935              return $data;
 936          }
 937  
 938          if (function_exists('gzdecode')) {
 939              $decoded = @gzdecode($data);
 940              if ($decoded !== false) {
 941                  return $decoded;
 942              }
 943          }
 944  
 945          if (function_exists('gzinflate')) {
 946              $decoded = @gzinflate($data);
 947              if ($decoded !== false) {
 948                  return $decoded;
 949              }
 950          }
 951  
 952          $decoded = self::compatible_gzinflate($data);
 953          if ($decoded !== false) {
 954              return $decoded;
 955          }
 956  
 957          if (function_exists('gzuncompress')) {
 958              $decoded = @gzuncompress($data);
 959              if ($decoded !== false) {
 960                  return $decoded;
 961              }
 962          }
 963  
 964          return $data;
 965      }
 966  
 967      /**
 968       * Decompression of deflated string while staying compatible with the majority of servers.
 969       *
 970       * Certain Servers will return deflated data with headers which PHP's gzinflate()
 971       * function cannot handle out of the box. The following function has been created from
 972       * various snippets on the gzinflate() PHP documentation.
 973       *
 974       * Warning: Magic numbers within. Due to the potential different formats that the compressed
 975       * data may be returned in, some "magic offsets" are needed to ensure proper decompression
 976       * takes place. For a simple progmatic way to determine the magic offset in use, see:
 977       * https://core.trac.wordpress.org/ticket/18273
 978       *
 979       * @since 1.6.0
 980       * @link https://core.trac.wordpress.org/ticket/18273
 981       * @link https://www.php.net/gzinflate#70875
 982       * @link https://www.php.net/gzinflate#77336
 983       *
 984       * @param string $gz_data String to decompress.
 985       * @return string|bool False on failure.
 986       *
 987       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string.
 988       */
 989  	public static function compatible_gzinflate($gz_data) {
 990          if (is_string($gz_data) === false) {
 991              throw InvalidArgument::create(1, '$gz_data', 'string', gettype($gz_data));
 992          }
 993  
 994          if (trim($gz_data, Trim::WHITESPACE_CHARS_NO_FF) === '') {
 995              return false;
 996          }
 997  
 998          // Compressed data might contain a full zlib header, if so strip it for
 999          // gzinflate()
1000          if (substr($gz_data, 0, 3) === "\x1f\x8b\x08") {
1001              $i   = 10;
1002              $flg = ord(substr($gz_data, 3, 1));
1003              if ($flg > 0) {
1004                  if ($flg & 4) {
1005                      list($xlen) = unpack('v', substr($gz_data, $i, 2));
1006                      $i         += 2 + $xlen;
1007                  }
1008  
1009                  if ($flg & 8) {
1010                      $i = strpos($gz_data, "\0", $i) + 1;
1011                  }
1012  
1013                  if ($flg & 16) {
1014                      $i = strpos($gz_data, "\0", $i) + 1;
1015                  }
1016  
1017                  if ($flg & 2) {
1018                      $i += 2;
1019                  }
1020              }
1021  
1022              $decompressed = self::compatible_gzinflate(substr($gz_data, $i));
1023              if ($decompressed !== false) {
1024                  return $decompressed;
1025              }
1026          }
1027  
1028          // If the data is Huffman Encoded, we must first strip the leading 2
1029          // byte Huffman marker for gzinflate()
1030          // The response is Huffman coded by many compressors such as
1031          // java.util.zip.Deflater, Ruby's Zlib::Deflate, and .NET's
1032          // System.IO.Compression.DeflateStream.
1033          //
1034          // See https://decompres.blogspot.com/ for a quick explanation of this
1035          // data type
1036          $huffman_encoded = false;
1037  
1038          // low nibble of first byte should be 0x08
1039          list(, $first_nibble) = unpack('h', $gz_data);
1040  
1041          // First 2 bytes should be divisible by 0x1F
1042          list(, $first_two_bytes) = unpack('n', $gz_data);
1043  
1044          if ($first_nibble === 0x08 && ($first_two_bytes % 0x1F) === 0) {
1045              $huffman_encoded = true;
1046          }
1047  
1048          if ($huffman_encoded) {
1049              $decompressed = @gzinflate(substr($gz_data, 2));
1050              if ($decompressed !== false) {
1051                  return $decompressed;
1052              }
1053          }
1054  
1055          if (substr($gz_data, 0, 4) === "\x50\x4b\x03\x04") {
1056              // ZIP file format header
1057              // Offset 6: 2 bytes, General-purpose field
1058              // Offset 26: 2 bytes, filename length
1059              // Offset 28: 2 bytes, optional field length
1060              // Offset 30: Filename field, followed by optional field, followed
1061              // immediately by data
1062              list(, $general_purpose_flag) = unpack('v', substr($gz_data, 6, 2));
1063  
1064              // If the file has been compressed on the fly, 0x08 bit is set of
1065              // the general purpose field. We can use this to differentiate
1066              // between a compressed document, and a ZIP file
1067              $zip_compressed_on_the_fly = ((0x08 & $general_purpose_flag) === 0x08);
1068  
1069              if (!$zip_compressed_on_the_fly) {
1070                  // Don't attempt to decode a compressed zip file
1071                  return $gz_data;
1072              }
1073  
1074              // Determine the first byte of data, based on the above ZIP header
1075              // offsets:
1076              $first_file_start = array_sum(unpack('v2', substr($gz_data, 26, 4)));
1077              $decompressed     = @gzinflate(substr($gz_data, 30 + $first_file_start));
1078              if ($decompressed !== false) {
1079                  return $decompressed;
1080              }
1081  
1082              return false;
1083          }
1084  
1085          // Finally fall back to straight gzinflate
1086          $decompressed = @gzinflate($gz_data);
1087          if ($decompressed !== false) {
1088              return $decompressed;
1089          }
1090  
1091          // Fallback for all above failing, not expected, but included for
1092          // debugging and preventing regressions and to track stats
1093          $decompressed = @gzinflate(substr($gz_data, 2));
1094          if ($decompressed !== false) {
1095              return $decompressed;
1096          }
1097  
1098          return false;
1099      }
1100  }


Generated : Sun Nov 22 08:20:01 2026 Cross-referenced by PHPXref