[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-http.php (source)

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


Generated : Thu Oct 24 08:20:01 2024 Cross-referenced by PHPXref