3 * Simple and uniform HTTP request API.
5 * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
6 * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
8 * @link https://core.trac.wordpress.org/ticket/4779 HTTP API Proposal
16 * WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
18 * This class is used to consistently make outgoing HTTP requests easy for developers
19 * while still being compatible with the many PHP configurations under which
22 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
31 * Send an HTTP request to a URI.
33 * Please note: The only URI that are supported in the HTTP Transport implementation
34 * are the HTTP and HTTPS protocols.
39 * @param string $url The request URL.
40 * @param string|array $args {
41 * Optional. Array or string of HTTP request arguments.
43 * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
44 * Some transports technically allow others, but should not be
45 * assumed. Default 'GET'.
46 * @type int $timeout How long the connection should stay open in seconds. Default 5.
47 * @type int $redirection Number of allowed redirects. Not supported by all transports
49 * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
51 * @type string $user-agent User-agent value sent.
52 * Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
53 * @type bool $reject_unsafe_urls Whether to pass URLs through {@see wp_http_validate_url()}.
55 * @type bool $blocking Whether the calling code requires the result of the request.
56 * If set to false, the request will be sent to the remote server,
57 * and processing returned to the calling code immediately, the caller
58 * will know if the request succeeded or failed, but will not receive
59 * any response from the remote server. Default true.
60 * @type string|array $headers Array or string of headers to send with the request.
61 * Default empty array.
62 * @type array $cookies List of cookies to send with the request. Default empty array.
63 * @type string|array $body Body to send with the request. Default null.
64 * @type bool $compress Whether to compress the $body when sending the request.
66 * @type bool $decompress Whether to decompress a compressed response. If set to false and
67 * compressed content is returned in the response anyway, it will
68 * need to be separately decompressed. Default true.
69 * @type bool $sslverify Whether to verify SSL for the request. Default true.
70 * @type string sslcertificates Absolute path to an SSL certificate .crt file.
71 * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
72 * @type bool $stream Whether to stream to a file. If set to true and no filename was
73 * given, it will be droped it in the WP temp dir and its name will
74 * be set using the basename of the URL. Default false.
75 * @type string $filename Filename of the file to write to when streaming. $stream must be
76 * set to true. Default null.
77 * @type int $limit_response_size Size in bytes to limit the response to. Default null.
80 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
81 * A WP_Error instance upon error.
83 public function request( $url, $args = array() ) {
89 * Filter the timeout value for an HTTP request.
93 * @param int $timeout_value Time in seconds until a request times out.
96 'timeout' => apply_filters( 'http_request_timeout', 5 ),
98 * Filter the number of redirects allowed during an HTTP request.
102 * @param int $redirect_count Number of redirects allowed. Default 5.
104 'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
106 * Filter the version of the HTTP protocol used in a request.
110 * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
113 'httpversion' => apply_filters( 'http_request_version', '1.0' ),
115 * Filter the user agent value sent with an HTTP request.
119 * @param string $user_agent WordPress user agent string.
121 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
123 * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
127 * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
130 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
132 'headers' => array(),
133 'cookies' => array(),
136 'decompress' => true,
138 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
141 'limit_response_size' => null,
144 // Pre-parse for the HEAD checks.
145 $args = wp_parse_args( $args );
147 // By default, Head requests do not cause redirections.
148 if ( isset($args['method']) && 'HEAD' == $args['method'] )
149 $defaults['redirection'] = 0;
151 $r = wp_parse_args( $args, $defaults );
153 * Filter the arguments used in an HTTP request.
157 * @param array $r An array of HTTP request arguments.
158 * @param string $url The request URL.
160 $r = apply_filters( 'http_request_args', $r, $url );
162 // The transports decrement this, store a copy of the original value for loop purposes.
163 if ( ! isset( $r['_redirection'] ) )
164 $r['_redirection'] = $r['redirection'];
167 * Filter whether to preempt an HTTP request's return.
169 * Returning a truthy value to the filter will short-circuit
170 * the HTTP request and return early with that value.
174 * @param bool $preempt Whether to preempt an HTTP request return. Default false.
175 * @param array $r HTTP request arguments.
176 * @param string $url The request URL.
178 $pre = apply_filters( 'pre_http_request', false, $r, $url );
179 if ( false !== $pre )
182 if ( function_exists( 'wp_kses_bad_protocol' ) ) {
183 if ( $r['reject_unsafe_urls'] )
184 $url = wp_http_validate_url( $url );
185 $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
188 $arrURL = @parse_url( $url );
190 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
191 return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
193 if ( $this->block_request( $url ) )
194 return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
197 * Determine if this is a https call and pass that on to the transport functions
198 * so that we can blacklist the transports that do not support ssl verification
200 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
202 // Determine if this request is to OUR install of WordPress.
203 $homeURL = parse_url( get_bloginfo( 'url' ) );
204 $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
208 * If we are streaming to a file but no filename was given drop it in the WP temp dir
209 * and pick its name using the basename of the $url.
211 if ( $r['stream'] && empty( $r['filename'] ) ) {
212 $r['filename'] = wp_unique_filename( get_temp_dir(), basename( $url ) );
216 * Force some settings if we are streaming to a file and check for existence and perms
217 * of destination directory.
219 if ( $r['stream'] ) {
220 $r['blocking'] = true;
221 if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
222 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
225 if ( is_null( $r['headers'] ) )
226 $r['headers'] = array();
228 if ( ! is_array( $r['headers'] ) ) {
229 $processedHeaders = WP_Http::processHeaders( $r['headers'], $url );
230 $r['headers'] = $processedHeaders['headers'];
233 if ( isset( $r['headers']['User-Agent'] ) ) {
234 $r['user-agent'] = $r['headers']['User-Agent'];
235 unset( $r['headers']['User-Agent'] );
238 if ( isset( $r['headers']['user-agent'] ) ) {
239 $r['user-agent'] = $r['headers']['user-agent'];
240 unset( $r['headers']['user-agent'] );
243 if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
244 $r['headers']['connection'] = 'close';
247 // Construct Cookie: header if any cookies are set.
248 WP_Http::buildCookieHeader( $r );
250 // Avoid issues where mbstring.func_overload is enabled.
251 mbstring_binary_safe_encoding();
253 if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
254 if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
255 $r['headers']['Accept-Encoding'] = $encoding;
258 if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
259 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
260 $r['body'] = http_build_query( $r['body'], null, '&' );
262 if ( ! isset( $r['headers']['Content-Type'] ) )
263 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
266 if ( '' === $r['body'] )
269 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
270 $r['headers']['Content-Length'] = strlen( $r['body'] );
273 $response = $this->_dispatch_request( $url, $r );
275 reset_mbstring_encoding();
277 if ( is_wp_error( $response ) )
280 // Append cookies that were used in this request to the response
281 if ( ! empty( $r['cookies'] ) ) {
282 $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
283 foreach ( $r['cookies'] as $cookie ) {
284 if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
285 $response['cookies'][] = $cookie;
294 * Tests which transports are capable of supporting the request.
299 * @param array $args Request arguments
300 * @param string $url URL to Request
302 * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
304 public function _get_first_available_transport( $args, $url = null ) {
306 * Filter which HTTP transports are available and in what order.
310 * @param array $value Array of HTTP transports to check. Default array contains
311 * 'curl', and 'streams', in that order.
312 * @param array $args HTTP request arguments.
313 * @param string $url The URL to request.
315 $request_order = apply_filters( 'http_api_transports', array( 'curl', 'streams' ), $args, $url );
317 // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
318 foreach ( $request_order as $transport ) {
319 $class = 'WP_HTTP_' . $transport;
321 // Check to see if this transport is a possibility, calls the transport statically.
322 if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
332 * Dispatches a HTTP request to a supporting transport.
334 * Tests each transport in order to find a transport which matches the request arguments.
335 * Also caches the transport instance to be used later.
337 * The order for requests is cURL, and then PHP Streams.
342 * @param string $url URL to Request
343 * @param array $args Request arguments
344 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
346 private function _dispatch_request( $url, $args ) {
347 static $transports = array();
349 $class = $this->_get_first_available_transport( $args, $url );
351 return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
353 // Transport claims to support request, instantiate it and give it a whirl.
354 if ( empty( $transports[$class] ) )
355 $transports[$class] = new $class;
357 $response = $transports[$class]->request( $url, $args );
360 * Fires after an HTTP API response is received and before the response is returned.
364 * @param array|WP_Error $response HTTP response or WP_Error object.
365 * @param string $context Context under which the hook is fired.
366 * @param string $class HTTP transport used.
367 * @param array $args HTTP request arguments.
368 * @param string $url The request URL.
370 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
372 if ( is_wp_error( $response ) )
376 * Filter the HTTP API response immediately before the response is returned.
380 * @param array $response HTTP response.
381 * @param array $args HTTP request arguments.
382 * @param string $url The request URL.
384 return apply_filters( 'http_response', $response, $args, $url );
388 * Uses the POST HTTP method.
390 * Used for sending data that is expected to be in the body.
395 * @param string $url The request URL.
396 * @param string|array $args Optional. Override the defaults.
397 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
399 public function post($url, $args = array()) {
400 $defaults = array('method' => 'POST');
401 $r = wp_parse_args( $args, $defaults );
402 return $this->request($url, $r);
406 * Uses the GET HTTP method.
408 * Used for sending data that is expected to be in the body.
413 * @param string $url The request URL.
414 * @param string|array $args Optional. Override the defaults.
415 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
417 public function get($url, $args = array()) {
418 $defaults = array('method' => 'GET');
419 $r = wp_parse_args( $args, $defaults );
420 return $this->request($url, $r);
424 * Uses the HEAD HTTP method.
426 * Used for sending data that is expected to be in the body.
431 * @param string $url The request URL.
432 * @param string|array $args Optional. Override the defaults.
433 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
435 public function head($url, $args = array()) {
436 $defaults = array('method' => 'HEAD');
437 $r = wp_parse_args( $args, $defaults );
438 return $this->request($url, $r);
442 * Parses the responses and splits the parts into headers and body.
448 * @param string $strResponse The full response string
449 * @return array Array with 'headers' and 'body' keys.
451 public static function processResponse($strResponse) {
452 $res = explode("\r\n\r\n", $strResponse, 2);
454 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
458 * Transform header string into an array.
460 * If an array is given then it is assumed to be raw header data with numeric keys with the
461 * headers as the values. No headers must be passed that were already processed.
467 * @param string|array $headers
468 * @param string $url The URL that was requested
469 * @return array Processed string headers. If duplicate headers are encountered,
470 * Then a numbered array is returned as the value of that header-key.
472 public static function processHeaders( $headers, $url = '' ) {
473 // Split headers, one per array element.
474 if ( is_string($headers) ) {
475 // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
476 $headers = str_replace("\r\n", "\n", $headers);
478 * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
479 * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
481 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
482 // Create the headers array.
483 $headers = explode("\n", $headers);
486 $response = array('code' => 0, 'message' => '');
489 * If a redirection has taken place, The headers for each page request may have been passed.
490 * In this case, determine the final HTTP header and parse from there.
492 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
493 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
494 $headers = array_splice($headers, $i);
500 $newheaders = array();
501 foreach ( (array) $headers as $tempheader ) {
502 if ( empty($tempheader) )
505 if ( false === strpos($tempheader, ':') ) {
506 $stack = explode(' ', $tempheader, 3);
508 list( , $response['code'], $response['message']) = $stack;
512 list($key, $value) = explode(':', $tempheader, 2);
514 $key = strtolower( $key );
515 $value = trim( $value );
517 if ( isset( $newheaders[ $key ] ) ) {
518 if ( ! is_array( $newheaders[ $key ] ) )
519 $newheaders[$key] = array( $newheaders[ $key ] );
520 $newheaders[ $key ][] = $value;
522 $newheaders[ $key ] = $value;
524 if ( 'set-cookie' == $key )
525 $cookies[] = new WP_Http_Cookie( $value, $url );
528 // Cast the Response Code to an int
529 $response['code'] = intval( $response['code'] );
531 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
535 * Takes the arguments for a ::request() and checks for the cookie array.
537 * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
538 * which are each parsed into strings and added to the Cookie: header (within the arguments array).
539 * Edits the array by reference.
545 * @param array $r Full array of args passed into ::request()
547 public static function buildCookieHeader( &$r ) {
548 if ( ! empty($r['cookies']) ) {
549 // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
550 foreach ( $r['cookies'] as $name => $value ) {
551 if ( ! is_object( $value ) )
552 $r['cookies'][ $name ] = new WP_HTTP_Cookie( array( 'name' => $name, 'value' => $value ) );
555 $cookies_header = '';
556 foreach ( (array) $r['cookies'] as $cookie ) {
557 $cookies_header .= $cookie->getHeaderValue() . '; ';
560 $cookies_header = substr( $cookies_header, 0, -2 );
561 $r['headers']['cookie'] = $cookies_header;
566 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
568 * Based off the HTTP http_encoding_dechunk function.
570 * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
576 * @param string $body Body content
577 * @return string Chunked decoded body on success or raw body on failure.
579 public static function chunkTransferDecode( $body ) {
580 // The body is not chunked encoded or is malformed.
581 if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
586 // We'll be altering $body, so need a backup in case of error.
587 $body_original = $body;
590 $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
591 if ( ! $has_chunk || empty( $match[1] ) )
592 return $body_original;
594 $length = hexdec( $match[1] );
595 $chunk_length = strlen( $match[0] );
597 // Parse out the chunk of data.
598 $parsed_body .= substr( $body, $chunk_length, $length );
600 // Remove the chunk from the raw data.
601 $body = substr( $body, $length + $chunk_length );
603 // End of the document.
604 if ( '0' === trim( $body ) )
610 * Block requests through the proxy.
612 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
613 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
615 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
616 * file and this will only allow localhost and your blog to make requests. The constant
617 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
618 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
619 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
622 * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
623 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
625 * @param string $uri URI of url.
626 * @return bool True to block, false to allow.
628 public function block_request($uri) {
629 // We don't need to block requests, because nothing is blocked.
630 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
633 $check = parse_url($uri);
637 $home = parse_url( get_option('siteurl') );
639 // Don't block requests back to ourselves by default.
640 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
642 * Filter whether to block local requests through the proxy.
646 * @param bool $block Whether to block local requests through proxy.
649 return apply_filters( 'block_local_requests', false );
652 if ( !defined('WP_ACCESSIBLE_HOSTS') )
655 static $accessible_hosts;
656 static $wildcard_regex = false;
657 if ( null == $accessible_hosts ) {
658 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
660 if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
661 $wildcard_regex = array();
662 foreach ( $accessible_hosts as $host )
663 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
664 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
668 if ( !empty($wildcard_regex) )
669 return !preg_match($wildcard_regex, $check['host']);
671 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
676 * A wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7
678 * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including
679 * schemeless and relative url's with :// in the path, this works around those
680 * limitations providing a standard output on PHP 5.2~5.4+.
682 * Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated
683 * when URL parsing failed.
688 * @param string $url The URL to parse.
689 * @return bool|array False on failure; Array of URL components on success;
690 * See parse_url()'s return values.
692 protected static function parse_url( $url ) {
693 $parts = @parse_url( $url );
695 // < PHP 5.4.7 compat, trouble with relative paths including a scheme break in the path
696 if ( '/' == $url[0] && false !== strpos( $url, '://' ) ) {
697 // Since we know it's a relative path, prefix with a scheme/host placeholder and try again
698 if ( ! $parts = @parse_url( 'placeholder://placeholder' . $url ) ) {
701 // Remove the placeholder values
702 unset( $parts['scheme'], $parts['host'] );
708 // < PHP 5.4.7 compat, doesn't detect schemeless URL's host field
709 if ( '//' == substr( $url, 0, 2 ) && ! isset( $parts['host'] ) ) {
710 list( $parts['host'], $slashless_path ) = explode( '/', substr( $parts['path'], 2 ), 2 );
711 $parts['path'] = "/{$slashless_path}";
718 * Converts a relative URL to an absolute URL relative to a given URL.
720 * If an Absolute URL is provided, no processing of that URL is done.
725 * @param string $maybe_relative_path The URL which might be relative
726 * @param string $url The URL which $maybe_relative_path is relative to
727 * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
729 public static function make_absolute_url( $maybe_relative_path, $url ) {
731 return $maybe_relative_path;
733 if ( ! $url_parts = WP_HTTP::parse_url( $url ) ) {
734 return $maybe_relative_path;
737 if ( ! $relative_url_parts = WP_HTTP::parse_url( $maybe_relative_path ) ) {
738 return $maybe_relative_path;
741 // Check for a scheme on the 'relative' url
742 if ( ! empty( $relative_url_parts['scheme'] ) ) {
743 return $maybe_relative_path;
746 $absolute_path = $url_parts['scheme'] . '://';
748 // 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
749 if ( isset( $relative_url_parts['host'] ) ) {
750 $absolute_path .= $relative_url_parts['host'];
751 if ( isset( $relative_url_parts['port'] ) )
752 $absolute_path .= ':' . $relative_url_parts['port'];
754 $absolute_path .= $url_parts['host'];
755 if ( isset( $url_parts['port'] ) )
756 $absolute_path .= ':' . $url_parts['port'];
759 // Start off with the Absolute URL path.
760 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
762 // If it's a root-relative path, then great.
763 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
764 $path = $relative_url_parts['path'];
766 // Else it's a relative path.
767 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
768 // Strip off any file components from the absolute path.
769 $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
771 // Build the new path.
772 $path .= $relative_url_parts['path'];
774 // Strip all /path/../ out of the path.
775 while ( strpos( $path, '../' ) > 1 ) {
776 $path = preg_replace( '![^/]+/\.\./!', '', $path );
779 // Strip any final leading ../ from the path.
780 $path = preg_replace( '!^/(\.\./)+!', '', $path );
783 // Add the Query string.
784 if ( ! empty( $relative_url_parts['query'] ) )
785 $path .= '?' . $relative_url_parts['query'];
787 return $absolute_path . '/' . ltrim( $path, '/' );
791 * Handles HTTP Redirects and follows them if appropriate.
795 * @param string $url The URL which was requested.
796 * @param array $args The Arguments which were used to make the request.
797 * @param array $response The Response of the HTTP request.
798 * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
800 public static function handle_redirects( $url, $args, $response ) {
801 // If no redirects are present, or, redirects were not requested, perform no action.
802 if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
805 // Only perform redirections on redirection http codes.
806 if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
809 // Don't redirect if we've run out of redirects.
810 if ( $args['redirection']-- <= 0 )
811 return new WP_Error( 'http_request_failed', __('Too many redirects.') );
813 $redirect_location = $response['headers']['location'];
815 // If there were multiple Location headers, use the last header specified.
816 if ( is_array( $redirect_location ) )
817 $redirect_location = array_pop( $redirect_location );
819 $redirect_location = WP_HTTP::make_absolute_url( $redirect_location, $url );
821 // POST requests should not POST to a redirected location.
822 if ( 'POST' == $args['method'] ) {
823 if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
824 $args['method'] = 'GET';
827 // Include valid cookies in the redirect process.
828 if ( ! empty( $response['cookies'] ) ) {
829 foreach ( $response['cookies'] as $cookie ) {
830 if ( $cookie->test( $redirect_location ) )
831 $args['cookies'][] = $cookie;
835 return wp_remote_request( $redirect_location, $args );
839 * Determines if a specified string represents an IP address or not.
841 * This function also detects the type of the IP address, returning either
842 * '4' or '6' to represent a IPv4 and IPv6 address respectively.
843 * This does not verify if the IP is a valid IP, only that it appears to be
846 * @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
851 * @param string $maybe_ip A suspected IP address
852 * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
854 public static function is_ip_address( $maybe_ip ) {
855 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
858 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, ' []' ) ) )
867 * HTTP request method uses PHP Streams to retrieve the url.
870 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
872 class WP_Http_Streams {
874 * Send a HTTP request to a URI using PHP Streams.
876 * @see WP_Http::request For default options descriptions.
879 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
882 * @param string $url The request URL.
883 * @param string|array $args Optional. Override the defaults.
884 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
886 public function request($url, $args = array()) {
888 'method' => 'GET', 'timeout' => 5,
889 'redirection' => 5, 'httpversion' => '1.0',
891 'headers' => array(), 'body' => null, 'cookies' => array()
894 $r = wp_parse_args( $args, $defaults );
896 if ( isset($r['headers']['User-Agent']) ) {
897 $r['user-agent'] = $r['headers']['User-Agent'];
898 unset($r['headers']['User-Agent']);
899 } else if ( isset($r['headers']['user-agent']) ) {
900 $r['user-agent'] = $r['headers']['user-agent'];
901 unset($r['headers']['user-agent']);
904 // Construct Cookie: header if any cookies are set.
905 WP_Http::buildCookieHeader( $r );
907 $arrURL = parse_url($url);
909 $connect_host = $arrURL['host'];
911 $secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
912 if ( ! isset( $arrURL['port'] ) ) {
913 if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
914 $arrURL['port'] = 443;
915 $secure_transport = true;
917 $arrURL['port'] = 80;
921 // Always pass a Path, defaulting to the root in cases such as http://example.com
922 if ( ! isset( $arrURL['path'] ) ) {
923 $arrURL['path'] = '/';
926 if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
927 if ( isset( $r['headers']['Host'] ) )
928 $arrURL['host'] = $r['headers']['Host'];
930 $arrURL['host'] = $r['headers']['host'];
931 unset( $r['headers']['Host'], $r['headers']['host'] );
935 * Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
936 * to ::1, which fails when the server is not set up for it. For compatibility, always
937 * connect to the IPv4 address.
939 if ( 'localhost' == strtolower( $connect_host ) )
940 $connect_host = '127.0.0.1';
942 $connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
944 $is_local = isset( $r['local'] ) && $r['local'];
945 $ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
948 * Filter whether SSL should be verified for local requests.
952 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
954 $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
955 } elseif ( ! $is_local ) {
957 * Filter whether SSL should be verified for non-local requests.
961 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
963 $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
966 $proxy = new WP_HTTP_Proxy();
968 $context = stream_context_create( array(
970 'verify_peer' => $ssl_verify,
971 //'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
972 'capture_peer_cert' => $ssl_verify,
973 'SNI_enabled' => true,
974 'cafile' => $r['sslcertificates'],
975 'allow_self_signed' => ! $ssl_verify,
979 $timeout = (int) floor( $r['timeout'] );
980 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
981 $connect_timeout = max( $timeout, 1 );
983 // Store error number.
984 $connection_error = null;
986 // Store error string.
987 $connection_error_str = null;
990 // In the event that the SSL connection fails, silence the many PHP Warnings.
991 if ( $secure_transport )
992 $error_reporting = error_reporting(0);
994 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
995 $handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
997 $handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
999 if ( $secure_transport )
1000 error_reporting( $error_reporting );
1003 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
1004 $handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1006 $handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1009 if ( false === $handle ) {
1010 // SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
1011 if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
1012 return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1014 return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
1017 // Verify that the SSL certificate is valid for this request.
1018 if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
1019 if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
1020 return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1023 stream_set_timeout( $handle, $timeout, $utimeout );
1025 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
1026 $requestPath = $url;
1028 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
1030 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
1032 $include_port_in_host_header = (
1033 ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) ||
1034 ( 'http' == $arrURL['scheme'] && 80 != $arrURL['port'] ) ||
1035 ( 'https' == $arrURL['scheme'] && 443 != $arrURL['port'] )
1038 if ( $include_port_in_host_header ) {
1039 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
1041 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
1044 if ( isset($r['user-agent']) )
1045 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
1047 if ( is_array($r['headers']) ) {
1048 foreach ( (array) $r['headers'] as $header => $headerValue )
1049 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
1051 $strHeaders .= $r['headers'];
1054 if ( $proxy->use_authentication() )
1055 $strHeaders .= $proxy->authentication_header() . "\r\n";
1057 $strHeaders .= "\r\n";
1059 if ( ! is_null($r['body']) )
1060 $strHeaders .= $r['body'];
1062 fwrite($handle, $strHeaders);
1064 if ( ! $r['blocking'] ) {
1065 stream_set_blocking( $handle, 0 );
1067 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1071 $bodyStarted = false;
1072 $keep_reading = true;
1074 if ( isset( $r['limit_response_size'] ) )
1075 $block_size = min( $block_size, $r['limit_response_size'] );
1077 // If streaming to a file setup the file handle.
1078 if ( $r['stream'] ) {
1080 $stream_handle = @fopen( $r['filename'], 'w+' );
1082 $stream_handle = fopen( $r['filename'], 'w+' );
1083 if ( ! $stream_handle )
1084 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1087 while ( ! feof($handle) && $keep_reading ) {
1088 $block = fread( $handle, $block_size );
1089 if ( ! $bodyStarted ) {
1090 $strResponse .= $block;
1091 if ( strpos( $strResponse, "\r\n\r\n" ) ) {
1092 $process = WP_Http::processResponse( $strResponse );
1093 $bodyStarted = true;
1094 $block = $process['body'];
1095 unset( $strResponse );
1096 $process['body'] = '';
1100 $this_block_size = strlen( $block );
1102 if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] ) {
1103 $this_block_size = ( $r['limit_response_size'] - $bytes_written );
1104 $block = substr( $block, 0, $this_block_size );
1107 $bytes_written_to_file = fwrite( $stream_handle, $block );
1109 if ( $bytes_written_to_file != $this_block_size ) {
1111 fclose( $stream_handle );
1112 return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1115 $bytes_written += $bytes_written_to_file;
1117 $keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
1120 fclose( $stream_handle );
1124 while ( ! feof( $handle ) && $keep_reading ) {
1125 $block = fread( $handle, $block_size );
1126 $strResponse .= $block;
1127 if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
1128 $header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
1129 $bodyStarted = true;
1131 $keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
1134 $process = WP_Http::processResponse( $strResponse );
1135 unset( $strResponse );
1141 $arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
1144 'headers' => $arrHeaders['headers'],
1145 // Not yet processed.
1147 'response' => $arrHeaders['response'],
1148 'cookies' => $arrHeaders['cookies'],
1149 'filename' => $r['filename']
1152 // Handle redirects.
1153 if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1154 return $redirect_response;
1156 // If the body was chunk encoded, then decode it.
1157 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
1158 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
1160 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
1161 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
1163 if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
1164 $process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
1166 $response['body'] = $process['body'];
1172 * Verifies the received SSL certificate against it's Common Names and subjectAltName fields
1174 * PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
1175 * the certificate is valid for the hostname which was requested.
1176 * This function verifies the requested hostname against certificate's subjectAltName field,
1177 * if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
1179 * IP Address support is included if the request is being made to an IP address.
1184 * @param stream $stream The PHP Stream which the SSL request is being made over
1185 * @param string $host The hostname being requested
1186 * @return bool If the cerficiate presented in $stream is valid for $host
1188 public static function verify_ssl_certificate( $stream, $host ) {
1189 $context_options = stream_context_get_options( $stream );
1191 if ( empty( $context_options['ssl']['peer_certificate'] ) )
1194 $cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
1199 * If the request is being made to an IP address, we'll validate against IP fields
1200 * in the cert (if they exist)
1202 $host_type = ( WP_HTTP::is_ip_address( $host ) ? 'ip' : 'dns' );
1204 $certificate_hostnames = array();
1205 if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
1206 $match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
1207 foreach ( $match_against as $match ) {
1208 list( $match_type, $match_host ) = explode( ':', $match );
1209 if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
1210 $certificate_hostnames[] = strtolower( trim( $match_host ) );
1212 } elseif ( !empty( $cert['subject']['CN'] ) ) {
1213 // Only use the CN when the certificate includes no subjectAltName extension.
1214 $certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
1217 // Exact hostname/IP matches.
1218 if ( in_array( strtolower( $host ), $certificate_hostnames ) )
1221 // IP's can't be wildcards, Stop processing.
1222 if ( 'ip' == $host_type )
1225 // Test to see if the domain is at least 2 deep for wildcard support.
1226 if ( substr_count( $host, '.' ) < 2 )
1229 // Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
1230 $wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
1232 return in_array( strtolower( $wildcard_host ), $certificate_hostnames );
1236 * Whether this class can be used for retrieving a URL.
1241 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
1243 * @return boolean False means this class can not be used, true means it can.
1245 public static function test( $args = array() ) {
1246 if ( ! function_exists( 'stream_socket_client' ) )
1249 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1252 if ( ! extension_loaded( 'openssl' ) )
1254 if ( ! function_exists( 'openssl_x509_parse' ) )
1259 * Filter whether streams can be used as a transport for retrieving a URL.
1263 * @param bool $use_class Whether the class can be used. Default true.
1264 * @param array $args Request arguments.
1266 return apply_filters( 'use_streams_transport', true, $args );
1271 * Deprecated HTTP Transport method which used fsockopen.
1273 * This class is not used, and is included for backwards compatibility only.
1274 * All code should make use of WP_HTTP directly through it's API.
1276 * @see WP_HTTP::request
1279 * @deprecated 3.7.0 Please use WP_HTTP::request() directly
1281 class WP_HTTP_Fsockopen extends WP_HTTP_Streams {
1282 // For backwards compatibility for users who are using the class directly.
1286 * HTTP request method uses Curl extension to retrieve the url.
1288 * Requires the Curl extension to be installed.
1290 * @package WordPress
1294 class WP_Http_Curl {
1297 * Temporary header storage for during requests.
1303 private $headers = '';
1306 * Temporary body storage for during requests.
1315 * The maximum amount of data to receive from the remote server.
1321 private $max_body_length = false;
1324 * The file resource used for streaming to file.
1330 private $stream_handle = false;
1333 * The total bytes written in the current request.
1339 private $bytes_written_total = 0;
1342 * Send a HTTP request to a URI using cURL extension.
1347 * @param string $url The request URL.
1348 * @param string|array $args Optional. Override the defaults.
1349 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
1351 public function request($url, $args = array()) {
1353 'method' => 'GET', 'timeout' => 5,
1354 'redirection' => 5, 'httpversion' => '1.0',
1356 'headers' => array(), 'body' => null, 'cookies' => array()
1359 $r = wp_parse_args( $args, $defaults );
1361 if ( isset($r['headers']['User-Agent']) ) {
1362 $r['user-agent'] = $r['headers']['User-Agent'];
1363 unset($r['headers']['User-Agent']);
1364 } else if ( isset($r['headers']['user-agent']) ) {
1365 $r['user-agent'] = $r['headers']['user-agent'];
1366 unset($r['headers']['user-agent']);
1369 // Construct Cookie: header if any cookies are set.
1370 WP_Http::buildCookieHeader( $r );
1372 $handle = curl_init();
1374 // cURL offers really easy proxy support.
1375 $proxy = new WP_HTTP_Proxy();
1377 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1379 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1380 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1381 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1383 if ( $proxy->use_authentication() ) {
1384 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1385 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1389 $is_local = isset($r['local']) && $r['local'];
1390 $ssl_verify = isset($r['sslverify']) && $r['sslverify'];
1392 /** This filter is documented in wp-includes/class-http.php */
1393 $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
1394 } elseif ( ! $is_local ) {
1395 /** This filter is documented in wp-includes/class-http.php */
1396 $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
1400 * CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
1401 * a value of 0 will allow an unlimited timeout.
1403 $timeout = (int) ceil( $r['timeout'] );
1404 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1405 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1407 curl_setopt( $handle, CURLOPT_URL, $url);
1408 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1409 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
1410 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1411 curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
1412 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1415 * The option doesn't work with safe mode or when open_basedir is set, and there's
1416 * a bug #17490 with redirected POST requests, so handle redirections outside Curl.
1418 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
1419 if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
1420 curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
1422 switch ( $r['method'] ) {
1424 curl_setopt( $handle, CURLOPT_NOBODY, true );
1427 curl_setopt( $handle, CURLOPT_POST, true );
1428 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1431 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1432 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1435 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
1436 if ( ! is_null( $r['body'] ) )
1437 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1441 if ( true === $r['blocking'] ) {
1442 curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
1443 curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
1446 curl_setopt( $handle, CURLOPT_HEADER, false );
1448 if ( isset( $r['limit_response_size'] ) )
1449 $this->max_body_length = intval( $r['limit_response_size'] );
1451 $this->max_body_length = false;
1453 // If streaming to a file open a file handle, and setup our curl streaming handler.
1454 if ( $r['stream'] ) {
1456 $this->stream_handle = @fopen( $r['filename'], 'w+' );
1458 $this->stream_handle = fopen( $r['filename'], 'w+' );
1459 if ( ! $this->stream_handle )
1460 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1462 $this->stream_handle = false;
1465 if ( !empty( $r['headers'] ) ) {
1466 // cURL expects full header strings in each element.
1468 foreach ( $r['headers'] as $name => $value ) {
1469 $headers[] = "{$name}: $value";
1471 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1474 if ( $r['httpversion'] == '1.0' )
1475 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1477 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1480 * Fires before the cURL request is executed.
1482 * Cookies are not currently handled by the HTTP API. This action allows
1483 * plugins to handle cookies themselves.
1487 * @param resource &$handle The cURL handle returned by curl_init().
1488 * @param array $r The HTTP request arguments.
1489 * @param string $url The request URL.
1491 do_action_ref_array( 'http_api_curl', array( &$handle, $r, $url ) );
1493 // We don't need to return the body, so don't. Just execute request and return.
1494 if ( ! $r['blocking'] ) {
1495 curl_exec( $handle );
1497 if ( $curl_error = curl_error( $handle ) ) {
1498 curl_close( $handle );
1499 return new WP_Error( 'http_request_failed', $curl_error );
1501 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1502 curl_close( $handle );
1503 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1506 curl_close( $handle );
1507 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1510 curl_exec( $handle );
1511 $theHeaders = WP_Http::processHeaders( $this->headers, $url );
1512 $theBody = $this->body;
1513 $bytes_written_total = $this->bytes_written_total;
1515 $this->headers = '';
1517 $this->bytes_written_total = 0;
1519 $curl_error = curl_errno( $handle );
1521 // If an error occurred, or, no response.
1522 if ( $curl_error || ( 0 == strlen( $theBody ) && empty( $theHeaders['headers'] ) ) ) {
1523 if ( CURLE_WRITE_ERROR /* 23 */ == $curl_error && $r['stream'] ) {
1524 if ( ! $this->max_body_length || $this->max_body_length != $bytes_written_total ) {
1525 fclose( $this->stream_handle );
1526 return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1529 if ( $curl_error = curl_error( $handle ) ) {
1530 curl_close( $handle );
1531 return new WP_Error( 'http_request_failed', $curl_error );
1534 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1535 curl_close( $handle );
1536 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1540 curl_close( $handle );
1543 fclose( $this->stream_handle );
1546 'headers' => $theHeaders['headers'],
1548 'response' => $theHeaders['response'],
1549 'cookies' => $theHeaders['cookies'],
1550 'filename' => $r['filename']
1553 // Handle redirects.
1554 if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1555 return $redirect_response;
1557 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1558 $theBody = WP_Http_Encoding::decompress( $theBody );
1560 $response['body'] = $theBody;
1566 * Grab the headers of the cURL request
1568 * Each header is sent individually to this callback, so we append to the $header property for temporary storage
1574 private function stream_headers( $handle, $headers ) {
1575 $this->headers .= $headers;
1576 return strlen( $headers );
1580 * Grab the body of the cURL request
1582 * The contents of the document are passed in chunks, so we append to the $body property for temporary storage.
1583 * Returning a length shorter than the length of $data passed in will cause cURL to abort the request with CURLE_WRITE_ERROR
1589 private function stream_body( $handle, $data ) {
1590 $data_length = strlen( $data );
1592 if ( $this->max_body_length && ( $this->bytes_written_total + $data_length ) > $this->max_body_length ) {
1593 $data_length = ( $this->max_body_length - $this->bytes_written_total );
1594 $data = substr( $data, 0, $data_length );
1597 if ( $this->stream_handle ) {
1598 $bytes_written = fwrite( $this->stream_handle, $data );
1600 $this->body .= $data;
1601 $bytes_written = $data_length;
1604 $this->bytes_written_total += $bytes_written;
1606 // Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR.
1607 return $bytes_written;
1611 * Whether this class can be used for retrieving an URL.
1616 * @return boolean False means this class can not be used, true means it can.
1618 public static function test( $args = array() ) {
1619 if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
1622 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1625 $curl_version = curl_version();
1626 // Check whether this cURL version support SSL requests.
1627 if ( ! (CURL_VERSION_SSL & $curl_version['features']) )
1632 * Filter whether cURL can be used as a transport for retrieving a URL.
1636 * @param bool $use_class Whether the class can be used. Default true.
1637 * @param array $args An array of request arguments.
1639 return apply_filters( 'use_curl_transport', true, $args );
1644 * Adds Proxy support to the WordPress HTTP API.
1646 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1647 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1650 * Please note that only BASIC authentication is supported by most transports.
1651 * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
1653 * The constants are as follows:
1655 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1656 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1657 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1658 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1659 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1660 * You do not need to have localhost and the blog host in this list, because they will not be passed
1661 * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1664 * An example can be as seen below.
1666 * define('WP_PROXY_HOST', '192.168.84.101');
1667 * define('WP_PROXY_PORT', '8080');
1668 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1670 * @link https://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1671 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1674 class WP_HTTP_Proxy {
1677 * Whether proxy connection should be used.
1681 * @use WP_PROXY_HOST
1682 * @use WP_PROXY_PORT
1686 public function is_enabled() {
1687 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1691 * Whether authentication should be used.
1695 * @use WP_PROXY_USERNAME
1696 * @use WP_PROXY_PASSWORD
1700 public function use_authentication() {
1701 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1705 * Retrieve the host for the proxy server.
1711 public function host() {
1712 if ( defined('WP_PROXY_HOST') )
1713 return WP_PROXY_HOST;
1719 * Retrieve the port for the proxy server.
1725 public function port() {
1726 if ( defined('WP_PROXY_PORT') )
1727 return WP_PROXY_PORT;
1733 * Retrieve the username for proxy authentication.
1739 public function username() {
1740 if ( defined('WP_PROXY_USERNAME') )
1741 return WP_PROXY_USERNAME;
1747 * Retrieve the password for proxy authentication.
1753 public function password() {
1754 if ( defined('WP_PROXY_PASSWORD') )
1755 return WP_PROXY_PASSWORD;
1761 * Retrieve authentication string for proxy authentication.
1767 public function authentication() {
1768 return $this->username() . ':' . $this->password();
1772 * Retrieve header string for proxy authentication.
1778 public function authentication_header() {
1779 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1783 * Whether URL should be sent through the proxy server.
1785 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1786 * some proxies can not handle this. We also have the constant available for defining other
1787 * hosts that won't be sent through the proxy.
1791 * @param string $uri URI to check.
1792 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1794 public function send_through_proxy( $uri ) {
1796 * parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1797 * This will be displayed on blogs, which is not reasonable.
1799 $check = @parse_url($uri);
1801 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1802 if ( $check === false )
1805 $home = parse_url( get_option('siteurl') );
1808 * Filter whether to preempt sending the request through the proxy server.
1810 * Returning false will bypass the proxy; returning true will send
1811 * the request through the proxy. Returning null bypasses the filter.
1815 * @param null $override Whether to override the request result. Default null.
1816 * @param string $uri URL to check.
1817 * @param array $check Associative array result of parsing the URI.
1818 * @param array $home Associative array result of parsing the site URL.
1820 $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
1821 if ( ! is_null( $result ) )
1824 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) )
1827 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1830 static $bypass_hosts;
1831 static $wildcard_regex = false;
1832 if ( null == $bypass_hosts ) {
1833 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1835 if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1836 $wildcard_regex = array();
1837 foreach ( $bypass_hosts as $host )
1838 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
1839 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1843 if ( !empty($wildcard_regex) )
1844 return !preg_match($wildcard_regex, $check['host']);
1846 return !in_array( $check['host'], $bypass_hosts );
1850 * Internal representation of a single cookie.
1852 * Returned cookies are represented using this class, and when cookies are set, if they are not
1853 * already a WP_Http_Cookie() object, then they are turned into one.
1855 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1856 * names. Need to switch to use underscores instead for the methods.
1858 * @package WordPress
1862 class WP_Http_Cookie {
1881 * When the cookie expires.
1905 * Sets up this cookie object.
1907 * The parameter $data should be either an associative array containing the indices names below
1908 * or a header string detailing it.
1913 * @param string|array $data {
1914 * Raw cookie data as header string or data array.
1916 * @type string $name Cookie name.
1917 * @type mixed $value Value. Should NOT already be urlencoded.
1918 * @type string|int $expires Optional. Unix timestamp or formatted date. Default null.
1919 * @type string $path Optional. Path. Default '/'.
1920 * @type string $domain Optional. Domain. Default host of parsed $requested_url.
1921 * @type int $port Optional. Port. Default null.
1923 * @param string $requested_url The URL which the cookie was set on, used for default $domain
1926 public function __construct( $data, $requested_url = '' ) {
1927 if ( $requested_url )
1928 $arrURL = @parse_url( $requested_url );
1929 if ( isset( $arrURL['host'] ) )
1930 $this->domain = $arrURL['host'];
1931 $this->path = isset( $arrURL['path'] ) ? $arrURL['path'] : '/';
1932 if ( '/' != substr( $this->path, -1 ) )
1933 $this->path = dirname( $this->path ) . '/';
1935 if ( is_string( $data ) ) {
1936 // Assume it's a header string direct from a previous request.
1937 $pairs = explode( ';', $data );
1939 // Special handling for first pair; name=value. Also be careful of "=" in value.
1940 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1941 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1942 $this->name = $name;
1943 $this->value = urldecode( $value );
1945 // Removes name=value from items.
1946 array_shift( $pairs );
1948 // Set everything else as a property.
1949 foreach ( $pairs as $pair ) {
1950 $pair = rtrim($pair);
1952 // Handle the cookie ending in ; which results in a empty final pair.
1956 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1957 $key = strtolower( trim( $key ) );
1958 if ( 'expires' == $key )
1959 $val = strtotime( $val );
1963 if ( !isset( $data['name'] ) )
1966 // Set properties based directly on parameters.
1967 foreach ( array( 'name', 'value', 'path', 'domain', 'port' ) as $field ) {
1968 if ( isset( $data[ $field ] ) )
1969 $this->$field = $data[ $field ];
1972 if ( isset( $data['expires'] ) )
1973 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1975 $this->expires = null;
1980 * Confirms that it's OK to send this cookie to the URL checked against.
1982 * Decision is based on RFC 2109/2965, so look there for details on validity.
1987 * @param string $url URL you intend to send this cookie to
1988 * @return boolean true if allowed, false otherwise.
1990 public function test( $url ) {
1991 if ( is_null( $this->name ) )
1994 // Expires - if expired then nothing else matters.
1995 if ( isset( $this->expires ) && time() > $this->expires )
1998 // Get details on the URL we're thinking about sending to.
1999 $url = parse_url( $url );
2000 $url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' == $url['scheme'] ? 443 : 80 );
2001 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
2003 // Values to use for comparison against the URL.
2004 $path = isset( $this->path ) ? $this->path : '/';
2005 $port = isset( $this->port ) ? $this->port : null;
2006 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
2007 if ( false === stripos( $domain, '.' ) )
2008 $domain .= '.local';
2010 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
2011 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
2012 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
2015 // Port - supports "port-lists" in the format: "80,8000,8080".
2016 if ( !empty( $port ) && !in_array( $url['port'], explode( ',', $port) ) )
2019 // Path - request path must start with path restriction.
2020 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
2027 * Convert cookie name and value back to header string.
2032 * @return string Header encoded cookie name and value.
2034 public function getHeaderValue() {
2035 if ( ! isset( $this->name ) || ! isset( $this->value ) )
2039 * Filter the header-encoded cookie value.
2043 * @param string $value The cookie value.
2044 * @param string $name The cookie name.
2046 return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
2050 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
2057 public function getFullHeader() {
2058 return 'Cookie: ' . $this->getHeaderValue();
2063 * Implementation for deflate and gzip transfer encodings.
2065 * Includes RFC 1950, RFC 1951, and RFC 1952.
2068 * @package WordPress
2071 class WP_Http_Encoding {
2074 * Compress raw string using the deflate format.
2076 * Supports the RFC 1951 standard.
2080 * @param string $raw String to compress.
2081 * @param int $level Optional, default is 9. Compression level, 9 is highest.
2082 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
2083 * @return string|false False on failure.
2085 public static function compress( $raw, $level = 9, $supports = null ) {
2086 return gzdeflate( $raw, $level );
2090 * Decompression of deflated string.
2092 * Will attempt to decompress using the RFC 1950 standard, and if that fails
2093 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
2094 * 1952 standard gzip decode will be attempted. If all fail, then the
2095 * original compressed string will be returned.
2099 * @param string $compressed String to decompress.
2100 * @param int $length The optional length of the compressed data.
2101 * @return string|bool False on failure.
2103 public static function decompress( $compressed, $length = null ) {
2105 if ( empty($compressed) )
2108 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
2109 return $decompressed;
2111 if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
2112 return $decompressed;
2114 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
2115 return $decompressed;
2117 if ( function_exists('gzdecode') ) {
2118 $decompressed = @gzdecode( $compressed );
2120 if ( false !== $decompressed )
2121 return $decompressed;
2128 * Decompression of deflated string while staying compatible with the majority of servers.
2130 * Certain Servers will return deflated data with headers which PHP's gzinflate()
2131 * function cannot handle out of the box. The following function has been created from
2132 * various snippets on the gzinflate() PHP documentation.
2134 * Warning: Magic numbers within. Due to the potential different formats that the compressed
2135 * data may be returned in, some "magic offsets" are needed to ensure proper decompression
2136 * takes place. For a simple progmatic way to determine the magic offset in use, see:
2137 * https://core.trac.wordpress.org/ticket/18273
2140 * @link https://core.trac.wordpress.org/ticket/18273
2141 * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
2142 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
2144 * @param string $gzData String to decompress.
2145 * @return string|bool False on failure.
2147 public static function compatible_gzinflate($gzData) {
2149 // Compressed data might contain a full header, if so strip it for gzinflate().
2150 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
2152 $flg = ord( substr($gzData, 3, 1) );
2155 list($xlen) = unpack('v', substr($gzData, $i, 2) );
2156 $i = $i + 2 + $xlen;
2159 $i = strpos($gzData, "\0", $i) + 1;
2161 $i = strpos($gzData, "\0", $i) + 1;
2165 $decompressed = @gzinflate( substr($gzData, $i, -8) );
2166 if ( false !== $decompressed )
2167 return $decompressed;
2170 // Compressed data from java.util.zip.Deflater amongst others.
2171 $decompressed = @gzinflate( substr($gzData, 2) );
2172 if ( false !== $decompressed )
2173 return $decompressed;
2179 * What encoding types to accept and their priority values.
2183 * @param string $url
2184 * @param array $args
2185 * @return string Types of encoding to accept.
2187 public static function accept_encoding( $url, $args ) {
2189 $compression_enabled = WP_Http_Encoding::is_available();
2191 if ( ! $args['decompress'] ) // Decompression specifically disabled.
2192 $compression_enabled = false;
2193 elseif ( $args['stream'] ) // Disable when streaming to file.
2194 $compression_enabled = false;
2195 elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it.
2196 $compression_enabled = false;
2198 if ( $compression_enabled ) {
2199 if ( function_exists( 'gzinflate' ) )
2200 $type[] = 'deflate;q=1.0';
2202 if ( function_exists( 'gzuncompress' ) )
2203 $type[] = 'compress;q=0.5';
2205 if ( function_exists( 'gzdecode' ) )
2206 $type[] = 'gzip;q=0.5';
2210 * Filter the allowed encoding types.
2214 * @param array $type Encoding types allowed. Accepts 'gzinflate',
2215 * 'gzuncompress', 'gzdecode'.
2216 * @param string $url URL of the HTTP request.
2217 * @param array $args HTTP request arguments.
2219 $type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
2221 return implode(', ', $type);
2225 * What encoding the content used when it was compressed to send in the headers.
2229 * @return string Content-Encoding string to send in the header.
2231 public static function content_encoding() {
2236 * Whether the content be decoded based on the headers.
2240 * @param array|string $headers All of the available headers.
2243 public static function should_decode($headers) {
2244 if ( is_array( $headers ) ) {
2245 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
2247 } else if ( is_string( $headers ) ) {
2248 return ( stripos($headers, 'content-encoding:') !== false );
2255 * Whether decompression and compression are supported by the PHP version.
2257 * Each function is tested instead of checking for the zlib extension, to
2258 * ensure that the functions all exist in the PHP version and aren't
2265 public static function is_available() {
2266 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );