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