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