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 if ( has_filter('http_transport_get_debug') )
122 do_action('http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport);
124 if ( isset($args['blocking']) && !$args['blocking'] )
125 return $nonblocking_transport;
127 return $blocking_transport;
131 * Tests the WordPress HTTP objects for an object to use and returns it.
133 * Tests all of the objects and returns the object that passes. Also caches
134 * that object to be used later. This is for posting content to a URL and
135 * is used when there is a body. The plain Fopen Transport can not be used
136 * to send content, but the streams transport can. This is a limitation that
137 * is addressed here, by just not including that transport.
142 * @param array $args Request args, default us an empty array
143 * @return object|null Null if no transports are available, HTTP transport object.
145 function &_postTransport( $args = array() ) {
146 static $working_transport, $blocking_transport, $nonblocking_transport;
148 if ( is_null($working_transport) ) {
149 if ( true === WP_Http_ExtHttp::test($args) ) {
150 $working_transport['exthttp'] = new WP_Http_ExtHttp();
151 $blocking_transport[] = &$working_transport['exthttp'];
152 } else if ( true === WP_Http_Curl::test($args) ) {
153 $working_transport['curl'] = new WP_Http_Curl();
154 $blocking_transport[] = &$working_transport['curl'];
155 } else if ( true === WP_Http_Streams::test($args) ) {
156 $working_transport['streams'] = new WP_Http_Streams();
157 $blocking_transport[] = &$working_transport['streams'];
158 } else if ( true === WP_Http_Fsockopen::test($args) ) {
159 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
160 $blocking_transport[] = &$working_transport['fsockopen'];
163 foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) {
164 if ( isset($working_transport[$transport]) )
165 $nonblocking_transport[] = &$working_transport[$transport];
169 if ( has_filter('http_transport_post_debug') )
170 do_action('http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport);
172 if ( isset($args['blocking']) && !$args['blocking'] )
173 return $nonblocking_transport;
175 return $blocking_transport;
179 * Send a HTTP request to a URI.
181 * The body and headers are part of the arguments. The 'body' argument is for the body and will
182 * accept either a string or an array. The 'headers' argument should be an array, but a string
183 * is acceptable. If the 'body' argument is an array, then it will automatically be escaped
184 * using http_build_query().
186 * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
187 * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send
188 * headers. Other protocols are unsupported and most likely will fail.
190 * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
193 * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
194 * others, but should not be assumed. The 'timeout' is used to sent how long the connection
195 * should stay open before failing when no response. 'redirection' is used to track how many
196 * redirects were taken and used to sent the amount for other transports, but not all transports
197 * accept setting that value.
199 * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
200 * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The
201 * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is
202 * 'WordPress/WP_Version', where WP_Version is the value from $wp_version.
204 * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP
205 * while it performs the request or continue regardless. Actually, that isn't entirely correct.
206 * Blocking mode really just means whether the fread should just pull what it can whenever it
207 * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading
208 * the entire content. It doesn't actually always mean that PHP will continue going after making
214 * @param string $url URI resource.
215 * @param str|array $args Optional. Override the defaults.
216 * @return array containing 'headers', 'body', 'response', 'cookies'
218 function request( $url, $args = array() ) {
223 'timeout' => apply_filters( 'http_request_timeout', 5),
224 'redirection' => apply_filters( 'http_request_redirection_count', 5),
225 'httpversion' => apply_filters( 'http_request_version', '1.0'),
226 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
228 'headers' => array(),
229 'cookies' => array(),
232 'decompress' => true,
236 $r = wp_parse_args( $args, $defaults );
237 $r = apply_filters( 'http_request_args', $r, $url );
239 $arrURL = parse_url($url);
241 if ( $this->block_request( $url ) )
242 return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.'));
244 // Determine if this is a https call and pass that on to the transport functions
245 // so that we can blacklist the transports that do not support ssl verification
246 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
248 // Determine if this request is to OUR install of WordPress
249 $homeURL = parse_url(get_bloginfo('url'));
250 $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
253 if ( is_null( $r['headers'] ) )
254 $r['headers'] = array();
256 if ( ! is_array($r['headers']) ) {
257 $processedHeaders = WP_Http::processHeaders($r['headers']);
258 $r['headers'] = $processedHeaders['headers'];
261 if ( isset($r['headers']['User-Agent']) ) {
262 $r['user-agent'] = $r['headers']['User-Agent'];
263 unset($r['headers']['User-Agent']);
266 if ( isset($r['headers']['user-agent']) ) {
267 $r['user-agent'] = $r['headers']['user-agent'];
268 unset($r['headers']['user-agent']);
271 // Construct Cookie: header if any cookies are set
272 WP_Http::buildCookieHeader( $r );
274 if ( WP_Http_Encoding::is_available() )
275 $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding();
277 if ( is_null($r['body']) ) {
278 // Some servers fail when sending content without the content-length
280 $r['headers']['Content-Length'] = 0;
281 $transports = WP_Http::_getTransport($r);
283 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
284 if ( ! version_compare(phpversion(), '5.1.2', '>=') )
285 $r['body'] = _http_build_query($r['body'], null, '&');
287 $r['body'] = http_build_query($r['body'], null, '&');
288 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset');
289 $r['headers']['Content-Length'] = strlen($r['body']);
292 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
293 $r['headers']['Content-Length'] = strlen($r['body']);
295 $transports = WP_Http::_postTransport($r);
298 if ( has_action('http_api_debug') )
299 do_action('http_api_debug', $transports, 'transports_list');
301 $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
302 foreach ( (array) $transports as $transport ) {
303 $response = $transport->request($url, $r);
305 if ( has_action('http_api_debug') )
306 do_action( 'http_api_debug', $response, 'response', get_class($transport) );
308 if ( ! is_wp_error($response) )
316 * Uses the POST HTTP method.
318 * Used for sending data that is expected to be in the body.
323 * @param string $url URI resource.
324 * @param str|array $args Optional. Override the defaults.
327 function post($url, $args = array()) {
328 $defaults = array('method' => 'POST');
329 $r = wp_parse_args( $args, $defaults );
330 return $this->request($url, $r);
334 * Uses the GET HTTP method.
336 * Used for sending data that is expected to be in the body.
341 * @param string $url URI resource.
342 * @param str|array $args Optional. Override the defaults.
345 function get($url, $args = array()) {
346 $defaults = array('method' => 'GET');
347 $r = wp_parse_args( $args, $defaults );
348 return $this->request($url, $r);
352 * Uses the HEAD HTTP method.
354 * Used for sending data that is expected to be in the body.
359 * @param string $url URI resource.
360 * @param str|array $args Optional. Override the defaults.
363 function head($url, $args = array()) {
364 $defaults = array('method' => 'HEAD');
365 $r = wp_parse_args( $args, $defaults );
366 return $this->request($url, $r);
370 * Parses the responses and splits the parts into headers and body.
376 * @param string $strResponse The full response string
377 * @return array Array with 'headers' and 'body' keys.
379 function processResponse($strResponse) {
380 list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2);
381 return array('headers' => $theHeaders, 'body' => $theBody);
385 * Transform header string into an array.
387 * If an array is given then it is assumed to be raw header data with numeric keys with the
388 * headers as the values. No headers must be passed that were already processed.
394 * @param string|array $headers
395 * @return array Processed string headers. If duplicate headers are encountered,
396 * Then a numbered array is returned as the value of that header-key.
398 function processHeaders($headers) {
399 // split headers, one per array element
400 if ( is_string($headers) ) {
401 // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
402 $headers = str_replace("\r\n", "\n", $headers);
403 // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
404 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
405 // create the headers array
406 $headers = explode("\n", $headers);
409 $response = array('code' => 0, 'message' => '');
412 $newheaders = array();
413 foreach ( $headers as $tempheader ) {
414 if ( empty($tempheader) )
417 if ( false === strpos($tempheader, ':') ) {
418 list( , $iResponseCode, $strResponseMsg) = explode(' ', $tempheader, 3);
419 $response['code'] = $iResponseCode;
420 $response['message'] = $strResponseMsg;
424 list($key, $value) = explode(':', $tempheader, 2);
426 if ( !empty( $value ) ) {
427 $key = strtolower( $key );
428 if ( isset( $newheaders[$key] ) ) {
429 $newheaders[$key] = array( $newheaders[$key], trim( $value ) );
431 $newheaders[$key] = trim( $value );
433 if ( 'set-cookie' == strtolower( $key ) )
434 $cookies[] = new WP_Http_Cookie( $value );
438 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
442 * Takes the arguments for a ::request() and checks for the cookie array.
444 * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
445 * into strings and added to the Cookie: header (within the arguments array). Edits the array by
452 * @param array $r Full array of args passed into ::request()
454 function buildCookieHeader( &$r ) {
455 if ( ! empty($r['cookies']) ) {
456 $cookies_header = '';
457 foreach ( (array) $r['cookies'] as $cookie ) {
458 $cookies_header .= $cookie->getHeaderValue() . '; ';
460 $cookies_header = substr( $cookies_header, 0, -2 );
461 $r['headers']['cookie'] = $cookies_header;
466 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
468 * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
469 * returning footer headers. Shouldn't be too difficult to support it though.
471 * @todo Add support for footer chunked headers.
476 * @param string $body Body content
477 * @return string Chunked decoded body on success or raw body on failure.
479 function chunkTransferDecode($body) {
480 $body = str_replace(array("\r\n", "\r"), "\n", $body);
481 // The body is not chunked encoding or is malformed.
482 if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
486 //$parsedHeaders = array(); Unsupported
489 $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
492 if ( empty( $match[1] ) )
495 $length = hexdec( $match[1] );
496 $chunkLength = strlen( $match[0] );
498 $strBody = substr($body, $chunkLength, $length);
499 $parsedBody .= $strBody;
501 $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
503 if ( "0" == trim($body) )
504 return $parsedBody; // Ignore footer headers.
512 * Block requests through the proxy.
514 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
515 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
517 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL in your wp-config.php file
518 * and this will only allow localhost and your blog to make requests. The constant
519 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
520 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
523 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
525 * @param string $uri URI of url.
526 * @return bool True to block, false to allow.
528 function block_request($uri) {
529 // We don't need to block requests, because nothing is blocked.
530 if ( ! defined('WP_HTTP_BLOCK_EXTERNAL') || ( defined('WP_HTTP_BLOCK_EXTERNAL') && WP_HTTP_BLOCK_EXTERNAL == false ) )
533 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
534 // This will be displayed on blogs, which is not reasonable.
535 $check = @parse_url($uri);
537 /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
539 * This isn't very security sound. There are instances where a hacker might attempt
540 * to bypass the proxy and this check. However, the reason for this behavior is that
541 * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
542 * the default unsecure nature of the HTTP request.
544 if ( $check === false )
547 $home = parse_url( get_option('siteurl') );
549 // Don't block requests back to ourselves by default
550 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
551 return apply_filters('block_local_requests', false);
553 if ( !defined('WP_ACCESSIBLE_HOSTS') )
556 static $accessible_hosts;
557 if ( null == $accessible_hosts )
558 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
560 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
565 * HTTP request method uses fsockopen function to retrieve the url.
567 * This would be the preferred method, but the fsockopen implementation has the most overhead of all
568 * the HTTP transport implementations.
574 class WP_Http_Fsockopen {
576 * Send a HTTP request to a URI using fsockopen().
578 * Does not support non-blocking mode.
580 * @see WP_Http::request For default options descriptions.
584 * @param string $url URI resource.
585 * @param str|array $args Optional. Override the defaults.
586 * @return array 'headers', 'body', 'cookies' and 'response' keys.
588 function request($url, $args = array()) {
590 'method' => 'GET', 'timeout' => 5,
591 'redirection' => 5, 'httpversion' => '1.0',
593 'headers' => array(), 'body' => null, 'cookies' => array()
596 $r = wp_parse_args( $args, $defaults );
598 if ( isset($r['headers']['User-Agent']) ) {
599 $r['user-agent'] = $r['headers']['User-Agent'];
600 unset($r['headers']['User-Agent']);
601 } else if( isset($r['headers']['user-agent']) ) {
602 $r['user-agent'] = $r['headers']['user-agent'];
603 unset($r['headers']['user-agent']);
606 // Construct Cookie: header if any cookies are set
607 WP_Http::buildCookieHeader( $r );
609 $iError = null; // Store error number
610 $strError = null; // Store error string
612 $arrURL = parse_url($url);
614 $fsockopen_host = $arrURL['host'];
616 $secure_transport = false;
618 if ( ! isset( $arrURL['port'] ) ) {
619 if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
620 $fsockopen_host = "ssl://$fsockopen_host";
621 $arrURL['port'] = 443;
622 $secure_transport = true;
624 $arrURL['port'] = 80;
628 // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
629 // ignored and should be ignored.
630 if ( true === $secure_transport )
631 $error_reporting = error_reporting(0);
633 $startDelay = time();
635 $proxy = new WP_HTTP_Proxy();
637 if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) {
638 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
639 $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
641 $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
643 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
644 $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
646 $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
651 // If the delay is greater than the timeout then fsockopen should't be used, because it will
652 // cause a long delay.
653 $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
654 if ( true === $elapseDelay )
655 add_option( 'disable_fsockopen', $endDelay, null, true );
657 if ( false === $handle )
658 return new WP_Error('http_request_failed', $iError . ': ' . $strError);
660 stream_set_timeout($handle, $r['timeout'] );
662 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
665 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
667 if ( empty($requestPath) )
670 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
672 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
673 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
675 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
677 if ( isset($r['user-agent']) )
678 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
680 if ( is_array($r['headers']) ) {
681 foreach ( (array) $r['headers'] as $header => $headerValue )
682 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
684 $strHeaders .= $r['headers'];
687 if ( $proxy->use_authentication() )
688 $strHeaders .= $proxy->authentication_header() . "\r\n";
690 $strHeaders .= "\r\n";
692 if ( ! is_null($r['body']) )
693 $strHeaders .= $r['body'];
695 fwrite($handle, $strHeaders);
697 if ( ! $r['blocking'] ) {
699 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
703 while ( ! feof($handle) )
704 $strResponse .= fread($handle, 4096);
708 if ( true === $secure_transport )
709 error_reporting($error_reporting);
711 $process = WP_Http::processResponse($strResponse);
712 $arrHeaders = WP_Http::processHeaders($process['headers']);
714 // Is the response code within the 400 range?
715 if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 )
716 return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']);
718 // If location is found, then assume redirect and redirect to location.
719 if ( isset($arrHeaders['headers']['location']) ) {
720 if ( $r['redirection']-- > 0 ) {
721 return $this->request($arrHeaders['headers']['location'], $r);
723 return new WP_Error('http_request_failed', __('Too many redirects.'));
727 // If the body was chunk encoded, then decode it.
728 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
729 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
731 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
732 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
734 return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']);
738 * Whether this class can be used for retrieving an URL.
742 * @return boolean False means this class can not be used, true means it can.
744 function test( $args = array() ) {
745 if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
748 $is_ssl = isset($args['ssl']) && $args['ssl'];
750 if ( ! $is_ssl && function_exists( 'fsockopen' ) )
752 elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) )
757 return apply_filters('use_fsockopen_transport', $use, $args);
762 * HTTP request method uses fopen function to retrieve the url.
764 * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support,
765 * but should still be okay, to write the headers, before getting the response. Also requires that
766 * 'allow_url_fopen' to be enabled.
772 class WP_Http_Fopen {
774 * Send a HTTP request to a URI using fopen().
776 * This transport does not support sending of headers and body, therefore should not be used in
777 * the instances, where there is a body and headers.
779 * Notes: Does not support non-blocking mode. Ignores 'redirection' option.
781 * @see WP_Http::retrieve For default options descriptions.
786 * @param string $url URI resource.
787 * @param str|array $args Optional. Override the defaults.
788 * @return array 'headers', 'body', 'cookies' and 'response' keys.
790 function request($url, $args = array()) {
792 'method' => 'GET', 'timeout' => 5,
793 'redirection' => 5, 'httpversion' => '1.0',
795 'headers' => array(), 'body' => null, 'cookies' => array()
798 $r = wp_parse_args( $args, $defaults );
800 $arrURL = parse_url($url);
802 if ( false === $arrURL )
803 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
805 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
806 $url = str_replace($arrURL['scheme'], 'http', $url);
808 if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) )
809 $handle = @fopen($url, 'r');
811 $handle = fopen($url, 'r');
814 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
816 stream_set_timeout($handle, $r['timeout'] );
818 if ( ! $r['blocking'] ) {
820 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
824 while ( ! feof($handle) )
825 $strResponse .= fread($handle, 4096);
827 if ( function_exists('stream_get_meta_data') ) {
828 $meta = stream_get_meta_data($handle);
829 $theHeaders = $meta['wrapper_data'];
830 if ( isset( $meta['wrapper_data']['headers'] ) )
831 $theHeaders = $meta['wrapper_data']['headers'];
833 //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper
834 //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php
835 $theHeaders = $http_response_header;
840 $processedHeaders = WP_Http::processHeaders($theHeaders);
842 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
843 $strResponse = WP_Http::chunkTransferDecode($strResponse);
845 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
846 $strResponse = WP_Http_Encoding::decompress( $strResponse );
848 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
852 * Whether this class can be used for retrieving an URL.
856 * @return boolean False means this class can not be used, true means it can.
858 function test($args = array()) {
859 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
864 //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off.
865 $is_ssl = isset($args['ssl']) && $args['ssl'];
867 $is_local = isset($args['local']) && $args['local'];
868 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
869 if ( $is_local && true != apply_filters('https_local_ssl_verify', true) )
871 elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) )
873 elseif ( !$ssl_verify )
879 return apply_filters('use_fopen_transport', $use, $args);
884 * HTTP request method uses Streams to retrieve the url.
886 * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
889 * Second preferred method for getting the URL, for PHP 5.
895 class WP_Http_Streams {
897 * Send a HTTP request to a URI using streams with fopen().
903 * @param str|array $args Optional. Override the defaults.
904 * @return array 'headers', 'body', 'cookies' and 'response' keys.
906 function request($url, $args = array()) {
908 'method' => 'GET', 'timeout' => 5,
909 'redirection' => 5, 'httpversion' => '1.0',
911 'headers' => array(), 'body' => null, 'cookies' => array()
914 $r = wp_parse_args( $args, $defaults );
916 if ( isset($r['headers']['User-Agent']) ) {
917 $r['user-agent'] = $r['headers']['User-Agent'];
918 unset($r['headers']['User-Agent']);
919 } else if( isset($r['headers']['user-agent']) ) {
920 $r['user-agent'] = $r['headers']['user-agent'];
921 unset($r['headers']['user-agent']);
924 // Construct Cookie: header if any cookies are set
925 WP_Http::buildCookieHeader( $r );
927 $arrURL = parse_url($url);
929 if ( false === $arrURL )
930 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
932 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
933 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
935 // Convert Header array to string.
937 if ( is_array( $r['headers'] ) )
938 foreach ( $r['headers'] as $name => $value )
939 $strHeaders .= "{$name}: $value\r\n";
940 else if ( is_string( $r['headers'] ) )
941 $strHeaders = $r['headers'];
943 $is_local = isset($args['local']) && $args['local'];
944 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
946 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
947 elseif ( ! $is_local )
948 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
950 $arrContext = array('http' =>
952 'method' => strtoupper($r['method']),
953 'user_agent' => $r['user-agent'],
954 'max_redirects' => $r['redirection'],
955 'protocol_version' => (float) $r['httpversion'],
956 'header' => $strHeaders,
957 'timeout' => $r['timeout'],
959 'verify_peer' => $ssl_verify,
960 'verify_host' => $ssl_verify
965 $proxy = new WP_HTTP_Proxy();
967 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
968 $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
969 $arrContext['http']['request_fulluri'] = true;
971 // We only support Basic authentication so this will only work if that is what your proxy supports.
972 if ( $proxy->use_authentication() )
973 $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
976 if ( ! is_null($r['body']) && ! empty($r['body'] ) )
977 $arrContext['http']['content'] = $r['body'];
979 $context = stream_context_create($arrContext);
981 if ( ! defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) )
982 $handle = @fopen($url, 'r', false, $context);
984 $handle = fopen($url, 'r', false, $context);
987 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
989 // WordPress supports PHP 4.3, which has this function. Removed sanity checking for
990 // performance reasons.
991 stream_set_timeout($handle, $r['timeout'] );
993 if ( ! $r['blocking'] ) {
994 stream_set_blocking($handle, 0);
996 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
999 $strResponse = stream_get_contents($handle);
1000 $meta = stream_get_meta_data($handle);
1004 $processedHeaders = array();
1005 if ( isset( $meta['wrapper_data']['headers'] ) )
1006 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
1008 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
1010 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1011 $strResponse = WP_Http::chunkTransferDecode($strResponse);
1013 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1014 $strResponse = WP_Http_Encoding::decompress( $strResponse );
1016 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
1020 * Whether this class can be used for retrieving an URL.
1026 * @return boolean False means this class can not be used, true means it can.
1028 function test($args = array()) {
1029 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
1032 if ( version_compare(PHP_VERSION, '5.0', '<') )
1035 //HTTPS via Proxy was added in 5.1.0
1036 $is_ssl = isset($args['ssl']) && $args['ssl'];
1037 if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) {
1038 $proxy = new WP_HTTP_Proxy();
1040 * No URL check, as its not currently passed to the ::test() function
1041 * In the case where a Proxy is in use, Just bypass this transport for HTTPS.
1043 if ( $proxy->is_enabled() )
1047 return apply_filters('use_streams_transport', true, $args);
1052 * HTTP request method uses HTTP extension to retrieve the url.
1054 * Requires the HTTP extension to be installed. This would be the preferred transport since it can
1055 * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+
1056 * is being used, it doesn't mean that the HTTP extension will be enabled.
1058 * @package WordPress
1062 class WP_Http_ExtHTTP {
1064 * Send a HTTP request to a URI using HTTP extension.
1066 * Does not support non-blocking.
1071 * @param string $url
1072 * @param str|array $args Optional. Override the defaults.
1073 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1075 function request($url, $args = array()) {
1077 'method' => 'GET', 'timeout' => 5,
1078 'redirection' => 5, 'httpversion' => '1.0',
1080 'headers' => array(), 'body' => null, 'cookies' => array()
1083 $r = wp_parse_args( $args, $defaults );
1085 if ( isset($r['headers']['User-Agent']) ) {
1086 $r['user-agent'] = $r['headers']['User-Agent'];
1087 unset($r['headers']['User-Agent']);
1088 } else if( isset($r['headers']['user-agent']) ) {
1089 $r['user-agent'] = $r['headers']['user-agent'];
1090 unset($r['headers']['user-agent']);
1093 // Construct Cookie: header if any cookies are set
1094 WP_Http::buildCookieHeader( $r );
1096 switch ( $r['method'] ) {
1098 $r['method'] = HTTP_METH_POST;
1101 $r['method'] = HTTP_METH_HEAD;
1105 $r['method'] = HTTP_METH_GET;
1108 $arrURL = parse_url($url);
1110 if ( 'http' != $arrURL['scheme'] || 'https' != $arrURL['scheme'] )
1111 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1113 $is_local = isset($args['local']) && $args['local'];
1114 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1116 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1117 elseif ( ! $is_local )
1118 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1121 'timeout' => $r['timeout'],
1122 'connecttimeout' => $r['timeout'],
1123 'redirect' => $r['redirection'],
1124 'useragent' => $r['user-agent'],
1125 'headers' => $r['headers'],
1127 'verifypeer' => $ssl_verify,
1128 'verifyhost' => $ssl_verify
1132 // The HTTP extensions offers really easy proxy support.
1133 $proxy = new WP_HTTP_Proxy();
1135 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1136 $options['proxyhost'] = $proxy->host();
1137 $options['proxyport'] = $proxy->port();
1138 $options['proxytype'] = HTTP_PROXY_HTTP;
1140 if ( $proxy->use_authentication() ) {
1141 $options['proxyauth'] = $proxy->authentication();
1142 $options['proxyauthtype'] = HTTP_AUTH_BASIC;
1146 if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) //Emits warning level notices for max redirects and timeouts
1147 $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
1149 $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts
1151 // Error may still be set, Response may return headers or partial document, and error
1152 // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
1153 if ( false === $strResponse || ! empty($info['error']) )
1154 return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
1156 if ( ! $r['blocking'] )
1157 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1159 list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2);
1160 $theHeaders = WP_Http::processHeaders($theHeaders);
1162 if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) {
1163 if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) )
1164 $theBody = @http_chunked_decode($theBody);
1166 $theBody = http_chunked_decode($theBody);
1169 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1170 $theBody = http_inflate( $theBody );
1172 $theResponse = array();
1173 $theResponse['code'] = $info['response_code'];
1174 $theResponse['message'] = get_status_header_desc($info['response_code']);
1176 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
1180 * Whether this class can be used for retrieving an URL.
1185 * @return boolean False means this class can not be used, true means it can.
1187 function test($args = array()) {
1188 return apply_filters('use_http_extension_transport', function_exists('http_request'), $args );
1193 * HTTP request method uses Curl extension to retrieve the url.
1195 * Requires the Curl extension to be installed.
1197 * @package WordPress
1201 class WP_Http_Curl {
1204 * Send a HTTP request to a URI using cURL extension.
1209 * @param string $url
1210 * @param str|array $args Optional. Override the defaults.
1211 * @return array 'headers', 'body', 'cookies' and 'response' keys.
1213 function request($url, $args = array()) {
1215 'method' => 'GET', 'timeout' => 5,
1216 'redirection' => 5, 'httpversion' => '1.0',
1218 'headers' => array(), 'body' => null, 'cookies' => array()
1221 $r = wp_parse_args( $args, $defaults );
1223 if ( isset($r['headers']['User-Agent']) ) {
1224 $r['user-agent'] = $r['headers']['User-Agent'];
1225 unset($r['headers']['User-Agent']);
1226 } else if( isset($r['headers']['user-agent']) ) {
1227 $r['user-agent'] = $r['headers']['user-agent'];
1228 unset($r['headers']['user-agent']);
1231 // Construct Cookie: header if any cookies are set.
1232 WP_Http::buildCookieHeader( $r );
1234 // cURL extension will sometimes fail when the timeout is less than 1 as it may round down
1235 // to 0, which gives it unlimited timeout.
1236 if ( $r['timeout'] > 0 && $r['timeout'] < 1 )
1239 $handle = curl_init();
1241 // cURL offers really easy proxy support.
1242 $proxy = new WP_HTTP_Proxy();
1244 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1246 $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
1249 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1250 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1251 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1253 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() );
1256 if ( $proxy->use_authentication() ) {
1258 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_BASIC );
1260 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1264 $is_local = isset($args['local']) && $args['local'];
1265 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1267 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1268 elseif ( ! $is_local )
1269 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1271 curl_setopt( $handle, CURLOPT_URL, $url);
1272 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1273 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify );
1274 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1275 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1276 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $r['timeout'] );
1277 curl_setopt( $handle, CURLOPT_TIMEOUT, $r['timeout'] );
1278 curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1280 switch ( $r['method'] ) {
1282 curl_setopt( $handle, CURLOPT_NOBODY, true );
1285 curl_setopt( $handle, CURLOPT_POST, true );
1286 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1290 if ( true === $r['blocking'] )
1291 curl_setopt( $handle, CURLOPT_HEADER, true );
1293 curl_setopt( $handle, CURLOPT_HEADER, false );
1295 // The option doesn't work with safe mode or when open_basedir is set.
1296 if ( !ini_get('safe_mode') && !ini_get('open_basedir') )
1297 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1299 if ( !empty( $r['headers'] ) ) {
1300 // cURL expects full header strings in each element
1302 foreach ( $r['headers'] as $name => $value ) {
1303 $headers[] = "{$name}: $value";
1305 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1308 if ( $r['httpversion'] == '1.0' )
1309 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1311 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1313 // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1314 // themselves... Although, it is somewhat pointless without some reference.
1315 do_action_ref_array( 'http_api_curl', array(&$handle) );
1317 // We don't need to return the body, so don't. Just execute request and return.
1318 if ( ! $r['blocking'] ) {
1319 curl_exec( $handle );
1320 curl_close( $handle );
1321 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1324 $theResponse = curl_exec( $handle );
1326 if ( !empty($theResponse) ) {
1327 $parts = explode("\r\n\r\n", $theResponse);
1329 $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
1330 $theHeaders = trim( substr($theResponse, 0, $headerLength) );
1331 $theBody = substr( $theResponse, $headerLength );
1332 if ( false !== strrpos($theHeaders, "\r\n\r\n") ) {
1333 $headerParts = explode("\r\n\r\n", $theHeaders);
1334 $theHeaders = $headerParts[ count($headerParts) -1 ];
1336 $theHeaders = WP_Http::processHeaders($theHeaders);
1338 if ( $curl_error = curl_error($handle) )
1339 return new WP_Error('http_request_failed', $curl_error);
1340 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1341 return new WP_Error('http_request_failed', __('Too many redirects.'));
1343 $theHeaders = array( 'headers' => array(), 'cookies' => array() );
1347 $response = array();
1348 $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1349 $response['message'] = get_status_header_desc($response['code']);
1351 curl_close( $handle );
1353 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1354 $theBody = WP_Http_Encoding::decompress( $theBody );
1356 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']);
1360 * Whether this class can be used for retrieving an URL.
1365 * @return boolean False means this class can not be used, true means it can.
1367 function test($args = array()) {
1368 if ( function_exists('curl_init') && function_exists('curl_exec') )
1369 return apply_filters('use_curl_transport', true, $args);
1376 * Adds Proxy support to the WordPress HTTP API.
1378 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1379 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1382 * The constants are as follows:
1384 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1385 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1386 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1387 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1388 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1389 * You do not need to have localhost and the blog host in this list, because they will not be passed
1390 * through the proxy. The list should be presented in a comma separated list</li>
1393 * An example can be as seen below.
1395 * define('WP_PROXY_HOST', '192.168.84.101');
1396 * define('WP_PROXY_PORT', '8080');
1397 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com');
1400 * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1403 class WP_HTTP_Proxy {
1406 * Whether proxy connection should be used.
1409 * @use WP_PROXY_HOST
1410 * @use WP_PROXY_PORT
1414 function is_enabled() {
1415 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1419 * Whether authentication should be used.
1422 * @use WP_PROXY_USERNAME
1423 * @use WP_PROXY_PASSWORD
1427 function use_authentication() {
1428 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1432 * Retrieve the host for the proxy server.
1439 if ( defined('WP_PROXY_HOST') )
1440 return WP_PROXY_HOST;
1446 * Retrieve the port for the proxy server.
1453 if ( defined('WP_PROXY_PORT') )
1454 return WP_PROXY_PORT;
1460 * Retrieve the username for proxy authentication.
1466 function username() {
1467 if ( defined('WP_PROXY_USERNAME') )
1468 return WP_PROXY_USERNAME;
1474 * Retrieve the password for proxy authentication.
1480 function password() {
1481 if ( defined('WP_PROXY_PASSWORD') )
1482 return WP_PROXY_PASSWORD;
1488 * Retrieve authentication string for proxy authentication.
1494 function authentication() {
1495 return $this->username() . ':' . $this->password();
1499 * Retrieve header string for proxy authentication.
1505 function authentication_header() {
1506 return 'Proxy-Authentication: Basic ' . base64_encode( $this->authentication() );
1510 * Whether URL should be sent through the proxy server.
1512 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1513 * some proxies can not handle this. We also have the constant available for defining other
1514 * hosts that won't be sent through the proxy.
1516 * @uses WP_PROXY_BYPASS_HOSTS
1519 * @param string $uri URI to check.
1520 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1522 function send_through_proxy( $uri ) {
1523 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1524 // This will be displayed on blogs, which is not reasonable.
1525 $check = @parse_url($uri);
1527 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1528 if ( $check === false )
1531 $home = parse_url( get_option('siteurl') );
1533 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1536 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1539 static $bypass_hosts;
1540 if ( null == $bypass_hosts )
1541 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1543 return !in_array( $check['host'], $bypass_hosts );
1547 * Internal representation of a single cookie.
1549 * Returned cookies are represented using this class, and when cookies are set, if they are not
1550 * already a WP_Http_Cookie() object, then they are turned into one.
1552 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1553 * names. Need to switch to use underscores instead for the methods.
1555 * @package WordPress
1558 * @author Beau Lebens
1560 class WP_Http_Cookie {
1579 * When the cookie expires.
1603 * PHP4 style Constructor - Calls PHP5 Style Constructor.
1607 * @param string|array $data Raw cookie data.
1609 function WP_Http_Cookie( $data ) {
1610 $this->__construct( $data );
1614 * Sets up this cookie object.
1616 * The parameter $data should be either an associative array containing the indices names below
1617 * or a header string detailing it.
1619 * If it's an array, it should include the following elements:
1622 * <li>Value - should NOT be urlencoded already.</li>
1623 * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1624 * <li>Path (optional)</li>
1625 * <li>Domain (optional)</li>
1631 * @param string|array $data Raw cookie data.
1633 function __construct( $data ) {
1634 if ( is_string( $data ) ) {
1635 // Assume it's a header string direct from a previous request
1636 $pairs = explode( ';', $data );
1638 // Special handling for first pair; name=value. Also be careful of "=" in value
1639 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1640 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1641 $this->name = $name;
1642 $this->value = urldecode( $value );
1643 array_shift( $pairs ); //Removes name=value from items.
1645 // Set everything else as a property
1646 foreach ( $pairs as $pair ) {
1647 if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1650 list( $key, $val ) = explode( '=', $pair );
1651 $key = strtolower( trim( $key ) );
1652 if ( 'expires' == $key )
1653 $val = strtotime( $val );
1657 if ( !isset( $data['name'] ) )
1660 // Set properties based directly on parameters
1661 $this->name = $data['name'];
1662 $this->value = isset( $data['value'] ) ? $data['value'] : '';
1663 $this->path = isset( $data['path'] ) ? $data['path'] : '';
1664 $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1666 if ( isset( $data['expires'] ) )
1667 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1669 $this->expires = null;
1674 * Confirms that it's OK to send this cookie to the URL checked against.
1676 * Decision is based on RFC 2109/2965, so look there for details on validity.
1681 * @param string $url URL you intend to send this cookie to
1682 * @return boolean TRUE if allowed, FALSE otherwise.
1684 function test( $url ) {
1685 // Expires - if expired then nothing else matters
1686 if ( time() > $this->expires )
1689 // Get details on the URL we're thinking about sending to
1690 $url = parse_url( $url );
1691 $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1692 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1694 // Values to use for comparison against the URL
1695 $path = isset( $this->path ) ? $this->path : '/';
1696 $port = isset( $this->port ) ? $this->port : 80;
1697 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1698 if ( false === stripos( $domain, '.' ) )
1699 $domain .= '.local';
1701 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1702 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1703 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1706 // Port - supports "port-lists" in the format: "80,8000,8080"
1707 if ( !in_array( $url['port'], explode( ',', $port) ) )
1710 // Path - request path must start with path restriction
1711 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1718 * Convert cookie name and value back to header string.
1723 * @return string Header encoded cookie name and value.
1725 function getHeaderValue() {
1726 if ( empty( $this->name ) || empty( $this->value ) )
1729 return $this->name . '=' . urlencode( $this->value );
1733 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1740 function getFullHeader() {
1741 return 'Cookie: ' . $this->getHeaderValue();
1746 * Implementation for deflate and gzip transfer encodings.
1748 * Includes RFC 1950, RFC 1951, and RFC 1952.
1751 * @package WordPress
1754 class WP_Http_Encoding {
1757 * Compress raw string using the deflate format.
1759 * Supports the RFC 1951 standard.
1763 * @param string $raw String to compress.
1764 * @param int $level Optional, default is 9. Compression level, 9 is highest.
1765 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1766 * @return string|bool False on failure.
1768 function compress( $raw, $level = 9, $supports = null ) {
1769 return gzdeflate( $raw, $level );
1773 * Decompression of deflated string.
1775 * Will attempt to decompress using the RFC 1950 standard, and if that fails
1776 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1777 * 1952 standard gzip decode will be attempted. If all fail, then the
1778 * original compressed string will be returned.
1782 * @param string $compressed String to decompress.
1783 * @param int $length The optional length of the compressed data.
1784 * @return string|bool False on failure.
1786 function decompress( $compressed, $length = null ) {
1787 $decompressed = gzinflate( $compressed );
1789 if ( false !== $decompressed )
1790 return $decompressed;
1792 $decompressed = gzuncompress( $compressed );
1794 if ( false !== $decompressed )
1795 return $decompressed;
1797 if ( function_exists('gzdecode') ) {
1798 $decompressed = gzdecode( $compressed );
1800 if ( false !== $decompressed )
1801 return $decompressed;
1808 * What encoding types to accept and their priority values.
1812 * @return string Types of encoding to accept.
1814 function accept_encoding() {
1816 if ( function_exists( 'gzinflate' ) )
1817 $type[] = 'deflate;q=1.0';
1819 if ( function_exists( 'gzuncompress' ) )
1820 $type[] = 'compress;q=0.5';
1822 if ( function_exists( 'gzdecode' ) )
1823 $type[] = 'gzip;q=0.5';
1825 return implode(', ', $type);
1829 * What enconding the content used when it was compressed to send in the headers.
1833 * @return string Content-Encoding string to send in the header.
1835 function content_encoding() {
1840 * Whether the content be decoded based on the headers.
1844 * @param array|string $headers All of the available headers.
1847 function should_decode($headers) {
1848 if ( is_array( $headers ) ) {
1849 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
1851 } else if( is_string( $headers ) ) {
1852 return ( stripos($headers, 'content-encoding:') !== false );
1859 * Whether decompression and compression are supported by the PHP version.
1861 * Each function is tested instead of checking for the zlib extension, to
1862 * ensure that the functions all exist in the PHP version and aren't
1869 function is_available() {
1870 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
1875 * Returns the initialized WP_Http Object
1880 * @return WP_Http HTTP Transport object.
1882 function &_wp_http_get_object() {
1885 if ( is_null($http) )
1886 $http = new WP_Http();
1892 * Retrieve the raw response from the HTTP request.
1894 * The array structure is a little complex.
1897 * $res = array( 'headers' => array(), 'response' => array('code' => int, 'message' => string) );
1900 * All of the headers in $res['headers'] are with the name as the key and the
1901 * value as the value. So to get the User-Agent, you would do the following.
1904 * $user_agent = $res['headers']['user-agent'];
1907 * The body is the raw response content and can be retrieved from $res['body'].
1909 * This function is called first to make the request and there are other API
1910 * functions to abstract out the above convoluted setup.
1914 * @param string $url Site URL to retrieve.
1915 * @param array $args Optional. Override the defaults.
1916 * @return WP_Error|array The response or WP_Error on failure.
1918 function wp_remote_request($url, $args = array()) {
1919 $objFetchSite = _wp_http_get_object();
1920 return $objFetchSite->request($url, $args);
1924 * Retrieve the raw response from the HTTP request using the GET method.
1926 * @see wp_remote_request() For more information on the response array format.
1930 * @param string $url Site URL to retrieve.
1931 * @param array $args Optional. Override the defaults.
1932 * @return WP_Error|array The response or WP_Error on failure.
1934 function wp_remote_get($url, $args = array()) {
1935 $objFetchSite = _wp_http_get_object();
1936 return $objFetchSite->get($url, $args);
1940 * Retrieve the raw response from the HTTP request using the POST method.
1942 * @see wp_remote_request() For more information on the response array format.
1946 * @param string $url Site URL to retrieve.
1947 * @param array $args Optional. Override the defaults.
1948 * @return WP_Error|array The response or WP_Error on failure.
1950 function wp_remote_post($url, $args = array()) {
1951 $objFetchSite = _wp_http_get_object();
1952 return $objFetchSite->post($url, $args);
1956 * Retrieve the raw response from the HTTP request using the HEAD method.
1958 * @see wp_remote_request() For more information on the response array format.
1962 * @param string $url Site URL to retrieve.
1963 * @param array $args Optional. Override the defaults.
1964 * @return WP_Error|array The response or WP_Error on failure.
1966 function wp_remote_head($url, $args = array()) {
1967 $objFetchSite = _wp_http_get_object();
1968 return $objFetchSite->head($url, $args);
1972 * Retrieve only the headers from the raw response.
1976 * @param array $response HTTP response.
1977 * @return array The headers of the response. Empty array if incorrect parameter given.
1979 function wp_remote_retrieve_headers(&$response) {
1980 if ( is_wp_error($response) || ! isset($response['headers']) || ! is_array($response['headers']))
1983 return $response['headers'];
1987 * Retrieve a single header by name from the raw response.
1991 * @param array $response
1992 * @param string $header Header name to retrieve value from.
1993 * @return string The header value. Empty string on if incorrect parameter given, or if the header doesnt exist.
1995 function wp_remote_retrieve_header(&$response, $header) {
1996 if ( is_wp_error($response) || ! isset($response['headers']) || ! is_array($response['headers']))
1999 if ( array_key_exists($header, $response['headers']) )
2000 return $response['headers'][$header];
2006 * Retrieve only the response code from the raw response.
2008 * Will return an empty array if incorrect parameter value is given.
2012 * @param array $response HTTP response.
2013 * @return string the response code. Empty string on incorrect parameter given.
2015 function wp_remote_retrieve_response_code(&$response) {
2016 if ( is_wp_error($response) || ! isset($response['response']) || ! is_array($response['response']))
2019 return $response['response']['code'];
2023 * Retrieve only the response message from the raw response.
2025 * Will return an empty array if incorrect parameter value is given.
2029 * @param array $response HTTP response.
2030 * @return string The response message. Empty string on incorrect parameter given.
2032 function wp_remote_retrieve_response_message(&$response) {
2033 if ( is_wp_error($response) || ! isset($response['response']) || ! is_array($response['response']))
2036 return $response['response']['message'];
2040 * Retrieve only the body from the raw response.
2044 * @param array $response HTTP response.
2045 * @return string The body of the response. Empty string if no body or incorrect parameter given.
2047 function wp_remote_retrieve_body(&$response) {
2048 if ( is_wp_error($response) || ! isset($response['body']) )
2051 return $response['body'];