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


Generated : Sat Oct 24 08:20:34 2026 Cross-referenced by PHPXref