[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-http.php (source)

   1  <?php
   2  /**
   3   * HTTP API: WP_Http class
   4   *
   5   * @package WordPress
   6   * @subpackage HTTP
   7   * @since 2.7.0
   8   */
   9  
  10  // Don't load directly.
  11  if ( ! defined( 'ABSPATH' ) ) {
  12      exit;
  13  }
  14  
  15  if ( ! class_exists( 'WpOrg\Requests\Autoload' ) ) {
  16      require  ABSPATH . WPINC . '/Requests/src/Autoload.php';
  17  
  18      WpOrg\Requests\Autoload::register();
  19      WpOrg\Requests\Requests::set_certificate_path( ABSPATH . WPINC . '/certificates/ca-bundle.crt' );
  20  }
  21  
  22  /**
  23   * Core class used for managing HTTP transports and making HTTP requests.
  24   *
  25   * This class is used to consistently make outgoing HTTP requests easy for developers
  26   * while still being compatible with the many PHP configurations under which
  27   * WordPress runs.
  28   *
  29   * Debugging includes several actions, which pass different variables for debugging the HTTP API.
  30   *
  31   * @since 2.7.0
  32   *
  33   * @phpstan-type HTTP_Response array{
  34   *     headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array<string, string>,
  35   *     body: string,
  36   *     response: array{code: int|false, message: string|false},
  37   *     cookies: WP_Http_Cookie[],
  38   *     filename?: string|null,
  39   *     http_response?: WP_HTTP_Requests_Response|null,
  40   * }
  41   */
  42  #[AllowDynamicProperties]
  43  class WP_Http {
  44  
  45      // Aliases for HTTP response codes.
  46      const HTTP_CONTINUE       = 100;
  47      const SWITCHING_PROTOCOLS = 101;
  48      const PROCESSING          = 102;
  49      const EARLY_HINTS         = 103;
  50  
  51      const OK                            = 200;
  52      const CREATED                       = 201;
  53      const ACCEPTED                      = 202;
  54      const NON_AUTHORITATIVE_INFORMATION = 203;
  55      const NO_CONTENT                    = 204;
  56      const RESET_CONTENT                 = 205;
  57      const PARTIAL_CONTENT               = 206;
  58      const MULTI_STATUS                  = 207;
  59      const IM_USED                       = 226;
  60  
  61      const MULTIPLE_CHOICES   = 300;
  62      const MOVED_PERMANENTLY  = 301;
  63      const FOUND              = 302;
  64      const SEE_OTHER          = 303;
  65      const NOT_MODIFIED       = 304;
  66      const USE_PROXY          = 305;
  67      const RESERVED           = 306;
  68      const TEMPORARY_REDIRECT = 307;
  69      const PERMANENT_REDIRECT = 308;
  70  
  71      const BAD_REQUEST                     = 400;
  72      const UNAUTHORIZED                    = 401;
  73      const PAYMENT_REQUIRED                = 402;
  74      const FORBIDDEN                       = 403;
  75      const NOT_FOUND                       = 404;
  76      const METHOD_NOT_ALLOWED              = 405;
  77      const NOT_ACCEPTABLE                  = 406;
  78      const PROXY_AUTHENTICATION_REQUIRED   = 407;
  79      const REQUEST_TIMEOUT                 = 408;
  80      const CONFLICT                        = 409;
  81      const GONE                            = 410;
  82      const LENGTH_REQUIRED                 = 411;
  83      const PRECONDITION_FAILED             = 412;
  84      const REQUEST_ENTITY_TOO_LARGE        = 413;
  85      const REQUEST_URI_TOO_LONG            = 414;
  86      const UNSUPPORTED_MEDIA_TYPE          = 415;
  87      const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
  88      const EXPECTATION_FAILED              = 417;
  89      const IM_A_TEAPOT                     = 418;
  90      const MISDIRECTED_REQUEST             = 421;
  91      const UNPROCESSABLE_ENTITY            = 422;
  92      const LOCKED                          = 423;
  93      const FAILED_DEPENDENCY               = 424;
  94      const TOO_EARLY                       = 425;
  95      const UPGRADE_REQUIRED                = 426;
  96      const PRECONDITION_REQUIRED           = 428;
  97      const TOO_MANY_REQUESTS               = 429;
  98      const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
  99      const UNAVAILABLE_FOR_LEGAL_REASONS   = 451;
 100  
 101      const INTERNAL_SERVER_ERROR           = 500;
 102      const NOT_IMPLEMENTED                 = 501;
 103      const BAD_GATEWAY                     = 502;
 104      const SERVICE_UNAVAILABLE             = 503;
 105      const GATEWAY_TIMEOUT                 = 504;
 106      const HTTP_VERSION_NOT_SUPPORTED      = 505;
 107      const VARIANT_ALSO_NEGOTIATES         = 506;
 108      const INSUFFICIENT_STORAGE            = 507;
 109      const NOT_EXTENDED                    = 510;
 110      const NETWORK_AUTHENTICATION_REQUIRED = 511;
 111  
 112      /**
 113       * Send an HTTP request to a URI.
 114       *
 115       * Please note: The only URI that are supported in the HTTP Transport implementation
 116       * are the HTTP and HTTPS protocols.
 117       *
 118       * @since 2.7.0
 119       *
 120       * @param string       $url  The request URL.
 121       * @param string|array $args {
 122       *     Optional. Array or string of HTTP request arguments.
 123       *
 124       *     @type string       $method              Request method. Accepts 'GET', 'POST', 'HEAD', 'PUT', 'DELETE',
 125       *                                             'TRACE', 'OPTIONS', or 'PATCH'.
 126       *                                             Some transports technically allow others, but should not be
 127       *                                             assumed. Default 'GET'.
 128       *     @type float        $timeout             How long the connection should stay open in seconds. Default 5.
 129       *     @type int          $redirection         Number of allowed redirects. Not supported by all transports.
 130       *                                             Default 5.
 131       *     @type string       $httpversion         Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
 132       *                                             Default '1.0'.
 133       *     @type string       $user-agent          User-agent value sent.
 134       *                                             Default 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ).
 135       *     @type bool         $reject_unsafe_urls  Whether to pass URLs through wp_http_validate_url().
 136       *                                             Default false.
 137       *     @type bool         $blocking            Whether the calling code requires the result of the request.
 138       *                                             If set to false, the request will be sent to the remote server,
 139       *                                             and processing returned to the calling code immediately, the caller
 140       *                                             will know if the request succeeded or failed, but will not receive
 141       *                                             any response from the remote server. Default true.
 142       *     @type string|array $headers             Array or string of headers to send with the request.
 143       *                                             Default empty array.
 144       *     @type array        $cookies             List of cookies to send with the request. Default empty array.
 145       *     @type string|array $body                Body to send with the request. Default null.
 146       *     @type bool         $compress            Whether to compress the $body when sending the request.
 147       *                                             Default false.
 148       *     @type bool         $decompress          Whether to decompress a compressed response. If set to false and
 149       *                                             compressed content is returned in the response anyway, it will
 150       *                                             need to be separately decompressed. Default true.
 151       *     @type bool         $sslverify           Whether to verify SSL for the request. Default true.
 152       *     @type string       $sslcertificates     Absolute path to an SSL certificate .crt file.
 153       *                                             Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
 154       *     @type bool         $stream              Whether to stream to a file. If set to true and no filename was
 155       *                                             given, it will be dropped it in the WP temp dir and its name will
 156       *                                             be set using the basename of the URL. Default false.
 157       *     @type string       $filename            Filename of the file to write to when streaming. $stream must be
 158       *                                             set to true. Default null.
 159       *     @type int          $limit_response_size Size in bytes to limit the response to. Default null.
 160       *
 161       * }
 162       * @return array|WP_Error {
 163       *     Array of response data, or a WP_Error instance upon error.
 164       *
 165       *     @type \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array $headers       Response headers keyed by name.
 166       *                                                                                  An empty array for a non-blocking request.
 167       *     @type string                                                 $body          Response body.
 168       *     @type array                                                  $response      {
 169       *         Array of HTTP response data.
 170       *
 171       *         @type int|false    $code    HTTP response status code.
 172       *         @type string|false $message HTTP response message.
 173       *     }
 174       *     @type WP_Http_Cookie[]                                       $cookies       Array of cookies set by the server.
 175       *     @type string|null                                            $filename      Optional. Filename of the response.
 176       *     @type WP_HTTP_Requests_Response|null                         $http_response Response object.
 177       * }
 178       *
 179       * @phpstan-return HTTP_Response|WP_Error
 180       */
 181  	public function request( $url, $args = array() ) {
 182          $defaults = array(
 183              'method'              => 'GET',
 184              /**
 185               * Filters the timeout value for an HTTP request.
 186               *
 187               * @since 2.7.0
 188               * @since 5.1.0 The `$url` parameter was added.
 189               *
 190               * @param float  $timeout_value Time in seconds until a request times out. Default 5.
 191               * @param string $url           The request URL.
 192               */
 193              'timeout'             => apply_filters( 'http_request_timeout', 5, $url ),
 194              /**
 195               * Filters the number of redirects allowed during an HTTP request.
 196               *
 197               * @since 2.7.0
 198               * @since 5.1.0 The `$url` parameter was added.
 199               *
 200               * @param int    $redirect_count Number of redirects allowed. Default 5.
 201               * @param string $url            The request URL.
 202               */
 203              'redirection'         => apply_filters( 'http_request_redirection_count', 5, $url ),
 204              /**
 205               * Filters the version of the HTTP protocol used in a request.
 206               *
 207               * @since 2.7.0
 208               * @since 5.1.0 The `$url` parameter was added.
 209               *
 210               * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'. Default '1.0'.
 211               * @param string $url     The request URL.
 212               */
 213              'httpversion'         => apply_filters( 'http_request_version', '1.0', $url ),
 214              /**
 215               * Filters the user agent value sent with an HTTP request.
 216               *
 217               * @since 2.7.0
 218               * @since 5.1.0 The `$url` parameter was added.
 219               *
 220               * @param string $user_agent WordPress user agent string.
 221               * @param string $url        The request URL.
 222               */
 223              'user-agent'          => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $url ),
 224              /**
 225               * Filters whether to pass URLs through wp_http_validate_url() in an HTTP request.
 226               *
 227               * @since 3.6.0
 228               * @since 5.1.0 The `$url` parameter was added.
 229               *
 230               * @param bool   $pass_url Whether to pass URLs through wp_http_validate_url(). Default false.
 231               * @param string $url      The request URL.
 232               */
 233              'reject_unsafe_urls'  => apply_filters( 'http_request_reject_unsafe_urls', false, $url ),
 234              'blocking'            => true,
 235              'headers'             => array(),
 236              'cookies'             => array(),
 237              'body'                => null,
 238              'compress'            => false,
 239              'decompress'          => true,
 240              'sslverify'           => true,
 241              'sslcertificates'     => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
 242              'stream'              => false,
 243              'filename'            => null,
 244              'limit_response_size' => null,
 245          );
 246  
 247          // Pre-parse for the HEAD checks.
 248          $args = wp_parse_args( $args );
 249  
 250          // By default, HEAD requests do not cause redirections.
 251          if ( isset( $args['method'] ) && 'HEAD' === $args['method'] ) {
 252              $defaults['redirection'] = 0;
 253          }
 254  
 255          $parsed_args = wp_parse_args( $args, $defaults );
 256          /**
 257           * Filters the arguments used in an HTTP request.
 258           *
 259           * @since 2.7.0
 260           *
 261           * @param array  $parsed_args An array of HTTP request arguments.
 262           * @param string $url         The request URL.
 263           */
 264          $parsed_args = apply_filters( 'http_request_args', $parsed_args, $url );
 265  
 266          // The transports decrement this, store a copy of the original value for loop purposes.
 267          if ( ! isset( $parsed_args['_redirection'] ) ) {
 268              $parsed_args['_redirection'] = $parsed_args['redirection'];
 269          }
 270  
 271          /**
 272           * Filters the preemptive return value of an HTTP request.
 273           *
 274           * Returning a non-false value from the filter will short-circuit the HTTP request and return
 275           * early with that value. A filter should return one of:
 276           *
 277           *  - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
 278           *  - A WP_Error instance
 279           *  - Boolean false to avoid short-circuiting the response
 280           *
 281           * Returning any other value may result in unexpected behavior.
 282           *
 283           * @since 2.9.0
 284           *
 285           * @param false|array|WP_Error $response    A preemptive return value of an HTTP request. Default false.
 286           * @param array                $parsed_args HTTP request arguments.
 287           * @param string               $url         The request URL.
 288           */
 289          $pre = apply_filters( 'pre_http_request', false, $parsed_args, $url );
 290  
 291          if ( false !== $pre ) {
 292              return $pre;
 293          }
 294  
 295          if ( function_exists( 'wp_kses_bad_protocol' ) ) {
 296              if ( $parsed_args['reject_unsafe_urls'] ) {
 297                  $url = wp_http_validate_url( $url );
 298              }
 299              if ( $url ) {
 300                  $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
 301              }
 302          }
 303  
 304          $parsed_url = parse_url( $url );
 305  
 306          if ( empty( $url ) || empty( $parsed_url['scheme'] ) ) {
 307              $response = new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.' ) );
 308              /** This action is documented in wp-includes/class-wp-http.php */
 309              do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url );
 310              return $response;
 311          }
 312  
 313          if ( $this->block_request( $url ) ) {
 314              /* translators: %s: URL to which the HTTP request was blocked. */
 315              $response = new WP_Error( 'http_request_not_executed', sprintf( __( 'User has blocked requests through HTTP to the URL: %s.' ), $url ) );
 316              /** This action is documented in wp-includes/class-wp-http.php */
 317              do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url );
 318              return $response;
 319          }
 320  
 321          // If we are streaming to a file but no filename was given drop it in the WP temp dir
 322          // and pick its name using the basename of the $url.
 323          if ( $parsed_args['stream'] ) {
 324              if ( empty( $parsed_args['filename'] ) ) {
 325                  $parsed_args['filename'] = get_temp_dir() . basename( $url );
 326              }
 327  
 328              // Force some settings if we are streaming to a file and check for existence
 329              // and perms of destination directory.
 330              $parsed_args['blocking'] = true;
 331              if ( ! wp_is_writable( dirname( $parsed_args['filename'] ) ) ) {
 332                  $response = new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
 333                  /** This action is documented in wp-includes/class-wp-http.php */
 334                  do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url );
 335                  return $response;
 336              }
 337          }
 338  
 339          if ( is_null( $parsed_args['headers'] ) ) {
 340              $parsed_args['headers'] = array();
 341          }
 342  
 343          // WP allows passing in headers as a string, weirdly.
 344          if ( ! is_array( $parsed_args['headers'] ) ) {
 345              $processed_headers      = self::processHeaders( $parsed_args['headers'] );
 346              $parsed_args['headers'] = $processed_headers['headers'];
 347          }
 348  
 349          // Setup arguments.
 350          $headers = $parsed_args['headers'];
 351          $data    = $parsed_args['body'];
 352          $type    = $parsed_args['method'];
 353          $options = array(
 354              'timeout'   => $parsed_args['timeout'],
 355              'useragent' => $parsed_args['user-agent'],
 356              'blocking'  => $parsed_args['blocking'],
 357              'hooks'     => new WP_HTTP_Requests_Hooks( $url, $parsed_args ),
 358          );
 359  
 360          // Ensure redirects follow browser behavior.
 361          $options['hooks']->register( 'requests.before_redirect', array( static::class, 'browser_redirect_compatibility' ) );
 362  
 363          // Validate redirected URLs.
 364          if ( function_exists( 'wp_kses_bad_protocol' ) && $parsed_args['reject_unsafe_urls'] ) {
 365              $options['hooks']->register( 'requests.before_redirect', array( static::class, 'validate_redirects' ) );
 366          }
 367  
 368          if ( $parsed_args['stream'] ) {
 369              $options['filename'] = $parsed_args['filename'];
 370          }
 371          if ( empty( $parsed_args['redirection'] ) ) {
 372              $options['follow_redirects'] = false;
 373          } else {
 374              $options['redirects'] = $parsed_args['redirection'];
 375          }
 376  
 377          // Use byte limit, if we can.
 378          if ( isset( $parsed_args['limit_response_size'] ) ) {
 379              $options['max_bytes'] = $parsed_args['limit_response_size'];
 380          }
 381  
 382          // If we've got cookies, use and convert them to WpOrg\Requests\Cookie.
 383          if ( ! empty( $parsed_args['cookies'] ) ) {
 384              $options['cookies'] = self::normalize_cookies( $parsed_args['cookies'] );
 385          }
 386  
 387          // SSL certificate handling.
 388          if ( ! $parsed_args['sslverify'] ) {
 389              $options['verify']     = false;
 390              $options['verifyname'] = false;
 391          } else {
 392              $options['verify'] = $parsed_args['sslcertificates'];
 393          }
 394  
 395          // All non-GET/HEAD requests should put the arguments in the form body.
 396          if ( 'HEAD' !== $type && 'GET' !== $type ) {
 397              $options['data_format'] = 'body';
 398          }
 399  
 400          /**
 401           * Filters whether SSL should be verified for non-local requests.
 402           *
 403           * @since 2.8.0
 404           * @since 5.1.0 The `$url` parameter was added.
 405           *
 406           * @param bool|string $ssl_verify Boolean to control whether to verify the SSL connection
 407           *                                or path to an SSL certificate.
 408           * @param string      $url        The request URL.
 409           */
 410          $options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url );
 411  
 412          // Check for proxies.
 413          $proxy = new WP_HTTP_Proxy();
 414          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
 415              $options['proxy'] = new WpOrg\Requests\Proxy\Http( $proxy->host() . ':' . $proxy->port() );
 416  
 417              if ( $proxy->use_authentication() ) {
 418                  $options['proxy']->use_authentication = true;
 419                  $options['proxy']->user               = $proxy->username();
 420                  $options['proxy']->pass               = $proxy->password();
 421              }
 422          }
 423  
 424          // Avoid issues where mbstring.func_overload is enabled.
 425          mbstring_binary_safe_encoding();
 426  
 427          try {
 428              $requests_response = WpOrg\Requests\Requests::request( $url, $headers, $data, $type, $options );
 429  
 430              // Convert the response into an array.
 431              $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] );
 432              $response      = $http_response->to_array();
 433  
 434              // Add the original object to the array.
 435              $response['http_response'] = $http_response;
 436          } catch ( WpOrg\Requests\Exception $e ) {
 437              $response = new WP_Error( 'http_request_failed', $e->getMessage() );
 438          }
 439  
 440          reset_mbstring_encoding();
 441  
 442          /**
 443           * Fires after an HTTP API response is received and before the response is returned.
 444           *
 445           * @since 2.8.0
 446           *
 447           * @param array|WP_Error $response    HTTP response or WP_Error object.
 448           * @param string         $context     Context under which the hook is fired.
 449           * @param string         $class       HTTP transport used.
 450           * @param array          $parsed_args HTTP request arguments.
 451           * @param string         $url         The request URL.
 452           */
 453          do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url );
 454          if ( is_wp_error( $response ) ) {
 455              return $response;
 456          }
 457  
 458          if ( ! $parsed_args['blocking'] ) {
 459              return array(
 460                  'headers'       => array(),
 461                  'body'          => '',
 462                  'response'      => array(
 463                      'code'    => false,
 464                      'message' => false,
 465                  ),
 466                  'cookies'       => array(),
 467                  'http_response' => null,
 468              );
 469          }
 470  
 471          /**
 472           * Filters a successful HTTP API response immediately before the response is returned.
 473           *
 474           * @since 2.9.0
 475           *
 476           * @param array  $response    HTTP response.
 477           * @param array  $parsed_args HTTP request arguments.
 478           * @param string $url         The request URL.
 479           */
 480          return apply_filters( 'http_response', $response, $parsed_args, $url );
 481      }
 482  
 483      /**
 484       * Normalizes cookies for using in Requests.
 485       *
 486       * @since 4.6.0
 487       *
 488       * @param array<int|string, WP_Http_Cookie|scalar> $cookies Array of cookies to send with the request,
 489       *                                                          as WP_Http_Cookie objects or name/value pairs.
 490       *                                                          Cookies without a scalar value are ignored.
 491       * @return WpOrg\Requests\Cookie\Jar Cookie holder object.
 492       */
 493  	public static function normalize_cookies( $cookies ) {
 494          $cookie_jar = new WpOrg\Requests\Cookie\Jar();
 495  
 496          foreach ( $cookies as $name => $value ) {
 497              if ( $value instanceof WP_Http_Cookie ) {
 498                  $cookie_name  = (string) $value->name;
 499                  $cookie_value = $value->value;
 500                  $attributes   = array_filter(
 501                      $value->get_attributes(),
 502                      static function ( $attr ) {
 503                          return null !== $attr;
 504                      }
 505                  );
 506                  $flags        = array( 'host-only' => $value->host_only );
 507              } else {
 508                  $cookie_name  = (string) $name;
 509                  $cookie_value = $value;
 510                  $attributes   = array();
 511                  $flags        = array();
 512              }
 513  
 514              // A cookie without a value is not sent by WP_Http_Cookie::getHeaderValue() either, and a non-scalar value cannot be represented.
 515              if ( ! is_scalar( $cookie_value ) ) {
 516                  continue;
 517              }
 518  
 519              $cookie_jar[ $cookie_name ] = new WpOrg\Requests\Cookie( $cookie_name, (string) $cookie_value, $attributes, $flags );
 520          }
 521  
 522          return $cookie_jar;
 523      }
 524  
 525      /**
 526       * Match redirect behavior to browser handling.
 527       *
 528       * Changes 302 redirects from POST to GET to match browser handling. Per
 529       * RFC 7231, user agents can deviate from the strict reading of the
 530       * specification for compatibility purposes.
 531       *
 532       * @since 4.6.0
 533       *
 534       * @param string                  $location URL to redirect to.
 535       * @param array                   $headers  Headers for the redirect.
 536       * @param string|array            $data     Body to send with the request.
 537       * @param array                   $options  Redirect request options.
 538       * @param WpOrg\Requests\Response $original Response object.
 539       */
 540  	public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) {
 541          // Browser compatibility.
 542          if ( 302 === $original->status_code ) {
 543              $options['type'] = WpOrg\Requests\Requests::GET;
 544          }
 545      }
 546  
 547      /**
 548       * Validate redirected URLs.
 549       *
 550       * @since 4.7.5
 551       *
 552       * @throws WpOrg\Requests\Exception On unsuccessful URL validation.
 553       * @param string $location URL to redirect to.
 554       */
 555  	public static function validate_redirects( $location ) {
 556          if ( ! wp_http_validate_url( $location ) ) {
 557              throw new WpOrg\Requests\Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' );
 558          }
 559      }
 560  
 561      /**
 562       * Tests which transports are capable of supporting the request.
 563       *
 564       * @since 3.2.0
 565       * @deprecated 6.4.0 Use WpOrg\Requests\Requests::get_transport_class()
 566       * @see WpOrg\Requests\Requests::get_transport_class()
 567       *
 568       * @param array  $args Request arguments.
 569       * @param string $url  URL to request.
 570       * @return string|false Class name for the first transport that claims to support the request.
 571       *                      False if no transport claims to support the request.
 572       */
 573  	public function _get_first_available_transport( $args, $url = null ) {
 574          $transports = array( 'curl', 'streams' );
 575  
 576          /**
 577           * Filters which HTTP transports are available and in what order.
 578           *
 579           * @since 3.7.0
 580           * @deprecated 6.4.0 Use WpOrg\Requests\Requests::get_transport_class()
 581           *
 582           * @param string[] $transports Array of HTTP transports to check. Default array contains
 583           *                             'curl' and 'streams', in that order.
 584           * @param array    $args       HTTP request arguments.
 585           * @param string   $url        The URL to request.
 586           */
 587          $request_order = apply_filters_deprecated( 'http_api_transports', array( $transports, $args, $url ), '6.4.0' );
 588  
 589          // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
 590          foreach ( $request_order as $transport ) {
 591              if ( in_array( $transport, $transports, true ) ) {
 592                  $transport = ucfirst( $transport );
 593              }
 594              $class = 'WP_Http_' . $transport;
 595  
 596              // Check to see if this transport is a possibility, calls the transport statically.
 597              if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) {
 598                  continue;
 599              }
 600  
 601              return $class;
 602          }
 603  
 604          return false;
 605      }
 606  
 607      /**
 608       * Dispatches a HTTP request to a supporting transport.
 609       *
 610       * Tests each transport in order to find a transport which matches the request arguments.
 611       * Also caches the transport instance to be used later.
 612       *
 613       * The order for requests is cURL, and then PHP Streams.
 614       *
 615       * @since 3.2.0
 616       * @deprecated 5.1.0 Use WP_Http::request()
 617       * @see WP_Http::request()
 618       *
 619       * @param string $url  URL to request.
 620       * @param array  $args Request arguments.
 621       * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
 622       *                        A WP_Error instance upon error.
 623       */
 624  	private function _dispatch_request( $url, $args ) {
 625          static $transports = array();
 626  
 627          $class = $this->_get_first_available_transport( $args, $url );
 628          if ( ! $class ) {
 629              return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
 630          }
 631  
 632          // Transport claims to support request, instantiate it and give it a whirl.
 633          if ( empty( $transports[ $class ] ) ) {
 634              $transports[ $class ] = new $class();
 635          }
 636  
 637          $response = $transports[ $class ]->request( $url, $args );
 638  
 639          /** This action is documented in wp-includes/class-wp-http.php */
 640          do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
 641  
 642          if ( is_wp_error( $response ) ) {
 643              return $response;
 644          }
 645  
 646          /** This filter is documented in wp-includes/class-wp-http.php */
 647          return apply_filters( 'http_response', $response, $args, $url );
 648      }
 649  
 650      /**
 651       * Uses the POST HTTP method.
 652       *
 653       * Used for sending data that is expected to be in the body.
 654       *
 655       * @since 2.7.0
 656       *
 657       * @param string       $url  The request URL.
 658       * @param string|array $args Optional. Override the defaults.
 659       * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
 660       *                        A WP_Error instance upon error. See WP_Http::response() for details.
 661       *
 662       * @phpstan-return HTTP_Response|WP_Error
 663       */
 664  	public function post( $url, $args = array() ) {
 665          $defaults    = array( 'method' => 'POST' );
 666          $parsed_args = wp_parse_args( $args, $defaults );
 667          return $this->request( $url, $parsed_args );
 668      }
 669  
 670      /**
 671       * Uses the GET HTTP method.
 672       *
 673       * Used for sending data that is expected to be in the body.
 674       *
 675       * @since 2.7.0
 676       *
 677       * @param string       $url  The request URL.
 678       * @param string|array $args Optional. Override the defaults.
 679       * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
 680       *                        A WP_Error instance upon error. See WP_Http::response() for details.
 681       *
 682       * @phpstan-return HTTP_Response|WP_Error
 683       */
 684  	public function get( $url, $args = array() ) {
 685          $defaults    = array( 'method' => 'GET' );
 686          $parsed_args = wp_parse_args( $args, $defaults );
 687          return $this->request( $url, $parsed_args );
 688      }
 689  
 690      /**
 691       * Uses the HEAD HTTP method.
 692       *
 693       * Used for sending data that is expected to be in the body.
 694       *
 695       * @since 2.7.0
 696       *
 697       * @param string       $url  The request URL.
 698       * @param string|array $args Optional. Override the defaults.
 699       * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
 700       *                        A WP_Error instance upon error. See WP_Http::response() for details.
 701       *
 702       * @phpstan-return HTTP_Response|WP_Error
 703       */
 704  	public function head( $url, $args = array() ) {
 705          $defaults    = array( 'method' => 'HEAD' );
 706          $parsed_args = wp_parse_args( $args, $defaults );
 707          return $this->request( $url, $parsed_args );
 708      }
 709  
 710      /**
 711       * Parses the responses and splits the parts into headers and body.
 712       *
 713       * @since 2.7.0
 714       *
 715       * @param string $response The full response string.
 716       * @return array {
 717       *     Array with response headers and body.
 718       *
 719       *     @type string $headers HTTP response headers.
 720       *     @type string $body    HTTP response body.
 721       * }
 722       */
 723  	public static function processResponse( $response ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
 724          $response = explode( "\r\n\r\n", $response, 2 );
 725  
 726          return array(
 727              'headers' => $response[0],
 728              'body'    => $response[1] ?? '',
 729          );
 730      }
 731  
 732      /**
 733       * Transforms header string into an array.
 734       *
 735       * @since 2.7.0
 736       *
 737       * @param string|array $headers The original headers. If a string is passed, it will be converted
 738       *                              to an array. If an array is passed, then it is assumed to be
 739       *                              raw header data with numeric keys with the headers as the values.
 740       *                              No headers must be passed that were already processed.
 741       * @param string       $url     Optional. The URL that was requested. Default empty.
 742       * @return array {
 743       *     Processed string headers. If duplicate headers are encountered,
 744       *     then a numbered array is returned as the value of that header-key.
 745       *
 746       *     @type array                         $response {
 747       *         @type int    $code    The response status code. Default 0.
 748       *         @type string $message The response message. Default empty.
 749       *     }
 750       *     @type array<string, string|string[]> $headers  The processed header data, keyed by lowercased header name.
 751       *     @type WP_Http_Cookie[]               $cookies  If the original headers contain the 'Set-Cookie' key,
 752       *                                                    an array containing `WP_Http_Cookie` objects is returned.
 753       * }
 754       */
 755  	public static function processHeaders( $headers, $url = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
 756          // Split headers, one per array element.
 757          if ( is_string( $headers ) ) {
 758              // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
 759              $headers = str_replace( "\r\n", "\n", $headers );
 760              /*
 761               * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
 762               * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
 763               */
 764              $headers = preg_replace( '/\n[ \t]/', ' ', $headers );
 765              // Create the headers array.
 766              $headers = explode( "\n", $headers );
 767          }
 768  
 769          $response = array(
 770              'code'    => 0,
 771              'message' => '',
 772          );
 773  
 774          /*
 775           * If a redirection has taken place, The headers for each page request may have been passed.
 776           * In this case, determine the final HTTP header and parse from there.
 777           */
 778          for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) {
 779              if ( ! empty( $headers[ $i ] ) && ! str_contains( $headers[ $i ], ':' ) ) {
 780                  $headers = array_splice( $headers, $i );
 781                  break;
 782              }
 783          }
 784  
 785          $cookies    = array();
 786          $newheaders = array();
 787          foreach ( (array) $headers as $tempheader ) {
 788              if ( empty( $tempheader ) ) {
 789                  continue;
 790              }
 791  
 792              if ( ! str_contains( $tempheader, ':' ) ) {
 793                  $stack   = explode( ' ', $tempheader, 3 );
 794                  $stack[] = '';
 795                  list( , $response['code'], $response['message']) = $stack;
 796                  continue;
 797              }
 798  
 799              list($key, $value) = explode( ':', $tempheader, 2 );
 800  
 801              $key   = strtolower( $key );
 802              $value = trim( $value );
 803  
 804              if ( isset( $newheaders[ $key ] ) ) {
 805                  if ( ! is_array( $newheaders[ $key ] ) ) {
 806                      $newheaders[ $key ] = array( $newheaders[ $key ] );
 807                  }
 808                  $newheaders[ $key ][] = $value;
 809              } else {
 810                  $newheaders[ $key ] = $value;
 811              }
 812              if ( 'set-cookie' === $key ) {
 813                  $cookies[] = new WP_Http_Cookie( $value, $url );
 814              }
 815          }
 816  
 817          // Cast the Response Code to an int.
 818          $response['code'] = (int) $response['code'];
 819  
 820          return array(
 821              'response' => $response,
 822              'headers'  => $newheaders,
 823              'cookies'  => $cookies,
 824          );
 825      }
 826  
 827      /**
 828       * Takes the arguments for a ::request() and checks for the cookie array.
 829       *
 830       * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
 831       * which are each parsed into strings and added to the Cookie: header (within the arguments array).
 832       * Edits the array by reference.
 833       *
 834       * @since 2.8.0
 835       *
 836       * @param array $r Full array of args passed into ::request()
 837       */
 838  	public static function buildCookieHeader( &$r ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
 839          if ( ! empty( $r['cookies'] ) ) {
 840              // Upgrade any name => value cookie pairs to WP_Http_Cookie instances.
 841              foreach ( $r['cookies'] as $name => $value ) {
 842                  if ( ! is_object( $value ) ) {
 843                      $r['cookies'][ $name ] = new WP_Http_Cookie(
 844                          array(
 845                              'name'  => $name,
 846                              'value' => $value,
 847                          )
 848                      );
 849                  }
 850              }
 851  
 852              $cookies_header = '';
 853              foreach ( (array) $r['cookies'] as $cookie ) {
 854                  $cookies_header .= $cookie->getHeaderValue() . '; ';
 855              }
 856  
 857              $cookies_header         = substr( $cookies_header, 0, -2 );
 858              $r['headers']['cookie'] = $cookies_header;
 859          }
 860      }
 861  
 862      /**
 863       * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
 864       *
 865       * Based off the HTTP http_encoding_dechunk function.
 866       *
 867       * @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
 868       *
 869       * @since 2.7.0
 870       *
 871       * @param string $body Body content.
 872       * @return string Chunked decoded body on success or raw body on failure.
 873       */
 874  	public static function chunkTransferDecode( $body ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
 875          // The body is not chunked encoded or is malformed.
 876          if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) {
 877              return $body;
 878          }
 879  
 880          $parsed_body = '';
 881  
 882          // We'll be altering $body, so need a backup in case of error.
 883          $body_original = $body;
 884  
 885          while ( true ) {
 886              $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
 887              if ( ! $has_chunk || empty( $match[1] ) ) {
 888                  return $body_original;
 889              }
 890  
 891              $length       = hexdec( $match[1] );
 892              $chunk_length = strlen( $match[0] );
 893  
 894              // Parse out the chunk of data.
 895              $parsed_body .= substr( $body, $chunk_length, $length );
 896  
 897              // Remove the chunk from the raw data.
 898              $body = substr( $body, $length + $chunk_length );
 899  
 900              // End of the document.
 901              if ( '0' === trim( $body ) ) {
 902                  return $parsed_body;
 903              }
 904          }
 905      }
 906  
 907      /**
 908       * Determines whether an HTTP API request to the given URL should be blocked.
 909       *
 910       * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
 911       * prevent plugins from working and core functionality, if you don't include `api.wordpress.org`.
 912       *
 913       * You block external URL requests by defining `WP_HTTP_BLOCK_EXTERNAL` as true in your `wp-config.php`
 914       * file and this will only allow localhost and your site to make requests. The constant
 915       * `WP_ACCESSIBLE_HOSTS` will allow additional hosts to go through for requests. The format of the
 916       * `WP_ACCESSIBLE_HOSTS` constant is a comma separated list of hostnames to allow, wildcard domains
 917       * are supported, eg `*.wordpress.org` will allow for all subdomains of `wordpress.org` to be contacted.
 918       *
 919       * @since 2.8.0
 920       *
 921       * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
 922       * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
 923       *
 924       * @param string $uri URI of url.
 925       * @return bool True to block, false to allow.
 926       */
 927  	public function block_request( $uri ) {
 928          // We don't need to block requests, because nothing is blocked.
 929          if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) {
 930              return false;
 931          }
 932  
 933          $check = parse_url( $uri );
 934          if ( ! $check ) {
 935              return true;
 936          }
 937  
 938          $home = parse_url( get_option( 'siteurl' ) );
 939  
 940          // Don't block requests back to ourselves by default.
 941          if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) {
 942              /**
 943               * Filters whether to block local HTTP API requests.
 944               *
 945               * A local request is one to `localhost` or to the same host as the site itself.
 946               *
 947               * @since 2.8.0
 948               *
 949               * @param bool $block Whether to block local requests. Default false.
 950               */
 951              return apply_filters( 'block_local_requests', false );
 952          }
 953  
 954          if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
 955              return true;
 956          }
 957  
 958          static $accessible_hosts = null;
 959          static $wildcard_regex   = array();
 960          if ( null === $accessible_hosts ) {
 961              $accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS );
 962  
 963              if ( str_contains( WP_ACCESSIBLE_HOSTS, '*' ) ) {
 964                  $wildcard_regex = array();
 965                  foreach ( $accessible_hosts as $host ) {
 966                      $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
 967                  }
 968                  $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
 969              }
 970          }
 971  
 972          if ( ! empty( $wildcard_regex ) ) {
 973              return ! preg_match( $wildcard_regex, $check['host'] );
 974          } else {
 975              return ! in_array( $check['host'], $accessible_hosts, true ); // Inverse logic, if it's in the array, then don't block it.
 976          }
 977      }
 978  
 979      /**
 980       * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
 981       *
 982       * @deprecated 4.4.0 Use wp_parse_url()
 983       * @see wp_parse_url()
 984       *
 985       * @param string $url The URL to parse.
 986       * @return bool|array False on failure; Array of URL components on success;
 987       *                    See parse_url()'s return values.
 988       */
 989  	protected static function parse_url( $url ) {
 990          _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
 991          return wp_parse_url( $url );
 992      }
 993  
 994      /**
 995       * Converts a relative URL to an absolute URL relative to a given URL.
 996       *
 997       * If an Absolute URL is provided, no processing of that URL is done.
 998       *
 999       * @since 3.4.0
1000       *
1001       * @param string $maybe_relative_path The URL which might be relative.
1002       * @param string $url                 The URL which $maybe_relative_path is relative to.
1003       * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
1004       */
1005  	public static function make_absolute_url( $maybe_relative_path, $url ) {
1006          if ( empty( $url ) ) {
1007              return $maybe_relative_path;
1008          }
1009  
1010          $url_parts = wp_parse_url( $url );
1011          if ( ! $url_parts ) {
1012              return $maybe_relative_path;
1013          }
1014  
1015          $relative_url_parts = wp_parse_url( $maybe_relative_path );
1016          if ( ! $relative_url_parts ) {
1017              return $maybe_relative_path;
1018          }
1019  
1020          // Check for a scheme on the 'relative' URL.
1021          if ( ! empty( $relative_url_parts['scheme'] ) ) {
1022              return $maybe_relative_path;
1023          }
1024  
1025          $absolute_path = $url_parts['scheme'] . '://';
1026  
1027          // Schemeless URLs will make it this far, so we check for a host in the relative URL
1028          // and convert it to a protocol-URL.
1029          if ( isset( $relative_url_parts['host'] ) ) {
1030              $absolute_path .= $relative_url_parts['host'];
1031              if ( isset( $relative_url_parts['port'] ) ) {
1032                  $absolute_path .= ':' . $relative_url_parts['port'];
1033              }
1034          } else {
1035              $absolute_path .= $url_parts['host'];
1036              if ( isset( $url_parts['port'] ) ) {
1037                  $absolute_path .= ':' . $url_parts['port'];
1038              }
1039          }
1040  
1041          // Start off with the absolute URL path.
1042          $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
1043  
1044          // If it's a root-relative path, then great.
1045          if ( ! empty( $relative_url_parts['path'] ) && '/' === $relative_url_parts['path'][0] ) {
1046              $path = $relative_url_parts['path'];
1047  
1048              // Else it's a relative path.
1049          } elseif ( ! empty( $relative_url_parts['path'] ) ) {
1050              // Strip off any file components from the absolute path.
1051              $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
1052  
1053              // Build the new path.
1054              $path .= $relative_url_parts['path'];
1055  
1056              // Strip all /path/../ out of the path.
1057              while ( strpos( $path, '../' ) > 1 ) {
1058                  $path = preg_replace( '![^/]+/\.\./!', '', $path, -1, $segment_replacement_count );
1059                  if ( 0 === $segment_replacement_count ) {
1060                      break;
1061                  }
1062              }
1063  
1064              // Strip any final leading ../ from the path.
1065              $path = preg_replace( '!^/(\.\./)+!', '', $path );
1066          }
1067  
1068          // Add the query string.
1069          if ( ! empty( $relative_url_parts['query'] ) ) {
1070              $path .= '?' . $relative_url_parts['query'];
1071          }
1072  
1073          // Add the fragment.
1074          if ( ! empty( $relative_url_parts['fragment'] ) ) {
1075              $path .= '#' . $relative_url_parts['fragment'];
1076          }
1077  
1078          return $absolute_path . '/' . ltrim( $path, '/' );
1079      }
1080  
1081      /**
1082       * Handles an HTTP redirect and follows it if appropriate.
1083       *
1084       * @since 3.7.0
1085       *
1086       * @param string $url      The URL which was requested.
1087       * @param array  $args     The arguments which were used to make the request.
1088       * @param array  $response The response of the HTTP request.
1089       * @return array|false|WP_Error An HTTP API response array if the redirect is successfully followed,
1090       *                              false if no redirect is present, or a WP_Error object if there's an error.
1091       */
1092  	public static function handle_redirects( $url, $args, $response ) {
1093          // If no redirects are present, or, redirects were not requested, perform no action.
1094          if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) {
1095              return false;
1096          }
1097  
1098          // Only perform redirections on redirection http codes.
1099          if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) {
1100              return false;
1101          }
1102  
1103          // Don't redirect if we've run out of redirects.
1104          if ( $args['redirection']-- <= 0 ) {
1105              return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1106          }
1107  
1108          $redirect_location = $response['headers']['location'];
1109  
1110          // If there were multiple Location headers, use the last header specified.
1111          if ( is_array( $redirect_location ) ) {
1112              $redirect_location = array_pop( $redirect_location );
1113          }
1114  
1115          $redirect_location = self::make_absolute_url( $redirect_location, $url );
1116  
1117          // POST requests should not POST to a redirected location.
1118          if ( 'POST' === $args['method'] ) {
1119              if ( in_array( $response['response']['code'], array( 302, 303 ), true ) ) {
1120                  $args['method'] = 'GET';
1121              }
1122          }
1123  
1124          // Include valid cookies in the redirect process.
1125          if ( ! empty( $response['cookies'] ) ) {
1126              foreach ( $response['cookies'] as $cookie ) {
1127                  if ( $cookie->test( $redirect_location ) ) {
1128                      $args['cookies'][] = $cookie;
1129                  }
1130              }
1131          }
1132  
1133          return wp_remote_request( $redirect_location, $args );
1134      }
1135  
1136      /**
1137       * Determines if a specified string represents an IP address or not.
1138       *
1139       * This function also detects the type of the IP address, returning either
1140       * '4' or '6' to represent an IPv4 and IPv6 address respectively.
1141       * This does not verify if the IP is a valid IP, only that it appears to be
1142       * an IP address.
1143       *
1144       * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex.
1145       *
1146       * @since 3.7.0
1147       *
1148       * @param string $maybe_ip A suspected IP address.
1149       * @return int|false Upon success, '4' or '6' to represent an IPv4 or IPv6 address, false upon failure.
1150       */
1151  	public static function is_ip_address( $maybe_ip ) {
1152          if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) {
1153              return 4;
1154          }
1155  
1156          if ( str_contains( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) ) {
1157              return 6;
1158          }
1159  
1160          return false;
1161      }
1162  }


Generated : Mon Nov 30 08:20:01 2026 Cross-referenced by PHPXref