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