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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7