3 * HTTP API: WP_Http class
11 * Core class used for managing HTTP transports and making HTTP requests.
13 * This class is used to consistently make outgoing HTTP requests easy for developers
14 * while still being compatible with the many PHP configurations under which
17 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
23 // Aliases for HTTP response codes.
24 const HTTP_CONTINUE = 100;
25 const SWITCHING_PROTOCOLS = 101;
26 const PROCESSING = 102;
31 const NON_AUTHORITATIVE_INFORMATION = 203;
32 const NO_CONTENT = 204;
33 const RESET_CONTENT = 205;
34 const PARTIAL_CONTENT = 206;
35 const MULTI_STATUS = 207;
38 const MULTIPLE_CHOICES = 300;
39 const MOVED_PERMANENTLY = 301;
41 const SEE_OTHER = 303;
42 const NOT_MODIFIED = 304;
43 const USE_PROXY = 305;
45 const TEMPORARY_REDIRECT = 307;
46 const PERMANENT_REDIRECT = 308;
48 const BAD_REQUEST = 400;
49 const UNAUTHORIZED = 401;
50 const PAYMENT_REQUIRED = 402;
51 const FORBIDDEN = 403;
52 const NOT_FOUND = 404;
53 const METHOD_NOT_ALLOWED = 405;
54 const NOT_ACCEPTABLE = 406;
55 const PROXY_AUTHENTICATION_REQUIRED = 407;
56 const REQUEST_TIMEOUT = 408;
59 const LENGTH_REQUIRED = 411;
60 const PRECONDITION_FAILED = 412;
61 const REQUEST_ENTITY_TOO_LARGE = 413;
62 const REQUEST_URI_TOO_LONG = 414;
63 const UNSUPPORTED_MEDIA_TYPE = 415;
64 const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
65 const EXPECTATION_FAILED = 417;
66 const IM_A_TEAPOT = 418;
67 const MISDIRECTED_REQUEST = 421;
68 const UNPROCESSABLE_ENTITY = 422;
70 const FAILED_DEPENDENCY = 424;
71 const UPGRADE_REQUIRED = 426;
72 const PRECONDITION_REQUIRED = 428;
73 const TOO_MANY_REQUESTS = 429;
74 const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
75 const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
77 const INTERNAL_SERVER_ERROR = 500;
78 const NOT_IMPLEMENTED = 501;
79 const BAD_GATEWAY = 502;
80 const SERVICE_UNAVAILABLE = 503;
81 const GATEWAY_TIMEOUT = 504;
82 const HTTP_VERSION_NOT_SUPPORTED = 505;
83 const VARIANT_ALSO_NEGOTIATES = 506;
84 const INSUFFICIENT_STORAGE = 507;
85 const NOT_EXTENDED = 510;
86 const NETWORK_AUTHENTICATION_REQUIRED = 511;
89 * Send an HTTP request to a URI.
91 * Please note: The only URI that are supported in the HTTP Transport implementation
92 * are the HTTP and HTTPS protocols.
97 * @global string $wp_version
99 * @param string $url The request URL.
100 * @param string|array $args {
101 * Optional. Array or string of HTTP request arguments.
103 * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
104 * Some transports technically allow others, but should not be
105 * assumed. Default 'GET'.
106 * @type int $timeout How long the connection should stay open in seconds. Default 5.
107 * @type int $redirection Number of allowed redirects. Not supported by all transports
109 * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
111 * @type string $user-agent User-agent value sent.
112 * Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
113 * @type bool $reject_unsafe_urls Whether to pass URLs through {@see wp_http_validate_url()}.
115 * @type bool $blocking Whether the calling code requires the result of the request.
116 * If set to false, the request will be sent to the remote server,
117 * and processing returned to the calling code immediately, the caller
118 * will know if the request succeeded or failed, but will not receive
119 * any response from the remote server. Default true.
120 * @type string|array $headers Array or string of headers to send with the request.
121 * Default empty array.
122 * @type array $cookies List of cookies to send with the request. Default empty array.
123 * @type string|array $body Body to send with the request. Default null.
124 * @type bool $compress Whether to compress the $body when sending the request.
126 * @type bool $decompress Whether to decompress a compressed response. If set to false and
127 * compressed content is returned in the response anyway, it will
128 * need to be separately decompressed. Default true.
129 * @type bool $sslverify Whether to verify SSL for the request. Default true.
130 * @type string sslcertificates Absolute path to an SSL certificate .crt file.
131 * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
132 * @type bool $stream Whether to stream to a file. If set to true and no filename was
133 * given, it will be droped it in the WP temp dir and its name will
134 * be set using the basename of the URL. Default false.
135 * @type string $filename Filename of the file to write to when streaming. $stream must be
136 * set to true. Default null.
137 * @type int $limit_response_size Size in bytes to limit the response to. Default null.
140 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
141 * A WP_Error instance upon error.
143 public function request( $url, $args = array() ) {
149 * Filter the timeout value for an HTTP request.
153 * @param int $timeout_value Time in seconds until a request times out.
156 'timeout' => apply_filters( 'http_request_timeout', 5 ),
158 * Filter the number of redirects allowed during an HTTP request.
162 * @param int $redirect_count Number of redirects allowed. Default 5.
164 'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
166 * Filter the version of the HTTP protocol used in a request.
170 * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
173 'httpversion' => apply_filters( 'http_request_version', '1.0' ),
175 * Filter the user agent value sent with an HTTP request.
179 * @param string $user_agent WordPress user agent string.
181 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
183 * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
187 * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
190 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
192 'headers' => array(),
193 'cookies' => array(),
196 'decompress' => true,
198 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
201 'limit_response_size' => null,
204 // Pre-parse for the HEAD checks.
205 $args = wp_parse_args( $args );
207 // By default, Head requests do not cause redirections.
208 if ( isset($args['method']) && 'HEAD' == $args['method'] )
209 $defaults['redirection'] = 0;
211 $r = wp_parse_args( $args, $defaults );
213 * Filter the arguments used in an HTTP request.
217 * @param array $r An array of HTTP request arguments.
218 * @param string $url The request URL.
220 $r = apply_filters( 'http_request_args', $r, $url );
222 // The transports decrement this, store a copy of the original value for loop purposes.
223 if ( ! isset( $r['_redirection'] ) )
224 $r['_redirection'] = $r['redirection'];
227 * Filter whether to preempt an HTTP request's return value.
229 * Returning a non-false value from the filter will short-circuit the HTTP request and return
230 * early with that value. A filter should return either:
232 * - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
233 * - A WP_Error instance
234 * - boolean false (to avoid short-circuiting the response)
236 * Returning any other value may result in unexpected behaviour.
240 * @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value. Default false.
241 * @param array $r HTTP request arguments.
242 * @param string $url The request URL.
244 $pre = apply_filters( 'pre_http_request', false, $r, $url );
246 if ( false !== $pre )
249 if ( function_exists( 'wp_kses_bad_protocol' ) ) {
250 if ( $r['reject_unsafe_urls'] )
251 $url = wp_http_validate_url( $url );
253 $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
257 $arrURL = @parse_url( $url );
259 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
260 return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
262 if ( $this->block_request( $url ) )
263 return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
266 * Determine if this is a https call and pass that on to the transport functions
267 * so that we can blacklist the transports that do not support ssl verification
269 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
271 // Determine if this request is to OUR install of WordPress.
272 $homeURL = parse_url( get_bloginfo( 'url' ) );
273 $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
277 * If we are streaming to a file but no filename was given drop it in the WP temp dir
278 * and pick its name using the basename of the $url.
280 if ( $r['stream'] && empty( $r['filename'] ) ) {
281 $r['filename'] = get_temp_dir() . wp_unique_filename( get_temp_dir(), basename( $url ) );
285 * Force some settings if we are streaming to a file and check for existence and perms
286 * of destination directory.
288 if ( $r['stream'] ) {
289 $r['blocking'] = true;
290 if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
291 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
294 if ( is_null( $r['headers'] ) )
295 $r['headers'] = array();
297 if ( ! is_array( $r['headers'] ) ) {
298 $processedHeaders = self::processHeaders( $r['headers'], $url );
299 $r['headers'] = $processedHeaders['headers'];
302 if ( isset( $r['headers']['User-Agent'] ) ) {
303 $r['user-agent'] = $r['headers']['User-Agent'];
304 unset( $r['headers']['User-Agent'] );
307 if ( isset( $r['headers']['user-agent'] ) ) {
308 $r['user-agent'] = $r['headers']['user-agent'];
309 unset( $r['headers']['user-agent'] );
312 if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
313 $r['headers']['connection'] = 'close';
316 // Construct Cookie: header if any cookies are set.
317 self::buildCookieHeader( $r );
319 // Avoid issues where mbstring.func_overload is enabled.
320 mbstring_binary_safe_encoding();
322 if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
323 if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
324 $r['headers']['Accept-Encoding'] = $encoding;
327 if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
328 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
329 $r['body'] = http_build_query( $r['body'], null, '&' );
331 if ( ! isset( $r['headers']['Content-Type'] ) )
332 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
335 if ( '' === $r['body'] )
338 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
339 $r['headers']['Content-Length'] = strlen( $r['body'] );
342 $response = $this->_dispatch_request( $url, $r );
344 reset_mbstring_encoding();
346 if ( is_wp_error( $response ) )
349 // Append cookies that were used in this request to the response
350 if ( ! empty( $r['cookies'] ) ) {
351 $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
352 foreach ( $r['cookies'] as $cookie ) {
353 if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
354 $response['cookies'][] = $cookie;
363 * Tests which transports are capable of supporting the request.
368 * @param array $args Request arguments
369 * @param string $url URL to Request
371 * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
373 public function _get_first_available_transport( $args, $url = null ) {
374 $transports = array( 'curl', 'streams' );
377 * Filter which HTTP transports are available and in what order.
381 * @param array $transports Array of HTTP transports to check. Default array contains
382 * 'curl', and 'streams', in that order.
383 * @param array $args HTTP request arguments.
384 * @param string $url The URL to request.
386 $request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
388 // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
389 foreach ( $request_order as $transport ) {
390 if ( in_array( $transport, $transports ) ) {
391 $transport = ucfirst( $transport );
393 $class = 'WP_Http_' . $transport;
395 // Check to see if this transport is a possibility, calls the transport statically.
396 if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
406 * Dispatches a HTTP request to a supporting transport.
408 * Tests each transport in order to find a transport which matches the request arguments.
409 * Also caches the transport instance to be used later.
411 * The order for requests is cURL, and then PHP Streams.
418 * @param string $url URL to Request
419 * @param array $args Request arguments
420 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
422 private function _dispatch_request( $url, $args ) {
423 static $transports = array();
425 $class = $this->_get_first_available_transport( $args, $url );
427 return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
429 // Transport claims to support request, instantiate it and give it a whirl.
430 if ( empty( $transports[$class] ) )
431 $transports[$class] = new $class;
433 $response = $transports[$class]->request( $url, $args );
436 * Fires after an HTTP API response is received and before the response is returned.
440 * @param array|WP_Error $response HTTP response or WP_Error object.
441 * @param string $context Context under which the hook is fired.
442 * @param string $class HTTP transport used.
443 * @param array $args HTTP request arguments.
444 * @param string $url The request URL.
446 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
448 if ( is_wp_error( $response ) )
452 * Filter the HTTP API response immediately before the response is returned.
456 * @param array $response HTTP response.
457 * @param array $args HTTP request arguments.
458 * @param string $url The request URL.
460 return apply_filters( 'http_response', $response, $args, $url );
464 * Uses the POST HTTP method.
466 * Used for sending data that is expected to be in the body.
471 * @param string $url The request URL.
472 * @param string|array $args Optional. Override the defaults.
473 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
475 public function post($url, $args = array()) {
476 $defaults = array('method' => 'POST');
477 $r = wp_parse_args( $args, $defaults );
478 return $this->request($url, $r);
482 * Uses the GET HTTP method.
484 * Used for sending data that is expected to be in the body.
489 * @param string $url The request URL.
490 * @param string|array $args Optional. Override the defaults.
491 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
493 public function get($url, $args = array()) {
494 $defaults = array('method' => 'GET');
495 $r = wp_parse_args( $args, $defaults );
496 return $this->request($url, $r);
500 * Uses the HEAD HTTP method.
502 * Used for sending data that is expected to be in the body.
507 * @param string $url The request URL.
508 * @param string|array $args Optional. Override the defaults.
509 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
511 public function head($url, $args = array()) {
512 $defaults = array('method' => 'HEAD');
513 $r = wp_parse_args( $args, $defaults );
514 return $this->request($url, $r);
518 * Parses the responses and splits the parts into headers and body.
524 * @param string $strResponse The full response string
525 * @return array Array with 'headers' and 'body' keys.
527 public static function processResponse($strResponse) {
528 $res = explode("\r\n\r\n", $strResponse, 2);
530 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
534 * Transform header string into an array.
536 * If an array is given then it is assumed to be raw header data with numeric keys with the
537 * headers as the values. No headers must be passed that were already processed.
543 * @param string|array $headers
544 * @param string $url The URL that was requested
545 * @return array Processed string headers. If duplicate headers are encountered,
546 * Then a numbered array is returned as the value of that header-key.
548 public static function processHeaders( $headers, $url = '' ) {
549 // Split headers, one per array element.
550 if ( is_string($headers) ) {
551 // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
552 $headers = str_replace("\r\n", "\n", $headers);
554 * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
555 * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
557 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
558 // Create the headers array.
559 $headers = explode("\n", $headers);
562 $response = array('code' => 0, 'message' => '');
565 * If a redirection has taken place, The headers for each page request may have been passed.
566 * In this case, determine the final HTTP header and parse from there.
568 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
569 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
570 $headers = array_splice($headers, $i);
576 $newheaders = array();
577 foreach ( (array) $headers as $tempheader ) {
578 if ( empty($tempheader) )
581 if ( false === strpos($tempheader, ':') ) {
582 $stack = explode(' ', $tempheader, 3);
584 list( , $response['code'], $response['message']) = $stack;
588 list($key, $value) = explode(':', $tempheader, 2);
590 $key = strtolower( $key );
591 $value = trim( $value );
593 if ( isset( $newheaders[ $key ] ) ) {
594 if ( ! is_array( $newheaders[ $key ] ) )
595 $newheaders[$key] = array( $newheaders[ $key ] );
596 $newheaders[ $key ][] = $value;
598 $newheaders[ $key ] = $value;
600 if ( 'set-cookie' == $key )
601 $cookies[] = new WP_Http_Cookie( $value, $url );
604 // Cast the Response Code to an int
605 $response['code'] = intval( $response['code'] );
607 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
611 * Takes the arguments for a ::request() and checks for the cookie array.
613 * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
614 * which are each parsed into strings and added to the Cookie: header (within the arguments array).
615 * Edits the array by reference.
621 * @param array $r Full array of args passed into ::request()
623 public static function buildCookieHeader( &$r ) {
624 if ( ! empty($r['cookies']) ) {
625 // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
626 foreach ( $r['cookies'] as $name => $value ) {
627 if ( ! is_object( $value ) )
628 $r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
631 $cookies_header = '';
632 foreach ( (array) $r['cookies'] as $cookie ) {
633 $cookies_header .= $cookie->getHeaderValue() . '; ';
636 $cookies_header = substr( $cookies_header, 0, -2 );
637 $r['headers']['cookie'] = $cookies_header;
642 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
644 * Based off the HTTP http_encoding_dechunk function.
646 * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
652 * @param string $body Body content
653 * @return string Chunked decoded body on success or raw body on failure.
655 public static function chunkTransferDecode( $body ) {
656 // The body is not chunked encoded or is malformed.
657 if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
662 // We'll be altering $body, so need a backup in case of error.
663 $body_original = $body;
666 $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
667 if ( ! $has_chunk || empty( $match[1] ) )
668 return $body_original;
670 $length = hexdec( $match[1] );
671 $chunk_length = strlen( $match[0] );
673 // Parse out the chunk of data.
674 $parsed_body .= substr( $body, $chunk_length, $length );
676 // Remove the chunk from the raw data.
677 $body = substr( $body, $length + $chunk_length );
679 // End of the document.
680 if ( '0' === trim( $body ) )
686 * Block requests through the proxy.
688 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
689 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
691 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
692 * file and this will only allow localhost and your site to make requests. The constant
693 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
694 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
695 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
698 * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
699 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
701 * @staticvar array|null $accessible_hosts
702 * @staticvar array $wildcard_regex
704 * @param string $uri URI of url.
705 * @return bool True to block, false to allow.
707 public function block_request($uri) {
708 // We don't need to block requests, because nothing is blocked.
709 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
712 $check = parse_url($uri);
716 $home = parse_url( get_option('siteurl') );
718 // Don't block requests back to ourselves by default.
719 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
721 * Filter whether to block local requests through the proxy.
725 * @param bool $block Whether to block local requests through proxy.
728 return apply_filters( 'block_local_requests', false );
731 if ( !defined('WP_ACCESSIBLE_HOSTS') )
734 static $accessible_hosts = null;
735 static $wildcard_regex = array();
736 if ( null === $accessible_hosts ) {
737 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
739 if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
740 $wildcard_regex = array();
741 foreach ( $accessible_hosts as $host )
742 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
743 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
747 if ( !empty($wildcard_regex) )
748 return !preg_match($wildcard_regex, $check['host']);
750 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
755 * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
758 * @deprecated 4.4.0 Use wp_parse_url()
759 * @see wp_parse_url()
761 * @param string $url The URL to parse.
762 * @return bool|array False on failure; Array of URL components on success;
763 * See parse_url()'s return values.
765 protected static function parse_url( $url ) {
766 _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
767 return wp_parse_url( $url );
771 * Converts a relative URL to an absolute URL relative to a given URL.
773 * If an Absolute URL is provided, no processing of that URL is done.
780 * @param string $maybe_relative_path The URL which might be relative
781 * @param string $url The URL which $maybe_relative_path is relative to
782 * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
784 public static function make_absolute_url( $maybe_relative_path, $url ) {
786 return $maybe_relative_path;
788 if ( ! $url_parts = wp_parse_url( $url ) ) {
789 return $maybe_relative_path;
792 if ( ! $relative_url_parts = wp_parse_url( $maybe_relative_path ) ) {
793 return $maybe_relative_path;
796 // Check for a scheme on the 'relative' url
797 if ( ! empty( $relative_url_parts['scheme'] ) ) {
798 return $maybe_relative_path;
801 $absolute_path = $url_parts['scheme'] . '://';
803 // 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
804 if ( isset( $relative_url_parts['host'] ) ) {
805 $absolute_path .= $relative_url_parts['host'];
806 if ( isset( $relative_url_parts['port'] ) )
807 $absolute_path .= ':' . $relative_url_parts['port'];
809 $absolute_path .= $url_parts['host'];
810 if ( isset( $url_parts['port'] ) )
811 $absolute_path .= ':' . $url_parts['port'];
814 // Start off with the Absolute URL path.
815 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
817 // If it's a root-relative path, then great.
818 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
819 $path = $relative_url_parts['path'];
821 // Else it's a relative path.
822 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
823 // Strip off any file components from the absolute path.
824 $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
826 // Build the new path.
827 $path .= $relative_url_parts['path'];
829 // Strip all /path/../ out of the path.
830 while ( strpos( $path, '../' ) > 1 ) {
831 $path = preg_replace( '![^/]+/\.\./!', '', $path );
834 // Strip any final leading ../ from the path.
835 $path = preg_replace( '!^/(\.\./)+!', '', $path );
838 // Add the Query string.
839 if ( ! empty( $relative_url_parts['query'] ) )
840 $path .= '?' . $relative_url_parts['query'];
842 return $absolute_path . '/' . ltrim( $path, '/' );
846 * Handles HTTP Redirects and follows them if appropriate.
852 * @param string $url The URL which was requested.
853 * @param array $args The Arguments which were used to make the request.
854 * @param array $response The Response of the HTTP request.
855 * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
857 public static function handle_redirects( $url, $args, $response ) {
858 // If no redirects are present, or, redirects were not requested, perform no action.
859 if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
862 // Only perform redirections on redirection http codes.
863 if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
866 // Don't redirect if we've run out of redirects.
867 if ( $args['redirection']-- <= 0 )
868 return new WP_Error( 'http_request_failed', __('Too many redirects.') );
870 $redirect_location = $response['headers']['location'];
872 // If there were multiple Location headers, use the last header specified.
873 if ( is_array( $redirect_location ) )
874 $redirect_location = array_pop( $redirect_location );
876 $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
878 // POST requests should not POST to a redirected location.
879 if ( 'POST' == $args['method'] ) {
880 if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
881 $args['method'] = 'GET';
884 // Include valid cookies in the redirect process.
885 if ( ! empty( $response['cookies'] ) ) {
886 foreach ( $response['cookies'] as $cookie ) {
887 if ( $cookie->test( $redirect_location ) )
888 $args['cookies'][] = $cookie;
892 return wp_remote_request( $redirect_location, $args );
896 * Determines if a specified string represents an IP address or not.
898 * This function also detects the type of the IP address, returning either
899 * '4' or '6' to represent a IPv4 and IPv6 address respectively.
900 * This does not verify if the IP is a valid IP, only that it appears to be
903 * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex
908 * @param string $maybe_ip A suspected IP address
909 * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
911 public static function is_ip_address( $maybe_ip ) {
912 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
915 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, ' []' ) ) )