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 http://trac.wordpress.org/ticket/4779 HTTP API Proposal
16 * WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
18 * This class is called for the functionality of making HTTP requests and replaces Snoopy
19 * functionality. There is no available functionality to add HTTP transport implementations, since
20 * most of the HTTP transports are added and available for use.
22 * There are no properties, because none are needed and for performance reasons. Some of the
23 * functions are static and while they do have some overhead over functions in PHP4, the purpose is
24 * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword
25 * to the code. It is not as easy to convert a function to a method after enough code uses the old
28 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
30 * <strong>http_transport_get_debug</strong> - gives working, nonblocking, and blocking transports.
32 * <strong>http_transport_post_debug</strong> - gives working, nonblocking, and blocking transports.
41 * PHP4 style Constructor - Calls PHP5 Style Constructor
51 * PHP5 style Constructor - Set up available transport if not available.
53 * PHP4 does not have the 'self' keyword and since WordPress supports PHP4, the class needs to
54 * be used for the static call. The transport are set up to save time and will only be created
55 * once. This class can be created many times without having to go through the step of finding
56 * which transports are available.
61 function __construct() {
62 WP_Http::_getTransport();
63 WP_Http::_postTransport();
67 * Tests the WordPress HTTP objects for an object to use and returns it.
69 * Tests all of the objects and returns the object that passes. Also caches that object to be
72 * The order for the GET/HEAD requests are HTTP Extension, cURL, Streams, Fopen, and finally
73 * Fsockopen. fsockopen() is used last, because it has the most overhead in its implementation.
74 * There isn't any real way around it, since redirects have to be supported, much the same way
75 * the other transports also handle redirects.
77 * There are currently issues with "localhost" not resolving correctly with DNS. This may cause
78 * an error "failed to open stream: A connection attempt failed because the connected party did
79 * not properly respond after a period of time, or established connection failed because [the]
80 * connected host has failed to respond."
85 * @param array $args Request args, default us an empty array
86 * @return object|null Null if no transports are available, HTTP transport object.
88 function &_getTransport( $args = array() ) {
89 static $working_transport, $blocking_transport, $nonblocking_transport;
91 if ( is_null($working_transport) ) {
92 if ( true === WP_Http_ExtHttp::test($args) ) {
93 $working_transport['exthttp'] = new WP_Http_ExtHttp();
94 $blocking_transport[] = &$working_transport['exthttp'];
95 } else if ( true === WP_Http_Curl::test($args) ) {
96 $working_transport['curl'] = new WP_Http_Curl();
97 $blocking_transport[] = &$working_transport['curl'];
98 } else if ( true === WP_Http_Streams::test($args) ) {
99 $working_transport['streams'] = new WP_Http_Streams();
100 $blocking_transport[] = &$working_transport['streams'];
101 } else if ( true === WP_Http_Fopen::test($args) ) {
102 $working_transport['fopen'] = new WP_Http_Fopen();
103 $blocking_transport[] = &$working_transport['fopen'];
104 } else if ( true === WP_Http_Fsockopen::test($args) ) {
105 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
106 $blocking_transport[] = &$working_transport['fsockopen'];
109 foreach ( array('curl', 'streams', 'fopen', 'fsockopen', 'exthttp') as $transport ) {
110 if ( isset($working_transport[$transport]) )
111 $nonblocking_transport[] = &$working_transport[$transport];
115 do_action( 'http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport );
117 if ( isset($args['blocking']) && !$args['blocking'] )
118 return $nonblocking_transport;
120 return $blocking_transport;
124 * Tests the WordPress HTTP objects for an object to use and returns it.
126 * Tests all of the objects and returns the object that passes. Also caches
127 * that object to be used later. This is for posting content to a URL and
128 * is used when there is a body. The plain Fopen Transport can not be used
129 * to send content, but the streams transport can. This is a limitation that
130 * is addressed here, by just not including that transport.
135 * @param array $args Request args, default us an empty array
136 * @return object|null Null if no transports are available, HTTP transport object.
138 function &_postTransport( $args = array() ) {
139 static $working_transport, $blocking_transport, $nonblocking_transport;
141 if ( is_null($working_transport) ) {
142 if ( true === WP_Http_ExtHttp::test($args) ) {
143 $working_transport['exthttp'] = new WP_Http_ExtHttp();
144 $blocking_transport[] = &$working_transport['exthttp'];
145 } else if ( true === WP_Http_Curl::test($args) ) {
146 $working_transport['curl'] = new WP_Http_Curl();
147 $blocking_transport[] = &$working_transport['curl'];
148 } else if ( true === WP_Http_Streams::test($args) ) {
149 $working_transport['streams'] = new WP_Http_Streams();
150 $blocking_transport[] = &$working_transport['streams'];
151 } else if ( true === WP_Http_Fsockopen::test($args) ) {
152 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
153 $blocking_transport[] = &$working_transport['fsockopen'];
156 foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) {
157 if ( isset($working_transport[$transport]) )
158 $nonblocking_transport[] = &$working_transport[$transport];
162 do_action( 'http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport );
164 if ( isset($args['blocking']) && !$args['blocking'] )
165 return $nonblocking_transport;
167 return $blocking_transport;
171 * Send a HTTP request to a URI.
173 * The body and headers are part of the arguments. The 'body' argument is for the body and will
174 * accept either a string or an array. The 'headers' argument should be an array, but a string
175 * is acceptable. If the 'body' argument is an array, then it will automatically be escaped
176 * using http_build_query().
178 * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
179 * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send
180 * headers. Other protocols are unsupported and most likely will fail.
182 * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
185 * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
186 * others, but should not be assumed. The 'timeout' is used to sent how long the connection
187 * should stay open before failing when no response. 'redirection' is used to track how many
188 * redirects were taken and used to sent the amount for other transports, but not all transports
189 * accept setting that value.
191 * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
192 * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The
193 * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is
194 * 'WordPress/WP_Version', where WP_Version is the value from $wp_version.
196 * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP
197 * while it performs the request or continue regardless. Actually, that isn't entirely correct.
198 * Blocking mode really just means whether the fread should just pull what it can whenever it
199 * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading
200 * the entire content. It doesn't actually always mean that PHP will continue going after making
205 * @todo Refactor this code. The code in this method extends the scope of its original purpose
206 * and should be refactored to allow for cleaner abstraction and reduce duplication of the
207 * code. One suggestion is to create a class specifically for the arguments, however
208 * preliminary refactoring to this affect has affect more than just the scope of the
209 * arguments. Something to ponder at least.
211 * @param string $url URI resource.
212 * @param str|array $args Optional. Override the defaults.
213 * @return array containing 'headers', 'body', 'response', 'cookies'
215 function request( $url, $args = array() ) {
220 'timeout' => apply_filters( 'http_request_timeout', 5),
221 'redirection' => apply_filters( 'http_request_redirection_count', 5),
222 'httpversion' => apply_filters( 'http_request_version', '1.0'),
223 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
225 'headers' => array(),
226 'cookies' => array(),
229 'decompress' => true,
233 $r = wp_parse_args( $args, $defaults );
234 $r = apply_filters( 'http_request_args', $r, $url );
236 // Allow plugins to short-circuit the request
237 $pre = apply_filters( 'pre_http_request', false, $r, $url );
238 if ( false !== $pre )
241 $arrURL = parse_url($url);
243 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
244 return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
246 if ( $this->block_request( $url ) )
247 return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.'));
249 // Determine if this is a https call and pass that on to the transport functions
250 // so that we can blacklist the transports that do not support ssl verification
251 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
253 // Determine if this request is to OUR install of WordPress
254 $homeURL = parse_url( get_bloginfo('url') );
255 $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
258 if ( is_null( $r['headers'] ) )
259 $r['headers'] = array();
261 if ( ! is_array($r['headers']) ) {
262 $processedHeaders = WP_Http::processHeaders($r['headers']);
263 $r['headers'] = $processedHeaders['headers'];
266 if ( isset($r['headers']['User-Agent']) ) {
267 $r['user-agent'] = $r['headers']['User-Agent'];
268 unset($r['headers']['User-Agent']);
271 if ( isset($r['headers']['user-agent']) ) {
272 $r['user-agent'] = $r['headers']['user-agent'];
273 unset($r['headers']['user-agent']);
276 // Construct Cookie: header if any cookies are set
277 WP_Http::buildCookieHeader( $r );
279 if ( WP_Http_Encoding::is_available() )
280 $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding();
282 if ( empty($r['body']) ) {
283 // Some servers fail when sending content without the content-length header being set.
284 // Also, to fix another bug, we only send when doing POST and PUT and the content-length
285 // header isn't already set.
286 if( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset($r['headers']['Content-Length']) )
287 $r['headers']['Content-Length'] = 0;
289 // The method is ambiguous, because we aren't talking about HTTP methods, the "get" in
290 // this case is simply that we aren't sending any bodies and to get the transports that
291 // don't support sending bodies along with those which do.
292 $transports = WP_Http::_getTransport($r);
294 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
295 if ( ! version_compare(phpversion(), '5.1.2', '>=') )
296 $r['body'] = _http_build_query($r['body'], null, '&');
298 $r['body'] = http_build_query($r['body'], null, '&');
299 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset');
300 $r['headers']['Content-Length'] = strlen($r['body']);
303 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
304 $r['headers']['Content-Length'] = strlen($r['body']);
306 // The method is ambiguous, because we aren't talking about HTTP methods, the "post" in
307 // this case is simply that we are sending HTTP body and to get the transports that do
308 // support sending the body. Not all do, depending on the limitations of the PHP core
310 $transports = WP_Http::_postTransport($r);
313 do_action( 'http_api_debug', $transports, 'transports_list' );
315 $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
316 foreach ( (array) $transports as $transport ) {
317 $response = $transport->request($url, $r);
319 do_action( 'http_api_debug', $response, 'response', get_class($transport) );
321 if ( ! is_wp_error($response) )
322 return apply_filters( 'http_response', $response, $r, $url );
329 * Uses the POST HTTP method.
331 * Used for sending data that is expected to be in the body.
336 * @param string $url URI resource.
337 * @param str|array $args Optional. Override the defaults.
340 function post($url, $args = array()) {
341 $defaults = array('method' => 'POST');
342 $r = wp_parse_args( $args, $defaults );
343 return $this->request($url, $r);
347 * Uses the GET HTTP method.
349 * Used for sending data that is expected to be in the body.
354 * @param string $url URI resource.
355 * @param str|array $args Optional. Override the defaults.
358 function get($url, $args = array()) {
359 $defaults = array('method' => 'GET');
360 $r = wp_parse_args( $args, $defaults );
361 return $this->request($url, $r);
365 * Uses the HEAD HTTP method.
367 * Used for sending data that is expected to be in the body.
372 * @param string $url URI resource.
373 * @param str|array $args Optional. Override the defaults.
376 function head($url, $args = array()) {
377 $defaults = array('method' => 'HEAD');
378 $r = wp_parse_args( $args, $defaults );
379 return $this->request($url, $r);
383 * Parses the responses and splits the parts into headers and body.
389 * @param string $strResponse The full response string
390 * @return array Array with 'headers' and 'body' keys.
392 function processResponse($strResponse) {
393 $res = explode("\r\n\r\n", $strResponse, 2);
395 return array('headers' => isset($res[0]) ? $res[0] : array(), 'body' => isset($res[1]) ? $res[1] : '');
399 * Transform header string into an array.
401 * If an array is given then it is assumed to be raw header data with numeric keys with the
402 * headers as the values. No headers must be passed that were already processed.
408 * @param string|array $headers
409 * @return array Processed string headers. If duplicate headers are encountered,
410 * Then a numbered array is returned as the value of that header-key.
412 function processHeaders($headers) {
413 // split headers, one per array element
414 if ( is_string($headers) ) {
415 // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
416 $headers = str_replace("\r\n", "\n", $headers);
417 // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
418 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
419 // create the headers array
420 $headers = explode("\n", $headers);
423 $response = array('code' => 0, 'message' => '');
425 // If a redirection has taken place, The headers for each page request may have been passed.
426 // In this case, determine the final HTTP header and parse from there.
427 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
428 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
429 $headers = array_splice($headers, $i);
435 $newheaders = array();
436 foreach ( $headers as $tempheader ) {
437 if ( empty($tempheader) )
440 if ( false === strpos($tempheader, ':') ) {
441 list( , $response['code'], $response['message']) = explode(' ', $tempheader, 3);
445 list($key, $value) = explode(':', $tempheader, 2);
447 if ( !empty( $value ) ) {
448 $key = strtolower( $key );
449 if ( isset( $newheaders[$key] ) ) {
450 if ( !is_array($newheaders[$key]) )
451 $newheaders[$key] = array($newheaders[$key]);
452 $newheaders[$key][] = trim( $value );
454 $newheaders[$key] = trim( $value );
456 if ( 'set-cookie' == strtolower( $key ) )
457 $cookies[] = new WP_Http_Cookie( $value );
461 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
465 * Takes the arguments for a ::request() and checks for the cookie array.
467 * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
468 * into strings and added to the Cookie: header (within the arguments array). Edits the array by
475 * @param array $r Full array of args passed into ::request()
477 function buildCookieHeader( &$r ) {
478 if ( ! empty($r['cookies']) ) {
479 $cookies_header = '';
480 foreach ( (array) $r['cookies'] as $cookie ) {
481 $cookies_header .= $cookie->getHeaderValue() . '; ';
483 $cookies_header = substr( $cookies_header, 0, -2 );
484 $r['headers']['cookie'] = $cookies_header;
489 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
491 * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
492 * returning footer headers. Shouldn't be too difficult to support it though.
494 * @todo Add support for footer chunked headers.
499 * @param string $body Body content
500 * @return string Chunked decoded body on success or raw body on failure.
502 function chunkTransferDecode($body) {
503 $body = str_replace(array("\r\n", "\r"), "\n", $body);
504 // The body is not chunked encoding or is malformed.
505 if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
509 //$parsedHeaders = array(); Unsupported
512 $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
515 if ( empty( $match[1] ) )
518 $length = hexdec( $match[1] );
519 $chunkLength = strlen( $match[0] );
521 $strBody = substr($body, $chunkLength, $length);
522 $parsedBody .= $strBody;
524 $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
526 if ( "0" == trim($body) )
527 return $parsedBody; // Ignore footer headers.
535 * Block requests through the proxy.
537 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
538 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
540 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
541 * file and this will only allow localhost and your blog to make requests. The constant
542 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
543 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
546 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
548 * @param string $uri URI of url.
549 * @return bool True to block, false to allow.
551 function block_request($uri) {
552 // We don't need to block requests, because nothing is blocked.
553 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
556 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
557 // This will be displayed on blogs, which is not reasonable.
558 $check = @parse_url($uri);
560 /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
562 * This isn't very security sound. There are instances where a hacker might attempt
563 * to bypass the proxy and this check. However, the reason for this behavior is that
564 * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
565 * the default unsecure nature of the HTTP request.
567 if ( $check === false )
570 $home = parse_url( get_option('siteurl') );
572 // Don't block requests back to ourselves by default
573 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
574 return apply_filters('block_local_requests', false);
576 if ( !defined('WP_ACCESSIBLE_HOSTS') )
579 static $accessible_hosts;
580 if ( null == $accessible_hosts )
581 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
583 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
588 * HTTP request method uses fsockopen function to retrieve the url.
590 * This would be the preferred method, but the fsockopen implementation has the most overhead of all
591 * the HTTP transport implementations.
597 class WP_Http_Fsockopen {
599 * Send a HTTP request to a URI using fsockopen().
601 * Does not support non-blocking mode.
603 * @see WP_Http::request For default options descriptions.
607 * @param string $url URI resource.
608 * @param str|array $args Optional. Override the defaults.
609 * @return array 'headers', 'body', 'cookies' and 'response' keys.
611 function request($url, $args = array()) {
613 'method' => 'GET', 'timeout' => 5,
614 'redirection' => 5, 'httpversion' => '1.0',
616 'headers' => array(), 'body' => null, 'cookies' => array()
619 $r = wp_parse_args( $args, $defaults );
621 if ( isset($r['headers']['User-Agent']) ) {
622 $r['user-agent'] = $r['headers']['User-Agent'];
623 unset($r['headers']['User-Agent']);
624 } else if( isset($r['headers']['user-agent']) ) {
625 $r['user-agent'] = $r['headers']['user-agent'];
626 unset($r['headers']['user-agent']);
629 // Construct Cookie: header if any cookies are set
630 WP_Http::buildCookieHeader( $r );
632 $iError = null; // Store error number
633 $strError = null; // Store error string
635 $arrURL = parse_url($url);
637 $fsockopen_host = $arrURL['host'];
639 $secure_transport = false;
641 if ( ! isset( $arrURL['port'] ) ) {
642 if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
643 $fsockopen_host = "ssl://$fsockopen_host";
644 $arrURL['port'] = 443;
645 $secure_transport = true;
647 $arrURL['port'] = 80;
651 //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
652 // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
653 if ( 'localhost' == strtolower($fsockopen_host) )
654 $fsockopen_host = '127.0.0.1';
656 // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
657 // ignored and should be ignored.
658 if ( true === $secure_transport )
659 $error_reporting = error_reporting(0);
661 $startDelay = time();
663 $proxy = new WP_HTTP_Proxy();
666 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
667 $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
669 $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
671 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
672 $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
674 $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
679 // If the delay is greater than the timeout then fsockopen should't be used, because it will
680 // cause a long delay.
681 $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
682 if ( true === $elapseDelay )
683 add_option( 'disable_fsockopen', $endDelay, null, true );
685 if ( false === $handle )
686 return new WP_Error('http_request_failed', $iError . ': ' . $strError);
688 $timeout = (int) floor( $r['timeout'] );
689 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
690 stream_set_timeout( $handle, $timeout, $utimeout );
692 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
695 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
697 if ( empty($requestPath) )
700 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
702 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
703 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
705 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
707 if ( isset($r['user-agent']) )
708 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
710 if ( is_array($r['headers']) ) {
711 foreach ( (array) $r['headers'] as $header => $headerValue )
712 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
714 $strHeaders .= $r['headers'];
717 if ( $proxy->use_authentication() )
718 $strHeaders .= $proxy->authentication_header() . "\r\n";
720 $strHeaders .= "\r\n";
722 if ( ! is_null($r['body']) )
723 $strHeaders .= $r['body'];
725 fwrite($handle, $strHeaders);
727 if ( ! $r['blocking'] ) {
729 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
733 while ( ! feof($handle) )
734 $strResponse .= fread($handle, 4096);
738 if ( true === $secure_transport )
739 error_reporting($error_reporting);
741 $process = WP_Http::processResponse($strResponse);
742 $arrHeaders = WP_Http::processHeaders($process['headers']);
744 // Is the response code within the 400 range?
745 if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 )
746 return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']);
748 // If location is found, then assume redirect and redirect to location.
749 if ( 'HEAD' != $r['method'] && isset($arrHeaders['headers']['location']) ) {
750 if ( $r['redirection']-- > 0 ) {
751 return $this->request($arrHeaders['headers']['location'], $r);
753 return new WP_Error('http_request_failed', __('Too many redirects.'));
757 // If the body was chunk encoded, then decode it.
758 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
759 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
761 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
762 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
764 return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']);
768 * Whether this class can be used for retrieving an URL.
772 * @return boolean False means this class can not be used, true means it can.
774 function test( $args = array() ) {
775 if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
778 $is_ssl = isset($args['ssl']) && $args['ssl'];
780 if ( ! $is_ssl && function_exists( 'fsockopen' ) )
782 elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) )
787 return apply_filters('use_fsockopen_transport', $use, $args);
792 * HTTP request method uses fopen function to retrieve the url.
794 * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support,
795 * but should still be okay, to write the headers, before getting the response. Also requires that
796 * 'allow_url_fopen' to be enabled.
802 class WP_Http_Fopen {
804 * Send a HTTP request to a URI using fopen().
806 * This transport does not support sending of headers and body, therefore should not be used in
807 * the instances, where there is a body and headers.
809 * Notes: Does not support non-blocking mode. Ignores 'redirection' option.
811 * @see WP_Http::retrieve For default options descriptions.
816 * @param string $url URI resource.
817 * @param str|array $args Optional. Override the defaults.
818 * @return array 'headers', 'body', 'cookies' and 'response' keys.
820 function request($url, $args = array()) {
822 'method' => 'GET', 'timeout' => 5,
823 'redirection' => 5, 'httpversion' => '1.0',
825 'headers' => array(), 'body' => null, 'cookies' => array()
828 $r = wp_parse_args( $args, $defaults );
830 $arrURL = parse_url($url);
832 if ( false === $arrURL )
833 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
835 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
836 $url = str_replace($arrURL['scheme'], 'http', $url);
838 if ( is_null( $r['headers'] ) )
839 $r['headers'] = array();
841 if ( is_string($r['headers']) ) {
842 $processedHeaders = WP_Http::processHeaders($r['headers']);
843 $r['headers'] = $processedHeaders['headers'];
846 $initial_user_agent = ini_get('user_agent');
848 if ( !empty($r['headers']) && is_array($r['headers']) ) {
849 $user_agent_extra_headers = '';
850 foreach ( $r['headers'] as $header => $value )
851 $user_agent_extra_headers .= "\r\n$header: $value";
852 @ini_set('user_agent', $r['user-agent'] . $user_agent_extra_headers);
854 @ini_set('user_agent', $r['user-agent']);
858 $handle = @fopen($url, 'r');
860 $handle = fopen($url, 'r');
863 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
865 $timeout = (int) floor( $r['timeout'] );
866 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
867 stream_set_timeout( $handle, $timeout, $utimeout );
869 if ( ! $r['blocking'] ) {
871 @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
872 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
876 while ( ! feof($handle) )
877 $strResponse .= fread($handle, 4096);
879 if ( function_exists('stream_get_meta_data') ) {
880 $meta = stream_get_meta_data($handle);
882 $theHeaders = $meta['wrapper_data'];
883 if ( isset( $meta['wrapper_data']['headers'] ) )
884 $theHeaders = $meta['wrapper_data']['headers'];
886 //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper
887 //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php
888 $theHeaders = $http_response_header;
893 @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
895 $processedHeaders = WP_Http::processHeaders($theHeaders);
897 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
898 $strResponse = WP_Http::chunkTransferDecode($strResponse);
900 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
901 $strResponse = WP_Http_Encoding::decompress( $strResponse );
903 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
907 * Whether this class can be used for retrieving an URL.
911 * @return boolean False means this class can not be used, true means it can.
913 function test($args = array()) {
914 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
917 if ( isset($args['method']) && 'HEAD' == $args['method'] ) //This transport cannot make a HEAD request
921 //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off.
922 $is_ssl = isset($args['ssl']) && $args['ssl'];
924 $is_local = isset($args['local']) && $args['local'];
925 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
926 if ( $is_local && true != apply_filters('https_local_ssl_verify', true) )
928 elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) )
930 elseif ( !$ssl_verify )
936 return apply_filters('use_fopen_transport', $use, $args);
941 * HTTP request method uses Streams to retrieve the url.
943 * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
946 * Second preferred method for getting the URL, for PHP 5.
952 class WP_Http_Streams {
954 * Send a HTTP request to a URI using streams with fopen().
960 * @param str|array $args Optional. Override the defaults.
961 * @return array 'headers', 'body', 'cookies' and 'response' keys.
963 function request($url, $args = array()) {
965 'method' => 'GET', 'timeout' => 5,
966 'redirection' => 5, 'httpversion' => '1.0',
968 'headers' => array(), 'body' => null, 'cookies' => array()
971 $r = wp_parse_args( $args, $defaults );
973 if ( isset($r['headers']['User-Agent']) ) {
974 $r['user-agent'] = $r['headers']['User-Agent'];
975 unset($r['headers']['User-Agent']);
976 } else if( isset($r['headers']['user-agent']) ) {
977 $r['user-agent'] = $r['headers']['user-agent'];
978 unset($r['headers']['user-agent']);
981 // Construct Cookie: header if any cookies are set
982 WP_Http::buildCookieHeader( $r );
984 $arrURL = parse_url($url);
986 if ( false === $arrURL )
987 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
989 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
990 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
992 // Convert Header array to string.
994 if ( is_array( $r['headers'] ) )
995 foreach ( $r['headers'] as $name => $value )
996 $strHeaders .= "{$name}: $value\r\n";
997 else if ( is_string( $r['headers'] ) )
998 $strHeaders = $r['headers'];
1000 $is_local = isset($args['local']) && $args['local'];
1001 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1003 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1004 elseif ( ! $is_local )
1005 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1007 $arrContext = array('http' =>
1009 'method' => strtoupper($r['method']),
1010 'user_agent' => $r['user-agent'],
1011 'max_redirects' => $r['redirection'] + 1, // See #11557
1012 'protocol_version' => (float) $r['httpversion'],
1013 'header' => $strHeaders,
1014 'ignore_errors' => true, // Return non-200 requests.
1015 'timeout' => $r['timeout'],
1017 'verify_peer' => $ssl_verify,
1018 'verify_host' => $ssl_verify
1023 $proxy = new WP_HTTP_Proxy();
1025 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1026 $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
1027 $arrContext['http']['request_fulluri'] = true;
1029 // We only support Basic authentication so this will only work if that is what your proxy supports.
1030 if ( $proxy->use_authentication() )
1031 $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
1034 if ( 'HEAD' == $r['method'] ) // Disable redirects for HEAD requests
1035 $arrContext['http']['max_redirects'] = 1;
1037 if ( ! empty($r['body'] ) )
1038 $arrContext['http']['content'] = $r['body'];
1040 $context = stream_context_create($arrContext);
1043 $handle = @fopen($url, 'r', false, $context);
1045 $handle = fopen($url, 'r', false, $context);
1048 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
1050 $timeout = (int) floor( $r['timeout'] );
1051 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
1052 stream_set_timeout( $handle, $timeout, $utimeout );
1054 if ( ! $r['blocking'] ) {
1055 stream_set_blocking($handle, 0);
1057 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1060 $strResponse = stream_get_contents($handle);
1061 $meta = stream_get_meta_data($handle);
1065 $processedHeaders = array();
1066 if ( isset( $meta['wrapper_data']['headers'] ) )
1067 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
1069 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
1071 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1072 $strResponse = WP_Http::chunkTransferDecode($strResponse);
1074 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1075 $strResponse = WP_Http_Encoding::decompress( $strResponse );
1077 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
1081 * Whether this class can be used for retrieving an URL.
1087 * @return boolean False means this class can not be used, true means it can.
1089 function test($args = array()) {
1090 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
1093 if ( version_compare(PHP_VERSION, '5.0', '<') )
1096 //HTTPS via Proxy was added in 5.1.0
1097 $is_ssl = isset($args['ssl']) && $args['ssl'];
1098 if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) {
1099 $proxy = new WP_HTTP_Proxy();
1101 * No URL check, as its not currently passed to the ::test() function
1102 * In the case where a Proxy is in use, Just bypass this transport for HTTPS.
1104 if ( $proxy->is_enabled() )
1108 return apply_filters('use_streams_transport', true, $args);
1113 * HTTP request method uses HTTP extension to retrieve the url.
1115 * Requires the HTTP extension to be installed. This would be the preferred transport since it can
1116 * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+
1117 * is being used, it doesn't mean that the HTTP extension will be enabled.
1119 * @package WordPress
1123 class WP_Http_ExtHTTP {
1125 * Send a HTTP request to a URI using HTTP extension.
1127 * Does not support non-blocking.
1132 * @param string $url
1133 * @param str|array $args Optional. Override the defaults.
1134 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1136 function request($url, $args = array()) {
1138 'method' => 'GET', 'timeout' => 5,
1139 'redirection' => 5, 'httpversion' => '1.0',
1141 'headers' => array(), 'body' => null, 'cookies' => array()
1144 $r = wp_parse_args( $args, $defaults );
1146 if ( isset($r['headers']['User-Agent']) ) {
1147 $r['user-agent'] = $r['headers']['User-Agent'];
1148 unset($r['headers']['User-Agent']);
1149 } else if( isset($r['headers']['user-agent']) ) {
1150 $r['user-agent'] = $r['headers']['user-agent'];
1151 unset($r['headers']['user-agent']);
1154 // Construct Cookie: header if any cookies are set
1155 WP_Http::buildCookieHeader( $r );
1157 switch ( $r['method'] ) {
1159 $r['method'] = HTTP_METH_POST;
1162 $r['method'] = HTTP_METH_HEAD;
1165 $r['method'] = HTTP_METH_PUT;
1169 $r['method'] = HTTP_METH_GET;
1172 $arrURL = parse_url($url);
1174 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
1175 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1177 $is_local = isset($args['local']) && $args['local'];
1178 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1180 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1181 elseif ( ! $is_local )
1182 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1184 $r['timeout'] = (int) ceil( $r['timeout'] );
1187 'timeout' => $r['timeout'],
1188 'connecttimeout' => $r['timeout'],
1189 'redirect' => $r['redirection'],
1190 'useragent' => $r['user-agent'],
1191 'headers' => $r['headers'],
1193 'verifypeer' => $ssl_verify,
1194 'verifyhost' => $ssl_verify
1198 if ( HTTP_METH_HEAD == $r['method'] )
1199 $options['redirect'] = 0; // Assumption: Docs seem to suggest that this means do not follow. Untested.
1201 // The HTTP extensions offers really easy proxy support.
1202 $proxy = new WP_HTTP_Proxy();
1204 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1205 $options['proxyhost'] = $proxy->host();
1206 $options['proxyport'] = $proxy->port();
1207 $options['proxytype'] = HTTP_PROXY_HTTP;
1209 if ( $proxy->use_authentication() ) {
1210 $options['proxyauth'] = $proxy->authentication();
1211 $options['proxyauthtype'] = HTTP_AUTH_ANY;
1215 if ( !WP_DEBUG ) //Emits warning level notices for max redirects and timeouts
1216 $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
1218 $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts
1220 // Error may still be set, Response may return headers or partial document, and error
1221 // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
1222 if ( false === $strResponse || ! empty($info['error']) )
1223 return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
1225 if ( ! $r['blocking'] )
1226 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1228 $headers_body = WP_HTTP::processResponse($strResponse);
1229 $theHeaders = $headers_body['headers'];
1230 $theBody = $headers_body['body'];
1231 unset($headers_body);
1233 $theHeaders = WP_Http::processHeaders($theHeaders);
1235 if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) {
1237 $theBody = @http_chunked_decode($theBody);
1239 $theBody = http_chunked_decode($theBody);
1242 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1243 $theBody = http_inflate( $theBody );
1245 $theResponse = array();
1246 $theResponse['code'] = $info['response_code'];
1247 $theResponse['message'] = get_status_header_desc($info['response_code']);
1249 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
1253 * Whether this class can be used for retrieving an URL.
1258 * @return boolean False means this class can not be used, true means it can.
1260 function test($args = array()) {
1261 return apply_filters('use_http_extension_transport', function_exists('http_request'), $args );
1266 * HTTP request method uses Curl extension to retrieve the url.
1268 * Requires the Curl extension to be installed.
1270 * @package WordPress
1274 class WP_Http_Curl {
1277 * Send a HTTP request to a URI using cURL extension.
1282 * @param string $url
1283 * @param str|array $args Optional. Override the defaults.
1284 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1286 function request($url, $args = array()) {
1288 'method' => 'GET', 'timeout' => 5,
1289 'redirection' => 5, 'httpversion' => '1.0',
1291 'headers' => array(), 'body' => null, 'cookies' => array()
1294 $r = wp_parse_args( $args, $defaults );
1296 if ( isset($r['headers']['User-Agent']) ) {
1297 $r['user-agent'] = $r['headers']['User-Agent'];
1298 unset($r['headers']['User-Agent']);
1299 } else if( isset($r['headers']['user-agent']) ) {
1300 $r['user-agent'] = $r['headers']['user-agent'];
1301 unset($r['headers']['user-agent']);
1304 // Construct Cookie: header if any cookies are set.
1305 WP_Http::buildCookieHeader( $r );
1307 $handle = curl_init();
1309 // cURL offers really easy proxy support.
1310 $proxy = new WP_HTTP_Proxy();
1312 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1314 $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
1317 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1318 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1319 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1321 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() );
1324 if ( $proxy->use_authentication() ) {
1326 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1328 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1332 $is_local = isset($args['local']) && $args['local'];
1333 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1335 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1336 elseif ( ! $is_local )
1337 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1340 // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
1341 // a value of 0 will allow an ulimited timeout.
1342 $timeout = (int) ceil( $r['timeout'] );
1343 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1344 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1346 curl_setopt( $handle, CURLOPT_URL, $url);
1347 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1348 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify );
1349 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1350 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1351 curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1353 switch ( $r['method'] ) {
1355 curl_setopt( $handle, CURLOPT_NOBODY, true );
1358 curl_setopt( $handle, CURLOPT_POST, true );
1359 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1362 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1363 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1367 if ( true === $r['blocking'] )
1368 curl_setopt( $handle, CURLOPT_HEADER, true );
1370 curl_setopt( $handle, CURLOPT_HEADER, false );
1372 // The option doesn't work with safe mode or when open_basedir is set.
1373 // Disable HEAD when making HEAD requests.
1374 if ( !ini_get('safe_mode') && !ini_get('open_basedir') && 'HEAD' != $r['method'] )
1375 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1377 if ( !empty( $r['headers'] ) ) {
1378 // cURL expects full header strings in each element
1380 foreach ( $r['headers'] as $name => $value ) {
1381 $headers[] = "{$name}: $value";
1383 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1386 if ( $r['httpversion'] == '1.0' )
1387 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1389 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1391 // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1392 // themselves... Although, it is somewhat pointless without some reference.
1393 do_action_ref_array( 'http_api_curl', array(&$handle) );
1395 // We don't need to return the body, so don't. Just execute request and return.
1396 if ( ! $r['blocking'] ) {
1397 curl_exec( $handle );
1398 curl_close( $handle );
1399 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1402 $theResponse = curl_exec( $handle );
1404 if ( !empty($theResponse) ) {
1405 $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
1406 $theHeaders = trim( substr($theResponse, 0, $headerLength) );
1407 if ( strlen($theResponse) > $headerLength )
1408 $theBody = substr( $theResponse, $headerLength );
1411 if ( false !== strrpos($theHeaders, "\r\n\r\n") ) {
1412 $headerParts = explode("\r\n\r\n", $theHeaders);
1413 $theHeaders = $headerParts[ count($headerParts) -1 ];
1415 $theHeaders = WP_Http::processHeaders($theHeaders);
1417 if ( $curl_error = curl_error($handle) )
1418 return new WP_Error('http_request_failed', $curl_error);
1419 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1420 return new WP_Error('http_request_failed', __('Too many redirects.'));
1422 $theHeaders = array( 'headers' => array(), 'cookies' => array() );
1426 $response = array();
1427 $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1428 $response['message'] = get_status_header_desc($response['code']);
1430 curl_close( $handle );
1432 // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
1433 if ( !empty($theHeaders['headers']['location']) && (ini_get('safe_mode') || ini_get('open_basedir')) ) {
1434 if ( $r['redirection']-- > 0 ) {
1435 return $this->request($theHeaders['headers']['location'], $r);
1437 return new WP_Error('http_request_failed', __('Too many redirects.'));
1441 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1442 $theBody = WP_Http_Encoding::decompress( $theBody );
1444 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']);
1448 * Whether this class can be used for retrieving an URL.
1453 * @return boolean False means this class can not be used, true means it can.
1455 function test($args = array()) {
1456 if ( function_exists('curl_init') && function_exists('curl_exec') )
1457 return apply_filters('use_curl_transport', true, $args);
1464 * Adds Proxy support to the WordPress HTTP API.
1466 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1467 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1470 * Please note that only BASIC authentication is supported by most transports.
1471 * cURL and the PHP HTTP Extension MAY support more methods (such as NTLM authentication) depending on your environment.
1473 * The constants are as follows:
1475 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1476 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1477 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1478 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1479 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1480 * You do not need to have localhost and the blog host in this list, because they will not be passed
1481 * through the proxy. The list should be presented in a comma separated list</li>
1484 * An example can be as seen below.
1486 * define('WP_PROXY_HOST', '192.168.84.101');
1487 * define('WP_PROXY_PORT', '8080');
1488 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com');
1491 * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1494 class WP_HTTP_Proxy {
1497 * Whether proxy connection should be used.
1500 * @use WP_PROXY_HOST
1501 * @use WP_PROXY_PORT
1505 function is_enabled() {
1506 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1510 * Whether authentication should be used.
1513 * @use WP_PROXY_USERNAME
1514 * @use WP_PROXY_PASSWORD
1518 function use_authentication() {
1519 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1523 * Retrieve the host for the proxy server.
1530 if ( defined('WP_PROXY_HOST') )
1531 return WP_PROXY_HOST;
1537 * Retrieve the port for the proxy server.
1544 if ( defined('WP_PROXY_PORT') )
1545 return WP_PROXY_PORT;
1551 * Retrieve the username for proxy authentication.
1557 function username() {
1558 if ( defined('WP_PROXY_USERNAME') )
1559 return WP_PROXY_USERNAME;
1565 * Retrieve the password for proxy authentication.
1571 function password() {
1572 if ( defined('WP_PROXY_PASSWORD') )
1573 return WP_PROXY_PASSWORD;
1579 * Retrieve authentication string for proxy authentication.
1585 function authentication() {
1586 return $this->username() . ':' . $this->password();
1590 * Retrieve header string for proxy authentication.
1596 function authentication_header() {
1597 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1601 * Whether URL should be sent through the proxy server.
1603 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1604 * some proxies can not handle this. We also have the constant available for defining other
1605 * hosts that won't be sent through the proxy.
1607 * @uses WP_PROXY_BYPASS_HOSTS
1610 * @param string $uri URI to check.
1611 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1613 function send_through_proxy( $uri ) {
1614 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1615 // This will be displayed on blogs, which is not reasonable.
1616 $check = @parse_url($uri);
1618 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1619 if ( $check === false )
1622 $home = parse_url( get_option('siteurl') );
1624 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1627 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1630 static $bypass_hosts;
1631 if ( null == $bypass_hosts )
1632 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1634 return !in_array( $check['host'], $bypass_hosts );
1638 * Internal representation of a single cookie.
1640 * Returned cookies are represented using this class, and when cookies are set, if they are not
1641 * already a WP_Http_Cookie() object, then they are turned into one.
1643 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1644 * names. Need to switch to use underscores instead for the methods.
1646 * @package WordPress
1650 class WP_Http_Cookie {
1669 * When the cookie expires.
1693 * PHP4 style Constructor - Calls PHP5 Style Constructor.
1697 * @param string|array $data Raw cookie data.
1699 function WP_Http_Cookie( $data ) {
1700 $this->__construct( $data );
1704 * Sets up this cookie object.
1706 * The parameter $data should be either an associative array containing the indices names below
1707 * or a header string detailing it.
1709 * If it's an array, it should include the following elements:
1712 * <li>Value - should NOT be urlencoded already.</li>
1713 * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1714 * <li>Path (optional)</li>
1715 * <li>Domain (optional)</li>
1721 * @param string|array $data Raw cookie data.
1723 function __construct( $data ) {
1724 if ( is_string( $data ) ) {
1725 // Assume it's a header string direct from a previous request
1726 $pairs = explode( ';', $data );
1728 // Special handling for first pair; name=value. Also be careful of "=" in value
1729 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1730 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1731 $this->name = $name;
1732 $this->value = urldecode( $value );
1733 array_shift( $pairs ); //Removes name=value from items.
1735 // Set everything else as a property
1736 foreach ( $pairs as $pair ) {
1737 $pair = rtrim($pair);
1738 if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1741 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1742 $key = strtolower( trim( $key ) );
1743 if ( 'expires' == $key )
1744 $val = strtotime( $val );
1748 if ( !isset( $data['name'] ) )
1751 // Set properties based directly on parameters
1752 $this->name = $data['name'];
1753 $this->value = isset( $data['value'] ) ? $data['value'] : '';
1754 $this->path = isset( $data['path'] ) ? $data['path'] : '';
1755 $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1757 if ( isset( $data['expires'] ) )
1758 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1760 $this->expires = null;
1765 * Confirms that it's OK to send this cookie to the URL checked against.
1767 * Decision is based on RFC 2109/2965, so look there for details on validity.
1772 * @param string $url URL you intend to send this cookie to
1773 * @return boolean TRUE if allowed, FALSE otherwise.
1775 function test( $url ) {
1776 // Expires - if expired then nothing else matters
1777 if ( time() > $this->expires )
1780 // Get details on the URL we're thinking about sending to
1781 $url = parse_url( $url );
1782 $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1783 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1785 // Values to use for comparison against the URL
1786 $path = isset( $this->path ) ? $this->path : '/';
1787 $port = isset( $this->port ) ? $this->port : 80;
1788 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1789 if ( false === stripos( $domain, '.' ) )
1790 $domain .= '.local';
1792 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1793 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1794 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1797 // Port - supports "port-lists" in the format: "80,8000,8080"
1798 if ( !in_array( $url['port'], explode( ',', $port) ) )
1801 // Path - request path must start with path restriction
1802 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1809 * Convert cookie name and value back to header string.
1814 * @return string Header encoded cookie name and value.
1816 function getHeaderValue() {
1817 if ( empty( $this->name ) || empty( $this->value ) )
1820 return $this->name . '=' . urlencode( $this->value );
1824 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1831 function getFullHeader() {
1832 return 'Cookie: ' . $this->getHeaderValue();
1837 * Implementation for deflate and gzip transfer encodings.
1839 * Includes RFC 1950, RFC 1951, and RFC 1952.
1842 * @package WordPress
1845 class WP_Http_Encoding {
1848 * Compress raw string using the deflate format.
1850 * Supports the RFC 1951 standard.
1854 * @param string $raw String to compress.
1855 * @param int $level Optional, default is 9. Compression level, 9 is highest.
1856 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1857 * @return string|bool False on failure.
1859 function compress( $raw, $level = 9, $supports = null ) {
1860 return gzdeflate( $raw, $level );
1864 * Decompression of deflated string.
1866 * Will attempt to decompress using the RFC 1950 standard, and if that fails
1867 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1868 * 1952 standard gzip decode will be attempted. If all fail, then the
1869 * original compressed string will be returned.
1873 * @param string $compressed String to decompress.
1874 * @param int $length The optional length of the compressed data.
1875 * @return string|bool False on failure.
1877 function decompress( $compressed, $length = null ) {
1879 if ( empty($compressed) )
1882 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
1883 return $decompressed;
1885 if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
1886 return $decompressed;
1888 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
1889 return $decompressed;
1891 if ( function_exists('gzdecode') ) {
1892 $decompressed = @gzdecode( $compressed );
1894 if ( false !== $decompressed )
1895 return $decompressed;
1902 * Decompression of deflated string while staying compatible with the majority of servers.
1904 * Certain Servers will return deflated data with headers which PHP's gziniflate()
1905 * function cannot handle out of the box. The following function lifted from
1906 * http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate
1907 * the various return forms used.
1910 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
1912 * @param string $gzData String to decompress.
1913 * @return string|bool False on failure.
1915 function compatible_gzinflate($gzData) {
1916 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
1918 $flg = ord( substr($gzData, 3, 1) );
1921 list($xlen) = unpack('v', substr($gzData, $i, 2) );
1922 $i = $i + 2 + $xlen;
1925 $i = strpos($gzData, "\0", $i) + 1;
1927 $i = strpos($gzData, "\0", $i) + 1;
1931 return gzinflate( substr($gzData, $i, -8) );
1938 * What encoding types to accept and their priority values.
1942 * @return string Types of encoding to accept.
1944 function accept_encoding() {
1946 if ( function_exists( 'gzinflate' ) )
1947 $type[] = 'deflate;q=1.0';
1949 if ( function_exists( 'gzuncompress' ) )
1950 $type[] = 'compress;q=0.5';
1952 if ( function_exists( 'gzdecode' ) )
1953 $type[] = 'gzip;q=0.5';
1955 return implode(', ', $type);
1959 * What enconding the content used when it was compressed to send in the headers.
1963 * @return string Content-Encoding string to send in the header.
1965 function content_encoding() {
1970 * Whether the content be decoded based on the headers.
1974 * @param array|string $headers All of the available headers.
1977 function should_decode($headers) {
1978 if ( is_array( $headers ) ) {
1979 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
1981 } else if ( is_string( $headers ) ) {
1982 return ( stripos($headers, 'content-encoding:') !== false );
1989 * Whether decompression and compression are supported by the PHP version.
1991 * Each function is tested instead of checking for the zlib extension, to
1992 * ensure that the functions all exist in the PHP version and aren't
1999 function is_available() {
2000 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );