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 );
186 $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
190 $arrURL = @parse_url( $url );
192 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
193 return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
195 if ( $this->block_request( $url ) )
196 return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
199 * Determine if this is a https call and pass that on to the transport functions
200 * so that we can blacklist the transports that do not support ssl verification
202 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
204 // Determine if this request is to OUR install of WordPress.
205 $homeURL = parse_url( get_bloginfo( 'url' ) );
206 $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
210 * If we are streaming to a file but no filename was given drop it in the WP temp dir
211 * and pick its name using the basename of the $url.
213 if ( $r['stream'] && empty( $r['filename'] ) ) {
214 $r['filename'] = wp_unique_filename( get_temp_dir(), basename( $url ) );
218 * Force some settings if we are streaming to a file and check for existence and perms
219 * of destination directory.
221 if ( $r['stream'] ) {
222 $r['blocking'] = true;
223 if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
224 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
227 if ( is_null( $r['headers'] ) )
228 $r['headers'] = array();
230 if ( ! is_array( $r['headers'] ) ) {
231 $processedHeaders = self::processHeaders( $r['headers'], $url );
232 $r['headers'] = $processedHeaders['headers'];
235 if ( isset( $r['headers']['User-Agent'] ) ) {
236 $r['user-agent'] = $r['headers']['User-Agent'];
237 unset( $r['headers']['User-Agent'] );
240 if ( isset( $r['headers']['user-agent'] ) ) {
241 $r['user-agent'] = $r['headers']['user-agent'];
242 unset( $r['headers']['user-agent'] );
245 if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
246 $r['headers']['connection'] = 'close';
249 // Construct Cookie: header if any cookies are set.
250 self::buildCookieHeader( $r );
252 // Avoid issues where mbstring.func_overload is enabled.
253 mbstring_binary_safe_encoding();
255 if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
256 if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
257 $r['headers']['Accept-Encoding'] = $encoding;
260 if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
261 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
262 $r['body'] = http_build_query( $r['body'], null, '&' );
264 if ( ! isset( $r['headers']['Content-Type'] ) )
265 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
268 if ( '' === $r['body'] )
271 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
272 $r['headers']['Content-Length'] = strlen( $r['body'] );
275 $response = $this->_dispatch_request( $url, $r );
277 reset_mbstring_encoding();
279 if ( is_wp_error( $response ) )
282 // Append cookies that were used in this request to the response
283 if ( ! empty( $r['cookies'] ) ) {
284 $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
285 foreach ( $r['cookies'] as $cookie ) {
286 if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
287 $response['cookies'][] = $cookie;
296 * Tests which transports are capable of supporting the request.
301 * @param array $args Request arguments
302 * @param string $url URL to Request
304 * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
306 public function _get_first_available_transport( $args, $url = null ) {
308 * Filter which HTTP transports are available and in what order.
312 * @param array $value Array of HTTP transports to check. Default array contains
313 * 'curl', and 'streams', in that order.
314 * @param array $args HTTP request arguments.
315 * @param string $url The URL to request.
317 $request_order = apply_filters( 'http_api_transports', array( 'curl', 'streams' ), $args, $url );
319 // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
320 foreach ( $request_order as $transport ) {
321 $class = 'WP_HTTP_' . $transport;
323 // Check to see if this transport is a possibility, calls the transport statically.
324 if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
334 * Dispatches a HTTP request to a supporting transport.
336 * Tests each transport in order to find a transport which matches the request arguments.
337 * Also caches the transport instance to be used later.
339 * The order for requests is cURL, and then PHP Streams.
344 * @param string $url URL to Request
345 * @param array $args Request arguments
346 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
348 private function _dispatch_request( $url, $args ) {
349 static $transports = array();
351 $class = $this->_get_first_available_transport( $args, $url );
353 return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
355 // Transport claims to support request, instantiate it and give it a whirl.
356 if ( empty( $transports[$class] ) )
357 $transports[$class] = new $class;
359 $response = $transports[$class]->request( $url, $args );
362 * Fires after an HTTP API response is received and before the response is returned.
366 * @param array|WP_Error $response HTTP response or WP_Error object.
367 * @param string $context Context under which the hook is fired.
368 * @param string $class HTTP transport used.
369 * @param array $args HTTP request arguments.
370 * @param string $url The request URL.
372 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
374 if ( is_wp_error( $response ) )
378 * Filter the HTTP API response immediately before the response is returned.
382 * @param array $response HTTP response.
383 * @param array $args HTTP request arguments.
384 * @param string $url The request URL.
386 return apply_filters( 'http_response', $response, $args, $url );
390 * Uses the POST HTTP method.
392 * Used for sending data that is expected to be in the body.
397 * @param string $url The request URL.
398 * @param string|array $args Optional. Override the defaults.
399 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
401 public function post($url, $args = array()) {
402 $defaults = array('method' => 'POST');
403 $r = wp_parse_args( $args, $defaults );
404 return $this->request($url, $r);
408 * Uses the GET HTTP method.
410 * Used for sending data that is expected to be in the body.
415 * @param string $url The request URL.
416 * @param string|array $args Optional. Override the defaults.
417 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
419 public function get($url, $args = array()) {
420 $defaults = array('method' => 'GET');
421 $r = wp_parse_args( $args, $defaults );
422 return $this->request($url, $r);
426 * Uses the HEAD HTTP method.
428 * Used for sending data that is expected to be in the body.
433 * @param string $url The request URL.
434 * @param string|array $args Optional. Override the defaults.
435 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
437 public function head($url, $args = array()) {
438 $defaults = array('method' => 'HEAD');
439 $r = wp_parse_args( $args, $defaults );
440 return $this->request($url, $r);
444 * Parses the responses and splits the parts into headers and body.
450 * @param string $strResponse The full response string
451 * @return array Array with 'headers' and 'body' keys.
453 public static function processResponse($strResponse) {
454 $res = explode("\r\n\r\n", $strResponse, 2);
456 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
460 * Transform header string into an array.
462 * If an array is given then it is assumed to be raw header data with numeric keys with the
463 * headers as the values. No headers must be passed that were already processed.
469 * @param string|array $headers
470 * @param string $url The URL that was requested
471 * @return array Processed string headers. If duplicate headers are encountered,
472 * Then a numbered array is returned as the value of that header-key.
474 public static function processHeaders( $headers, $url = '' ) {
475 // Split headers, one per array element.
476 if ( is_string($headers) ) {
477 // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
478 $headers = str_replace("\r\n", "\n", $headers);
480 * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
481 * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
483 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
484 // Create the headers array.
485 $headers = explode("\n", $headers);
488 $response = array('code' => 0, 'message' => '');
491 * If a redirection has taken place, The headers for each page request may have been passed.
492 * In this case, determine the final HTTP header and parse from there.
494 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
495 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
496 $headers = array_splice($headers, $i);
502 $newheaders = array();
503 foreach ( (array) $headers as $tempheader ) {
504 if ( empty($tempheader) )
507 if ( false === strpos($tempheader, ':') ) {
508 $stack = explode(' ', $tempheader, 3);
510 list( , $response['code'], $response['message']) = $stack;
514 list($key, $value) = explode(':', $tempheader, 2);
516 $key = strtolower( $key );
517 $value = trim( $value );
519 if ( isset( $newheaders[ $key ] ) ) {
520 if ( ! is_array( $newheaders[ $key ] ) )
521 $newheaders[$key] = array( $newheaders[ $key ] );
522 $newheaders[ $key ][] = $value;
524 $newheaders[ $key ] = $value;
526 if ( 'set-cookie' == $key )
527 $cookies[] = new WP_Http_Cookie( $value, $url );
530 // Cast the Response Code to an int
531 $response['code'] = intval( $response['code'] );
533 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
537 * Takes the arguments for a ::request() and checks for the cookie array.
539 * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
540 * which are each parsed into strings and added to the Cookie: header (within the arguments array).
541 * Edits the array by reference.
547 * @param array $r Full array of args passed into ::request()
549 public static function buildCookieHeader( &$r ) {
550 if ( ! empty($r['cookies']) ) {
551 // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
552 foreach ( $r['cookies'] as $name => $value ) {
553 if ( ! is_object( $value ) )
554 $r['cookies'][ $name ] = new WP_HTTP_Cookie( array( 'name' => $name, 'value' => $value ) );
557 $cookies_header = '';
558 foreach ( (array) $r['cookies'] as $cookie ) {
559 $cookies_header .= $cookie->getHeaderValue() . '; ';
562 $cookies_header = substr( $cookies_header, 0, -2 );
563 $r['headers']['cookie'] = $cookies_header;
568 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
570 * Based off the HTTP http_encoding_dechunk function.
572 * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
578 * @param string $body Body content
579 * @return string Chunked decoded body on success or raw body on failure.
581 public static function chunkTransferDecode( $body ) {
582 // The body is not chunked encoded or is malformed.
583 if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
588 // We'll be altering $body, so need a backup in case of error.
589 $body_original = $body;
592 $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
593 if ( ! $has_chunk || empty( $match[1] ) )
594 return $body_original;
596 $length = hexdec( $match[1] );
597 $chunk_length = strlen( $match[0] );
599 // Parse out the chunk of data.
600 $parsed_body .= substr( $body, $chunk_length, $length );
602 // Remove the chunk from the raw data.
603 $body = substr( $body, $length + $chunk_length );
605 // End of the document.
606 if ( '0' === trim( $body ) )
612 * Block requests through the proxy.
614 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
615 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
617 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
618 * file and this will only allow localhost and your blog to make requests. The constant
619 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
620 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
621 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
624 * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
625 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
627 * @param string $uri URI of url.
628 * @return bool True to block, false to allow.
630 public function block_request($uri) {
631 // We don't need to block requests, because nothing is blocked.
632 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
635 $check = parse_url($uri);
639 $home = parse_url( get_option('siteurl') );
641 // Don't block requests back to ourselves by default.
642 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
644 * Filter whether to block local requests through the proxy.
648 * @param bool $block Whether to block local requests through proxy.
651 return apply_filters( 'block_local_requests', false );
654 if ( !defined('WP_ACCESSIBLE_HOSTS') )
657 static $accessible_hosts;
658 static $wildcard_regex = false;
659 if ( null == $accessible_hosts ) {
660 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
662 if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
663 $wildcard_regex = array();
664 foreach ( $accessible_hosts as $host )
665 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
666 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
670 if ( !empty($wildcard_regex) )
671 return !preg_match($wildcard_regex, $check['host']);
673 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
678 * A wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7
680 * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including
681 * schemeless and relative url's with :// in the path, this works around those
682 * limitations providing a standard output on PHP 5.2~5.4+.
684 * Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated
685 * when URL parsing failed.
690 * @param string $url The URL to parse.
691 * @return bool|array False on failure; Array of URL components on success;
692 * See parse_url()'s return values.
694 protected static function parse_url( $url ) {
695 $parts = @parse_url( $url );
697 // < PHP 5.4.7 compat, trouble with relative paths including a scheme break in the path
698 if ( '/' == $url[0] && false !== strpos( $url, '://' ) ) {
699 // Since we know it's a relative path, prefix with a scheme/host placeholder and try again
700 if ( ! $parts = @parse_url( 'placeholder://placeholder' . $url ) ) {
703 // Remove the placeholder values
704 unset( $parts['scheme'], $parts['host'] );
710 // < PHP 5.4.7 compat, doesn't detect schemeless URL's host field
711 if ( '//' == substr( $url, 0, 2 ) && ! isset( $parts['host'] ) ) {
712 list( $parts['host'], $slashless_path ) = explode( '/', substr( $parts['path'], 2 ), 2 );
713 $parts['path'] = "/{$slashless_path}";
720 * Converts a relative URL to an absolute URL relative to a given URL.
722 * If an Absolute URL is provided, no processing of that URL is done.
727 * @param string $maybe_relative_path The URL which might be relative
728 * @param string $url The URL which $maybe_relative_path is relative to
729 * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
731 public static function make_absolute_url( $maybe_relative_path, $url ) {
733 return $maybe_relative_path;
735 if ( ! $url_parts = WP_HTTP::parse_url( $url ) ) {
736 return $maybe_relative_path;
739 if ( ! $relative_url_parts = WP_HTTP::parse_url( $maybe_relative_path ) ) {
740 return $maybe_relative_path;
743 // Check for a scheme on the 'relative' url
744 if ( ! empty( $relative_url_parts['scheme'] ) ) {
745 return $maybe_relative_path;
748 $absolute_path = $url_parts['scheme'] . '://';
750 // 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
751 if ( isset( $relative_url_parts['host'] ) ) {
752 $absolute_path .= $relative_url_parts['host'];
753 if ( isset( $relative_url_parts['port'] ) )
754 $absolute_path .= ':' . $relative_url_parts['port'];
756 $absolute_path .= $url_parts['host'];
757 if ( isset( $url_parts['port'] ) )
758 $absolute_path .= ':' . $url_parts['port'];
761 // Start off with the Absolute URL path.
762 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
764 // If it's a root-relative path, then great.
765 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
766 $path = $relative_url_parts['path'];
768 // Else it's a relative path.
769 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
770 // Strip off any file components from the absolute path.
771 $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
773 // Build the new path.
774 $path .= $relative_url_parts['path'];
776 // Strip all /path/../ out of the path.
777 while ( strpos( $path, '../' ) > 1 ) {
778 $path = preg_replace( '![^/]+/\.\./!', '', $path );
781 // Strip any final leading ../ from the path.
782 $path = preg_replace( '!^/(\.\./)+!', '', $path );
785 // Add the Query string.
786 if ( ! empty( $relative_url_parts['query'] ) )
787 $path .= '?' . $relative_url_parts['query'];
789 return $absolute_path . '/' . ltrim( $path, '/' );
793 * Handles HTTP Redirects and follows them if appropriate.
797 * @param string $url The URL which was requested.
798 * @param array $args The Arguments which were used to make the request.
799 * @param array $response The Response of the HTTP request.
800 * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
802 public static function handle_redirects( $url, $args, $response ) {
803 // If no redirects are present, or, redirects were not requested, perform no action.
804 if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
807 // Only perform redirections on redirection http codes.
808 if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
811 // Don't redirect if we've run out of redirects.
812 if ( $args['redirection']-- <= 0 )
813 return new WP_Error( 'http_request_failed', __('Too many redirects.') );
815 $redirect_location = $response['headers']['location'];
817 // If there were multiple Location headers, use the last header specified.
818 if ( is_array( $redirect_location ) )
819 $redirect_location = array_pop( $redirect_location );
821 $redirect_location = WP_HTTP::make_absolute_url( $redirect_location, $url );
823 // POST requests should not POST to a redirected location.
824 if ( 'POST' == $args['method'] ) {
825 if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
826 $args['method'] = 'GET';
829 // Include valid cookies in the redirect process.
830 if ( ! empty( $response['cookies'] ) ) {
831 foreach ( $response['cookies'] as $cookie ) {
832 if ( $cookie->test( $redirect_location ) )
833 $args['cookies'][] = $cookie;
837 return wp_remote_request( $redirect_location, $args );
841 * Determines if a specified string represents an IP address or not.
843 * This function also detects the type of the IP address, returning either
844 * '4' or '6' to represent a IPv4 and IPv6 address respectively.
845 * This does not verify if the IP is a valid IP, only that it appears to be
848 * @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
853 * @param string $maybe_ip A suspected IP address
854 * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
856 public static function is_ip_address( $maybe_ip ) {
857 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
860 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, ' []' ) ) )
869 * HTTP request method uses PHP Streams to retrieve the url.
872 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
874 class WP_Http_Streams {
876 * Send a HTTP request to a URI using PHP Streams.
878 * @see WP_Http::request For default options descriptions.
881 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
884 * @param string $url The request URL.
885 * @param string|array $args Optional. Override the defaults.
886 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
888 public function request($url, $args = array()) {
890 'method' => 'GET', 'timeout' => 5,
891 'redirection' => 5, 'httpversion' => '1.0',
893 'headers' => array(), 'body' => null, 'cookies' => array()
896 $r = wp_parse_args( $args, $defaults );
898 if ( isset( $r['headers']['User-Agent'] ) ) {
899 $r['user-agent'] = $r['headers']['User-Agent'];
900 unset( $r['headers']['User-Agent'] );
901 } elseif ( isset( $r['headers']['user-agent'] ) ) {
902 $r['user-agent'] = $r['headers']['user-agent'];
903 unset( $r['headers']['user-agent'] );
906 // Construct Cookie: header if any cookies are set.
907 WP_Http::buildCookieHeader( $r );
909 $arrURL = parse_url($url);
911 $connect_host = $arrURL['host'];
913 $secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
914 if ( ! isset( $arrURL['port'] ) ) {
915 if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
916 $arrURL['port'] = 443;
917 $secure_transport = true;
919 $arrURL['port'] = 80;
923 // Always pass a Path, defaulting to the root in cases such as http://example.com
924 if ( ! isset( $arrURL['path'] ) ) {
925 $arrURL['path'] = '/';
928 if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
929 if ( isset( $r['headers']['Host'] ) )
930 $arrURL['host'] = $r['headers']['Host'];
932 $arrURL['host'] = $r['headers']['host'];
933 unset( $r['headers']['Host'], $r['headers']['host'] );
937 * Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
938 * to ::1, which fails when the server is not set up for it. For compatibility, always
939 * connect to the IPv4 address.
941 if ( 'localhost' == strtolower( $connect_host ) )
942 $connect_host = '127.0.0.1';
944 $connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
946 $is_local = isset( $r['local'] ) && $r['local'];
947 $ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
950 * Filter whether SSL should be verified for local requests.
954 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
956 $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
957 } elseif ( ! $is_local ) {
959 * Filter whether SSL should be verified for non-local requests.
963 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
965 $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
968 $proxy = new WP_HTTP_Proxy();
970 $context = stream_context_create( array(
972 'verify_peer' => $ssl_verify,
973 //'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
974 'capture_peer_cert' => $ssl_verify,
975 'SNI_enabled' => true,
976 'cafile' => $r['sslcertificates'],
977 'allow_self_signed' => ! $ssl_verify,
981 $timeout = (int) floor( $r['timeout'] );
982 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
983 $connect_timeout = max( $timeout, 1 );
985 // Store error number.
986 $connection_error = null;
988 // Store error string.
989 $connection_error_str = null;
992 // In the event that the SSL connection fails, silence the many PHP Warnings.
993 if ( $secure_transport )
994 $error_reporting = error_reporting(0);
996 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
997 $handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
999 $handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1001 if ( $secure_transport )
1002 error_reporting( $error_reporting );
1005 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
1006 $handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1008 $handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1011 if ( false === $handle ) {
1012 // SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
1013 if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
1014 return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1016 return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
1019 // Verify that the SSL certificate is valid for this request.
1020 if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
1021 if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
1022 return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1025 stream_set_timeout( $handle, $timeout, $utimeout );
1027 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
1028 $requestPath = $url;
1030 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
1032 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
1034 $include_port_in_host_header = (
1035 ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) ||
1036 ( 'http' == $arrURL['scheme'] && 80 != $arrURL['port'] ) ||
1037 ( 'https' == $arrURL['scheme'] && 443 != $arrURL['port'] )
1040 if ( $include_port_in_host_header ) {
1041 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
1043 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
1046 if ( isset($r['user-agent']) )
1047 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
1049 if ( is_array($r['headers']) ) {
1050 foreach ( (array) $r['headers'] as $header => $headerValue )
1051 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
1053 $strHeaders .= $r['headers'];
1056 if ( $proxy->use_authentication() )
1057 $strHeaders .= $proxy->authentication_header() . "\r\n";
1059 $strHeaders .= "\r\n";
1061 if ( ! is_null($r['body']) )
1062 $strHeaders .= $r['body'];
1064 fwrite($handle, $strHeaders);
1066 if ( ! $r['blocking'] ) {
1067 stream_set_blocking( $handle, 0 );
1069 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1073 $bodyStarted = false;
1074 $keep_reading = true;
1076 if ( isset( $r['limit_response_size'] ) )
1077 $block_size = min( $block_size, $r['limit_response_size'] );
1079 // If streaming to a file setup the file handle.
1080 if ( $r['stream'] ) {
1082 $stream_handle = @fopen( $r['filename'], 'w+' );
1084 $stream_handle = fopen( $r['filename'], 'w+' );
1085 if ( ! $stream_handle )
1086 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1089 while ( ! feof($handle) && $keep_reading ) {
1090 $block = fread( $handle, $block_size );
1091 if ( ! $bodyStarted ) {
1092 $strResponse .= $block;
1093 if ( strpos( $strResponse, "\r\n\r\n" ) ) {
1094 $process = WP_Http::processResponse( $strResponse );
1095 $bodyStarted = true;
1096 $block = $process['body'];
1097 unset( $strResponse );
1098 $process['body'] = '';
1102 $this_block_size = strlen( $block );
1104 if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] ) {
1105 $this_block_size = ( $r['limit_response_size'] - $bytes_written );
1106 $block = substr( $block, 0, $this_block_size );
1109 $bytes_written_to_file = fwrite( $stream_handle, $block );
1111 if ( $bytes_written_to_file != $this_block_size ) {
1113 fclose( $stream_handle );
1114 return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1117 $bytes_written += $bytes_written_to_file;
1119 $keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
1122 fclose( $stream_handle );
1126 while ( ! feof( $handle ) && $keep_reading ) {
1127 $block = fread( $handle, $block_size );
1128 $strResponse .= $block;
1129 if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
1130 $header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
1131 $bodyStarted = true;
1133 $keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
1136 $process = WP_Http::processResponse( $strResponse );
1137 unset( $strResponse );
1143 $arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
1146 'headers' => $arrHeaders['headers'],
1147 // Not yet processed.
1149 'response' => $arrHeaders['response'],
1150 'cookies' => $arrHeaders['cookies'],
1151 'filename' => $r['filename']
1154 // Handle redirects.
1155 if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1156 return $redirect_response;
1158 // If the body was chunk encoded, then decode it.
1159 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
1160 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
1162 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
1163 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
1165 if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
1166 $process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
1168 $response['body'] = $process['body'];
1174 * Verifies the received SSL certificate against it's Common Names and subjectAltName fields
1176 * PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
1177 * the certificate is valid for the hostname which was requested.
1178 * This function verifies the requested hostname against certificate's subjectAltName field,
1179 * if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
1181 * IP Address support is included if the request is being made to an IP address.
1186 * @param stream $stream The PHP Stream which the SSL request is being made over
1187 * @param string $host The hostname being requested
1188 * @return bool If the cerficiate presented in $stream is valid for $host
1190 public static function verify_ssl_certificate( $stream, $host ) {
1191 $context_options = stream_context_get_options( $stream );
1193 if ( empty( $context_options['ssl']['peer_certificate'] ) )
1196 $cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
1201 * If the request is being made to an IP address, we'll validate against IP fields
1202 * in the cert (if they exist)
1204 $host_type = ( WP_HTTP::is_ip_address( $host ) ? 'ip' : 'dns' );
1206 $certificate_hostnames = array();
1207 if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
1208 $match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
1209 foreach ( $match_against as $match ) {
1210 list( $match_type, $match_host ) = explode( ':', $match );
1211 if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
1212 $certificate_hostnames[] = strtolower( trim( $match_host ) );
1214 } elseif ( !empty( $cert['subject']['CN'] ) ) {
1215 // Only use the CN when the certificate includes no subjectAltName extension.
1216 $certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
1219 // Exact hostname/IP matches.
1220 if ( in_array( strtolower( $host ), $certificate_hostnames ) )
1223 // IP's can't be wildcards, Stop processing.
1224 if ( 'ip' == $host_type )
1227 // Test to see if the domain is at least 2 deep for wildcard support.
1228 if ( substr_count( $host, '.' ) < 2 )
1231 // Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
1232 $wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
1234 return in_array( strtolower( $wildcard_host ), $certificate_hostnames );
1238 * Whether this class can be used for retrieving a URL.
1243 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
1245 * @return boolean False means this class can not be used, true means it can.
1247 public static function test( $args = array() ) {
1248 if ( ! function_exists( 'stream_socket_client' ) )
1251 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1254 if ( ! extension_loaded( 'openssl' ) )
1256 if ( ! function_exists( 'openssl_x509_parse' ) )
1261 * Filter whether streams can be used as a transport for retrieving a URL.
1265 * @param bool $use_class Whether the class can be used. Default true.
1266 * @param array $args Request arguments.
1268 return apply_filters( 'use_streams_transport', true, $args );
1273 * Deprecated HTTP Transport method which used fsockopen.
1275 * This class is not used, and is included for backwards compatibility only.
1276 * All code should make use of WP_HTTP directly through it's API.
1278 * @see WP_HTTP::request
1281 * @deprecated 3.7.0 Please use WP_HTTP::request() directly
1283 class WP_HTTP_Fsockopen extends WP_HTTP_Streams {
1284 // For backwards compatibility for users who are using the class directly.
1288 * HTTP request method uses Curl extension to retrieve the url.
1290 * Requires the Curl extension to be installed.
1292 * @package WordPress
1296 class WP_Http_Curl {
1299 * Temporary header storage for during requests.
1305 private $headers = '';
1308 * Temporary body storage for during requests.
1317 * The maximum amount of data to receive from the remote server.
1323 private $max_body_length = false;
1326 * The file resource used for streaming to file.
1332 private $stream_handle = false;
1335 * The total bytes written in the current request.
1341 private $bytes_written_total = 0;
1344 * Send a HTTP request to a URI using cURL extension.
1349 * @param string $url The request URL.
1350 * @param string|array $args Optional. Override the defaults.
1351 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
1353 public function request($url, $args = array()) {
1355 'method' => 'GET', 'timeout' => 5,
1356 'redirection' => 5, 'httpversion' => '1.0',
1358 'headers' => array(), 'body' => null, 'cookies' => array()
1361 $r = wp_parse_args( $args, $defaults );
1363 if ( isset( $r['headers']['User-Agent'] ) ) {
1364 $r['user-agent'] = $r['headers']['User-Agent'];
1365 unset( $r['headers']['User-Agent'] );
1366 } elseif ( isset( $r['headers']['user-agent'] ) ) {
1367 $r['user-agent'] = $r['headers']['user-agent'];
1368 unset( $r['headers']['user-agent'] );
1371 // Construct Cookie: header if any cookies are set.
1372 WP_Http::buildCookieHeader( $r );
1374 $handle = curl_init();
1376 // cURL offers really easy proxy support.
1377 $proxy = new WP_HTTP_Proxy();
1379 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1381 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1382 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1383 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1385 if ( $proxy->use_authentication() ) {
1386 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1387 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1391 $is_local = isset($r['local']) && $r['local'];
1392 $ssl_verify = isset($r['sslverify']) && $r['sslverify'];
1394 /** This filter is documented in wp-includes/class-http.php */
1395 $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
1396 } elseif ( ! $is_local ) {
1397 /** This filter is documented in wp-includes/class-http.php */
1398 $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
1402 * CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
1403 * a value of 0 will allow an unlimited timeout.
1405 $timeout = (int) ceil( $r['timeout'] );
1406 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1407 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1409 curl_setopt( $handle, CURLOPT_URL, $url);
1410 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1411 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
1412 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1413 curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
1414 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1417 * The option doesn't work with safe mode or when open_basedir is set, and there's
1418 * a bug #17490 with redirected POST requests, so handle redirections outside Curl.
1420 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
1421 if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
1422 curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
1424 switch ( $r['method'] ) {
1426 curl_setopt( $handle, CURLOPT_NOBODY, true );
1429 curl_setopt( $handle, CURLOPT_POST, true );
1430 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1433 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1434 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1437 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
1438 if ( ! is_null( $r['body'] ) )
1439 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1443 if ( true === $r['blocking'] ) {
1444 curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
1445 curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
1448 curl_setopt( $handle, CURLOPT_HEADER, false );
1450 if ( isset( $r['limit_response_size'] ) )
1451 $this->max_body_length = intval( $r['limit_response_size'] );
1453 $this->max_body_length = false;
1455 // If streaming to a file open a file handle, and setup our curl streaming handler.
1456 if ( $r['stream'] ) {
1458 $this->stream_handle = @fopen( $r['filename'], 'w+' );
1460 $this->stream_handle = fopen( $r['filename'], 'w+' );
1461 if ( ! $this->stream_handle )
1462 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1464 $this->stream_handle = false;
1467 if ( !empty( $r['headers'] ) ) {
1468 // cURL expects full header strings in each element.
1470 foreach ( $r['headers'] as $name => $value ) {
1471 $headers[] = "{$name}: $value";
1473 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1476 if ( $r['httpversion'] == '1.0' )
1477 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1479 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1482 * Fires before the cURL request is executed.
1484 * Cookies are not currently handled by the HTTP API. This action allows
1485 * plugins to handle cookies themselves.
1489 * @param resource &$handle The cURL handle returned by curl_init().
1490 * @param array $r The HTTP request arguments.
1491 * @param string $url The request URL.
1493 do_action_ref_array( 'http_api_curl', array( &$handle, $r, $url ) );
1495 // We don't need to return the body, so don't. Just execute request and return.
1496 if ( ! $r['blocking'] ) {
1497 curl_exec( $handle );
1499 if ( $curl_error = curl_error( $handle ) ) {
1500 curl_close( $handle );
1501 return new WP_Error( 'http_request_failed', $curl_error );
1503 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1504 curl_close( $handle );
1505 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1508 curl_close( $handle );
1509 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1512 curl_exec( $handle );
1513 $theHeaders = WP_Http::processHeaders( $this->headers, $url );
1514 $theBody = $this->body;
1515 $bytes_written_total = $this->bytes_written_total;
1517 $this->headers = '';
1519 $this->bytes_written_total = 0;
1521 $curl_error = curl_errno( $handle );
1523 // If an error occurred, or, no response.
1524 if ( $curl_error || ( 0 == strlen( $theBody ) && empty( $theHeaders['headers'] ) ) ) {
1525 if ( CURLE_WRITE_ERROR /* 23 */ == $curl_error ) {
1526 if ( ! $this->max_body_length || $this->max_body_length != $bytes_written_total ) {
1527 if ( $r['stream'] ) {
1528 curl_close( $handle );
1529 fclose( $this->stream_handle );
1530 return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1532 curl_close( $handle );
1533 return new WP_Error( 'http_request_failed', curl_error( $handle ) );
1537 if ( $curl_error = curl_error( $handle ) ) {
1538 curl_close( $handle );
1539 return new WP_Error( 'http_request_failed', $curl_error );
1542 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1543 curl_close( $handle );
1544 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1548 curl_close( $handle );
1551 fclose( $this->stream_handle );
1554 'headers' => $theHeaders['headers'],
1556 'response' => $theHeaders['response'],
1557 'cookies' => $theHeaders['cookies'],
1558 'filename' => $r['filename']
1561 // Handle redirects.
1562 if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1563 return $redirect_response;
1565 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1566 $theBody = WP_Http_Encoding::decompress( $theBody );
1568 $response['body'] = $theBody;
1574 * Grab the headers of the cURL request
1576 * Each header is sent individually to this callback, so we append to the $header property for temporary storage
1582 private function stream_headers( $handle, $headers ) {
1583 $this->headers .= $headers;
1584 return strlen( $headers );
1588 * Grab the body of the cURL request
1590 * The contents of the document are passed in chunks, so we append to the $body property for temporary storage.
1591 * Returning a length shorter than the length of $data passed in will cause cURL to abort the request with CURLE_WRITE_ERROR
1597 private function stream_body( $handle, $data ) {
1598 $data_length = strlen( $data );
1600 if ( $this->max_body_length && ( $this->bytes_written_total + $data_length ) > $this->max_body_length ) {
1601 $data_length = ( $this->max_body_length - $this->bytes_written_total );
1602 $data = substr( $data, 0, $data_length );
1605 if ( $this->stream_handle ) {
1606 $bytes_written = fwrite( $this->stream_handle, $data );
1608 $this->body .= $data;
1609 $bytes_written = $data_length;
1612 $this->bytes_written_total += $bytes_written;
1614 // Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR.
1615 return $bytes_written;
1619 * Whether this class can be used for retrieving an URL.
1624 * @return boolean False means this class can not be used, true means it can.
1626 public static function test( $args = array() ) {
1627 if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
1630 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1633 $curl_version = curl_version();
1634 // Check whether this cURL version support SSL requests.
1635 if ( ! (CURL_VERSION_SSL & $curl_version['features']) )
1640 * Filter whether cURL can be used as a transport for retrieving a URL.
1644 * @param bool $use_class Whether the class can be used. Default true.
1645 * @param array $args An array of request arguments.
1647 return apply_filters( 'use_curl_transport', true, $args );
1652 * Adds Proxy support to the WordPress HTTP API.
1654 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1655 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1658 * Please note that only BASIC authentication is supported by most transports.
1659 * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
1661 * The constants are as follows:
1663 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1664 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1665 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1666 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1667 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1668 * You do not need to have localhost and the blog host in this list, because they will not be passed
1669 * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1672 * An example can be as seen below.
1674 * define('WP_PROXY_HOST', '192.168.84.101');
1675 * define('WP_PROXY_PORT', '8080');
1676 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1678 * @link https://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1679 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1682 class WP_HTTP_Proxy {
1685 * Whether proxy connection should be used.
1689 * @use WP_PROXY_HOST
1690 * @use WP_PROXY_PORT
1694 public function is_enabled() {
1695 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1699 * Whether authentication should be used.
1703 * @use WP_PROXY_USERNAME
1704 * @use WP_PROXY_PASSWORD
1708 public function use_authentication() {
1709 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1713 * Retrieve the host for the proxy server.
1719 public function host() {
1720 if ( defined('WP_PROXY_HOST') )
1721 return WP_PROXY_HOST;
1727 * Retrieve the port for the proxy server.
1733 public function port() {
1734 if ( defined('WP_PROXY_PORT') )
1735 return WP_PROXY_PORT;
1741 * Retrieve the username for proxy authentication.
1747 public function username() {
1748 if ( defined('WP_PROXY_USERNAME') )
1749 return WP_PROXY_USERNAME;
1755 * Retrieve the password for proxy authentication.
1761 public function password() {
1762 if ( defined('WP_PROXY_PASSWORD') )
1763 return WP_PROXY_PASSWORD;
1769 * Retrieve authentication string for proxy authentication.
1775 public function authentication() {
1776 return $this->username() . ':' . $this->password();
1780 * Retrieve header string for proxy authentication.
1786 public function authentication_header() {
1787 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1791 * Whether URL should be sent through the proxy server.
1793 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1794 * some proxies can not handle this. We also have the constant available for defining other
1795 * hosts that won't be sent through the proxy.
1799 * @param string $uri URI to check.
1800 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1802 public function send_through_proxy( $uri ) {
1804 * parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1805 * This will be displayed on blogs, which is not reasonable.
1807 $check = @parse_url($uri);
1809 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1810 if ( $check === false )
1813 $home = parse_url( get_option('siteurl') );
1816 * Filter whether to preempt sending the request through the proxy server.
1818 * Returning false will bypass the proxy; returning true will send
1819 * the request through the proxy. Returning null bypasses the filter.
1823 * @param null $override Whether to override the request result. Default null.
1824 * @param string $uri URL to check.
1825 * @param array $check Associative array result of parsing the URI.
1826 * @param array $home Associative array result of parsing the site URL.
1828 $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
1829 if ( ! is_null( $result ) )
1832 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) )
1835 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1838 static $bypass_hosts;
1839 static $wildcard_regex = false;
1840 if ( null == $bypass_hosts ) {
1841 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1843 if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1844 $wildcard_regex = array();
1845 foreach ( $bypass_hosts as $host )
1846 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
1847 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1851 if ( !empty($wildcard_regex) )
1852 return !preg_match($wildcard_regex, $check['host']);
1854 return !in_array( $check['host'], $bypass_hosts );
1858 * Internal representation of a single cookie.
1860 * Returned cookies are represented using this class, and when cookies are set, if they are not
1861 * already a WP_Http_Cookie() object, then they are turned into one.
1863 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1864 * names. Need to switch to use underscores instead for the methods.
1866 * @package WordPress
1870 class WP_Http_Cookie {
1889 * When the cookie expires.
1913 * Sets up this cookie object.
1915 * The parameter $data should be either an associative array containing the indices names below
1916 * or a header string detailing it.
1921 * @param string|array $data {
1922 * Raw cookie data as header string or data array.
1924 * @type string $name Cookie name.
1925 * @type mixed $value Value. Should NOT already be urlencoded.
1926 * @type string|int $expires Optional. Unix timestamp or formatted date. Default null.
1927 * @type string $path Optional. Path. Default '/'.
1928 * @type string $domain Optional. Domain. Default host of parsed $requested_url.
1929 * @type int $port Optional. Port. Default null.
1931 * @param string $requested_url The URL which the cookie was set on, used for default $domain
1934 public function __construct( $data, $requested_url = '' ) {
1935 if ( $requested_url )
1936 $arrURL = @parse_url( $requested_url );
1937 if ( isset( $arrURL['host'] ) )
1938 $this->domain = $arrURL['host'];
1939 $this->path = isset( $arrURL['path'] ) ? $arrURL['path'] : '/';
1940 if ( '/' != substr( $this->path, -1 ) )
1941 $this->path = dirname( $this->path ) . '/';
1943 if ( is_string( $data ) ) {
1944 // Assume it's a header string direct from a previous request.
1945 $pairs = explode( ';', $data );
1947 // Special handling for first pair; name=value. Also be careful of "=" in value.
1948 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1949 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1950 $this->name = $name;
1951 $this->value = urldecode( $value );
1953 // Removes name=value from items.
1954 array_shift( $pairs );
1956 // Set everything else as a property.
1957 foreach ( $pairs as $pair ) {
1958 $pair = rtrim($pair);
1960 // Handle the cookie ending in ; which results in a empty final pair.
1964 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1965 $key = strtolower( trim( $key ) );
1966 if ( 'expires' == $key )
1967 $val = strtotime( $val );
1971 if ( !isset( $data['name'] ) )
1974 // Set properties based directly on parameters.
1975 foreach ( array( 'name', 'value', 'path', 'domain', 'port' ) as $field ) {
1976 if ( isset( $data[ $field ] ) )
1977 $this->$field = $data[ $field ];
1980 if ( isset( $data['expires'] ) )
1981 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1983 $this->expires = null;
1988 * Confirms that it's OK to send this cookie to the URL checked against.
1990 * Decision is based on RFC 2109/2965, so look there for details on validity.
1995 * @param string $url URL you intend to send this cookie to
1996 * @return boolean true if allowed, false otherwise.
1998 public function test( $url ) {
1999 if ( is_null( $this->name ) )
2002 // Expires - if expired then nothing else matters.
2003 if ( isset( $this->expires ) && time() > $this->expires )
2006 // Get details on the URL we're thinking about sending to.
2007 $url = parse_url( $url );
2008 $url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' == $url['scheme'] ? 443 : 80 );
2009 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
2011 // Values to use for comparison against the URL.
2012 $path = isset( $this->path ) ? $this->path : '/';
2013 $port = isset( $this->port ) ? $this->port : null;
2014 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
2015 if ( false === stripos( $domain, '.' ) )
2016 $domain .= '.local';
2018 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
2019 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
2020 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
2023 // Port - supports "port-lists" in the format: "80,8000,8080".
2024 if ( !empty( $port ) && !in_array( $url['port'], explode( ',', $port) ) )
2027 // Path - request path must start with path restriction.
2028 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
2035 * Convert cookie name and value back to header string.
2040 * @return string Header encoded cookie name and value.
2042 public function getHeaderValue() {
2043 if ( ! isset( $this->name ) || ! isset( $this->value ) )
2047 * Filter the header-encoded cookie value.
2051 * @param string $value The cookie value.
2052 * @param string $name The cookie name.
2054 return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
2058 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
2065 public function getFullHeader() {
2066 return 'Cookie: ' . $this->getHeaderValue();
2071 * Implementation for deflate and gzip transfer encodings.
2073 * Includes RFC 1950, RFC 1951, and RFC 1952.
2076 * @package WordPress
2079 class WP_Http_Encoding {
2082 * Compress raw string using the deflate format.
2084 * Supports the RFC 1951 standard.
2088 * @param string $raw String to compress.
2089 * @param int $level Optional, default is 9. Compression level, 9 is highest.
2090 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
2091 * @return string|false False on failure.
2093 public static function compress( $raw, $level = 9, $supports = null ) {
2094 return gzdeflate( $raw, $level );
2098 * Decompression of deflated string.
2100 * Will attempt to decompress using the RFC 1950 standard, and if that fails
2101 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
2102 * 1952 standard gzip decode will be attempted. If all fail, then the
2103 * original compressed string will be returned.
2107 * @param string $compressed String to decompress.
2108 * @param int $length The optional length of the compressed data.
2109 * @return string|bool False on failure.
2111 public static function decompress( $compressed, $length = null ) {
2113 if ( empty($compressed) )
2116 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
2117 return $decompressed;
2119 if ( false !== ( $decompressed = self::compatible_gzinflate( $compressed ) ) )
2120 return $decompressed;
2122 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
2123 return $decompressed;
2125 if ( function_exists('gzdecode') ) {
2126 $decompressed = @gzdecode( $compressed );
2128 if ( false !== $decompressed )
2129 return $decompressed;
2136 * Decompression of deflated string while staying compatible with the majority of servers.
2138 * Certain Servers will return deflated data with headers which PHP's gzinflate()
2139 * function cannot handle out of the box. The following function has been created from
2140 * various snippets on the gzinflate() PHP documentation.
2142 * Warning: Magic numbers within. Due to the potential different formats that the compressed
2143 * data may be returned in, some "magic offsets" are needed to ensure proper decompression
2144 * takes place. For a simple progmatic way to determine the magic offset in use, see:
2145 * https://core.trac.wordpress.org/ticket/18273
2148 * @link https://core.trac.wordpress.org/ticket/18273
2149 * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
2150 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
2152 * @param string $gzData String to decompress.
2153 * @return string|bool False on failure.
2155 public static function compatible_gzinflate($gzData) {
2157 // Compressed data might contain a full header, if so strip it for gzinflate().
2158 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
2160 $flg = ord( substr($gzData, 3, 1) );
2163 list($xlen) = unpack('v', substr($gzData, $i, 2) );
2164 $i = $i + 2 + $xlen;
2167 $i = strpos($gzData, "\0", $i) + 1;
2169 $i = strpos($gzData, "\0", $i) + 1;
2173 $decompressed = @gzinflate( substr($gzData, $i, -8) );
2174 if ( false !== $decompressed )
2175 return $decompressed;
2178 // Compressed data from java.util.zip.Deflater amongst others.
2179 $decompressed = @gzinflate( substr($gzData, 2) );
2180 if ( false !== $decompressed )
2181 return $decompressed;
2187 * What encoding types to accept and their priority values.
2191 * @param string $url
2192 * @param array $args
2193 * @return string Types of encoding to accept.
2195 public static function accept_encoding( $url, $args ) {
2197 $compression_enabled = self::is_available();
2199 if ( ! $args['decompress'] ) // Decompression specifically disabled.
2200 $compression_enabled = false;
2201 elseif ( $args['stream'] ) // Disable when streaming to file.
2202 $compression_enabled = false;
2203 elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it.
2204 $compression_enabled = false;
2206 if ( $compression_enabled ) {
2207 if ( function_exists( 'gzinflate' ) )
2208 $type[] = 'deflate;q=1.0';
2210 if ( function_exists( 'gzuncompress' ) )
2211 $type[] = 'compress;q=0.5';
2213 if ( function_exists( 'gzdecode' ) )
2214 $type[] = 'gzip;q=0.5';
2218 * Filter the allowed encoding types.
2222 * @param array $type Encoding types allowed. Accepts 'gzinflate',
2223 * 'gzuncompress', 'gzdecode'.
2224 * @param string $url URL of the HTTP request.
2225 * @param array $args HTTP request arguments.
2227 $type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
2229 return implode(', ', $type);
2233 * What encoding the content used when it was compressed to send in the headers.
2237 * @return string Content-Encoding string to send in the header.
2239 public static function content_encoding() {
2244 * Whether the content be decoded based on the headers.
2248 * @param array|string $headers All of the available headers.
2251 public static function should_decode($headers) {
2252 if ( is_array( $headers ) ) {
2253 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
2255 } elseif ( is_string( $headers ) ) {
2256 return ( stripos($headers, 'content-encoding:') !== false );
2263 * Whether decompression and compression are supported by the PHP version.
2265 * Each function is tested instead of checking for the zlib extension, to
2266 * ensure that the functions all exist in the PHP version and aren't
2273 public static function is_available() {
2274 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );