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