[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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


Generated: Sat Nov 23 20:47:33 2019 Cross-referenced by PHPXref 0.7