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


Generated : Mon Jul 15 08:20:02 2024 Cross-referenced by PHPXref