3 * Simple and uniform HTTP request API.
5 * Will eventually replace and standardize the WordPress HTTP requests made.
7 * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal
12 * @author Jacob Santos <wordpress@santosj.name>
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 should replace Snoopy
19 * functionality, eventually. There is no available functionality to add HTTP transport
20 * implementations, since most of the HTTP transports are added and available for use.
22 * The exception is that cURL is not available as a transport and lacking an implementation. It will
23 * be added later and should be a patch on the WordPress Trac.
25 * There are no properties, because none are needed and for performance reasons. Some of the
26 * functions are static and while they do have some overhead over functions in PHP4, the purpose is
27 * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword
28 * to the code. It is not as easy to convert a function to a method after enough code uses the old
31 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
33 * <strong>http_transport_get_debug</strong> - gives working, nonblocking, and blocking transports.
35 * <strong>http_transport_post_debug</strong> - gives working, nonblocking, and blocking transports.
44 * PHP4 style Constructor - Calls PHP5 Style Constructor
54 * PHP5 style Constructor - Setup available transport if not available.
56 * PHP4 does not have the 'self' keyword and since WordPress supports PHP4,
57 * the class needs to be used for the static call.
59 * The transport are setup to save time. This should only be called once, so
60 * the overhead should be fine.
65 function __construct() {
66 WP_Http::_getTransport();
67 WP_Http::_postTransport();
71 * Tests the WordPress HTTP objects for an object to use and returns it.
73 * Tests all of the objects and returns the object that passes. Also caches
74 * that object to be used later.
76 * The order for the GET/HEAD requests are Streams, HTTP Extension, Fopen,
77 * and finally Fsockopen. fsockopen() is used last, because it has the most
78 * overhead in its implementation. There isn't any real way around it, since
79 * redirects have to be supported, much the same way the other transports
80 * also handle redirects.
82 * There are currently issues with "localhost" not resolving correctly with
83 * DNS. This may cause an error "failed to open stream: A connection attempt
84 * failed because the connected party did not properly respond after a
85 * period of time, or established connection failed because connected host
86 * has failed to respond."
91 * @param array $args Request args, default us an empty array
92 * @return object|null Null if no transports are available, HTTP transport object.
94 function &_getTransport( $args = array() ) {
95 static $working_transport, $blocking_transport, $nonblocking_transport;
97 if ( is_null($working_transport) ) {
98 if ( true === WP_Http_ExtHttp::test($args) ) {
99 $working_transport['exthttp'] = new WP_Http_ExtHttp();
100 $blocking_transport[] = &$working_transport['exthttp'];
101 } else if ( true === WP_Http_Curl::test($args) ) {
102 $working_transport['curl'] = new WP_Http_Curl();
103 $blocking_transport[] = &$working_transport['curl'];
104 } else if ( true === WP_Http_Streams::test($args) ) {
105 $working_transport['streams'] = new WP_Http_Streams();
106 $blocking_transport[] = &$working_transport['streams'];
107 } else if ( true === WP_Http_Fopen::test($args) ) {
108 $working_transport['fopen'] = new WP_Http_Fopen();
109 $blocking_transport[] = &$working_transport['fopen'];
110 } else if ( true === WP_Http_Fsockopen::test($args) ) {
111 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
112 $blocking_transport[] = &$working_transport['fsockopen'];
115 foreach ( array('curl', 'streams', 'fopen', 'fsockopen', 'exthttp') as $transport ) {
116 if ( isset($working_transport[$transport]) )
117 $nonblocking_transport[] = &$working_transport[$transport];
121 do_action( 'http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport );
123 if ( isset($args['blocking']) && !$args['blocking'] )
124 return $nonblocking_transport;
126 return $blocking_transport;
130 * Tests the WordPress HTTP objects for an object to use and returns it.
132 * Tests all of the objects and returns the object that passes. Also caches
133 * that object to be used later. This is for posting content to a URL and
134 * is used when there is a body. The plain Fopen Transport can not be used
135 * to send content, but the streams transport can. This is a limitation that
136 * is addressed here, by just not including that transport.
141 * @param array $args Request args, default us an empty array
142 * @return object|null Null if no transports are available, HTTP transport object.
144 function &_postTransport( $args = array() ) {
145 static $working_transport, $blocking_transport, $nonblocking_transport;
147 if ( is_null($working_transport) ) {
148 if ( true === WP_Http_ExtHttp::test($args) ) {
149 $working_transport['exthttp'] = new WP_Http_ExtHttp();
150 $blocking_transport[] = &$working_transport['exthttp'];
151 } else if ( true === WP_Http_Curl::test($args) ) {
152 $working_transport['curl'] = new WP_Http_Curl();
153 $blocking_transport[] = &$working_transport['curl'];
154 } else if ( true === WP_Http_Streams::test($args) ) {
155 $working_transport['streams'] = new WP_Http_Streams();
156 $blocking_transport[] = &$working_transport['streams'];
157 } else if ( true === WP_Http_Fsockopen::test($args) ) {
158 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
159 $blocking_transport[] = &$working_transport['fsockopen'];
162 foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) {
163 if ( isset($working_transport[$transport]) )
164 $nonblocking_transport[] = &$working_transport[$transport];
168 do_action( 'http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport );
170 if ( isset($args['blocking']) && !$args['blocking'] )
171 return $nonblocking_transport;
173 return $blocking_transport;
177 * Send a HTTP request to a URI.
179 * The body and headers are part of the arguments. The 'body' argument is for the body and will
180 * accept either a string or an array. The 'headers' argument should be an array, but a string
181 * is acceptable. If the 'body' argument is an array, then it will automatically be escaped
182 * using http_build_query().
184 * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
185 * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send
186 * headers. Other protocols are unsupported and most likely will fail.
188 * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
191 * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
192 * others, but should not be assumed. The 'timeout' is used to sent how long the connection
193 * should stay open before failing when no response. 'redirection' is used to track how many
194 * redirects were taken and used to sent the amount for other transports, but not all transports
195 * accept setting that value.
197 * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
198 * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The
199 * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is
200 * 'WordPress/WP_Version', where WP_Version is the value from $wp_version.
202 * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP
203 * while it performs the request or continue regardless. Actually, that isn't entirely correct.
204 * Blocking mode really just means whether the fread should just pull what it can whenever it
205 * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading
206 * the entire content. It doesn't actually always mean that PHP will continue going after making
211 * @todo Refactor this code. The code in this method extends the scope of its original purpose
212 * and should be refactored to allow for cleaner abstraction and reduce duplication of the
213 * code. One suggestion is to create a class specifically for the arguments, however
214 * preliminary refactoring to this affect has affect more than just the scope of the
215 * arguments. Something to ponder at least.
217 * @param string $url URI resource.
218 * @param str|array $args Optional. Override the defaults.
219 * @return array containing 'headers', 'body', 'response', 'cookies'
221 function request( $url, $args = array() ) {
226 'timeout' => apply_filters( 'http_request_timeout', 5),
227 'redirection' => apply_filters( 'http_request_redirection_count', 5),
228 'httpversion' => apply_filters( 'http_request_version', '1.0'),
229 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
231 'headers' => array(),
232 'cookies' => array(),
235 'decompress' => true,
239 $r = wp_parse_args( $args, $defaults );
240 $r = apply_filters( 'http_request_args', $r, $url );
242 // Allow plugins to short-circuit the request
243 $pre = apply_filters( 'pre_http_request', false, $r, $url );
244 if ( false !== $pre )
247 $arrURL = parse_url($url);
249 if ( $this->block_request( $url ) )
250 return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.'));
252 // Determine if this is a https call and pass that on to the transport functions
253 // so that we can blacklist the transports that do not support ssl verification
254 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
256 // Determine if this request is to OUR install of WordPress
257 $homeURL = parse_url(get_bloginfo('url'));
258 $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
261 if ( is_null( $r['headers'] ) )
262 $r['headers'] = array();
264 if ( ! is_array($r['headers']) ) {
265 $processedHeaders = WP_Http::processHeaders($r['headers']);
266 $r['headers'] = $processedHeaders['headers'];
269 if ( isset($r['headers']['User-Agent']) ) {
270 $r['user-agent'] = $r['headers']['User-Agent'];
271 unset($r['headers']['User-Agent']);
274 if ( isset($r['headers']['user-agent']) ) {
275 $r['user-agent'] = $r['headers']['user-agent'];
276 unset($r['headers']['user-agent']);
279 // Construct Cookie: header if any cookies are set
280 WP_Http::buildCookieHeader( $r );
282 if ( WP_Http_Encoding::is_available() )
283 $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding();
285 if ( empty($r['body']) ) {
286 // Some servers fail when sending content without the content-length header being set.
287 // Also, to fix another bug, we only send when doing POST and PUT and the content-length
288 // header isn't already set.
289 if( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset($r['headers']['Content-Length']) )
290 $r['headers']['Content-Length'] = 0;
292 // The method is ambiguous, because we aren't talking about HTTP methods, the "get" in
293 // this case is simply that we aren't sending any bodies and to get the transports that
294 // don't support sending bodies along with those which do.
295 $transports = WP_Http::_getTransport($r);
297 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
298 if ( ! version_compare(phpversion(), '5.1.2', '>=') )
299 $r['body'] = _http_build_query($r['body'], null, '&');
301 $r['body'] = http_build_query($r['body'], null, '&');
302 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset');
303 $r['headers']['Content-Length'] = strlen($r['body']);
306 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
307 $r['headers']['Content-Length'] = strlen($r['body']);
309 // The method is ambiguous, because we aren't talking about HTTP methods, the "post" in
310 // this case is simply that we are sending HTTP body and to get the transports that do
311 // support sending the body. Not all do, depending on the limitations of the PHP core
313 $transports = WP_Http::_postTransport($r);
316 do_action( 'http_api_debug', $transports, 'transports_list' );
318 $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
319 foreach ( (array) $transports as $transport ) {
320 $response = $transport->request($url, $r);
322 do_action( 'http_api_debug', $response, 'response', get_class($transport) );
324 if ( ! is_wp_error($response) )
325 return apply_filters( 'http_response', $response, $r, $url );
332 * Uses the POST HTTP method.
334 * Used for sending data that is expected to be in the body.
339 * @param string $url URI resource.
340 * @param str|array $args Optional. Override the defaults.
343 function post($url, $args = array()) {
344 $defaults = array('method' => 'POST');
345 $r = wp_parse_args( $args, $defaults );
346 return $this->request($url, $r);
350 * Uses the GET HTTP method.
352 * Used for sending data that is expected to be in the body.
357 * @param string $url URI resource.
358 * @param str|array $args Optional. Override the defaults.
361 function get($url, $args = array()) {
362 $defaults = array('method' => 'GET');
363 $r = wp_parse_args( $args, $defaults );
364 return $this->request($url, $r);
368 * Uses the HEAD HTTP method.
370 * Used for sending data that is expected to be in the body.
375 * @param string $url URI resource.
376 * @param str|array $args Optional. Override the defaults.
379 function head($url, $args = array()) {
380 $defaults = array('method' => 'HEAD');
381 $r = wp_parse_args( $args, $defaults );
382 return $this->request($url, $r);
386 * Parses the responses and splits the parts into headers and body.
392 * @param string $strResponse The full response string
393 * @return array Array with 'headers' and 'body' keys.
395 function processResponse($strResponse) {
396 list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2);
397 return array('headers' => $theHeaders, 'body' => $theBody);
401 * Transform header string into an array.
403 * If an array is given then it is assumed to be raw header data with numeric keys with the
404 * headers as the values. No headers must be passed that were already processed.
410 * @param string|array $headers
411 * @return array Processed string headers. If duplicate headers are encountered,
412 * Then a numbered array is returned as the value of that header-key.
414 function processHeaders($headers) {
415 // split headers, one per array element
416 if ( is_string($headers) ) {
417 // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
418 $headers = str_replace("\r\n", "\n", $headers);
419 // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
420 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
421 // create the headers array
422 $headers = explode("\n", $headers);
425 $response = array('code' => 0, 'message' => '');
428 $newheaders = array();
429 foreach ( $headers as $tempheader ) {
430 if ( empty($tempheader) )
433 if ( false === strpos($tempheader, ':') ) {
434 list( , $iResponseCode, $strResponseMsg) = explode(' ', $tempheader, 3);
435 $response['code'] = $iResponseCode;
436 $response['message'] = $strResponseMsg;
440 list($key, $value) = explode(':', $tempheader, 2);
442 if ( !empty( $value ) ) {
443 $key = strtolower( $key );
444 if ( isset( $newheaders[$key] ) ) {
445 $newheaders[$key] = array( $newheaders[$key], trim( $value ) );
447 $newheaders[$key] = trim( $value );
449 if ( 'set-cookie' == strtolower( $key ) )
450 $cookies[] = new WP_Http_Cookie( $value );
454 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
458 * Takes the arguments for a ::request() and checks for the cookie array.
460 * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
461 * into strings and added to the Cookie: header (within the arguments array). Edits the array by
468 * @param array $r Full array of args passed into ::request()
470 function buildCookieHeader( &$r ) {
471 if ( ! empty($r['cookies']) ) {
472 $cookies_header = '';
473 foreach ( (array) $r['cookies'] as $cookie ) {
474 $cookies_header .= $cookie->getHeaderValue() . '; ';
476 $cookies_header = substr( $cookies_header, 0, -2 );
477 $r['headers']['cookie'] = $cookies_header;
482 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
484 * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
485 * returning footer headers. Shouldn't be too difficult to support it though.
487 * @todo Add support for footer chunked headers.
492 * @param string $body Body content
493 * @return string Chunked decoded body on success or raw body on failure.
495 function chunkTransferDecode($body) {
496 $body = str_replace(array("\r\n", "\r"), "\n", $body);
497 // The body is not chunked encoding or is malformed.
498 if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
502 //$parsedHeaders = array(); Unsupported
505 $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
508 if ( empty( $match[1] ) )
511 $length = hexdec( $match[1] );
512 $chunkLength = strlen( $match[0] );
514 $strBody = substr($body, $chunkLength, $length);
515 $parsedBody .= $strBody;
517 $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
519 if ( "0" == trim($body) )
520 return $parsedBody; // Ignore footer headers.
528 * Block requests through the proxy.
530 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
531 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
533 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL in your wp-config.php file
534 * and this will only allow localhost and your blog to make requests. The constant
535 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
536 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
539 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
541 * @param string $uri URI of url.
542 * @return bool True to block, false to allow.
544 function block_request($uri) {
545 // We don't need to block requests, because nothing is blocked.
546 if ( ! defined('WP_HTTP_BLOCK_EXTERNAL') || ( defined('WP_HTTP_BLOCK_EXTERNAL') && WP_HTTP_BLOCK_EXTERNAL == false ) )
549 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
550 // This will be displayed on blogs, which is not reasonable.
551 $check = @parse_url($uri);
553 /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
555 * This isn't very security sound. There are instances where a hacker might attempt
556 * to bypass the proxy and this check. However, the reason for this behavior is that
557 * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
558 * the default unsecure nature of the HTTP request.
560 if ( $check === false )
563 $home = parse_url( get_option('siteurl') );
565 // Don't block requests back to ourselves by default
566 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
567 return apply_filters('block_local_requests', false);
569 if ( !defined('WP_ACCESSIBLE_HOSTS') )
572 static $accessible_hosts;
573 if ( null == $accessible_hosts )
574 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
576 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
581 * HTTP request method uses fsockopen function to retrieve the url.
583 * This would be the preferred method, but the fsockopen implementation has the most overhead of all
584 * the HTTP transport implementations.
590 class WP_Http_Fsockopen {
592 * Send a HTTP request to a URI using fsockopen().
594 * Does not support non-blocking mode.
596 * @see WP_Http::request For default options descriptions.
600 * @param string $url URI resource.
601 * @param str|array $args Optional. Override the defaults.
602 * @return array 'headers', 'body', 'cookies' and 'response' keys.
604 function request($url, $args = array()) {
606 'method' => 'GET', 'timeout' => 5,
607 'redirection' => 5, 'httpversion' => '1.0',
609 'headers' => array(), 'body' => null, 'cookies' => array()
612 $r = wp_parse_args( $args, $defaults );
614 if ( isset($r['headers']['User-Agent']) ) {
615 $r['user-agent'] = $r['headers']['User-Agent'];
616 unset($r['headers']['User-Agent']);
617 } else if( isset($r['headers']['user-agent']) ) {
618 $r['user-agent'] = $r['headers']['user-agent'];
619 unset($r['headers']['user-agent']);
622 // Construct Cookie: header if any cookies are set
623 WP_Http::buildCookieHeader( $r );
625 $iError = null; // Store error number
626 $strError = null; // Store error string
628 $arrURL = parse_url($url);
630 $fsockopen_host = $arrURL['host'];
632 $secure_transport = false;
634 if ( ! isset( $arrURL['port'] ) ) {
635 if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
636 $fsockopen_host = "ssl://$fsockopen_host";
637 $arrURL['port'] = 443;
638 $secure_transport = true;
640 $arrURL['port'] = 80;
644 //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
645 // which fails when the server is not setup for it. For compatibility, always connect to the IPv4 address.
646 if ( 'localhost' == strtolower($fsockopen_host) )
647 $fsockopen_host = '127.0.0.1';
649 // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
650 // ignored and should be ignored.
651 if ( true === $secure_transport )
652 $error_reporting = error_reporting(0);
654 $startDelay = time();
656 $proxy = new WP_HTTP_Proxy();
659 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
660 $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
662 $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
664 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
665 $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
667 $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
672 // If the delay is greater than the timeout then fsockopen should't be used, because it will
673 // cause a long delay.
674 $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
675 if ( true === $elapseDelay )
676 add_option( 'disable_fsockopen', $endDelay, null, true );
678 if ( false === $handle )
679 return new WP_Error('http_request_failed', $iError . ': ' . $strError);
681 $timeout = (int) floor( $r['timeout'] );
682 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
683 stream_set_timeout( $handle, $timeout, $utimeout );
685 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
688 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
690 if ( empty($requestPath) )
693 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
695 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
696 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
698 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
700 if ( isset($r['user-agent']) )
701 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
703 if ( is_array($r['headers']) ) {
704 foreach ( (array) $r['headers'] as $header => $headerValue )
705 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
707 $strHeaders .= $r['headers'];
710 if ( $proxy->use_authentication() )
711 $strHeaders .= $proxy->authentication_header() . "\r\n";
713 $strHeaders .= "\r\n";
715 if ( ! is_null($r['body']) )
716 $strHeaders .= $r['body'];
718 fwrite($handle, $strHeaders);
720 if ( ! $r['blocking'] ) {
722 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
726 while ( ! feof($handle) )
727 $strResponse .= fread($handle, 4096);
731 if ( true === $secure_transport )
732 error_reporting($error_reporting);
734 $process = WP_Http::processResponse($strResponse);
735 $arrHeaders = WP_Http::processHeaders($process['headers']);
737 // Is the response code within the 400 range?
738 if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 )
739 return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']);
741 // If location is found, then assume redirect and redirect to location.
742 if ( isset($arrHeaders['headers']['location']) ) {
743 if ( $r['redirection']-- > 0 ) {
744 return $this->request($arrHeaders['headers']['location'], $r);
746 return new WP_Error('http_request_failed', __('Too many redirects.'));
750 // If the body was chunk encoded, then decode it.
751 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
752 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
754 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
755 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
757 return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']);
761 * Whether this class can be used for retrieving an URL.
765 * @return boolean False means this class can not be used, true means it can.
767 function test( $args = array() ) {
768 if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
771 $is_ssl = isset($args['ssl']) && $args['ssl'];
773 if ( ! $is_ssl && function_exists( 'fsockopen' ) )
775 elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) )
780 return apply_filters('use_fsockopen_transport', $use, $args);
785 * HTTP request method uses fopen function to retrieve the url.
787 * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support,
788 * but should still be okay, to write the headers, before getting the response. Also requires that
789 * 'allow_url_fopen' to be enabled.
795 class WP_Http_Fopen {
797 * Send a HTTP request to a URI using fopen().
799 * This transport does not support sending of headers and body, therefore should not be used in
800 * the instances, where there is a body and headers.
802 * Notes: Does not support non-blocking mode. Ignores 'redirection' option.
804 * @see WP_Http::retrieve For default options descriptions.
809 * @param string $url URI resource.
810 * @param str|array $args Optional. Override the defaults.
811 * @return array 'headers', 'body', 'cookies' and 'response' keys.
813 function request($url, $args = array()) {
815 'method' => 'GET', 'timeout' => 5,
816 'redirection' => 5, 'httpversion' => '1.0',
818 'headers' => array(), 'body' => null, 'cookies' => array()
821 $r = wp_parse_args( $args, $defaults );
823 $arrURL = parse_url($url);
825 if ( false === $arrURL )
826 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
828 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
829 $url = str_replace($arrURL['scheme'], 'http', $url);
832 $handle = @fopen($url, 'r');
834 $handle = fopen($url, 'r');
837 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
839 $timeout = (int) floor( $r['timeout'] );
840 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
841 stream_set_timeout( $handle, $timeout, $utimeout );
843 if ( ! $r['blocking'] ) {
845 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
849 while ( ! feof($handle) )
850 $strResponse .= fread($handle, 4096);
852 if ( function_exists('stream_get_meta_data') ) {
853 $meta = stream_get_meta_data($handle);
854 $theHeaders = $meta['wrapper_data'];
855 if ( isset( $meta['wrapper_data']['headers'] ) )
856 $theHeaders = $meta['wrapper_data']['headers'];
858 //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper
859 //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php
860 $theHeaders = $http_response_header;
865 $processedHeaders = WP_Http::processHeaders($theHeaders);
867 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
868 $strResponse = WP_Http::chunkTransferDecode($strResponse);
870 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
871 $strResponse = WP_Http_Encoding::decompress( $strResponse );
873 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
877 * Whether this class can be used for retrieving an URL.
881 * @return boolean False means this class can not be used, true means it can.
883 function test($args = array()) {
884 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
889 //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off.
890 $is_ssl = isset($args['ssl']) && $args['ssl'];
892 $is_local = isset($args['local']) && $args['local'];
893 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
894 if ( $is_local && true != apply_filters('https_local_ssl_verify', true) )
896 elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) )
898 elseif ( !$ssl_verify )
904 return apply_filters('use_fopen_transport', $use, $args);
909 * HTTP request method uses Streams to retrieve the url.
911 * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
914 * Second preferred method for getting the URL, for PHP 5.
920 class WP_Http_Streams {
922 * Send a HTTP request to a URI using streams with fopen().
928 * @param str|array $args Optional. Override the defaults.
929 * @return array 'headers', 'body', 'cookies' and 'response' keys.
931 function request($url, $args = array()) {
933 'method' => 'GET', 'timeout' => 5,
934 'redirection' => 5, 'httpversion' => '1.0',
936 'headers' => array(), 'body' => null, 'cookies' => array()
939 $r = wp_parse_args( $args, $defaults );
941 if ( isset($r['headers']['User-Agent']) ) {
942 $r['user-agent'] = $r['headers']['User-Agent'];
943 unset($r['headers']['User-Agent']);
944 } else if( isset($r['headers']['user-agent']) ) {
945 $r['user-agent'] = $r['headers']['user-agent'];
946 unset($r['headers']['user-agent']);
949 // Construct Cookie: header if any cookies are set
950 WP_Http::buildCookieHeader( $r );
952 $arrURL = parse_url($url);
954 if ( false === $arrURL )
955 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
957 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
958 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
960 // Convert Header array to string.
962 if ( is_array( $r['headers'] ) )
963 foreach ( $r['headers'] as $name => $value )
964 $strHeaders .= "{$name}: $value\r\n";
965 else if ( is_string( $r['headers'] ) )
966 $strHeaders = $r['headers'];
968 $is_local = isset($args['local']) && $args['local'];
969 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
971 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
972 elseif ( ! $is_local )
973 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
975 $arrContext = array('http' =>
977 'method' => strtoupper($r['method']),
978 'user_agent' => $r['user-agent'],
979 'max_redirects' => $r['redirection'],
980 'protocol_version' => (float) $r['httpversion'],
981 'header' => $strHeaders,
982 'timeout' => $r['timeout'],
984 'verify_peer' => $ssl_verify,
985 'verify_host' => $ssl_verify
990 $proxy = new WP_HTTP_Proxy();
992 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
993 $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
994 $arrContext['http']['request_fulluri'] = true;
996 // We only support Basic authentication so this will only work if that is what your proxy supports.
997 if ( $proxy->use_authentication() )
998 $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
1001 if ( ! is_null($r['body']) && ! empty($r['body'] ) )
1002 $arrContext['http']['content'] = $r['body'];
1004 $context = stream_context_create($arrContext);
1007 $handle = @fopen($url, 'r', false, $context);
1009 $handle = fopen($url, 'r', false, $context);
1012 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
1014 $timeout = (int) floor( $r['timeout'] );
1015 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
1016 stream_set_timeout( $handle, $timeout, $utimeout );
1018 if ( ! $r['blocking'] ) {
1019 stream_set_blocking($handle, 0);
1021 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1024 $strResponse = stream_get_contents($handle);
1025 $meta = stream_get_meta_data($handle);
1029 $processedHeaders = array();
1030 if ( isset( $meta['wrapper_data']['headers'] ) )
1031 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
1033 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
1035 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1036 $strResponse = WP_Http::chunkTransferDecode($strResponse);
1038 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1039 $strResponse = WP_Http_Encoding::decompress( $strResponse );
1041 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
1045 * Whether this class can be used for retrieving an URL.
1051 * @return boolean False means this class can not be used, true means it can.
1053 function test($args = array()) {
1054 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
1057 if ( version_compare(PHP_VERSION, '5.0', '<') )
1060 //HTTPS via Proxy was added in 5.1.0
1061 $is_ssl = isset($args['ssl']) && $args['ssl'];
1062 if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) {
1063 $proxy = new WP_HTTP_Proxy();
1065 * No URL check, as its not currently passed to the ::test() function
1066 * In the case where a Proxy is in use, Just bypass this transport for HTTPS.
1068 if ( $proxy->is_enabled() )
1072 return apply_filters('use_streams_transport', true, $args);
1077 * HTTP request method uses HTTP extension to retrieve the url.
1079 * Requires the HTTP extension to be installed. This would be the preferred transport since it can
1080 * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+
1081 * is being used, it doesn't mean that the HTTP extension will be enabled.
1083 * @package WordPress
1087 class WP_Http_ExtHTTP {
1089 * Send a HTTP request to a URI using HTTP extension.
1091 * Does not support non-blocking.
1096 * @param string $url
1097 * @param str|array $args Optional. Override the defaults.
1098 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1100 function request($url, $args = array()) {
1102 'method' => 'GET', 'timeout' => 5,
1103 'redirection' => 5, 'httpversion' => '1.0',
1105 'headers' => array(), 'body' => null, 'cookies' => array()
1108 $r = wp_parse_args( $args, $defaults );
1110 if ( isset($r['headers']['User-Agent']) ) {
1111 $r['user-agent'] = $r['headers']['User-Agent'];
1112 unset($r['headers']['User-Agent']);
1113 } else if( isset($r['headers']['user-agent']) ) {
1114 $r['user-agent'] = $r['headers']['user-agent'];
1115 unset($r['headers']['user-agent']);
1118 // Construct Cookie: header if any cookies are set
1119 WP_Http::buildCookieHeader( $r );
1121 switch ( $r['method'] ) {
1123 $r['method'] = HTTP_METH_POST;
1126 $r['method'] = HTTP_METH_HEAD;
1129 $r['method'] = HTTP_METH_PUT;
1133 $r['method'] = HTTP_METH_GET;
1136 $arrURL = parse_url($url);
1138 if ( 'http' != $arrURL['scheme'] || 'https' != $arrURL['scheme'] )
1139 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1141 $is_local = isset($args['local']) && $args['local'];
1142 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1144 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1145 elseif ( ! $is_local )
1146 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1148 $r['timeout'] = (int) ceil( $r['timeout'] );
1151 'timeout' => $r['timeout'],
1152 'connecttimeout' => $r['timeout'],
1153 'redirect' => $r['redirection'],
1154 'useragent' => $r['user-agent'],
1155 'headers' => $r['headers'],
1157 'verifypeer' => $ssl_verify,
1158 'verifyhost' => $ssl_verify
1162 // The HTTP extensions offers really easy proxy support.
1163 $proxy = new WP_HTTP_Proxy();
1165 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1166 $options['proxyhost'] = $proxy->host();
1167 $options['proxyport'] = $proxy->port();
1168 $options['proxytype'] = HTTP_PROXY_HTTP;
1170 if ( $proxy->use_authentication() ) {
1171 $options['proxyauth'] = $proxy->authentication();
1172 $options['proxyauthtype'] = HTTP_AUTH_BASIC;
1176 if ( !WP_DEBUG ) //Emits warning level notices for max redirects and timeouts
1177 $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
1179 $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts
1181 // Error may still be set, Response may return headers or partial document, and error
1182 // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
1183 if ( false === $strResponse || ! empty($info['error']) )
1184 return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
1186 if ( ! $r['blocking'] )
1187 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1189 list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2);
1190 $theHeaders = WP_Http::processHeaders($theHeaders);
1192 if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) {
1194 $theBody = @http_chunked_decode($theBody);
1196 $theBody = http_chunked_decode($theBody);
1199 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1200 $theBody = http_inflate( $theBody );
1202 $theResponse = array();
1203 $theResponse['code'] = $info['response_code'];
1204 $theResponse['message'] = get_status_header_desc($info['response_code']);
1206 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
1210 * Whether this class can be used for retrieving an URL.
1215 * @return boolean False means this class can not be used, true means it can.
1217 function test($args = array()) {
1218 return apply_filters('use_http_extension_transport', function_exists('http_request'), $args );
1223 * HTTP request method uses Curl extension to retrieve the url.
1225 * Requires the Curl extension to be installed.
1227 * @package WordPress
1231 class WP_Http_Curl {
1234 * Send a HTTP request to a URI using cURL extension.
1239 * @param string $url
1240 * @param str|array $args Optional. Override the defaults.
1241 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1243 function request($url, $args = array()) {
1245 'method' => 'GET', 'timeout' => 5,
1246 'redirection' => 5, 'httpversion' => '1.0',
1248 'headers' => array(), 'body' => null, 'cookies' => array()
1251 $r = wp_parse_args( $args, $defaults );
1253 if ( isset($r['headers']['User-Agent']) ) {
1254 $r['user-agent'] = $r['headers']['User-Agent'];
1255 unset($r['headers']['User-Agent']);
1256 } else if( isset($r['headers']['user-agent']) ) {
1257 $r['user-agent'] = $r['headers']['user-agent'];
1258 unset($r['headers']['user-agent']);
1261 // Construct Cookie: header if any cookies are set.
1262 WP_Http::buildCookieHeader( $r );
1264 $handle = curl_init();
1266 // cURL offers really easy proxy support.
1267 $proxy = new WP_HTTP_Proxy();
1269 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1271 $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
1274 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1275 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1276 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1278 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() );
1281 if ( $proxy->use_authentication() ) {
1283 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_BASIC );
1285 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1289 $is_local = isset($args['local']) && $args['local'];
1290 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1292 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1293 elseif ( ! $is_local )
1294 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1297 // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
1298 // a value of 0 will allow an ulimited timeout.
1299 // Use _MS if available.
1300 if ( defined( 'CURLOPT_TIMEOUT_MS' ) ) {
1301 $timeout_ms = (int) ceil( 1000 * $r['timeout'] );
1302 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT_MS, $timeout_ms );
1303 curl_setopt( $handle, CURLOPT_TIMEOUT_MS, $timeout_ms );
1305 $timeout = (int) ceil( $r['timeout'] );
1306 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1307 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1310 curl_setopt( $handle, CURLOPT_URL, $url);
1311 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1312 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify );
1313 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1314 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1315 curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1317 switch ( $r['method'] ) {
1319 curl_setopt( $handle, CURLOPT_NOBODY, true );
1322 curl_setopt( $handle, CURLOPT_POST, true );
1323 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1326 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1327 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1331 if ( true === $r['blocking'] )
1332 curl_setopt( $handle, CURLOPT_HEADER, true );
1334 curl_setopt( $handle, CURLOPT_HEADER, false );
1336 // The option doesn't work with safe mode or when open_basedir is set.
1337 if ( !ini_get('safe_mode') && !ini_get('open_basedir') )
1338 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1340 if ( !empty( $r['headers'] ) ) {
1341 // cURL expects full header strings in each element
1343 foreach ( $r['headers'] as $name => $value ) {
1344 $headers[] = "{$name}: $value";
1346 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1349 if ( $r['httpversion'] == '1.0' )
1350 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1352 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1354 // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1355 // themselves... Although, it is somewhat pointless without some reference.
1356 do_action_ref_array( 'http_api_curl', array(&$handle) );
1358 // We don't need to return the body, so don't. Just execute request and return.
1359 if ( ! $r['blocking'] ) {
1360 curl_exec( $handle );
1361 curl_close( $handle );
1362 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1365 $theResponse = curl_exec( $handle );
1367 if ( !empty($theResponse) ) {
1368 $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
1369 $theHeaders = trim( substr($theResponse, 0, $headerLength) );
1370 $theBody = substr( $theResponse, $headerLength );
1371 if ( false !== strrpos($theHeaders, "\r\n\r\n") ) {
1372 $headerParts = explode("\r\n\r\n", $theHeaders);
1373 $theHeaders = $headerParts[ count($headerParts) -1 ];
1375 $theHeaders = WP_Http::processHeaders($theHeaders);
1377 if ( $curl_error = curl_error($handle) )
1378 return new WP_Error('http_request_failed', $curl_error);
1379 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1380 return new WP_Error('http_request_failed', __('Too many redirects.'));
1382 $theHeaders = array( 'headers' => array(), 'cookies' => array() );
1386 $response = array();
1387 $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1388 $response['message'] = get_status_header_desc($response['code']);
1390 curl_close( $handle );
1392 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1393 $theBody = WP_Http_Encoding::decompress( $theBody );
1395 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']);
1399 * Whether this class can be used for retrieving an URL.
1404 * @return boolean False means this class can not be used, true means it can.
1406 function test($args = array()) {
1407 if ( function_exists('curl_init') && function_exists('curl_exec') )
1408 return apply_filters('use_curl_transport', true, $args);
1415 * Adds Proxy support to the WordPress HTTP API.
1417 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1418 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1421 * The constants are as follows:
1423 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1424 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1425 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1426 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1427 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1428 * You do not need to have localhost and the blog host in this list, because they will not be passed
1429 * through the proxy. The list should be presented in a comma separated list</li>
1432 * An example can be as seen below.
1434 * define('WP_PROXY_HOST', '192.168.84.101');
1435 * define('WP_PROXY_PORT', '8080');
1436 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com');
1439 * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1442 class WP_HTTP_Proxy {
1445 * Whether proxy connection should be used.
1448 * @use WP_PROXY_HOST
1449 * @use WP_PROXY_PORT
1453 function is_enabled() {
1454 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1458 * Whether authentication should be used.
1461 * @use WP_PROXY_USERNAME
1462 * @use WP_PROXY_PASSWORD
1466 function use_authentication() {
1467 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1471 * Retrieve the host for the proxy server.
1478 if ( defined('WP_PROXY_HOST') )
1479 return WP_PROXY_HOST;
1485 * Retrieve the port for the proxy server.
1492 if ( defined('WP_PROXY_PORT') )
1493 return WP_PROXY_PORT;
1499 * Retrieve the username for proxy authentication.
1505 function username() {
1506 if ( defined('WP_PROXY_USERNAME') )
1507 return WP_PROXY_USERNAME;
1513 * Retrieve the password for proxy authentication.
1519 function password() {
1520 if ( defined('WP_PROXY_PASSWORD') )
1521 return WP_PROXY_PASSWORD;
1527 * Retrieve authentication string for proxy authentication.
1533 function authentication() {
1534 return $this->username() . ':' . $this->password();
1538 * Retrieve header string for proxy authentication.
1544 function authentication_header() {
1545 return 'Proxy-Authentication: Basic ' . base64_encode( $this->authentication() );
1549 * Whether URL should be sent through the proxy server.
1551 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1552 * some proxies can not handle this. We also have the constant available for defining other
1553 * hosts that won't be sent through the proxy.
1555 * @uses WP_PROXY_BYPASS_HOSTS
1558 * @param string $uri URI to check.
1559 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1561 function send_through_proxy( $uri ) {
1562 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1563 // This will be displayed on blogs, which is not reasonable.
1564 $check = @parse_url($uri);
1566 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1567 if ( $check === false )
1570 $home = parse_url( get_option('siteurl') );
1572 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1575 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1578 static $bypass_hosts;
1579 if ( null == $bypass_hosts )
1580 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1582 return !in_array( $check['host'], $bypass_hosts );
1586 * Internal representation of a single cookie.
1588 * Returned cookies are represented using this class, and when cookies are set, if they are not
1589 * already a WP_Http_Cookie() object, then they are turned into one.
1591 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1592 * names. Need to switch to use underscores instead for the methods.
1594 * @package WordPress
1597 * @author Beau Lebens
1599 class WP_Http_Cookie {
1618 * When the cookie expires.
1642 * PHP4 style Constructor - Calls PHP5 Style Constructor.
1646 * @param string|array $data Raw cookie data.
1648 function WP_Http_Cookie( $data ) {
1649 $this->__construct( $data );
1653 * Sets up this cookie object.
1655 * The parameter $data should be either an associative array containing the indices names below
1656 * or a header string detailing it.
1658 * If it's an array, it should include the following elements:
1661 * <li>Value - should NOT be urlencoded already.</li>
1662 * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1663 * <li>Path (optional)</li>
1664 * <li>Domain (optional)</li>
1670 * @param string|array $data Raw cookie data.
1672 function __construct( $data ) {
1673 if ( is_string( $data ) ) {
1674 // Assume it's a header string direct from a previous request
1675 $pairs = explode( ';', $data );
1677 // Special handling for first pair; name=value. Also be careful of "=" in value
1678 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1679 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1680 $this->name = $name;
1681 $this->value = urldecode( $value );
1682 array_shift( $pairs ); //Removes name=value from items.
1684 // Set everything else as a property
1685 foreach ( $pairs as $pair ) {
1686 if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1689 list( $key, $val ) = explode( '=', $pair );
1690 $key = strtolower( trim( $key ) );
1691 if ( 'expires' == $key )
1692 $val = strtotime( $val );
1696 if ( !isset( $data['name'] ) )
1699 // Set properties based directly on parameters
1700 $this->name = $data['name'];
1701 $this->value = isset( $data['value'] ) ? $data['value'] : '';
1702 $this->path = isset( $data['path'] ) ? $data['path'] : '';
1703 $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1705 if ( isset( $data['expires'] ) )
1706 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1708 $this->expires = null;
1713 * Confirms that it's OK to send this cookie to the URL checked against.
1715 * Decision is based on RFC 2109/2965, so look there for details on validity.
1720 * @param string $url URL you intend to send this cookie to
1721 * @return boolean TRUE if allowed, FALSE otherwise.
1723 function test( $url ) {
1724 // Expires - if expired then nothing else matters
1725 if ( time() > $this->expires )
1728 // Get details on the URL we're thinking about sending to
1729 $url = parse_url( $url );
1730 $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1731 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1733 // Values to use for comparison against the URL
1734 $path = isset( $this->path ) ? $this->path : '/';
1735 $port = isset( $this->port ) ? $this->port : 80;
1736 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1737 if ( false === stripos( $domain, '.' ) )
1738 $domain .= '.local';
1740 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1741 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1742 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1745 // Port - supports "port-lists" in the format: "80,8000,8080"
1746 if ( !in_array( $url['port'], explode( ',', $port) ) )
1749 // Path - request path must start with path restriction
1750 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1757 * Convert cookie name and value back to header string.
1762 * @return string Header encoded cookie name and value.
1764 function getHeaderValue() {
1765 if ( empty( $this->name ) || empty( $this->value ) )
1768 return $this->name . '=' . urlencode( $this->value );
1772 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1779 function getFullHeader() {
1780 return 'Cookie: ' . $this->getHeaderValue();
1785 * Implementation for deflate and gzip transfer encodings.
1787 * Includes RFC 1950, RFC 1951, and RFC 1952.
1790 * @package WordPress
1793 class WP_Http_Encoding {
1796 * Compress raw string using the deflate format.
1798 * Supports the RFC 1951 standard.
1802 * @param string $raw String to compress.
1803 * @param int $level Optional, default is 9. Compression level, 9 is highest.
1804 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1805 * @return string|bool False on failure.
1807 function compress( $raw, $level = 9, $supports = null ) {
1808 return gzdeflate( $raw, $level );
1812 * Decompression of deflated string.
1814 * Will attempt to decompress using the RFC 1950 standard, and if that fails
1815 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1816 * 1952 standard gzip decode will be attempted. If all fail, then the
1817 * original compressed string will be returned.
1821 * @param string $compressed String to decompress.
1822 * @param int $length The optional length of the compressed data.
1823 * @return string|bool False on failure.
1825 function decompress( $compressed, $length = null ) {
1826 $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed );
1828 if ( false !== $decompressed )
1829 return $decompressed;
1831 $decompressed = gzuncompress( $compressed );
1833 if ( false !== $decompressed )
1834 return $decompressed;
1836 if ( function_exists('gzdecode') ) {
1837 $decompressed = gzdecode( $compressed );
1839 if ( false !== $decompressed )
1840 return $decompressed;
1847 * Decompression of deflated string while staying compatible with the majority of servers.
1849 * Certain Servers will return deflated data with headers which PHP's gziniflate()
1850 * function cannot handle out of the box. The following function lifted from
1851 * http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate
1852 * the various return forms used.
1855 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
1857 * @param string $gzData String to decompress.
1858 * @return string|bool False on failure.
1860 function compatible_gzinflate($gzData) {
1861 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
1863 $flg = ord( substr($gzData, 3, 1) );
1866 list($xlen) = unpack('v', substr($gzData, $i, 2) );
1867 $i = $i + 2 + $xlen;
1870 $i = strpos($gzData, "\0", $i) + 1;
1872 $i = strpos($gzData, "\0", $i) + 1;
1876 return gzinflate( substr($gzData, $i, -8) );
1883 * What encoding types to accept and their priority values.
1887 * @return string Types of encoding to accept.
1889 function accept_encoding() {
1891 if ( function_exists( 'gzinflate' ) )
1892 $type[] = 'deflate;q=1.0';
1894 if ( function_exists( 'gzuncompress' ) )
1895 $type[] = 'compress;q=0.5';
1897 if ( function_exists( 'gzdecode' ) )
1898 $type[] = 'gzip;q=0.5';
1900 return implode(', ', $type);
1904 * What enconding the content used when it was compressed to send in the headers.
1908 * @return string Content-Encoding string to send in the header.
1910 function content_encoding() {
1915 * Whether the content be decoded based on the headers.
1919 * @param array|string $headers All of the available headers.
1922 function should_decode($headers) {
1923 if ( is_array( $headers ) ) {
1924 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
1926 } else if( is_string( $headers ) ) {
1927 return ( stripos($headers, 'content-encoding:') !== false );
1934 * Whether decompression and compression are supported by the PHP version.
1936 * Each function is tested instead of checking for the zlib extension, to
1937 * ensure that the functions all exist in the PHP version and aren't
1944 function is_available() {
1945 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
1950 * Returns the initialized WP_Http Object
1955 * @return WP_Http HTTP Transport object.
1957 function &_wp_http_get_object() {
1960 if ( is_null($http) )
1961 $http = new WP_Http();
1967 * Retrieve the raw response from the HTTP request.
1969 * The array structure is a little complex.
1972 * $res = array( 'headers' => array(), 'response' => array('code' => int, 'message' => string) );
1975 * All of the headers in $res['headers'] are with the name as the key and the
1976 * value as the value. So to get the User-Agent, you would do the following.
1979 * $user_agent = $res['headers']['user-agent'];
1982 * The body is the raw response content and can be retrieved from $res['body'].
1984 * This function is called first to make the request and there are other API
1985 * functions to abstract out the above convoluted setup.
1989 * @param string $url Site URL to retrieve.
1990 * @param array $args Optional. Override the defaults.
1991 * @return WP_Error|array The response or WP_Error on failure.
1993 function wp_remote_request($url, $args = array()) {
1994 $objFetchSite = _wp_http_get_object();
1995 return $objFetchSite->request($url, $args);
1999 * Retrieve the raw response from the HTTP request using the GET method.
2001 * @see wp_remote_request() For more information on the response array format.
2005 * @param string $url Site URL to retrieve.
2006 * @param array $args Optional. Override the defaults.
2007 * @return WP_Error|array The response or WP_Error on failure.
2009 function wp_remote_get($url, $args = array()) {
2010 $objFetchSite = _wp_http_get_object();
2011 return $objFetchSite->get($url, $args);
2015 * Retrieve the raw response from the HTTP request using the POST method.
2017 * @see wp_remote_request() For more information on the response array format.
2021 * @param string $url Site URL to retrieve.
2022 * @param array $args Optional. Override the defaults.
2023 * @return WP_Error|array The response or WP_Error on failure.
2025 function wp_remote_post($url, $args = array()) {
2026 $objFetchSite = _wp_http_get_object();
2027 return $objFetchSite->post($url, $args);
2031 * Retrieve the raw response from the HTTP request using the HEAD method.
2033 * @see wp_remote_request() For more information on the response array format.
2037 * @param string $url Site URL to retrieve.
2038 * @param array $args Optional. Override the defaults.
2039 * @return WP_Error|array The response or WP_Error on failure.
2041 function wp_remote_head($url, $args = array()) {
2042 $objFetchSite = _wp_http_get_object();
2043 return $objFetchSite->head($url, $args);
2047 * Retrieve only the headers from the raw response.
2051 * @param array $response HTTP response.
2052 * @return array The headers of the response. Empty array if incorrect parameter given.
2054 function wp_remote_retrieve_headers(&$response) {
2055 if ( is_wp_error($response) || ! isset($response['headers']) || ! is_array($response['headers']))
2058 return $response['headers'];
2062 * Retrieve a single header by name from the raw response.
2066 * @param array $response
2067 * @param string $header Header name to retrieve value from.
2068 * @return string The header value. Empty string on if incorrect parameter given, or if the header doesnt exist.
2070 function wp_remote_retrieve_header(&$response, $header) {
2071 if ( is_wp_error($response) || ! isset($response['headers']) || ! is_array($response['headers']))
2074 if ( array_key_exists($header, $response['headers']) )
2075 return $response['headers'][$header];
2081 * Retrieve only the response code from the raw response.
2083 * Will return an empty array if incorrect parameter value is given.
2087 * @param array $response HTTP response.
2088 * @return string the response code. Empty string on incorrect parameter given.
2090 function wp_remote_retrieve_response_code(&$response) {
2091 if ( is_wp_error($response) || ! isset($response['response']) || ! is_array($response['response']))
2094 return $response['response']['code'];
2098 * Retrieve only the response message from the raw response.
2100 * Will return an empty array if incorrect parameter value is given.
2104 * @param array $response HTTP response.
2105 * @return string The response message. Empty string on incorrect parameter given.
2107 function wp_remote_retrieve_response_message(&$response) {
2108 if ( is_wp_error($response) || ! isset($response['response']) || ! is_array($response['response']))
2111 return $response['response']['message'];
2115 * Retrieve only the body from the raw response.
2119 * @param array $response HTTP response.
2120 * @return string The body of the response. Empty string if no body or incorrect parameter given.
2122 function wp_remote_retrieve_body(&$response) {
2123 if ( is_wp_error($response) || ! isset($response['body']) )
2126 return $response['body'];