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