3 * HTTP API: WP_Http class
10 if ( ! class_exists( 'Requests' ) ) {
11 require( ABSPATH . WPINC . '/class-requests.php' );
13 Requests::register_autoloader();
14 Requests::set_certificate_path( ABSPATH . WPINC . '/certificates/ca-bundle.crt' );
18 * Core class used for managing HTTP transports and making HTTP requests.
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
24 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
30 // Aliases for HTTP response codes.
31 const HTTP_CONTINUE = 100;
32 const SWITCHING_PROTOCOLS = 101;
33 const PROCESSING = 102;
38 const NON_AUTHORITATIVE_INFORMATION = 203;
39 const NO_CONTENT = 204;
40 const RESET_CONTENT = 205;
41 const PARTIAL_CONTENT = 206;
42 const MULTI_STATUS = 207;
45 const MULTIPLE_CHOICES = 300;
46 const MOVED_PERMANENTLY = 301;
48 const SEE_OTHER = 303;
49 const NOT_MODIFIED = 304;
50 const USE_PROXY = 305;
52 const TEMPORARY_REDIRECT = 307;
53 const PERMANENT_REDIRECT = 308;
55 const BAD_REQUEST = 400;
56 const UNAUTHORIZED = 401;
57 const PAYMENT_REQUIRED = 402;
58 const FORBIDDEN = 403;
59 const NOT_FOUND = 404;
60 const METHOD_NOT_ALLOWED = 405;
61 const NOT_ACCEPTABLE = 406;
62 const PROXY_AUTHENTICATION_REQUIRED = 407;
63 const REQUEST_TIMEOUT = 408;
66 const LENGTH_REQUIRED = 411;
67 const PRECONDITION_FAILED = 412;
68 const REQUEST_ENTITY_TOO_LARGE = 413;
69 const REQUEST_URI_TOO_LONG = 414;
70 const UNSUPPORTED_MEDIA_TYPE = 415;
71 const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
72 const EXPECTATION_FAILED = 417;
73 const IM_A_TEAPOT = 418;
74 const MISDIRECTED_REQUEST = 421;
75 const UNPROCESSABLE_ENTITY = 422;
77 const FAILED_DEPENDENCY = 424;
78 const UPGRADE_REQUIRED = 426;
79 const PRECONDITION_REQUIRED = 428;
80 const TOO_MANY_REQUESTS = 429;
81 const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
82 const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
84 const INTERNAL_SERVER_ERROR = 500;
85 const NOT_IMPLEMENTED = 501;
86 const BAD_GATEWAY = 502;
87 const SERVICE_UNAVAILABLE = 503;
88 const GATEWAY_TIMEOUT = 504;
89 const HTTP_VERSION_NOT_SUPPORTED = 505;
90 const VARIANT_ALSO_NEGOTIATES = 506;
91 const INSUFFICIENT_STORAGE = 507;
92 const NOT_EXTENDED = 510;
93 const NETWORK_AUTHENTICATION_REQUIRED = 511;
96 * Send an HTTP request to a URI.
98 * Please note: The only URI that are supported in the HTTP Transport implementation
99 * are the HTTP and HTTPS protocols.
104 * @global string $wp_version
106 * @param string $url The request URL.
107 * @param string|array $args {
108 * Optional. Array or string of HTTP request arguments.
110 * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
111 * Some transports technically allow others, but should not be
112 * assumed. Default 'GET'.
113 * @type int $timeout How long the connection should stay open in seconds. Default 5.
114 * @type int $redirection Number of allowed redirects. Not supported by all transports
116 * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
118 * @type string $user-agent User-agent value sent.
119 * Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
120 * @type bool $reject_unsafe_urls Whether to pass URLs through wp_http_validate_url().
122 * @type bool $blocking Whether the calling code requires the result of the request.
123 * If set to false, the request will be sent to the remote server,
124 * and processing returned to the calling code immediately, the caller
125 * will know if the request succeeded or failed, but will not receive
126 * any response from the remote server. Default true.
127 * @type string|array $headers Array or string of headers to send with the request.
128 * Default empty array.
129 * @type array $cookies List of cookies to send with the request. Default empty array.
130 * @type string|array $body Body to send with the request. Default null.
131 * @type bool $compress Whether to compress the $body when sending the request.
133 * @type bool $decompress Whether to decompress a compressed response. If set to false and
134 * compressed content is returned in the response anyway, it will
135 * need to be separately decompressed. Default true.
136 * @type bool $sslverify Whether to verify SSL for the request. Default true.
137 * @type string sslcertificates Absolute path to an SSL certificate .crt file.
138 * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
139 * @type bool $stream Whether to stream to a file. If set to true and no filename was
140 * given, it will be droped it in the WP temp dir and its name will
141 * be set using the basename of the URL. Default false.
142 * @type string $filename Filename of the file to write to when streaming. $stream must be
143 * set to true. Default null.
144 * @type int $limit_response_size Size in bytes to limit the response to. Default null.
147 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
148 * A WP_Error instance upon error.
150 public function request( $url, $args = array() ) {
156 * Filters the timeout value for an HTTP request.
160 * @param int $timeout_value Time in seconds until a request times out.
163 'timeout' => apply_filters( 'http_request_timeout', 5 ),
165 * Filters the number of redirects allowed during an HTTP request.
169 * @param int $redirect_count Number of redirects allowed. Default 5.
171 'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
173 * Filters the version of the HTTP protocol used in a request.
177 * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
180 'httpversion' => apply_filters( 'http_request_version', '1.0' ),
182 * Filters the user agent value sent with an HTTP request.
186 * @param string $user_agent WordPress user agent string.
188 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
190 * Filters whether to pass URLs through wp_http_validate_url() in an HTTP request.
194 * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
197 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
199 'headers' => array(),
200 'cookies' => array(),
203 'decompress' => true,
205 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
208 'limit_response_size' => null,
211 // Pre-parse for the HEAD checks.
212 $args = wp_parse_args( $args );
214 // By default, Head requests do not cause redirections.
215 if ( isset($args['method']) && 'HEAD' == $args['method'] )
216 $defaults['redirection'] = 0;
218 $r = wp_parse_args( $args, $defaults );
220 * Filters the arguments used in an HTTP request.
224 * @param array $r An array of HTTP request arguments.
225 * @param string $url The request URL.
227 $r = apply_filters( 'http_request_args', $r, $url );
229 // The transports decrement this, store a copy of the original value for loop purposes.
230 if ( ! isset( $r['_redirection'] ) )
231 $r['_redirection'] = $r['redirection'];
234 * Filters whether to preempt an HTTP request's return value.
236 * Returning a non-false value from the filter will short-circuit the HTTP request and return
237 * early with that value. A filter should return either:
239 * - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
240 * - A WP_Error instance
241 * - boolean false (to avoid short-circuiting the response)
243 * Returning any other value may result in unexpected behaviour.
247 * @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value. Default false.
248 * @param array $r HTTP request arguments.
249 * @param string $url The request URL.
251 $pre = apply_filters( 'pre_http_request', false, $r, $url );
253 if ( false !== $pre )
256 if ( function_exists( 'wp_kses_bad_protocol' ) ) {
257 if ( $r['reject_unsafe_urls'] ) {
258 $url = wp_http_validate_url( $url );
261 $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
265 $arrURL = @parse_url( $url );
267 if ( empty( $url ) || empty( $arrURL['scheme'] ) ) {
268 return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
271 if ( $this->block_request( $url ) ) {
272 return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
275 // If we are streaming to a file but no filename was given drop it in the WP temp dir
276 // and pick its name using the basename of the $url
277 if ( $r['stream'] ) {
278 if ( empty( $r['filename'] ) ) {
279 $r['filename'] = get_temp_dir() . basename( $url );
282 // Force some settings if we are streaming to a file and check for existence and perms of destination directory
283 $r['blocking'] = true;
284 if ( ! wp_is_writable( dirname( $r['filename'] ) ) ) {
285 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
289 if ( is_null( $r['headers'] ) ) {
290 $r['headers'] = array();
293 // WP allows passing in headers as a string, weirdly.
294 if ( ! is_array( $r['headers'] ) ) {
295 $processedHeaders = WP_Http::processHeaders( $r['headers'] );
296 $r['headers'] = $processedHeaders['headers'];
300 $headers = $r['headers'];
302 $type = $r['method'];
304 'timeout' => $r['timeout'],
305 'useragent' => $r['user-agent'],
306 'blocking' => $r['blocking'],
307 'hooks' => new Requests_Hooks(),
310 // Ensure redirects follow browser behaviour.
311 $options['hooks']->register( 'requests.before_redirect', array( get_class(), 'browser_redirect_compatibility' ) );
313 if ( $r['stream'] ) {
314 $options['filename'] = $r['filename'];
316 if ( empty( $r['redirection'] ) ) {
317 $options['follow_redirects'] = false;
319 $options['redirects'] = $r['redirection'];
322 // Use byte limit, if we can
323 if ( isset( $r['limit_response_size'] ) ) {
324 $options['max_bytes'] = $r['limit_response_size'];
327 // If we've got cookies, use and convert them to Requests_Cookie.
328 if ( ! empty( $r['cookies'] ) ) {
329 $options['cookies'] = WP_Http::normalize_cookies( $r['cookies'] );
332 // SSL certificate handling
333 if ( ! $r['sslverify'] ) {
334 $options['verify'] = false;
335 $options['verifyname'] = false;
337 $options['verify'] = $r['sslcertificates'];
340 // All non-GET/HEAD requests should put the arguments in the form body.
341 if ( 'HEAD' !== $type && 'GET' !== $type ) {
342 $options['data_format'] = 'body';
346 * Filters whether SSL should be verified for non-local requests.
350 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
352 $options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'] );
354 // Check for proxies.
355 $proxy = new WP_HTTP_Proxy();
356 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
357 $options['proxy'] = new Requests_Proxy_HTTP( $proxy->host() . ':' . $proxy->port() );
359 if ( $proxy->use_authentication() ) {
360 $options['proxy']->use_authentication = true;
361 $options['proxy']->user = $proxy->username();
362 $options['proxy']->pass = $proxy->password();
366 // Avoid issues where mbstring.func_overload is enabled
367 mbstring_binary_safe_encoding();
370 $requests_response = Requests::request( $url, $headers, $data, $type, $options );
372 // Convert the response into an array
373 $http_response = new WP_HTTP_Requests_Response( $requests_response, $r['filename'] );
374 $response = $http_response->to_array();
376 // Add the original object to the array.
377 $response['http_response'] = $http_response;
379 catch ( Requests_Exception $e ) {
380 $response = new WP_Error( 'http_request_failed', $e->getMessage() );
383 reset_mbstring_encoding();
386 * Fires after an HTTP API response is received and before the response is returned.
390 * @param array|WP_Error $response HTTP response or WP_Error object.
391 * @param string $context Context under which the hook is fired.
392 * @param string $class HTTP transport used.
393 * @param array $args HTTP request arguments.
394 * @param string $url The request URL.
396 do_action( 'http_api_debug', $response, 'response', 'Requests', $r, $url );
397 if ( is_wp_error( $response ) ) {
401 if ( ! $r['blocking'] ) {
403 'headers' => array(),
409 'cookies' => array(),
410 'http_response' => null,
415 * Filters the HTTP API response immediately before the response is returned.
419 * @param array $response HTTP response.
420 * @param array $r HTTP request arguments.
421 * @param string $url The request URL.
423 return apply_filters( 'http_response', $response, $r, $url );
427 * Normalizes cookies for using in Requests.
433 * @param array $cookies List of cookies to send with the request.
434 * @return Requests_Cookie_Jar Cookie holder object.
436 public static function normalize_cookies( $cookies ) {
437 $cookie_jar = new Requests_Cookie_Jar();
439 foreach ( $cookies as $name => $value ) {
440 if ( $value instanceof WP_Http_Cookie ) {
441 $cookie_jar[ $value->name ] = new Requests_Cookie( $value->name, $value->value, $value->get_attributes() );
442 } elseif ( is_scalar( $value ) ) {
443 $cookie_jar[ $name ] = new Requests_Cookie( $name, $value );
451 * Match redirect behaviour to browser handling.
453 * Changes 302 redirects from POST to GET to match browser handling. Per
454 * RFC 7231, user agents can deviate from the strict reading of the
455 * specification for compatibility purposes.
461 * @param string $location URL to redirect to.
462 * @param array $headers Headers for the redirect.
463 * @param array $options Redirect request options.
464 * @param Requests_Response $original Response object.
466 public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) {
468 if ( $original->status_code === 302 ) {
469 $options['type'] = Requests::GET;
474 * Tests which transports are capable of supporting the request.
479 * @param array $args Request arguments
480 * @param string $url URL to Request
482 * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
484 public function _get_first_available_transport( $args, $url = null ) {
485 $transports = array( 'curl', 'streams' );
488 * Filters which HTTP transports are available and in what order.
492 * @param array $transports Array of HTTP transports to check. Default array contains
493 * 'curl', and 'streams', in that order.
494 * @param array $args HTTP request arguments.
495 * @param string $url The URL to request.
497 $request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
499 // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
500 foreach ( $request_order as $transport ) {
501 if ( in_array( $transport, $transports ) ) {
502 $transport = ucfirst( $transport );
504 $class = 'WP_Http_' . $transport;
506 // Check to see if this transport is a possibility, calls the transport statically.
507 if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
517 * Dispatches a HTTP request to a supporting transport.
519 * Tests each transport in order to find a transport which matches the request arguments.
520 * Also caches the transport instance to be used later.
522 * The order for requests is cURL, and then PHP Streams.
529 * @param string $url URL to Request
530 * @param array $args Request arguments
531 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
533 private function _dispatch_request( $url, $args ) {
534 static $transports = array();
536 $class = $this->_get_first_available_transport( $args, $url );
538 return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
540 // Transport claims to support request, instantiate it and give it a whirl.
541 if ( empty( $transports[$class] ) )
542 $transports[$class] = new $class;
544 $response = $transports[$class]->request( $url, $args );
546 /** This action is documented in wp-includes/class-http.php */
547 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
549 if ( is_wp_error( $response ) )
553 * Filters the HTTP API response immediately before the response is returned.
557 * @param array $response HTTP response.
558 * @param array $args HTTP request arguments.
559 * @param string $url The request URL.
561 return apply_filters( 'http_response', $response, $args, $url );
565 * Uses the POST HTTP method.
567 * Used for sending data that is expected to be in the body.
572 * @param string $url The request URL.
573 * @param string|array $args Optional. Override the defaults.
574 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
576 public function post($url, $args = array()) {
577 $defaults = array('method' => 'POST');
578 $r = wp_parse_args( $args, $defaults );
579 return $this->request($url, $r);
583 * Uses the GET HTTP method.
585 * Used for sending data that is expected to be in the body.
590 * @param string $url The request URL.
591 * @param string|array $args Optional. Override the defaults.
592 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
594 public function get($url, $args = array()) {
595 $defaults = array('method' => 'GET');
596 $r = wp_parse_args( $args, $defaults );
597 return $this->request($url, $r);
601 * Uses the HEAD HTTP method.
603 * Used for sending data that is expected to be in the body.
608 * @param string $url The request URL.
609 * @param string|array $args Optional. Override the defaults.
610 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
612 public function head($url, $args = array()) {
613 $defaults = array('method' => 'HEAD');
614 $r = wp_parse_args( $args, $defaults );
615 return $this->request($url, $r);
619 * Parses the responses and splits the parts into headers and body.
625 * @param string $strResponse The full response string
626 * @return array Array with 'headers' and 'body' keys.
628 public static function processResponse($strResponse) {
629 $res = explode("\r\n\r\n", $strResponse, 2);
631 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
635 * Transform header string into an array.
637 * If an array is given then it is assumed to be raw header data with numeric keys with the
638 * headers as the values. No headers must be passed that were already processed.
644 * @param string|array $headers
645 * @param string $url The URL that was requested
646 * @return array Processed string headers. If duplicate headers are encountered,
647 * Then a numbered array is returned as the value of that header-key.
649 public static function processHeaders( $headers, $url = '' ) {
650 // Split headers, one per array element.
651 if ( is_string($headers) ) {
652 // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
653 $headers = str_replace("\r\n", "\n", $headers);
655 * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
656 * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
658 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
659 // Create the headers array.
660 $headers = explode("\n", $headers);
663 $response = array('code' => 0, 'message' => '');
666 * If a redirection has taken place, The headers for each page request may have been passed.
667 * In this case, determine the final HTTP header and parse from there.
669 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
670 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
671 $headers = array_splice($headers, $i);
677 $newheaders = array();
678 foreach ( (array) $headers as $tempheader ) {
679 if ( empty($tempheader) )
682 if ( false === strpos($tempheader, ':') ) {
683 $stack = explode(' ', $tempheader, 3);
685 list( , $response['code'], $response['message']) = $stack;
689 list($key, $value) = explode(':', $tempheader, 2);
691 $key = strtolower( $key );
692 $value = trim( $value );
694 if ( isset( $newheaders[ $key ] ) ) {
695 if ( ! is_array( $newheaders[ $key ] ) )
696 $newheaders[$key] = array( $newheaders[ $key ] );
697 $newheaders[ $key ][] = $value;
699 $newheaders[ $key ] = $value;
701 if ( 'set-cookie' == $key )
702 $cookies[] = new WP_Http_Cookie( $value, $url );
705 // Cast the Response Code to an int
706 $response['code'] = intval( $response['code'] );
708 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
712 * Takes the arguments for a ::request() and checks for the cookie array.
714 * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
715 * which are each parsed into strings and added to the Cookie: header (within the arguments array).
716 * Edits the array by reference.
722 * @param array $r Full array of args passed into ::request()
724 public static function buildCookieHeader( &$r ) {
725 if ( ! empty($r['cookies']) ) {
726 // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
727 foreach ( $r['cookies'] as $name => $value ) {
728 if ( ! is_object( $value ) )
729 $r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
732 $cookies_header = '';
733 foreach ( (array) $r['cookies'] as $cookie ) {
734 $cookies_header .= $cookie->getHeaderValue() . '; ';
737 $cookies_header = substr( $cookies_header, 0, -2 );
738 $r['headers']['cookie'] = $cookies_header;
743 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
745 * Based off the HTTP http_encoding_dechunk function.
747 * @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
753 * @param string $body Body content
754 * @return string Chunked decoded body on success or raw body on failure.
756 public static function chunkTransferDecode( $body ) {
757 // The body is not chunked encoded or is malformed.
758 if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
763 // We'll be altering $body, so need a backup in case of error.
764 $body_original = $body;
767 $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
768 if ( ! $has_chunk || empty( $match[1] ) )
769 return $body_original;
771 $length = hexdec( $match[1] );
772 $chunk_length = strlen( $match[0] );
774 // Parse out the chunk of data.
775 $parsed_body .= substr( $body, $chunk_length, $length );
777 // Remove the chunk from the raw data.
778 $body = substr( $body, $length + $chunk_length );
780 // End of the document.
781 if ( '0' === trim( $body ) )
787 * Block requests through the proxy.
789 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
790 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
792 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
793 * file and this will only allow localhost and your site to make requests. The constant
794 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
795 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
796 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
799 * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
800 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
802 * @staticvar array|null $accessible_hosts
803 * @staticvar array $wildcard_regex
805 * @param string $uri URI of url.
806 * @return bool True to block, false to allow.
808 public function block_request($uri) {
809 // We don't need to block requests, because nothing is blocked.
810 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
813 $check = parse_url($uri);
817 $home = parse_url( get_option('siteurl') );
819 // Don't block requests back to ourselves by default.
820 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
822 * Filters whether to block local requests through the proxy.
826 * @param bool $block Whether to block local requests through proxy.
829 return apply_filters( 'block_local_requests', false );
832 if ( !defined('WP_ACCESSIBLE_HOSTS') )
835 static $accessible_hosts = null;
836 static $wildcard_regex = array();
837 if ( null === $accessible_hosts ) {
838 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
840 if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
841 $wildcard_regex = array();
842 foreach ( $accessible_hosts as $host )
843 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
844 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
848 if ( !empty($wildcard_regex) )
849 return !preg_match($wildcard_regex, $check['host']);
851 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
856 * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
859 * @deprecated 4.4.0 Use wp_parse_url()
860 * @see wp_parse_url()
862 * @param string $url The URL to parse.
863 * @return bool|array False on failure; Array of URL components on success;
864 * See parse_url()'s return values.
866 protected static function parse_url( $url ) {
867 _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
868 return wp_parse_url( $url );
872 * Converts a relative URL to an absolute URL relative to a given URL.
874 * If an Absolute URL is provided, no processing of that URL is done.
881 * @param string $maybe_relative_path The URL which might be relative
882 * @param string $url The URL which $maybe_relative_path is relative to
883 * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
885 public static function make_absolute_url( $maybe_relative_path, $url ) {
887 return $maybe_relative_path;
889 if ( ! $url_parts = wp_parse_url( $url ) ) {
890 return $maybe_relative_path;
893 if ( ! $relative_url_parts = wp_parse_url( $maybe_relative_path ) ) {
894 return $maybe_relative_path;
897 // Check for a scheme on the 'relative' url
898 if ( ! empty( $relative_url_parts['scheme'] ) ) {
899 return $maybe_relative_path;
902 $absolute_path = $url_parts['scheme'] . '://';
904 // Schemeless URL's will make it this far, so we check for a host in the relative url and convert it to a protocol-url
905 if ( isset( $relative_url_parts['host'] ) ) {
906 $absolute_path .= $relative_url_parts['host'];
907 if ( isset( $relative_url_parts['port'] ) )
908 $absolute_path .= ':' . $relative_url_parts['port'];
910 $absolute_path .= $url_parts['host'];
911 if ( isset( $url_parts['port'] ) )
912 $absolute_path .= ':' . $url_parts['port'];
915 // Start off with the Absolute URL path.
916 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
918 // If it's a root-relative path, then great.
919 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
920 $path = $relative_url_parts['path'];
922 // Else it's a relative path.
923 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
924 // Strip off any file components from the absolute path.
925 $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
927 // Build the new path.
928 $path .= $relative_url_parts['path'];
930 // Strip all /path/../ out of the path.
931 while ( strpos( $path, '../' ) > 1 ) {
932 $path = preg_replace( '![^/]+/\.\./!', '', $path );
935 // Strip any final leading ../ from the path.
936 $path = preg_replace( '!^/(\.\./)+!', '', $path );
939 // Add the Query string.
940 if ( ! empty( $relative_url_parts['query'] ) )
941 $path .= '?' . $relative_url_parts['query'];
943 return $absolute_path . '/' . ltrim( $path, '/' );
947 * Handles HTTP Redirects and follows them if appropriate.
953 * @param string $url The URL which was requested.
954 * @param array $args The Arguments which were used to make the request.
955 * @param array $response The Response of the HTTP request.
956 * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
958 public static function handle_redirects( $url, $args, $response ) {
959 // If no redirects are present, or, redirects were not requested, perform no action.
960 if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
963 // Only perform redirections on redirection http codes.
964 if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
967 // Don't redirect if we've run out of redirects.
968 if ( $args['redirection']-- <= 0 )
969 return new WP_Error( 'http_request_failed', __('Too many redirects.') );
971 $redirect_location = $response['headers']['location'];
973 // If there were multiple Location headers, use the last header specified.
974 if ( is_array( $redirect_location ) )
975 $redirect_location = array_pop( $redirect_location );
977 $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
979 // POST requests should not POST to a redirected location.
980 if ( 'POST' == $args['method'] ) {
981 if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
982 $args['method'] = 'GET';
985 // Include valid cookies in the redirect process.
986 if ( ! empty( $response['cookies'] ) ) {
987 foreach ( $response['cookies'] as $cookie ) {
988 if ( $cookie->test( $redirect_location ) )
989 $args['cookies'][] = $cookie;
993 return wp_remote_request( $redirect_location, $args );
997 * Determines if a specified string represents an IP address or not.
999 * This function also detects the type of the IP address, returning either
1000 * '4' or '6' to represent a IPv4 and IPv6 address respectively.
1001 * This does not verify if the IP is a valid IP, only that it appears to be
1004 * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex
1009 * @param string $maybe_ip A suspected IP address
1010 * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
1012 public static function is_ip_address( $maybe_ip ) {
1013 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
1016 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, ' []' ) ) )