]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-http.php
Wordpress 3.1.3
[autoinstalls/wordpress.git] / wp-includes / class-http.php
1 <?php
2 /**
3  * Simple and uniform HTTP request API.
4  *
5  * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
6  * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
7  *
8  * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal
9  *
10  * @package WordPress
11  * @subpackage HTTP
12  * @since 2.7.0
13  */
14
15 /**
16  * WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
17  *
18  * This class is called for the functionality of making HTTP requests and replaces Snoopy
19  * functionality. There is no available functionality to add HTTP transport implementations, since
20  * most of the HTTP transports are added and available for use.
21  *
22  * There are no properties, because none are needed and for performance reasons. Some of the
23  * functions are static and while they do have some overhead over functions in PHP4, the purpose is
24  * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword
25  * to the code. It is not as easy to convert a function to a method after enough code uses the old
26  * way.
27  *
28  * Debugging includes several actions, which pass different variables for debugging the HTTP API.
29  *
30  * <strong>http_transport_get_debug</strong> - gives working, nonblocking, and blocking transports.
31  *
32  * <strong>http_transport_post_debug</strong> - gives working, nonblocking, and blocking transports.
33  *
34  * @package WordPress
35  * @subpackage HTTP
36  * @since 2.7.0
37  */
38 class WP_Http {
39
40         /**
41          * PHP4 style Constructor - Calls PHP5 Style Constructor
42          *
43          * @since 2.7.0
44          * @return WP_Http
45          */
46         function WP_Http() {
47                 $this->__construct();
48         }
49
50         /**
51          * PHP5 style Constructor - Set up available transport if not available.
52          *
53          * PHP4 does not have the 'self' keyword and since WordPress supports PHP4, the class needs to
54          * be used for the static call. The transport are set up to save time and will only be created
55          * once. This class can be created many times without having to go through the step of finding
56          * which transports are available.
57          *
58          * @since 2.7.0
59          * @return WP_Http
60          */
61         function __construct() {
62                 WP_Http::_getTransport();
63                 WP_Http::_postTransport();
64         }
65
66         /**
67          * Tests the WordPress HTTP objects for an object to use and returns it.
68          *
69          * Tests all of the objects and returns the object that passes. Also caches that object to be
70          * used later.
71          *
72          * The order for the GET/HEAD requests are HTTP Extension, cURL, Streams, Fopen, and finally
73          * Fsockopen. fsockopen() is used last, because it has the most overhead in its implementation.
74          * There isn't any real way around it, since redirects have to be supported, much the same way
75          * the other transports also handle redirects.
76          *
77          * There are currently issues with "localhost" not resolving correctly with DNS. This may cause
78          * an error "failed to open stream: A connection attempt failed because the connected party did
79          * not properly respond after a period of time, or established connection failed because [the]
80          * connected host has failed to respond."
81          *
82          * @since 2.7.0
83          * @access private
84          *
85          * @param array $args Request args, default us an empty array
86          * @return object|null Null if no transports are available, HTTP transport object.
87          */
88         function &_getTransport( $args = array() ) {
89                 static $working_transport, $blocking_transport, $nonblocking_transport;
90
91                 if ( is_null($working_transport) ) {
92                         if ( true === WP_Http_ExtHttp::test($args) ) {
93                                 $working_transport['exthttp'] = new WP_Http_ExtHttp();
94                                 $blocking_transport[] = &$working_transport['exthttp'];
95                         } else if ( true === WP_Http_Curl::test($args) ) {
96                                 $working_transport['curl'] = new WP_Http_Curl();
97                                 $blocking_transport[] = &$working_transport['curl'];
98                         } else if ( true === WP_Http_Streams::test($args) ) {
99                                 $working_transport['streams'] = new WP_Http_Streams();
100                                 $blocking_transport[] = &$working_transport['streams'];
101                         } else if ( true === WP_Http_Fopen::test($args) ) {
102                                 $working_transport['fopen'] = new WP_Http_Fopen();
103                                 $blocking_transport[] = &$working_transport['fopen'];
104                         } else if ( true === WP_Http_Fsockopen::test($args) ) {
105                                 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
106                                 $blocking_transport[] = &$working_transport['fsockopen'];
107                         }
108
109                         foreach ( array('curl', 'streams', 'fopen', 'fsockopen', 'exthttp') as $transport ) {
110                                 if ( isset($working_transport[$transport]) )
111                                         $nonblocking_transport[] = &$working_transport[$transport];
112                         }
113                 }
114
115                 do_action( 'http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport );
116
117                 if ( isset($args['blocking']) && !$args['blocking'] )
118                         return $nonblocking_transport;
119                 else
120                         return $blocking_transport;
121         }
122
123         /**
124          * Tests the WordPress HTTP objects for an object to use and returns it.
125          *
126          * Tests all of the objects and returns the object that passes. Also caches
127          * that object to be used later. This is for posting content to a URL and
128          * is used when there is a body. The plain Fopen Transport can not be used
129          * to send content, but the streams transport can. This is a limitation that
130          * is addressed here, by just not including that transport.
131          *
132          * @since 2.7.0
133          * @access private
134          *
135          * @param array $args Request args, default us an empty array
136          * @return object|null Null if no transports are available, HTTP transport object.
137          */
138         function &_postTransport( $args = array() ) {
139                 static $working_transport, $blocking_transport, $nonblocking_transport;
140
141                 if ( is_null($working_transport) ) {
142                         if ( true === WP_Http_ExtHttp::test($args) ) {
143                                 $working_transport['exthttp'] = new WP_Http_ExtHttp();
144                                 $blocking_transport[] = &$working_transport['exthttp'];
145                         } else if ( true === WP_Http_Curl::test($args) ) {
146                                 $working_transport['curl'] = new WP_Http_Curl();
147                                 $blocking_transport[] = &$working_transport['curl'];
148                         } else if ( true === WP_Http_Streams::test($args) ) {
149                                 $working_transport['streams'] = new WP_Http_Streams();
150                                 $blocking_transport[] = &$working_transport['streams'];
151                         } else if ( true === WP_Http_Fsockopen::test($args) ) {
152                                 $working_transport['fsockopen'] = new WP_Http_Fsockopen();
153                                 $blocking_transport[] = &$working_transport['fsockopen'];
154                         }
155
156                         foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) {
157                                 if ( isset($working_transport[$transport]) )
158                                         $nonblocking_transport[] = &$working_transport[$transport];
159                         }
160                 }
161
162                 do_action( 'http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport );
163
164                 if ( isset($args['blocking']) && !$args['blocking'] )
165                         return $nonblocking_transport;
166                 else
167                         return $blocking_transport;
168         }
169
170         /**
171          * Send a HTTP request to a URI.
172          *
173          * The body and headers are part of the arguments. The 'body' argument is for the body and will
174          * accept either a string or an array. The 'headers' argument should be an array, but a string
175          * is acceptable. If the 'body' argument is an array, then it will automatically be escaped
176          * using http_build_query().
177          *
178          * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
179          * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send
180          * headers. Other protocols are unsupported and most likely will fail.
181          *
182          * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
183          * 'user-agent'.
184          *
185          * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
186          * others, but should not be assumed. The 'timeout' is used to sent how long the connection
187          * should stay open before failing when no response. 'redirection' is used to track how many
188          * redirects were taken and used to sent the amount for other transports, but not all transports
189          * accept setting that value.
190          *
191          * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
192          * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The
193          * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is
194          * 'WordPress/WP_Version', where WP_Version is the value from $wp_version.
195          *
196          * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP
197          * while it performs the request or continue regardless. Actually, that isn't entirely correct.
198          * Blocking mode really just means whether the fread should just pull what it can whenever it
199          * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading
200          * the entire content. It doesn't actually always mean that PHP will continue going after making
201          * the request.
202          *
203          * @access public
204          * @since 2.7.0
205          * @todo Refactor this code. The code in this method extends the scope of its original purpose
206          *              and should be refactored to allow for cleaner abstraction and reduce duplication of the
207          *              code. One suggestion is to create a class specifically for the arguments, however
208          *              preliminary refactoring to this affect has affect more than just the scope of the
209          *              arguments. Something to ponder at least.
210          *
211          * @param string $url URI resource.
212          * @param str|array $args Optional. Override the defaults.
213          * @return array containing 'headers', 'body', 'response', 'cookies'
214          */
215         function request( $url, $args = array() ) {
216                 global $wp_version;
217
218                 $defaults = array(
219                         'method' => 'GET',
220                         'timeout' => apply_filters( 'http_request_timeout', 5),
221                         'redirection' => apply_filters( 'http_request_redirection_count', 5),
222                         'httpversion' => apply_filters( 'http_request_version', '1.0'),
223                         'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )  ),
224                         'blocking' => true,
225                         'headers' => array(),
226                         'cookies' => array(),
227                         'body' => null,
228                         'compress' => false,
229                         'decompress' => true,
230                         'sslverify' => true
231                 );
232
233                 $r = wp_parse_args( $args, $defaults );
234                 $r = apply_filters( 'http_request_args', $r, $url );
235
236                 // Allow plugins to short-circuit the request
237                 $pre = apply_filters( 'pre_http_request', false, $r, $url );
238                 if ( false !== $pre )
239                         return $pre;
240
241                 $arrURL = parse_url( $url );
242
243                 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
244                         return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
245
246                 if ( $this->block_request( $url ) )
247                         return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
248
249                 // Determine if this is a https call and pass that on to the transport functions
250                 // so that we can blacklist the transports that do not support ssl verification
251                 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
252
253                 // Determine if this request is to OUR install of WordPress
254                 $homeURL = parse_url( get_bloginfo( 'url' ) );
255                 $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
256                 unset( $homeURL );
257
258                 if ( is_null( $r['headers'] ) )
259                         $r['headers'] = array();
260
261                 if ( ! is_array( $r['headers'] ) ) {
262                         $processedHeaders = WP_Http::processHeaders( $r['headers'] );
263                         $r['headers'] = $processedHeaders['headers'];
264                 }
265
266                 if ( isset( $r['headers']['User-Agent'] ) ) {
267                         $r['user-agent'] = $r['headers']['User-Agent'];
268                         unset( $r['headers']['User-Agent'] );
269                 }
270
271                 if ( isset( $r['headers']['user-agent'] ) ) {
272                         $r['user-agent'] = $r['headers']['user-agent'];
273                         unset( $r['headers']['user-agent'] );
274                 }
275
276                 // Construct Cookie: header if any cookies are set
277                 WP_Http::buildCookieHeader( $r );
278
279                 if ( WP_Http_Encoding::is_available() )
280                         $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding();
281
282                 if ( empty($r['body']) ) {
283                         $r['body'] = null;
284                         // Some servers fail when sending content without the content-length header being set.
285                         // Also, to fix another bug, we only send when doing POST and PUT and the content-length
286                         // header isn't already set.
287                         if ( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset( $r['headers']['Content-Length'] ) )
288                                 $r['headers']['Content-Length'] = 0;
289
290                         // The method is ambiguous, because we aren't talking about HTTP methods, the "get" in
291                         // this case is simply that we aren't sending any bodies and to get the transports that
292                         // don't support sending bodies along with those which do.
293                         $transports = WP_Http::_getTransport( $r );
294                 } else {
295                         if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
296                                 if ( ! version_compare(phpversion(), '5.1.2', '>=') )
297                                         $r['body'] = _http_build_query( $r['body'], null, '&' );
298                                 else
299                                         $r['body'] = http_build_query( $r['body'], null, '&' );
300                                 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
301                                 $r['headers']['Content-Length'] = strlen( $r['body'] );
302                         }
303
304                         if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
305                                 $r['headers']['Content-Length'] = strlen( $r['body'] );
306
307                         // The method is ambiguous, because we aren't talking about HTTP methods, the "post" in
308                         // this case is simply that we are sending HTTP body and to get the transports that do
309                         // support sending the body. Not all do, depending on the limitations of the PHP core
310                         // limitations.
311                         $transports = WP_Http::_postTransport( $r );
312                 }
313
314                 do_action( 'http_api_debug', $transports, 'transports_list' );
315
316                 $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
317                 foreach ( (array) $transports as $transport ) {
318                         $response = $transport->request( $url, $r );
319
320                         do_action( 'http_api_debug', $response, 'response', get_class( $transport ) );
321
322                         if ( ! is_wp_error( $response ) )
323                                 return apply_filters( 'http_response', $response, $r, $url );
324                 }
325
326                 return $response;
327         }
328
329         /**
330          * Uses the POST HTTP method.
331          *
332          * Used for sending data that is expected to be in the body.
333          *
334          * @access public
335          * @since 2.7.0
336          *
337          * @param string $url URI resource.
338          * @param str|array $args Optional. Override the defaults.
339          * @return boolean
340          */
341         function post($url, $args = array()) {
342                 $defaults = array('method' => 'POST');
343                 $r = wp_parse_args( $args, $defaults );
344                 return $this->request($url, $r);
345         }
346
347         /**
348          * Uses the GET HTTP method.
349          *
350          * Used for sending data that is expected to be in the body.
351          *
352          * @access public
353          * @since 2.7.0
354          *
355          * @param string $url URI resource.
356          * @param str|array $args Optional. Override the defaults.
357          * @return boolean
358          */
359         function get($url, $args = array()) {
360                 $defaults = array('method' => 'GET');
361                 $r = wp_parse_args( $args, $defaults );
362                 return $this->request($url, $r);
363         }
364
365         /**
366          * Uses the HEAD HTTP method.
367          *
368          * Used for sending data that is expected to be in the body.
369          *
370          * @access public
371          * @since 2.7.0
372          *
373          * @param string $url URI resource.
374          * @param str|array $args Optional. Override the defaults.
375          * @return boolean
376          */
377         function head($url, $args = array()) {
378                 $defaults = array('method' => 'HEAD');
379                 $r = wp_parse_args( $args, $defaults );
380                 return $this->request($url, $r);
381         }
382
383         /**
384          * Parses the responses and splits the parts into headers and body.
385          *
386          * @access public
387          * @static
388          * @since 2.7.0
389          *
390          * @param string $strResponse The full response string
391          * @return array Array with 'headers' and 'body' keys.
392          */
393         function processResponse($strResponse) {
394                 $res = explode("\r\n\r\n", $strResponse, 2);
395
396                 return array('headers' => isset($res[0]) ? $res[0] : array(), 'body' => isset($res[1]) ? $res[1] : '');
397         }
398
399         /**
400          * Transform header string into an array.
401          *
402          * If an array is given then it is assumed to be raw header data with numeric keys with the
403          * headers as the values. No headers must be passed that were already processed.
404          *
405          * @access public
406          * @static
407          * @since 2.7.0
408          *
409          * @param string|array $headers
410          * @return array Processed string headers. If duplicate headers are encountered,
411          *                                      Then a numbered array is returned as the value of that header-key.
412          */
413         function processHeaders($headers) {
414                 // split headers, one per array element
415                 if ( is_string($headers) ) {
416                         // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
417                         $headers = str_replace("\r\n", "\n", $headers);
418                         // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
419                         $headers = preg_replace('/\n[ \t]/', ' ', $headers);
420                         // create the headers array
421                         $headers = explode("\n", $headers);
422                 }
423
424                 $response = array('code' => 0, 'message' => '');
425
426                 // If a redirection has taken place, The headers for each page request may have been passed.
427                 // In this case, determine the final HTTP header and parse from there.
428                 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
429                         if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
430                                 $headers = array_splice($headers, $i);
431                                 break;
432                         }
433                 }
434
435                 $cookies = array();
436                 $newheaders = array();
437                 foreach ( $headers as $tempheader ) {
438                         if ( empty($tempheader) )
439                                 continue;
440
441                         if ( false === strpos($tempheader, ':') ) {
442                                 list( , $response['code'], $response['message']) = explode(' ', $tempheader, 3);
443                                 continue;
444                         }
445
446                         list($key, $value) = explode(':', $tempheader, 2);
447
448                         if ( !empty( $value ) ) {
449                                 $key = strtolower( $key );
450                                 if ( isset( $newheaders[$key] ) ) {
451                                         if ( !is_array($newheaders[$key]) )
452                                                 $newheaders[$key] = array($newheaders[$key]);
453                                         $newheaders[$key][] = trim( $value );
454                                 } else {
455                                         $newheaders[$key] = trim( $value );
456                                 }
457                                 if ( 'set-cookie' == $key )
458                                         $cookies[] = new WP_Http_Cookie( $value );
459                         }
460                 }
461
462                 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
463         }
464
465         /**
466          * Takes the arguments for a ::request() and checks for the cookie array.
467          *
468          * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
469          * into strings and added to the Cookie: header (within the arguments array). Edits the array by
470          * reference.
471          *
472          * @access public
473          * @version 2.8.0
474          * @static
475          *
476          * @param array $r Full array of args passed into ::request()
477          */
478         function buildCookieHeader( &$r ) {
479                 if ( ! empty($r['cookies']) ) {
480                         $cookies_header = '';
481                         foreach ( (array) $r['cookies'] as $cookie ) {
482                                 $cookies_header .= $cookie->getHeaderValue() . '; ';
483                         }
484                         $cookies_header = substr( $cookies_header, 0, -2 );
485                         $r['headers']['cookie'] = $cookies_header;
486                 }
487         }
488
489         /**
490          * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
491          *
492          * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
493          * returning footer headers. Shouldn't be too difficult to support it though.
494          *
495          * @todo Add support for footer chunked headers.
496          * @access public
497          * @since 2.7.0
498          * @static
499          *
500          * @param string $body Body content
501          * @return string Chunked decoded body on success or raw body on failure.
502          */
503         function chunkTransferDecode($body) {
504                 $body = str_replace(array("\r\n", "\r"), "\n", $body);
505                 // The body is not chunked encoding or is malformed.
506                 if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
507                         return $body;
508
509                 $parsedBody = '';
510                 //$parsedHeaders = array(); Unsupported
511
512                 while ( true ) {
513                         $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
514
515                         if ( $hasChunk ) {
516                                 if ( empty( $match[1] ) )
517                                         return $body;
518
519                                 $length = hexdec( $match[1] );
520                                 $chunkLength = strlen( $match[0] );
521
522                                 $strBody = substr($body, $chunkLength, $length);
523                                 $parsedBody .= $strBody;
524
525                                 $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
526
527                                 if ( "0" == trim($body) )
528                                         return $parsedBody; // Ignore footer headers.
529                         } else {
530                                 return $body;
531                         }
532                 }
533         }
534
535         /**
536          * Block requests through the proxy.
537          *
538          * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
539          * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
540          *
541          * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
542          * file and this will only allow localhost and your blog to make requests. The constant
543          * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
544          * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
545          * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
546          *
547          * @since 2.8.0
548          * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
549          * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
550          *
551          * @param string $uri URI of url.
552          * @return bool True to block, false to allow.
553          */
554         function block_request($uri) {
555                 // We don't need to block requests, because nothing is blocked.
556                 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
557                         return false;
558
559                 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
560                 // This will be displayed on blogs, which is not reasonable.
561                 $check = @parse_url($uri);
562
563                 /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
564                  *
565                  * This isn't very security sound. There are instances where a hacker might attempt
566                  * to bypass the proxy and this check. However, the reason for this behavior is that
567                  * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
568                  * the default unsecure nature of the HTTP request.
569                  */
570                 if ( $check === false )
571                         return false;
572
573                 $home = parse_url( get_option('siteurl') );
574
575                 // Don't block requests back to ourselves by default
576                 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
577                         return apply_filters('block_local_requests', false);
578
579                 if ( !defined('WP_ACCESSIBLE_HOSTS') )
580                         return true;
581
582                 static $accessible_hosts;
583                 static $wildcard_regex = false;
584                 if ( null == $accessible_hosts ) {
585                         $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
586
587                         if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
588                                 $wildcard_regex = array();
589                                 foreach ( $accessible_hosts as $host )
590                                         $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
591                                 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
592                         }
593                 }
594
595                 if ( !empty($wildcard_regex) )
596                         return !preg_match($wildcard_regex, $check['host']);
597                 else
598                         return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
599
600
601
602         }
603 }
604
605 /**
606  * HTTP request method uses fsockopen function to retrieve the url.
607  *
608  * This would be the preferred method, but the fsockopen implementation has the most overhead of all
609  * the HTTP transport implementations.
610  *
611  * @package WordPress
612  * @subpackage HTTP
613  * @since 2.7.0
614  */
615 class WP_Http_Fsockopen {
616         /**
617          * Send a HTTP request to a URI using fsockopen().
618          *
619          * Does not support non-blocking mode.
620          *
621          * @see WP_Http::request For default options descriptions.
622          *
623          * @since 2.7
624          * @access public
625          * @param string $url URI resource.
626          * @param str|array $args Optional. Override the defaults.
627          * @return array 'headers', 'body', 'cookies' and 'response' keys.
628          */
629         function request($url, $args = array()) {
630                 $defaults = array(
631                         'method' => 'GET', 'timeout' => 5,
632                         'redirection' => 5, 'httpversion' => '1.0',
633                         'blocking' => true,
634                         'headers' => array(), 'body' => null, 'cookies' => array()
635                 );
636
637                 $r = wp_parse_args( $args, $defaults );
638
639                 if ( isset($r['headers']['User-Agent']) ) {
640                         $r['user-agent'] = $r['headers']['User-Agent'];
641                         unset($r['headers']['User-Agent']);
642                 } else if ( isset($r['headers']['user-agent']) ) {
643                         $r['user-agent'] = $r['headers']['user-agent'];
644                         unset($r['headers']['user-agent']);
645                 }
646
647                 // Construct Cookie: header if any cookies are set
648                 WP_Http::buildCookieHeader( $r );
649
650                 $iError = null; // Store error number
651                 $strError = null; // Store error string
652
653                 $arrURL = parse_url($url);
654
655                 $fsockopen_host = $arrURL['host'];
656
657                 $secure_transport = false;
658
659                 if ( ! isset( $arrURL['port'] ) ) {
660                         if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
661                                 $fsockopen_host = "ssl://$fsockopen_host";
662                                 $arrURL['port'] = 443;
663                                 $secure_transport = true;
664                         } else {
665                                 $arrURL['port'] = 80;
666                         }
667                 }
668
669                 //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
670                 // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
671                 if ( 'localhost' == strtolower($fsockopen_host) )
672                         $fsockopen_host = '127.0.0.1';
673
674                 // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
675                 // ignored and should be ignored.
676                 if ( true === $secure_transport )
677                         $error_reporting = error_reporting(0);
678
679                 $startDelay = time();
680
681                 $proxy = new WP_HTTP_Proxy();
682
683                 if ( !WP_DEBUG ) {
684                         if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
685                                 $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
686                         else
687                                 $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
688                 } else {
689                         if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
690                                 $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
691                         else
692                                 $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
693                 }
694
695                 $endDelay = time();
696
697                 // If the delay is greater than the timeout then fsockopen should't be used, because it will
698                 // cause a long delay.
699                 $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
700                 if ( true === $elapseDelay )
701                         add_option( 'disable_fsockopen', $endDelay, null, true );
702
703                 if ( false === $handle )
704                         return new WP_Error('http_request_failed', $iError . ': ' . $strError);
705
706                 $timeout = (int) floor( $r['timeout'] );
707                 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
708                 stream_set_timeout( $handle, $timeout, $utimeout );
709
710                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
711                         $requestPath = $url;
712                 else
713                         $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
714
715                 if ( empty($requestPath) )
716                         $requestPath .= '/';
717
718                 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
719
720                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
721                         $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
722                 else
723                         $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
724
725                 if ( isset($r['user-agent']) )
726                         $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
727
728                 if ( is_array($r['headers']) ) {
729                         foreach ( (array) $r['headers'] as $header => $headerValue )
730                                 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
731                 } else {
732                         $strHeaders .= $r['headers'];
733                 }
734
735                 if ( $proxy->use_authentication() )
736                         $strHeaders .= $proxy->authentication_header() . "\r\n";
737
738                 $strHeaders .= "\r\n";
739
740                 if ( ! is_null($r['body']) )
741                         $strHeaders .= $r['body'];
742
743                 fwrite($handle, $strHeaders);
744
745                 if ( ! $r['blocking'] ) {
746                         fclose($handle);
747                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
748                 }
749
750                 $strResponse = '';
751                 while ( ! feof($handle) )
752                         $strResponse .= fread($handle, 4096);
753
754                 fclose($handle);
755
756                 if ( true === $secure_transport )
757                         error_reporting($error_reporting);
758
759                 $process = WP_Http::processResponse($strResponse);
760                 $arrHeaders = WP_Http::processHeaders($process['headers']);
761
762                 // Is the response code within the 400 range?
763                 if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 )
764                         return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']);
765
766                 // If location is found, then assume redirect and redirect to location.
767                 if ( 'HEAD' != $r['method'] && isset($arrHeaders['headers']['location']) ) {
768                         if ( $r['redirection']-- > 0 ) {
769                                 return $this->request($arrHeaders['headers']['location'], $r);
770                         } else {
771                                 return new WP_Error('http_request_failed', __('Too many redirects.'));
772                         }
773                 }
774
775                 // If the body was chunk encoded, then decode it.
776                 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
777                         $process['body'] = WP_Http::chunkTransferDecode($process['body']);
778
779                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
780                         $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
781
782                 return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']);
783         }
784
785         /**
786          * Whether this class can be used for retrieving an URL.
787          *
788          * @since 2.7.0
789          * @static
790          * @return boolean False means this class can not be used, true means it can.
791          */
792         function test( $args = array() ) {
793                 if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
794                         return false;
795
796                 $is_ssl = isset($args['ssl']) && $args['ssl'];
797
798                 if ( ! $is_ssl && function_exists( 'fsockopen' ) )
799                         $use = true;
800                 elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) )
801                         $use = true;
802                 else
803                         $use = false;
804
805                 return apply_filters('use_fsockopen_transport', $use, $args);
806         }
807 }
808
809 /**
810  * HTTP request method uses fopen function to retrieve the url.
811  *
812  * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support,
813  * but should still be okay, to write the headers, before getting the response. Also requires that
814  * 'allow_url_fopen' to be enabled.
815  *
816  * @package WordPress
817  * @subpackage HTTP
818  * @since 2.7.0
819  */
820 class WP_Http_Fopen {
821         /**
822          * Send a HTTP request to a URI using fopen().
823          *
824          * This transport does not support sending of headers and body, therefore should not be used in
825          * the instances, where there is a body and headers.
826          *
827          * Notes: Does not support non-blocking mode. Ignores 'redirection' option.
828          *
829          * @see WP_Http::retrieve For default options descriptions.
830          *
831          * @access public
832          * @since 2.7.0
833          *
834          * @param string $url URI resource.
835          * @param str|array $args Optional. Override the defaults.
836          * @return array 'headers', 'body', 'cookies' and 'response' keys.
837          */
838         function request($url, $args = array()) {
839                 $defaults = array(
840                         'method' => 'GET', 'timeout' => 5,
841                         'redirection' => 5, 'httpversion' => '1.0',
842                         'blocking' => true,
843                         'headers' => array(), 'body' => null, 'cookies' => array()
844                 );
845
846                 $r = wp_parse_args( $args, $defaults );
847
848                 $arrURL = parse_url($url);
849
850                 if ( false === $arrURL )
851                         return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
852
853                 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
854                         $url = str_replace($arrURL['scheme'], 'http', $url);
855
856                 if ( is_null( $r['headers'] ) )
857                         $r['headers'] = array();
858
859                 if ( is_string($r['headers']) ) {
860                         $processedHeaders = WP_Http::processHeaders($r['headers']);
861                         $r['headers'] = $processedHeaders['headers'];
862                 }
863
864                 $initial_user_agent = ini_get('user_agent');
865
866                 if ( !empty($r['headers']) && is_array($r['headers']) ) {
867                         $user_agent_extra_headers = '';
868                         foreach ( $r['headers'] as $header => $value )
869                                 $user_agent_extra_headers .= "\r\n$header: $value";
870                         @ini_set('user_agent', $r['user-agent'] . $user_agent_extra_headers);
871                 } else {
872                         @ini_set('user_agent', $r['user-agent']);
873                 }
874
875                 if ( !WP_DEBUG )
876                         $handle = @fopen($url, 'r');
877                 else
878                         $handle = fopen($url, 'r');
879
880                 if (! $handle)
881                         return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
882
883                 $timeout = (int) floor( $r['timeout'] );
884                 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
885                 stream_set_timeout( $handle, $timeout, $utimeout );
886
887                 if ( ! $r['blocking'] ) {
888                         fclose($handle);
889                         @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
890                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
891                 }
892
893                 $strResponse = '';
894                 while ( ! feof($handle) )
895                         $strResponse .= fread($handle, 4096);
896
897                 if ( function_exists('stream_get_meta_data') ) {
898                         $meta = stream_get_meta_data($handle);
899
900                         $theHeaders = $meta['wrapper_data'];
901                         if ( isset( $meta['wrapper_data']['headers'] ) )
902                                 $theHeaders = $meta['wrapper_data']['headers'];
903                 } else {
904                         //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper
905                         //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php
906                         $theHeaders = $http_response_header;
907                 }
908
909                 fclose($handle);
910
911                 @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
912
913                 $processedHeaders = WP_Http::processHeaders($theHeaders);
914
915                 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
916                         $strResponse = WP_Http::chunkTransferDecode($strResponse);
917
918                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
919                         $strResponse = WP_Http_Encoding::decompress( $strResponse );
920
921                 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
922         }
923
924         /**
925          * Whether this class can be used for retrieving an URL.
926          *
927          * @since 2.7.0
928          * @static
929          * @return boolean False means this class can not be used, true means it can.
930          */
931         function test($args = array()) {
932                 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
933                         return false;
934
935                 if ( isset($args['method']) && 'HEAD' == $args['method'] ) //This transport cannot make a HEAD request
936                         return false;
937
938                 $use = true;
939                 //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off.
940                 $is_ssl = isset($args['ssl']) && $args['ssl'];
941                 if ( $is_ssl ) {
942                         $is_local = isset($args['local']) && $args['local'];
943                         $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
944                         if ( $is_local && true != apply_filters('https_local_ssl_verify', true) )
945                                 $use = true;
946                         elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) )
947                                 $use = true;
948                         elseif ( !$ssl_verify )
949                                 $use = true;
950                         else
951                                 $use = false;
952                 }
953
954                 return apply_filters('use_fopen_transport', $use, $args);
955         }
956 }
957
958 /**
959  * HTTP request method uses Streams to retrieve the url.
960  *
961  * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
962  * to be enabled.
963  *
964  * Second preferred method for getting the URL, for PHP 5.
965  *
966  * @package WordPress
967  * @subpackage HTTP
968  * @since 2.7.0
969  */
970 class WP_Http_Streams {
971         /**
972          * Send a HTTP request to a URI using streams with fopen().
973          *
974          * @access public
975          * @since 2.7.0
976          *
977          * @param string $url
978          * @param str|array $args Optional. Override the defaults.
979          * @return array 'headers', 'body', 'cookies' and 'response' keys.
980          */
981         function request($url, $args = array()) {
982                 $defaults = array(
983                         'method' => 'GET', 'timeout' => 5,
984                         'redirection' => 5, 'httpversion' => '1.0',
985                         'blocking' => true,
986                         'headers' => array(), 'body' => null, 'cookies' => array()
987                 );
988
989                 $r = wp_parse_args( $args, $defaults );
990
991                 if ( isset($r['headers']['User-Agent']) ) {
992                         $r['user-agent'] = $r['headers']['User-Agent'];
993                         unset($r['headers']['User-Agent']);
994                 } else if ( isset($r['headers']['user-agent']) ) {
995                         $r['user-agent'] = $r['headers']['user-agent'];
996                         unset($r['headers']['user-agent']);
997                 }
998
999                 // Construct Cookie: header if any cookies are set
1000                 WP_Http::buildCookieHeader( $r );
1001
1002                 $arrURL = parse_url($url);
1003
1004                 if ( false === $arrURL )
1005                         return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
1006
1007                 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
1008                         $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1009
1010                 // Convert Header array to string.
1011                 $strHeaders = '';
1012                 if ( is_array( $r['headers'] ) )
1013                         foreach ( $r['headers'] as $name => $value )
1014                                 $strHeaders .= "{$name}: $value\r\n";
1015                 else if ( is_string( $r['headers'] ) )
1016                         $strHeaders = $r['headers'];
1017
1018                 $is_local = isset($args['local']) && $args['local'];
1019                 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1020                 if ( $is_local )
1021                         $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1022                 elseif ( ! $is_local )
1023                         $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1024
1025                 $arrContext = array('http' =>
1026                         array(
1027                                 'method' => strtoupper($r['method']),
1028                                 'user_agent' => $r['user-agent'],
1029                                 'max_redirects' => $r['redirection'] + 1, // See #11557
1030                                 'protocol_version' => (float) $r['httpversion'],
1031                                 'header' => $strHeaders,
1032                                 'ignore_errors' => true, // Return non-200 requests.
1033                                 'timeout' => $r['timeout'],
1034                                 'ssl' => array(
1035                                                 'verify_peer' => $ssl_verify,
1036                                                 'verify_host' => $ssl_verify
1037                                 )
1038                         )
1039                 );
1040
1041                 $proxy = new WP_HTTP_Proxy();
1042
1043                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1044                         $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
1045                         $arrContext['http']['request_fulluri'] = true;
1046
1047                         // We only support Basic authentication so this will only work if that is what your proxy supports.
1048                         if ( $proxy->use_authentication() )
1049                                 $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
1050                 }
1051
1052                 if ( 'HEAD' == $r['method'] ) // Disable redirects for HEAD requests
1053                         $arrContext['http']['max_redirects'] = 1;
1054
1055                 if ( ! empty($r['body'] ) )
1056                         $arrContext['http']['content'] = $r['body'];
1057
1058                 $context = stream_context_create($arrContext);
1059
1060                 if ( !WP_DEBUG )
1061                         $handle = @fopen($url, 'r', false, $context);
1062                 else
1063                         $handle = fopen($url, 'r', false, $context);
1064
1065                 if ( ! $handle )
1066                         return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
1067
1068                 $timeout = (int) floor( $r['timeout'] );
1069                 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
1070                 stream_set_timeout( $handle, $timeout, $utimeout );
1071
1072                 if ( ! $r['blocking'] ) {
1073                         stream_set_blocking($handle, 0);
1074                         fclose($handle);
1075                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1076                 }
1077
1078                 $strResponse = stream_get_contents($handle);
1079                 $meta = stream_get_meta_data($handle);
1080
1081                 fclose($handle);
1082
1083                 $processedHeaders = array();
1084                 if ( isset( $meta['wrapper_data']['headers'] ) )
1085                         $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
1086                 else
1087                         $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
1088
1089                 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1090                         $strResponse = WP_Http::chunkTransferDecode($strResponse);
1091
1092                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1093                         $strResponse = WP_Http_Encoding::decompress( $strResponse );
1094
1095                 return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
1096         }
1097
1098         /**
1099          * Whether this class can be used for retrieving an URL.
1100          *
1101          * @static
1102          * @access public
1103          * @since 2.7.0
1104          *
1105          * @return boolean False means this class can not be used, true means it can.
1106          */
1107         function test($args = array()) {
1108                 if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
1109                         return false;
1110
1111                 if ( version_compare(PHP_VERSION, '5.0', '<') )
1112                         return false;
1113
1114                 //HTTPS via Proxy was added in 5.1.0
1115                 $is_ssl = isset($args['ssl']) && $args['ssl'];
1116                 if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) {
1117                         $proxy = new WP_HTTP_Proxy();
1118                         /**
1119                          * No URL check, as its not currently passed to the ::test() function
1120                          * In the case where a Proxy is in use, Just bypass this transport for HTTPS.
1121                          */
1122                         if ( $proxy->is_enabled() )
1123                                 return false;
1124                 }
1125
1126                 return apply_filters('use_streams_transport', true, $args);
1127         }
1128 }
1129
1130 /**
1131  * HTTP request method uses HTTP extension to retrieve the url.
1132  *
1133  * Requires the HTTP extension to be installed. This would be the preferred transport since it can
1134  * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+
1135  * is being used, it doesn't mean that the HTTP extension will be enabled.
1136  *
1137  * @package WordPress
1138  * @subpackage HTTP
1139  * @since 2.7.0
1140  */
1141 class WP_Http_ExtHttp {
1142         /**
1143          * Send a HTTP request to a URI using HTTP extension.
1144          *
1145          * Does not support non-blocking.
1146          *
1147          * @access public
1148          * @since 2.7
1149          *
1150          * @param string $url
1151          * @param str|array $args Optional. Override the defaults.
1152          * @return array 'headers', 'body', 'cookies' and 'response' keys.
1153          */
1154         function request($url, $args = array()) {
1155                 $defaults = array(
1156                         'method' => 'GET', 'timeout' => 5,
1157                         'redirection' => 5, 'httpversion' => '1.0',
1158                         'blocking' => true,
1159                         'headers' => array(), 'body' => null, 'cookies' => array()
1160                 );
1161
1162                 $r = wp_parse_args( $args, $defaults );
1163
1164                 if ( isset($r['headers']['User-Agent']) ) {
1165                         $r['user-agent'] = $r['headers']['User-Agent'];
1166                         unset($r['headers']['User-Agent']);
1167                 } else if ( isset($r['headers']['user-agent']) ) {
1168                         $r['user-agent'] = $r['headers']['user-agent'];
1169                         unset($r['headers']['user-agent']);
1170                 }
1171
1172                 // Construct Cookie: header if any cookies are set
1173                 WP_Http::buildCookieHeader( $r );
1174
1175                 switch ( $r['method'] ) {
1176                         case 'POST':
1177                                 $r['method'] = HTTP_METH_POST;
1178                                 break;
1179                         case 'HEAD':
1180                                 $r['method'] = HTTP_METH_HEAD;
1181                                 break;
1182                         case 'PUT':
1183                                 $r['method'] =  HTTP_METH_PUT;
1184                                 break;
1185                         case 'GET':
1186                         default:
1187                                 $r['method'] = HTTP_METH_GET;
1188                 }
1189
1190                 $arrURL = parse_url($url);
1191
1192                 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
1193                         $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1194
1195                 $is_local = isset($args['local']) && $args['local'];
1196                 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1197                 if ( $is_local )
1198                         $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1199                 elseif ( ! $is_local )
1200                         $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1201
1202                 $r['timeout'] = (int) ceil( $r['timeout'] );
1203
1204                 $options = array(
1205                         'timeout' => $r['timeout'],
1206                         'connecttimeout' => $r['timeout'],
1207                         'redirect' => $r['redirection'],
1208                         'useragent' => $r['user-agent'],
1209                         'headers' => $r['headers'],
1210                         'ssl' => array(
1211                                 'verifypeer' => $ssl_verify,
1212                                 'verifyhost' => $ssl_verify
1213                         )
1214                 );
1215
1216                 if ( HTTP_METH_HEAD == $r['method'] )
1217                         $options['redirect'] = 0; // Assumption: Docs seem to suggest that this means do not follow. Untested.
1218
1219                 // The HTTP extensions offers really easy proxy support.
1220                 $proxy = new WP_HTTP_Proxy();
1221
1222                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1223                         $options['proxyhost'] = $proxy->host();
1224                         $options['proxyport'] = $proxy->port();
1225                         $options['proxytype'] = HTTP_PROXY_HTTP;
1226
1227                         if ( $proxy->use_authentication() ) {
1228                                 $options['proxyauth'] = $proxy->authentication();
1229                                 $options['proxyauthtype'] = HTTP_AUTH_ANY;
1230                         }
1231                 }
1232
1233                 if ( !WP_DEBUG ) //Emits warning level notices for max redirects and timeouts
1234                         $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
1235                 else
1236                         $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts
1237
1238                 // Error may still be set, Response may return headers or partial document, and error
1239                 // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
1240                 if ( false === $strResponse || ! empty($info['error']) )
1241                         return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
1242
1243                 if ( ! $r['blocking'] )
1244                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1245
1246                 $headers_body = WP_HTTP::processResponse($strResponse);
1247                 $theHeaders = $headers_body['headers'];
1248                 $theBody = $headers_body['body'];
1249                 unset($headers_body);
1250
1251                 $theHeaders = WP_Http::processHeaders($theHeaders);
1252
1253                 if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) {
1254                         if ( !WP_DEBUG )
1255                                 $theBody = @http_chunked_decode($theBody);
1256                         else
1257                                 $theBody = http_chunked_decode($theBody);
1258                 }
1259
1260                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1261                         $theBody = http_inflate( $theBody );
1262
1263                 $theResponse = array();
1264                 $theResponse['code'] = $info['response_code'];
1265                 $theResponse['message'] = get_status_header_desc($info['response_code']);
1266
1267                 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
1268         }
1269
1270         /**
1271          * Whether this class can be used for retrieving an URL.
1272          *
1273          * @static
1274          * @since 2.7.0
1275          *
1276          * @return boolean False means this class can not be used, true means it can.
1277          */
1278         function test($args = array()) {
1279                 return apply_filters('use_http_extension_transport', function_exists('http_request'), $args );
1280         }
1281 }
1282
1283 /**
1284  * HTTP request method uses Curl extension to retrieve the url.
1285  *
1286  * Requires the Curl extension to be installed.
1287  *
1288  * @package WordPress
1289  * @subpackage HTTP
1290  * @since 2.7
1291  */
1292 class WP_Http_Curl {
1293
1294         /**
1295          * Send a HTTP request to a URI using cURL extension.
1296          *
1297          * @access public
1298          * @since 2.7.0
1299          *
1300          * @param string $url
1301          * @param str|array $args Optional. Override the defaults.
1302          * @return array 'headers', 'body', 'cookies' and 'response' keys.
1303          */
1304         function request($url, $args = array()) {
1305                 $defaults = array(
1306                         'method' => 'GET', 'timeout' => 5,
1307                         'redirection' => 5, 'httpversion' => '1.0',
1308                         'blocking' => true,
1309                         'headers' => array(), 'body' => null, 'cookies' => array()
1310                 );
1311
1312                 $r = wp_parse_args( $args, $defaults );
1313
1314                 if ( isset($r['headers']['User-Agent']) ) {
1315                         $r['user-agent'] = $r['headers']['User-Agent'];
1316                         unset($r['headers']['User-Agent']);
1317                 } else if ( isset($r['headers']['user-agent']) ) {
1318                         $r['user-agent'] = $r['headers']['user-agent'];
1319                         unset($r['headers']['user-agent']);
1320                 }
1321
1322                 // Construct Cookie: header if any cookies are set.
1323                 WP_Http::buildCookieHeader( $r );
1324
1325                 $handle = curl_init();
1326
1327                 // cURL offers really easy proxy support.
1328                 $proxy = new WP_HTTP_Proxy();
1329
1330                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1331
1332                         $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
1333
1334                         if ( $isPHP5 ) {
1335                                 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1336                                 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1337                                 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1338                         } else {
1339                                 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() );
1340                         }
1341
1342                         if ( $proxy->use_authentication() ) {
1343                                 if ( $isPHP5 )
1344                                         curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1345
1346                                 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1347                         }
1348                 }
1349
1350                 $is_local = isset($args['local']) && $args['local'];
1351                 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1352                 if ( $is_local )
1353                         $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1354                 elseif ( ! $is_local )
1355                         $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1356
1357
1358                 // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers.  Have to use ceil since
1359                 // a value of 0 will allow an ulimited timeout.
1360                 $timeout = (int) ceil( $r['timeout'] );
1361                 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1362                 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1363
1364                 curl_setopt( $handle, CURLOPT_URL, $url);
1365                 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1366                 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify );
1367                 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1368                 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1369                 curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1370
1371                 switch ( $r['method'] ) {
1372                         case 'HEAD':
1373                                 curl_setopt( $handle, CURLOPT_NOBODY, true );
1374                                 break;
1375                         case 'POST':
1376                                 curl_setopt( $handle, CURLOPT_POST, true );
1377                                 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1378                                 break;
1379                         case 'PUT':
1380                                 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1381                                 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1382                                 break;
1383                 }
1384
1385                 if ( true === $r['blocking'] )
1386                         curl_setopt( $handle, CURLOPT_HEADER, true );
1387                 else
1388                         curl_setopt( $handle, CURLOPT_HEADER, false );
1389
1390                 // The option doesn't work with safe mode or when open_basedir is set.
1391                 // Disable HEAD when making HEAD requests.
1392                 if ( !ini_get('safe_mode') && !ini_get('open_basedir') && 'HEAD' != $r['method'] )
1393                         curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1394
1395                 if ( !empty( $r['headers'] ) ) {
1396                         // cURL expects full header strings in each element
1397                         $headers = array();
1398                         foreach ( $r['headers'] as $name => $value ) {
1399                                 $headers[] = "{$name}: $value";
1400                         }
1401                         curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1402                 }
1403
1404                 if ( $r['httpversion'] == '1.0' )
1405                         curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1406                 else
1407                         curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1408
1409                 // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1410                 // themselves... Although, it is somewhat pointless without some reference.
1411                 do_action_ref_array( 'http_api_curl', array(&$handle) );
1412
1413                 // We don't need to return the body, so don't. Just execute request and return.
1414                 if ( ! $r['blocking'] ) {
1415                         curl_exec( $handle );
1416                         curl_close( $handle );
1417                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1418                 }
1419
1420                 $theResponse = curl_exec( $handle );
1421
1422                 if ( !empty($theResponse) ) {
1423                         $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
1424                         $theHeaders = trim( substr($theResponse, 0, $headerLength) );
1425                         if ( strlen($theResponse) > $headerLength )
1426                                 $theBody = substr( $theResponse, $headerLength );
1427                         else
1428                                 $theBody = '';
1429                         if ( false !== strpos($theHeaders, "\r\n\r\n") ) {
1430                                 $headerParts = explode("\r\n\r\n", $theHeaders);
1431                                 $theHeaders = $headerParts[ count($headerParts) -1 ];
1432                         }
1433                         $theHeaders = WP_Http::processHeaders($theHeaders);
1434                 } else {
1435                         if ( $curl_error = curl_error($handle) )
1436                                 return new WP_Error('http_request_failed', $curl_error);
1437                         if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1438                                 return new WP_Error('http_request_failed', __('Too many redirects.'));
1439
1440                         $theHeaders = array( 'headers' => array(), 'cookies' => array() );
1441                         $theBody = '';
1442                 }
1443
1444                 $response = array();
1445                 $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1446                 $response['message'] = get_status_header_desc($response['code']);
1447
1448                 curl_close( $handle );
1449
1450                 // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
1451                 if ( !empty($theHeaders['headers']['location']) && (ini_get('safe_mode') || ini_get('open_basedir')) ) {
1452                         if ( $r['redirection']-- > 0 ) {
1453                                 return $this->request($theHeaders['headers']['location'], $r);
1454                         } else {
1455                                 return new WP_Error('http_request_failed', __('Too many redirects.'));
1456                         }
1457                 }
1458
1459                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1460                         $theBody = WP_Http_Encoding::decompress( $theBody );
1461
1462                 return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']);
1463         }
1464
1465         /**
1466          * Whether this class can be used for retrieving an URL.
1467          *
1468          * @static
1469          * @since 2.7.0
1470          *
1471          * @return boolean False means this class can not be used, true means it can.
1472          */
1473         function test($args = array()) {
1474                 if ( function_exists('curl_init') && function_exists('curl_exec') )
1475                         return apply_filters('use_curl_transport', true, $args);
1476
1477                 return false;
1478         }
1479 }
1480
1481 /**
1482  * Adds Proxy support to the WordPress HTTP API.
1483  *
1484  * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1485  * enable proxy support. There are also a few filters that plugins can hook into for some of the
1486  * constants.
1487  *
1488  * Please note that only BASIC authentication is supported by most transports.
1489  * cURL and the PHP HTTP Extension MAY support more methods (such as NTLM authentication) depending on your environment.
1490  *
1491  * The constants are as follows:
1492  * <ol>
1493  * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1494  * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1495  * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1496  * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1497  * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1498  * You do not need to have localhost and the blog host in this list, because they will not be passed
1499  * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1500  * </ol>
1501  *
1502  * An example can be as seen below.
1503  * <code>
1504  * define('WP_PROXY_HOST', '192.168.84.101');
1505  * define('WP_PROXY_PORT', '8080');
1506  * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1507  * </code>
1508  *
1509  * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1510  * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1511  * @since 2.8
1512  */
1513 class WP_HTTP_Proxy {
1514
1515         /**
1516          * Whether proxy connection should be used.
1517          *
1518          * @since 2.8
1519          * @use WP_PROXY_HOST
1520          * @use WP_PROXY_PORT
1521          *
1522          * @return bool
1523          */
1524         function is_enabled() {
1525                 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1526         }
1527
1528         /**
1529          * Whether authentication should be used.
1530          *
1531          * @since 2.8
1532          * @use WP_PROXY_USERNAME
1533          * @use WP_PROXY_PASSWORD
1534          *
1535          * @return bool
1536          */
1537         function use_authentication() {
1538                 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1539         }
1540
1541         /**
1542          * Retrieve the host for the proxy server.
1543          *
1544          * @since 2.8
1545          *
1546          * @return string
1547          */
1548         function host() {
1549                 if ( defined('WP_PROXY_HOST') )
1550                         return WP_PROXY_HOST;
1551
1552                 return '';
1553         }
1554
1555         /**
1556          * Retrieve the port for the proxy server.
1557          *
1558          * @since 2.8
1559          *
1560          * @return string
1561          */
1562         function port() {
1563                 if ( defined('WP_PROXY_PORT') )
1564                         return WP_PROXY_PORT;
1565
1566                 return '';
1567         }
1568
1569         /**
1570          * Retrieve the username for proxy authentication.
1571          *
1572          * @since 2.8
1573          *
1574          * @return string
1575          */
1576         function username() {
1577                 if ( defined('WP_PROXY_USERNAME') )
1578                         return WP_PROXY_USERNAME;
1579
1580                 return '';
1581         }
1582
1583         /**
1584          * Retrieve the password for proxy authentication.
1585          *
1586          * @since 2.8
1587          *
1588          * @return string
1589          */
1590         function password() {
1591                 if ( defined('WP_PROXY_PASSWORD') )
1592                         return WP_PROXY_PASSWORD;
1593
1594                 return '';
1595         }
1596
1597         /**
1598          * Retrieve authentication string for proxy authentication.
1599          *
1600          * @since 2.8
1601          *
1602          * @return string
1603          */
1604         function authentication() {
1605                 return $this->username() . ':' . $this->password();
1606         }
1607
1608         /**
1609          * Retrieve header string for proxy authentication.
1610          *
1611          * @since 2.8
1612          *
1613          * @return string
1614          */
1615         function authentication_header() {
1616                 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1617         }
1618
1619         /**
1620          * Whether URL should be sent through the proxy server.
1621          *
1622          * We want to keep localhost and the blog URL from being sent through the proxy server, because
1623          * some proxies can not handle this. We also have the constant available for defining other
1624          * hosts that won't be sent through the proxy.
1625          *
1626          * @uses WP_PROXY_BYPASS_HOSTS
1627          * @since 2.8.0
1628          *
1629          * @param string $uri URI to check.
1630          * @return bool True, to send through the proxy and false if, the proxy should not be used.
1631          */
1632         function send_through_proxy( $uri ) {
1633                 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1634                 // This will be displayed on blogs, which is not reasonable.
1635                 $check = @parse_url($uri);
1636
1637                 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1638                 if ( $check === false )
1639                         return true;
1640
1641                 $home = parse_url( get_option('siteurl') );
1642
1643                 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1644                         return false;
1645
1646                 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1647                         return true;
1648
1649                 static $bypass_hosts;
1650                 static $wildcard_regex = false;
1651                 if ( null == $bypass_hosts ) {
1652                         $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1653
1654                         if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1655                                 $wildcard_regex = array();
1656                                 foreach ( $bypass_hosts as $host )
1657                                         $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
1658                                 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1659                         }
1660                 }
1661
1662                 if ( !empty($wildcard_regex) )
1663                         return !preg_match($wildcard_regex, $check['host']);
1664                 else
1665                         return !in_array( $check['host'], $bypass_hosts );
1666         }
1667 }
1668 /**
1669  * Internal representation of a single cookie.
1670  *
1671  * Returned cookies are represented using this class, and when cookies are set, if they are not
1672  * already a WP_Http_Cookie() object, then they are turned into one.
1673  *
1674  * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1675  * names. Need to switch to use underscores instead for the methods.
1676  *
1677  * @package WordPress
1678  * @subpackage HTTP
1679  * @since 2.8.0
1680  */
1681 class WP_Http_Cookie {
1682
1683         /**
1684          * Cookie name.
1685          *
1686          * @since 2.8.0
1687          * @var string
1688          */
1689         var $name;
1690
1691         /**
1692          * Cookie value.
1693          *
1694          * @since 2.8.0
1695          * @var string
1696          */
1697         var $value;
1698
1699         /**
1700          * When the cookie expires.
1701          *
1702          * @since 2.8.0
1703          * @var string
1704          */
1705         var $expires;
1706
1707         /**
1708          * Cookie URL path.
1709          *
1710          * @since 2.8.0
1711          * @var string
1712          */
1713         var $path;
1714
1715         /**
1716          * Cookie Domain.
1717          *
1718          * @since 2.8.0
1719          * @var string
1720          */
1721         var $domain;
1722
1723         /**
1724          * PHP4 style Constructor - Calls PHP5 Style Constructor.
1725          *
1726          * @access public
1727          * @since 2.8.0
1728          * @param string|array $data Raw cookie data.
1729          */
1730         function WP_Http_Cookie( $data ) {
1731                 $this->__construct( $data );
1732         }
1733
1734         /**
1735          * Sets up this cookie object.
1736          *
1737          * The parameter $data should be either an associative array containing the indices names below
1738          * or a header string detailing it.
1739          *
1740          * If it's an array, it should include the following elements:
1741          * <ol>
1742          * <li>Name</li>
1743          * <li>Value - should NOT be urlencoded already.</li>
1744          * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1745          * <li>Path (optional)</li>
1746          * <li>Domain (optional)</li>
1747          * </ol>
1748          *
1749          * @access public
1750          * @since 2.8.0
1751          *
1752          * @param string|array $data Raw cookie data.
1753          */
1754         function __construct( $data ) {
1755                 if ( is_string( $data ) ) {
1756                         // Assume it's a header string direct from a previous request
1757                         $pairs = explode( ';', $data );
1758
1759                         // Special handling for first pair; name=value. Also be careful of "=" in value
1760                         $name  = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1761                         $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1762                         $this->name  = $name;
1763                         $this->value = urldecode( $value );
1764                         array_shift( $pairs ); //Removes name=value from items.
1765
1766                         // Set everything else as a property
1767                         foreach ( $pairs as $pair ) {
1768                                 $pair = rtrim($pair);
1769                                 if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1770                                         continue;
1771
1772                                 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1773                                 $key = strtolower( trim( $key ) );
1774                                 if ( 'expires' == $key )
1775                                         $val = strtotime( $val );
1776                                 $this->$key = $val;
1777                         }
1778                 } else {
1779                         if ( !isset( $data['name'] ) )
1780                                 return false;
1781
1782                         // Set properties based directly on parameters
1783                         $this->name   = $data['name'];
1784                         $this->value  = isset( $data['value'] ) ? $data['value'] : '';
1785                         $this->path   = isset( $data['path'] ) ? $data['path'] : '';
1786                         $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1787
1788                         if ( isset( $data['expires'] ) )
1789                                 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1790                         else
1791                                 $this->expires = null;
1792                 }
1793         }
1794
1795         /**
1796          * Confirms that it's OK to send this cookie to the URL checked against.
1797          *
1798          * Decision is based on RFC 2109/2965, so look there for details on validity.
1799          *
1800          * @access public
1801          * @since 2.8.0
1802          *
1803          * @param string $url URL you intend to send this cookie to
1804          * @return boolean TRUE if allowed, FALSE otherwise.
1805          */
1806         function test( $url ) {
1807                 // Expires - if expired then nothing else matters
1808                 if ( time() > $this->expires )
1809                         return false;
1810
1811                 // Get details on the URL we're thinking about sending to
1812                 $url = parse_url( $url );
1813                 $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1814                 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1815
1816                 // Values to use for comparison against the URL
1817                 $path   = isset( $this->path )   ? $this->path   : '/';
1818                 $port   = isset( $this->port )   ? $this->port   : 80;
1819                 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1820                 if ( false === stripos( $domain, '.' ) )
1821                         $domain .= '.local';
1822
1823                 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1824                 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1825                 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1826                         return false;
1827
1828                 // Port - supports "port-lists" in the format: "80,8000,8080"
1829                 if ( !in_array( $url['port'], explode( ',', $port) ) )
1830                         return false;
1831
1832                 // Path - request path must start with path restriction
1833                 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1834                         return false;
1835
1836                 return true;
1837         }
1838
1839         /**
1840          * Convert cookie name and value back to header string.
1841          *
1842          * @access public
1843          * @since 2.8.0
1844          *
1845          * @return string Header encoded cookie name and value.
1846          */
1847         function getHeaderValue() {
1848                 if ( empty( $this->name ) || empty( $this->value ) )
1849                         return '';
1850
1851                 return $this->name . '=' . urlencode( $this->value );
1852         }
1853
1854         /**
1855          * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1856          *
1857          * @access public
1858          * @since 2.8.0
1859          *
1860          * @return string
1861          */
1862         function getFullHeader() {
1863                 return 'Cookie: ' . $this->getHeaderValue();
1864         }
1865 }
1866
1867 /**
1868  * Implementation for deflate and gzip transfer encodings.
1869  *
1870  * Includes RFC 1950, RFC 1951, and RFC 1952.
1871  *
1872  * @since 2.8
1873  * @package WordPress
1874  * @subpackage HTTP
1875  */
1876 class WP_Http_Encoding {
1877
1878         /**
1879          * Compress raw string using the deflate format.
1880          *
1881          * Supports the RFC 1951 standard.
1882          *
1883          * @since 2.8
1884          *
1885          * @param string $raw String to compress.
1886          * @param int $level Optional, default is 9. Compression level, 9 is highest.
1887          * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1888          * @return string|bool False on failure.
1889          */
1890         function compress( $raw, $level = 9, $supports = null ) {
1891                 return gzdeflate( $raw, $level );
1892         }
1893
1894         /**
1895          * Decompression of deflated string.
1896          *
1897          * Will attempt to decompress using the RFC 1950 standard, and if that fails
1898          * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1899          * 1952 standard gzip decode will be attempted. If all fail, then the
1900          * original compressed string will be returned.
1901          *
1902          * @since 2.8
1903          *
1904          * @param string $compressed String to decompress.
1905          * @param int $length The optional length of the compressed data.
1906          * @return string|bool False on failure.
1907          */
1908         function decompress( $compressed, $length = null ) {
1909
1910                 if ( empty($compressed) )
1911                         return $compressed;
1912
1913                 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
1914                         return $decompressed;
1915
1916                 if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
1917                         return $decompressed;
1918
1919                 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
1920                         return $decompressed;
1921
1922                 if ( function_exists('gzdecode') ) {
1923                         $decompressed = @gzdecode( $compressed );
1924
1925                         if ( false !== $decompressed )
1926                                 return $decompressed;
1927                 }
1928
1929                 return $compressed;
1930         }
1931
1932         /**
1933          * Decompression of deflated string while staying compatible with the majority of servers.
1934          *
1935          * Certain Servers will return deflated data with headers which PHP's gziniflate()
1936          * function cannot handle out of the box. The following function lifted from
1937          * http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate
1938          * the various return forms used.
1939          *
1940          * @since 2.8.1
1941          * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
1942          *
1943          * @param string $gzData String to decompress.
1944          * @return string|bool False on failure.
1945          */
1946         function compatible_gzinflate($gzData) {
1947                 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
1948                         $i = 10;
1949                         $flg = ord( substr($gzData, 3, 1) );
1950                         if ( $flg > 0 ) {
1951                                 if ( $flg & 4 ) {
1952                                         list($xlen) = unpack('v', substr($gzData, $i, 2) );
1953                                         $i = $i + 2 + $xlen;
1954                                 }
1955                                 if ( $flg & 8 )
1956                                         $i = strpos($gzData, "\0", $i) + 1;
1957                                 if ( $flg & 16 )
1958                                         $i = strpos($gzData, "\0", $i) + 1;
1959                                 if ( $flg & 2 )
1960                                         $i = $i + 2;
1961                         }
1962                         return gzinflate( substr($gzData, $i, -8) );
1963                 } else {
1964                         return false;
1965                 }
1966         }
1967
1968         /**
1969          * What encoding types to accept and their priority values.
1970          *
1971          * @since 2.8
1972          *
1973          * @return string Types of encoding to accept.
1974          */
1975         function accept_encoding() {
1976                 $type = array();
1977                 if ( function_exists( 'gzinflate' ) )
1978                         $type[] = 'deflate;q=1.0';
1979
1980                 if ( function_exists( 'gzuncompress' ) )
1981                         $type[] = 'compress;q=0.5';
1982
1983                 if ( function_exists( 'gzdecode' ) )
1984                         $type[] = 'gzip;q=0.5';
1985
1986                 return implode(', ', $type);
1987         }
1988
1989         /**
1990          * What enconding the content used when it was compressed to send in the headers.
1991          *
1992          * @since 2.8
1993          *
1994          * @return string Content-Encoding string to send in the header.
1995          */
1996         function content_encoding() {
1997                 return 'deflate';
1998         }
1999
2000         /**
2001          * Whether the content be decoded based on the headers.
2002          *
2003          * @since 2.8
2004          *
2005          * @param array|string $headers All of the available headers.
2006          * @return bool
2007          */
2008         function should_decode($headers) {
2009                 if ( is_array( $headers ) ) {
2010                         if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
2011                                 return true;
2012                 } else if ( is_string( $headers ) ) {
2013                         return ( stripos($headers, 'content-encoding:') !== false );
2014                 }
2015
2016                 return false;
2017         }
2018
2019         /**
2020          * Whether decompression and compression are supported by the PHP version.
2021          *
2022          * Each function is tested instead of checking for the zlib extension, to
2023          * ensure that the functions all exist in the PHP version and aren't
2024          * disabled.
2025          *
2026          * @since 2.8
2027          *
2028          * @return bool
2029          */
2030         function is_available() {
2031                 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
2032         }
2033 }