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


Generated : Wed Jun 24 08:20:11 2026 Cross-referenced by PHPXref