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