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']) ) {
284 // Some servers fail when sending content without the content-length header being set.
285 // Also, to fix another bug, we only send when doing POST and PUT and the content-length
286 // header isn't already set.
287 if ( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset( $r['headers']['Content-Length'] ) )
288 $r['headers']['Content-Length'] = 0;
290 // The method is ambiguous, because we aren't talking about HTTP methods, the "get" in
291 // this case is simply that we aren't sending any bodies and to get the transports that
292 // don't support sending bodies along with those which do.
293 $transports = WP_Http::_getTransport( $r );
295 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
296 if ( ! version_compare(phpversion(), '5.1.2', '>=') )
297 $r['body'] = _http_build_query( $r['body'], null, '&' );
299 $r['body'] = http_build_query( $r['body'], null, '&' );
300 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
301 $r['headers']['Content-Length'] = strlen( $r['body'] );
304 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
305 $r['headers']['Content-Length'] = strlen( $r['body'] );
307 // The method is ambiguous, because we aren't talking about HTTP methods, the "post" in
308 // this case is simply that we are sending HTTP body and to get the transports that do
309 // support sending the body. Not all do, depending on the limitations of the PHP core
311 $transports = WP_Http::_postTransport( $r );
314 do_action( 'http_api_debug', $transports, 'transports_list' );
316 $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
317 foreach ( (array) $transports as $transport ) {
318 $response = $transport->request( $url, $r );
320 do_action( 'http_api_debug', $response, 'response', get_class( $transport ) );
322 if ( ! is_wp_error( $response ) )
323 return apply_filters( 'http_response', $response, $r, $url );
330 * Uses the POST HTTP method.
332 * Used for sending data that is expected to be in the body.
337 * @param string $url URI resource.
338 * @param str|array $args Optional. Override the defaults.
341 function post($url, $args = array()) {
342 $defaults = array('method' => 'POST');
343 $r = wp_parse_args( $args, $defaults );
344 return $this->request($url, $r);
348 * Uses the GET HTTP method.
350 * Used for sending data that is expected to be in the body.
355 * @param string $url URI resource.
356 * @param str|array $args Optional. Override the defaults.
359 function get($url, $args = array()) {
360 $defaults = array('method' => 'GET');
361 $r = wp_parse_args( $args, $defaults );
362 return $this->request($url, $r);
366 * Uses the HEAD HTTP method.
368 * Used for sending data that is expected to be in the body.
373 * @param string $url URI resource.
374 * @param str|array $args Optional. Override the defaults.
377 function head($url, $args = array()) {
378 $defaults = array('method' => 'HEAD');
379 $r = wp_parse_args( $args, $defaults );
380 return $this->request($url, $r);
384 * Parses the responses and splits the parts into headers and body.
390 * @param string $strResponse The full response string
391 * @return array Array with 'headers' and 'body' keys.
393 function processResponse($strResponse) {
394 $res = explode("\r\n\r\n", $strResponse, 2);
396 return array('headers' => isset($res[0]) ? $res[0] : array(), 'body' => isset($res[1]) ? $res[1] : '');
400 * Transform header string into an array.
402 * If an array is given then it is assumed to be raw header data with numeric keys with the
403 * headers as the values. No headers must be passed that were already processed.
409 * @param string|array $headers
410 * @return array Processed string headers. If duplicate headers are encountered,
411 * Then a numbered array is returned as the value of that header-key.
413 function processHeaders($headers) {
414 // split headers, one per array element
415 if ( is_string($headers) ) {
416 // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
417 $headers = str_replace("\r\n", "\n", $headers);
418 // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
419 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
420 // create the headers array
421 $headers = explode("\n", $headers);
424 $response = array('code' => 0, 'message' => '');
426 // If a redirection has taken place, The headers for each page request may have been passed.
427 // In this case, determine the final HTTP header and parse from there.
428 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
429 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
430 $headers = array_splice($headers, $i);
436 $newheaders = array();
437 foreach ( $headers as $tempheader ) {
438 if ( empty($tempheader) )
441 if ( false === strpos($tempheader, ':') ) {
442 list( , $response['code'], $response['message']) = explode(' ', $tempheader, 3);
446 list($key, $value) = explode(':', $tempheader, 2);
448 if ( !empty( $value ) ) {
449 $key = strtolower( $key );
450 if ( isset( $newheaders[$key] ) ) {
451 if ( !is_array($newheaders[$key]) )
452 $newheaders[$key] = array($newheaders[$key]);
453 $newheaders[$key][] = trim( $value );
455 $newheaders[$key] = trim( $value );
457 if ( 'set-cookie' == $key )
458 $cookies[] = new WP_Http_Cookie( $value );
462 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
466 * Takes the arguments for a ::request() and checks for the cookie array.
468 * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
469 * into strings and added to the Cookie: header (within the arguments array). Edits the array by
476 * @param array $r Full array of args passed into ::request()
478 function buildCookieHeader( &$r ) {
479 if ( ! empty($r['cookies']) ) {
480 $cookies_header = '';
481 foreach ( (array) $r['cookies'] as $cookie ) {
482 $cookies_header .= $cookie->getHeaderValue() . '; ';
484 $cookies_header = substr( $cookies_header, 0, -2 );
485 $r['headers']['cookie'] = $cookies_header;
490 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
492 * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
493 * returning footer headers. Shouldn't be too difficult to support it though.
495 * @todo Add support for footer chunked headers.
500 * @param string $body Body content
501 * @return string Chunked decoded body on success or raw body on failure.
503 function chunkTransferDecode($body) {
504 $body = str_replace(array("\r\n", "\r"), "\n", $body);
505 // The body is not chunked encoding or is malformed.
506 if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
510 //$parsedHeaders = array(); Unsupported
513 $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
516 if ( empty( $match[1] ) )
519 $length = hexdec( $match[1] );
520 $chunkLength = strlen( $match[0] );
522 $strBody = substr($body, $chunkLength, $length);
523 $parsedBody .= $strBody;
525 $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
527 if ( "0" == trim($body) )
528 return $parsedBody; // Ignore footer headers.
536 * Block requests through the proxy.
538 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
539 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
541 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
542 * file and this will only allow localhost and your blog to make requests. The constant
543 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
544 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
545 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
548 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
549 * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
551 * @param string $uri URI of url.
552 * @return bool True to block, false to allow.
554 function block_request($uri) {
555 // We don't need to block requests, because nothing is blocked.
556 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
559 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
560 // This will be displayed on blogs, which is not reasonable.
561 $check = @parse_url($uri);
563 /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
565 * This isn't very security sound. There are instances where a hacker might attempt
566 * to bypass the proxy and this check. However, the reason for this behavior is that
567 * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
568 * the default unsecure nature of the HTTP request.
570 if ( $check === false )
573 $home = parse_url( get_option('siteurl') );
575 // Don't block requests back to ourselves by default
576 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
577 return apply_filters('block_local_requests', false);
579 if ( !defined('WP_ACCESSIBLE_HOSTS') )
582 static $accessible_hosts;
583 static $wildcard_regex = false;
584 if ( null == $accessible_hosts ) {
585 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
587 if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
588 $wildcard_regex = array();
589 foreach ( $accessible_hosts as $host )
590 $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
591 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
595 if ( !empty($wildcard_regex) )
596 return !preg_match($wildcard_regex, $check['host']);
598 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
606 * HTTP request method uses fsockopen function to retrieve the url.
608 * This would be the preferred method, but the fsockopen implementation has the most overhead of all
609 * the HTTP transport implementations.
615 class WP_Http_Fsockopen {
617 * Send a HTTP request to a URI using fsockopen().
619 * Does not support non-blocking mode.
621 * @see WP_Http::request For default options descriptions.
625 * @param string $url URI resource.
626 * @param str|array $args Optional. Override the defaults.
627 * @return array 'headers', 'body', 'cookies' and 'response' keys.
629 function request($url, $args = array()) {
631 'method' => 'GET', 'timeout' => 5,
632 'redirection' => 5, 'httpversion' => '1.0',
634 'headers' => array(), 'body' => null, 'cookies' => array()
637 $r = wp_parse_args( $args, $defaults );
639 if ( isset($r['headers']['User-Agent']) ) {
640 $r['user-agent'] = $r['headers']['User-Agent'];
641 unset($r['headers']['User-Agent']);
642 } else if ( isset($r['headers']['user-agent']) ) {
643 $r['user-agent'] = $r['headers']['user-agent'];
644 unset($r['headers']['user-agent']);
647 // Construct Cookie: header if any cookies are set
648 WP_Http::buildCookieHeader( $r );
650 $iError = null; // Store error number
651 $strError = null; // Store error string
653 $arrURL = parse_url($url);
655 $fsockopen_host = $arrURL['host'];
657 $secure_transport = false;
659 if ( ! isset( $arrURL['port'] ) ) {
660 if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
661 $fsockopen_host = "ssl://$fsockopen_host";
662 $arrURL['port'] = 443;
663 $secure_transport = true;
665 $arrURL['port'] = 80;
669 //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
670 // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
671 if ( 'localhost' == strtolower($fsockopen_host) )
672 $fsockopen_host = '127.0.0.1';
674 // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
675 // ignored and should be ignored.
676 if ( true === $secure_transport )
677 $error_reporting = error_reporting(0);
679 $startDelay = time();
681 $proxy = new WP_HTTP_Proxy();
684 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
685 $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
687 $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
689 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
690 $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
692 $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
697 // If the delay is greater than the timeout then fsockopen should't be used, because it will
698 // cause a long delay.
699 $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
700 if ( true === $elapseDelay )
701 add_option( 'disable_fsockopen', $endDelay, null, true );
703 if ( false === $handle )
704 return new WP_Error('http_request_failed', $iError . ': ' . $strError);
706 $timeout = (int) floor( $r['timeout'] );
707 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
708 stream_set_timeout( $handle, $timeout, $utimeout );
710 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
713 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
715 if ( empty($requestPath) )
718 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
720 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
721 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
723 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
725 if ( isset($r['user-agent']) )
726 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
728 if ( is_array($r['headers']) ) {
729 foreach ( (array) $r['headers'] as $header => $headerValue )
730 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
732 $strHeaders .= $r['headers'];
735 if ( $proxy->use_authentication() )
736 $strHeaders .= $proxy->authentication_header() . "\r\n";
738 $strHeaders .= "\r\n";
740 if ( ! is_null($r['body']) )
741 $strHeaders .= $r['body'];
743 fwrite($handle, $strHeaders);
745 if ( ! $r['blocking'] ) {
747 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
751 while ( ! feof($handle) )
752 $strResponse .= fread($handle, 4096);
756 if ( true === $secure_transport )
757 error_reporting($error_reporting);
759 $process = WP_Http::processResponse($strResponse);
760 $arrHeaders = WP_Http::processHeaders($process['headers']);
762 // Is the response code within the 400 range?
763 if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 )
764 return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']);
766 // If location is found, then assume redirect and redirect to location.
767 if ( 'HEAD' != $r['method'] && isset($arrHeaders['headers']['location']) ) {
768 if ( $r['redirection']-- > 0 ) {
769 return $this->request($arrHeaders['headers']['location'], $r);
771 return new WP_Error('http_request_failed', __('Too many redirects.'));
775 // If the body was chunk encoded, then decode it.
776 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
777 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
779 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
780 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
782 return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']);
786 * Whether this class can be used for retrieving an URL.
790 * @return boolean False means this class can not be used, true means it can.
792 function test( $args = array() ) {
793 if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
796 $is_ssl = isset($args['ssl']) && $args['ssl'];
798 if ( ! $is_ssl && function_exists( 'fsockopen' ) )
800 elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) )
805 return apply_filters('use_fsockopen_transport', $use, $args);
810 * HTTP request method uses fopen function to retrieve the url.
812 * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support,
813 * but should still be okay, to write the headers, before getting the response. Also requires that
814 * 'allow_url_fopen' to be enabled.
820 class WP_Http_Fopen {
822 * Send a HTTP request to a URI using fopen().
824 * This transport does not support sending of headers and body, therefore should not be used in
825 * the instances, where there is a body and headers.
827 * Notes: Does not support non-blocking mode. Ignores 'redirection' option.
829 * @see WP_Http::retrieve For default options descriptions.
834 * @param string $url URI resource.
835 * @param str|array $args Optional. Override the defaults.
836 * @return array 'headers', 'body', 'cookies' and 'response' keys.
838 function request($url, $args = array()) {
840 'method' => 'GET', 'timeout' => 5,
841 'redirection' => 5, 'httpversion' => '1.0',
843 'headers' => array(), 'body' => null, 'cookies' => array()
846 $r = wp_parse_args( $args, $defaults );
848 $arrURL = parse_url($url);
850 if ( false === $arrURL )
851 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
853 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
854 $url = str_replace($arrURL['scheme'], 'http', $url);
856 if ( is_null( $r['headers'] ) )
857 $r['headers'] = array();
859 if ( is_string($r['headers']) ) {
860 $processedHeaders = WP_Http::processHeaders($r['headers']);
861 $r['headers'] = $processedHeaders['headers'];
864 $initial_user_agent = ini_get('user_agent');
866 if ( !empty($r['headers']) && is_array($r['headers']) ) {
867 $user_agent_extra_headers = '';
868 foreach ( $r['headers'] as $header => $value )
869 $user_agent_extra_headers .= "\r\n$header: $value";
870 @ini_set('user_agent', $r['user-agent'] . $user_agent_extra_headers);
872 @ini_set('user_agent', $r['user-agent']);
876 $handle = @fopen($url, 'r');
878 $handle = fopen($url, 'r');
881 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
883 $timeout = (int) floor( $r['timeout'] );
884 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
885 stream_set_timeout( $handle, $timeout, $utimeout );
887 if ( ! $r['blocking'] ) {
889 @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
890 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
894 while ( ! feof($handle) )
895 $strResponse .= fread($handle, 4096);
897 if ( function_exists('stream_get_meta_data') ) {
898 $meta = stream_get_meta_data($handle);
900 $theHeaders = $meta['wrapper_data'];
901 if ( isset( $meta['wrapper_data']['headers'] ) )
902 $theHeaders = $meta['wrapper_data']['headers'];
904 //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper
905 //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php
906 $theHeaders = $http_response_header;
911 @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
913 $processedHeaders = WP_Http::processHeaders($theHeaders);
915 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
916 $strResponse = WP_Http::chunkTransferDecode($strResponse);
918 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
919 $strResponse = WP_Http_Encoding::decompress( $strResponse );
921 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
925 * Whether this class can be used for retrieving an URL.
929 * @return boolean False means this class can not be used, true means it can.
931 function test($args = array()) {
932 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
935 if ( isset($args['method']) && 'HEAD' == $args['method'] ) //This transport cannot make a HEAD request
939 //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off.
940 $is_ssl = isset($args['ssl']) && $args['ssl'];
942 $is_local = isset($args['local']) && $args['local'];
943 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
944 if ( $is_local && true != apply_filters('https_local_ssl_verify', true) )
946 elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) )
948 elseif ( !$ssl_verify )
954 return apply_filters('use_fopen_transport', $use, $args);
959 * HTTP request method uses Streams to retrieve the url.
961 * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
964 * Second preferred method for getting the URL, for PHP 5.
970 class WP_Http_Streams {
972 * Send a HTTP request to a URI using streams with fopen().
978 * @param str|array $args Optional. Override the defaults.
979 * @return array 'headers', 'body', 'cookies' and 'response' keys.
981 function request($url, $args = array()) {
983 'method' => 'GET', 'timeout' => 5,
984 'redirection' => 5, 'httpversion' => '1.0',
986 'headers' => array(), 'body' => null, 'cookies' => array()
989 $r = wp_parse_args( $args, $defaults );
991 if ( isset($r['headers']['User-Agent']) ) {
992 $r['user-agent'] = $r['headers']['User-Agent'];
993 unset($r['headers']['User-Agent']);
994 } else if ( isset($r['headers']['user-agent']) ) {
995 $r['user-agent'] = $r['headers']['user-agent'];
996 unset($r['headers']['user-agent']);
999 // Construct Cookie: header if any cookies are set
1000 WP_Http::buildCookieHeader( $r );
1002 $arrURL = parse_url($url);
1004 if ( false === $arrURL )
1005 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
1007 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
1008 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1010 // Convert Header array to string.
1012 if ( is_array( $r['headers'] ) )
1013 foreach ( $r['headers'] as $name => $value )
1014 $strHeaders .= "{$name}: $value\r\n";
1015 else if ( is_string( $r['headers'] ) )
1016 $strHeaders = $r['headers'];
1018 $is_local = isset($args['local']) && $args['local'];
1019 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1021 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1022 elseif ( ! $is_local )
1023 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1025 $arrContext = array('http' =>
1027 'method' => strtoupper($r['method']),
1028 'user_agent' => $r['user-agent'],
1029 'max_redirects' => $r['redirection'] + 1, // See #11557
1030 'protocol_version' => (float) $r['httpversion'],
1031 'header' => $strHeaders,
1032 'ignore_errors' => true, // Return non-200 requests.
1033 'timeout' => $r['timeout'],
1035 'verify_peer' => $ssl_verify,
1036 'verify_host' => $ssl_verify
1041 $proxy = new WP_HTTP_Proxy();
1043 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1044 $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
1045 $arrContext['http']['request_fulluri'] = true;
1047 // We only support Basic authentication so this will only work if that is what your proxy supports.
1048 if ( $proxy->use_authentication() )
1049 $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
1052 if ( 'HEAD' == $r['method'] ) // Disable redirects for HEAD requests
1053 $arrContext['http']['max_redirects'] = 1;
1055 if ( ! empty($r['body'] ) )
1056 $arrContext['http']['content'] = $r['body'];
1058 $context = stream_context_create($arrContext);
1061 $handle = @fopen($url, 'r', false, $context);
1063 $handle = fopen($url, 'r', false, $context);
1066 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
1068 $timeout = (int) floor( $r['timeout'] );
1069 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
1070 stream_set_timeout( $handle, $timeout, $utimeout );
1072 if ( ! $r['blocking'] ) {
1073 stream_set_blocking($handle, 0);
1075 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1078 $strResponse = stream_get_contents($handle);
1079 $meta = stream_get_meta_data($handle);
1083 $processedHeaders = array();
1084 if ( isset( $meta['wrapper_data']['headers'] ) )
1085 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
1087 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
1089 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1090 $strResponse = WP_Http::chunkTransferDecode($strResponse);
1092 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1093 $strResponse = WP_Http_Encoding::decompress( $strResponse );
1095 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
1099 * Whether this class can be used for retrieving an URL.
1105 * @return boolean False means this class can not be used, true means it can.
1107 function test($args = array()) {
1108 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
1111 if ( version_compare(PHP_VERSION, '5.0', '<') )
1114 //HTTPS via Proxy was added in 5.1.0
1115 $is_ssl = isset($args['ssl']) && $args['ssl'];
1116 if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) {
1117 $proxy = new WP_HTTP_Proxy();
1119 * No URL check, as its not currently passed to the ::test() function
1120 * In the case where a Proxy is in use, Just bypass this transport for HTTPS.
1122 if ( $proxy->is_enabled() )
1126 return apply_filters('use_streams_transport', true, $args);
1131 * HTTP request method uses HTTP extension to retrieve the url.
1133 * Requires the HTTP extension to be installed. This would be the preferred transport since it can
1134 * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+
1135 * is being used, it doesn't mean that the HTTP extension will be enabled.
1137 * @package WordPress
1141 class WP_Http_ExtHttp {
1143 * Send a HTTP request to a URI using HTTP extension.
1145 * Does not support non-blocking.
1150 * @param string $url
1151 * @param str|array $args Optional. Override the defaults.
1152 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1154 function request($url, $args = array()) {
1156 'method' => 'GET', 'timeout' => 5,
1157 'redirection' => 5, 'httpversion' => '1.0',
1159 'headers' => array(), 'body' => null, 'cookies' => array()
1162 $r = wp_parse_args( $args, $defaults );
1164 if ( isset($r['headers']['User-Agent']) ) {
1165 $r['user-agent'] = $r['headers']['User-Agent'];
1166 unset($r['headers']['User-Agent']);
1167 } else if ( isset($r['headers']['user-agent']) ) {
1168 $r['user-agent'] = $r['headers']['user-agent'];
1169 unset($r['headers']['user-agent']);
1172 // Construct Cookie: header if any cookies are set
1173 WP_Http::buildCookieHeader( $r );
1175 switch ( $r['method'] ) {
1177 $r['method'] = HTTP_METH_POST;
1180 $r['method'] = HTTP_METH_HEAD;
1183 $r['method'] = HTTP_METH_PUT;
1187 $r['method'] = HTTP_METH_GET;
1190 $arrURL = parse_url($url);
1192 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
1193 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1195 $is_local = isset($args['local']) && $args['local'];
1196 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1198 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1199 elseif ( ! $is_local )
1200 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1202 $r['timeout'] = (int) ceil( $r['timeout'] );
1205 'timeout' => $r['timeout'],
1206 'connecttimeout' => $r['timeout'],
1207 'redirect' => $r['redirection'],
1208 'useragent' => $r['user-agent'],
1209 'headers' => $r['headers'],
1211 'verifypeer' => $ssl_verify,
1212 'verifyhost' => $ssl_verify
1216 if ( HTTP_METH_HEAD == $r['method'] )
1217 $options['redirect'] = 0; // Assumption: Docs seem to suggest that this means do not follow. Untested.
1219 // The HTTP extensions offers really easy proxy support.
1220 $proxy = new WP_HTTP_Proxy();
1222 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1223 $options['proxyhost'] = $proxy->host();
1224 $options['proxyport'] = $proxy->port();
1225 $options['proxytype'] = HTTP_PROXY_HTTP;
1227 if ( $proxy->use_authentication() ) {
1228 $options['proxyauth'] = $proxy->authentication();
1229 $options['proxyauthtype'] = HTTP_AUTH_ANY;
1233 if ( !WP_DEBUG ) //Emits warning level notices for max redirects and timeouts
1234 $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
1236 $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts
1238 // Error may still be set, Response may return headers or partial document, and error
1239 // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
1240 if ( false === $strResponse || ! empty($info['error']) )
1241 return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
1243 if ( ! $r['blocking'] )
1244 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1246 $headers_body = WP_HTTP::processResponse($strResponse);
1247 $theHeaders = $headers_body['headers'];
1248 $theBody = $headers_body['body'];
1249 unset($headers_body);
1251 $theHeaders = WP_Http::processHeaders($theHeaders);
1253 if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) {
1255 $theBody = @http_chunked_decode($theBody);
1257 $theBody = http_chunked_decode($theBody);
1260 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1261 $theBody = http_inflate( $theBody );
1263 $theResponse = array();
1264 $theResponse['code'] = $info['response_code'];
1265 $theResponse['message'] = get_status_header_desc($info['response_code']);
1267 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
1271 * Whether this class can be used for retrieving an URL.
1276 * @return boolean False means this class can not be used, true means it can.
1278 function test($args = array()) {
1279 return apply_filters('use_http_extension_transport', function_exists('http_request'), $args );
1284 * HTTP request method uses Curl extension to retrieve the url.
1286 * Requires the Curl extension to be installed.
1288 * @package WordPress
1292 class WP_Http_Curl {
1295 * Send a HTTP request to a URI using cURL extension.
1300 * @param string $url
1301 * @param str|array $args Optional. Override the defaults.
1302 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1304 function request($url, $args = array()) {
1306 'method' => 'GET', 'timeout' => 5,
1307 'redirection' => 5, 'httpversion' => '1.0',
1309 'headers' => array(), 'body' => null, 'cookies' => array()
1312 $r = wp_parse_args( $args, $defaults );
1314 if ( isset($r['headers']['User-Agent']) ) {
1315 $r['user-agent'] = $r['headers']['User-Agent'];
1316 unset($r['headers']['User-Agent']);
1317 } else if ( isset($r['headers']['user-agent']) ) {
1318 $r['user-agent'] = $r['headers']['user-agent'];
1319 unset($r['headers']['user-agent']);
1322 // Construct Cookie: header if any cookies are set.
1323 WP_Http::buildCookieHeader( $r );
1325 $handle = curl_init();
1327 // cURL offers really easy proxy support.
1328 $proxy = new WP_HTTP_Proxy();
1330 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1332 $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
1335 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1336 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1337 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1339 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() );
1342 if ( $proxy->use_authentication() ) {
1344 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1346 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1350 $is_local = isset($args['local']) && $args['local'];
1351 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1353 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1354 elseif ( ! $is_local )
1355 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1358 // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
1359 // a value of 0 will allow an ulimited timeout.
1360 $timeout = (int) ceil( $r['timeout'] );
1361 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1362 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1364 curl_setopt( $handle, CURLOPT_URL, $url);
1365 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1366 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify );
1367 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1368 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1369 curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1371 switch ( $r['method'] ) {
1373 curl_setopt( $handle, CURLOPT_NOBODY, true );
1376 curl_setopt( $handle, CURLOPT_POST, true );
1377 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1380 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1381 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1385 if ( true === $r['blocking'] )
1386 curl_setopt( $handle, CURLOPT_HEADER, true );
1388 curl_setopt( $handle, CURLOPT_HEADER, false );
1390 // The option doesn't work with safe mode or when open_basedir is set.
1391 // Disable HEAD when making HEAD requests.
1392 if ( !ini_get('safe_mode') && !ini_get('open_basedir') && 'HEAD' != $r['method'] )
1393 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1395 if ( !empty( $r['headers'] ) ) {
1396 // cURL expects full header strings in each element
1398 foreach ( $r['headers'] as $name => $value ) {
1399 $headers[] = "{$name}: $value";
1401 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1404 if ( $r['httpversion'] == '1.0' )
1405 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1407 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1409 // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1410 // themselves... Although, it is somewhat pointless without some reference.
1411 do_action_ref_array( 'http_api_curl', array(&$handle) );
1413 // We don't need to return the body, so don't. Just execute request and return.
1414 if ( ! $r['blocking'] ) {
1415 curl_exec( $handle );
1416 curl_close( $handle );
1417 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1420 $theResponse = curl_exec( $handle );
1422 if ( !empty($theResponse) ) {
1423 $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
1424 $theHeaders = trim( substr($theResponse, 0, $headerLength) );
1425 if ( strlen($theResponse) > $headerLength )
1426 $theBody = substr( $theResponse, $headerLength );
1429 if ( false !== strpos($theHeaders, "\r\n\r\n") ) {
1430 $headerParts = explode("\r\n\r\n", $theHeaders);
1431 $theHeaders = $headerParts[ count($headerParts) -1 ];
1433 $theHeaders = WP_Http::processHeaders($theHeaders);
1435 if ( $curl_error = curl_error($handle) )
1436 return new WP_Error('http_request_failed', $curl_error);
1437 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1438 return new WP_Error('http_request_failed', __('Too many redirects.'));
1440 $theHeaders = array( 'headers' => array(), 'cookies' => array() );
1444 $response = array();
1445 $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1446 $response['message'] = get_status_header_desc($response['code']);
1448 curl_close( $handle );
1450 // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
1451 if ( !empty($theHeaders['headers']['location']) && (ini_get('safe_mode') || ini_get('open_basedir')) ) {
1452 if ( $r['redirection']-- > 0 ) {
1453 return $this->request($theHeaders['headers']['location'], $r);
1455 return new WP_Error('http_request_failed', __('Too many redirects.'));
1459 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1460 $theBody = WP_Http_Encoding::decompress( $theBody );
1462 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']);
1466 * Whether this class can be used for retrieving an URL.
1471 * @return boolean False means this class can not be used, true means it can.
1473 function test($args = array()) {
1474 if ( function_exists('curl_init') && function_exists('curl_exec') )
1475 return apply_filters('use_curl_transport', true, $args);
1482 * Adds Proxy support to the WordPress HTTP API.
1484 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1485 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1488 * Please note that only BASIC authentication is supported by most transports.
1489 * cURL and the PHP HTTP Extension MAY support more methods (such as NTLM authentication) depending on your environment.
1491 * The constants are as follows:
1493 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1494 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1495 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1496 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1497 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1498 * You do not need to have localhost and the blog host in this list, because they will not be passed
1499 * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1502 * An example can be as seen below.
1504 * define('WP_PROXY_HOST', '192.168.84.101');
1505 * define('WP_PROXY_PORT', '8080');
1506 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1509 * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1510 * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1513 class WP_HTTP_Proxy {
1516 * Whether proxy connection should be used.
1519 * @use WP_PROXY_HOST
1520 * @use WP_PROXY_PORT
1524 function is_enabled() {
1525 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1529 * Whether authentication should be used.
1532 * @use WP_PROXY_USERNAME
1533 * @use WP_PROXY_PASSWORD
1537 function use_authentication() {
1538 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1542 * Retrieve the host for the proxy server.
1549 if ( defined('WP_PROXY_HOST') )
1550 return WP_PROXY_HOST;
1556 * Retrieve the port for the proxy server.
1563 if ( defined('WP_PROXY_PORT') )
1564 return WP_PROXY_PORT;
1570 * Retrieve the username for proxy authentication.
1576 function username() {
1577 if ( defined('WP_PROXY_USERNAME') )
1578 return WP_PROXY_USERNAME;
1584 * Retrieve the password for proxy authentication.
1590 function password() {
1591 if ( defined('WP_PROXY_PASSWORD') )
1592 return WP_PROXY_PASSWORD;
1598 * Retrieve authentication string for proxy authentication.
1604 function authentication() {
1605 return $this->username() . ':' . $this->password();
1609 * Retrieve header string for proxy authentication.
1615 function authentication_header() {
1616 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1620 * Whether URL should be sent through the proxy server.
1622 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1623 * some proxies can not handle this. We also have the constant available for defining other
1624 * hosts that won't be sent through the proxy.
1626 * @uses WP_PROXY_BYPASS_HOSTS
1629 * @param string $uri URI to check.
1630 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1632 function send_through_proxy( $uri ) {
1633 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1634 // This will be displayed on blogs, which is not reasonable.
1635 $check = @parse_url($uri);
1637 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1638 if ( $check === false )
1641 $home = parse_url( get_option('siteurl') );
1643 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1646 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1649 static $bypass_hosts;
1650 static $wildcard_regex = false;
1651 if ( null == $bypass_hosts ) {
1652 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1654 if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1655 $wildcard_regex = array();
1656 foreach ( $bypass_hosts as $host )
1657 $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
1658 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1662 if ( !empty($wildcard_regex) )
1663 return !preg_match($wildcard_regex, $check['host']);
1665 return !in_array( $check['host'], $bypass_hosts );
1669 * Internal representation of a single cookie.
1671 * Returned cookies are represented using this class, and when cookies are set, if they are not
1672 * already a WP_Http_Cookie() object, then they are turned into one.
1674 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1675 * names. Need to switch to use underscores instead for the methods.
1677 * @package WordPress
1681 class WP_Http_Cookie {
1700 * When the cookie expires.
1724 * PHP4 style Constructor - Calls PHP5 Style Constructor.
1728 * @param string|array $data Raw cookie data.
1730 function WP_Http_Cookie( $data ) {
1731 $this->__construct( $data );
1735 * Sets up this cookie object.
1737 * The parameter $data should be either an associative array containing the indices names below
1738 * or a header string detailing it.
1740 * If it's an array, it should include the following elements:
1743 * <li>Value - should NOT be urlencoded already.</li>
1744 * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1745 * <li>Path (optional)</li>
1746 * <li>Domain (optional)</li>
1752 * @param string|array $data Raw cookie data.
1754 function __construct( $data ) {
1755 if ( is_string( $data ) ) {
1756 // Assume it's a header string direct from a previous request
1757 $pairs = explode( ';', $data );
1759 // Special handling for first pair; name=value. Also be careful of "=" in value
1760 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1761 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1762 $this->name = $name;
1763 $this->value = urldecode( $value );
1764 array_shift( $pairs ); //Removes name=value from items.
1766 // Set everything else as a property
1767 foreach ( $pairs as $pair ) {
1768 $pair = rtrim($pair);
1769 if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1772 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1773 $key = strtolower( trim( $key ) );
1774 if ( 'expires' == $key )
1775 $val = strtotime( $val );
1779 if ( !isset( $data['name'] ) )
1782 // Set properties based directly on parameters
1783 $this->name = $data['name'];
1784 $this->value = isset( $data['value'] ) ? $data['value'] : '';
1785 $this->path = isset( $data['path'] ) ? $data['path'] : '';
1786 $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1788 if ( isset( $data['expires'] ) )
1789 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1791 $this->expires = null;
1796 * Confirms that it's OK to send this cookie to the URL checked against.
1798 * Decision is based on RFC 2109/2965, so look there for details on validity.
1803 * @param string $url URL you intend to send this cookie to
1804 * @return boolean TRUE if allowed, FALSE otherwise.
1806 function test( $url ) {
1807 // Expires - if expired then nothing else matters
1808 if ( time() > $this->expires )
1811 // Get details on the URL we're thinking about sending to
1812 $url = parse_url( $url );
1813 $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1814 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1816 // Values to use for comparison against the URL
1817 $path = isset( $this->path ) ? $this->path : '/';
1818 $port = isset( $this->port ) ? $this->port : 80;
1819 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1820 if ( false === stripos( $domain, '.' ) )
1821 $domain .= '.local';
1823 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1824 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1825 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1828 // Port - supports "port-lists" in the format: "80,8000,8080"
1829 if ( !in_array( $url['port'], explode( ',', $port) ) )
1832 // Path - request path must start with path restriction
1833 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1840 * Convert cookie name and value back to header string.
1845 * @return string Header encoded cookie name and value.
1847 function getHeaderValue() {
1848 if ( empty( $this->name ) || empty( $this->value ) )
1851 return $this->name . '=' . urlencode( $this->value );
1855 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1862 function getFullHeader() {
1863 return 'Cookie: ' . $this->getHeaderValue();
1868 * Implementation for deflate and gzip transfer encodings.
1870 * Includes RFC 1950, RFC 1951, and RFC 1952.
1873 * @package WordPress
1876 class WP_Http_Encoding {
1879 * Compress raw string using the deflate format.
1881 * Supports the RFC 1951 standard.
1885 * @param string $raw String to compress.
1886 * @param int $level Optional, default is 9. Compression level, 9 is highest.
1887 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1888 * @return string|bool False on failure.
1890 function compress( $raw, $level = 9, $supports = null ) {
1891 return gzdeflate( $raw, $level );
1895 * Decompression of deflated string.
1897 * Will attempt to decompress using the RFC 1950 standard, and if that fails
1898 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1899 * 1952 standard gzip decode will be attempted. If all fail, then the
1900 * original compressed string will be returned.
1904 * @param string $compressed String to decompress.
1905 * @param int $length The optional length of the compressed data.
1906 * @return string|bool False on failure.
1908 function decompress( $compressed, $length = null ) {
1910 if ( empty($compressed) )
1913 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
1914 return $decompressed;
1916 if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
1917 return $decompressed;
1919 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
1920 return $decompressed;
1922 if ( function_exists('gzdecode') ) {
1923 $decompressed = @gzdecode( $compressed );
1925 if ( false !== $decompressed )
1926 return $decompressed;
1933 * Decompression of deflated string while staying compatible with the majority of servers.
1935 * Certain Servers will return deflated data with headers which PHP's gziniflate()
1936 * function cannot handle out of the box. The following function lifted from
1937 * http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate
1938 * the various return forms used.
1941 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
1943 * @param string $gzData String to decompress.
1944 * @return string|bool False on failure.
1946 function compatible_gzinflate($gzData) {
1947 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
1949 $flg = ord( substr($gzData, 3, 1) );
1952 list($xlen) = unpack('v', substr($gzData, $i, 2) );
1953 $i = $i + 2 + $xlen;
1956 $i = strpos($gzData, "\0", $i) + 1;
1958 $i = strpos($gzData, "\0", $i) + 1;
1962 return gzinflate( substr($gzData, $i, -8) );
1969 * What encoding types to accept and their priority values.
1973 * @return string Types of encoding to accept.
1975 function accept_encoding() {
1977 if ( function_exists( 'gzinflate' ) )
1978 $type[] = 'deflate;q=1.0';
1980 if ( function_exists( 'gzuncompress' ) )
1981 $type[] = 'compress;q=0.5';
1983 if ( function_exists( 'gzdecode' ) )
1984 $type[] = 'gzip;q=0.5';
1986 return implode(', ', $type);
1990 * What enconding the content used when it was compressed to send in the headers.
1994 * @return string Content-Encoding string to send in the header.
1996 function content_encoding() {
2001 * Whether the content be decoded based on the headers.
2005 * @param array|string $headers All of the available headers.
2008 function should_decode($headers) {
2009 if ( is_array( $headers ) ) {
2010 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
2012 } else if ( is_string( $headers ) ) {
2013 return ( stripos($headers, 'content-encoding:') !== false );
2020 * Whether decompression and compression are supported by the PHP version.
2022 * Each function is tested instead of checking for the zlib extension, to
2023 * ensure that the functions all exist in the PHP version and aren't
2030 function is_available() {
2031 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );