]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-http.php
WordPress 4.1.3
[autoinstalls/wordpress.git] / wp-includes / class-http.php
1 <?php
2 /**
3  * Simple and uniform HTTP request API.
4  *
5  * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
6  * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
7  *
8  * @link https://core.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 used to consistently make outgoing HTTP requests easy for developers
19  * while still being compatible with the many PHP configurations under which
20  * WordPress runs.
21  *
22  * Debugging includes several actions, which pass different variables for debugging the HTTP API.
23  *
24  * @package WordPress
25  * @subpackage HTTP
26  * @since 2.7.0
27  */
28 class WP_Http {
29
30         /**
31          * Send an HTTP request to a URI.
32          *
33          * Please note: The only URI that are supported in the HTTP Transport implementation
34          * are the HTTP and HTTPS protocols.
35          *
36          * @access public
37          * @since 2.7.0
38          *
39          * @param string       $url  The request URL.
40          * @param string|array $args {
41          *     Optional. Array or string of HTTP request arguments.
42          *
43          *     @type string       $method              Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
44          *                                             Some transports technically allow others, but should not be
45          *                                             assumed. Default 'GET'.
46          *     @type int          $timeout             How long the connection should stay open in seconds. Default 5.
47          *     @type int          $redirection         Number of allowed redirects. Not supported by all transports
48          *                                             Default 5.
49          *     @type string       $httpversion         Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
50          *                                             Default '1.0'.
51          *     @type string       $user-agent          User-agent value sent.
52          *                                             Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
53          *     @type bool         $reject_unsafe_urls  Whether to pass URLs through {@see wp_http_validate_url()}.
54          *                                             Default false.
55          *     @type bool         $blocking            Whether the calling code requires the result of the request.
56          *                                             If set to false, the request will be sent to the remote server,
57          *                                             and processing returned to the calling code immediately, the caller
58          *                                             will know if the request succeeded or failed, but will not receive
59          *                                             any response from the remote server. Default true.
60          *     @type string|array $headers             Array or string of headers to send with the request.
61          *                                             Default empty array.
62          *     @type array        $cookies             List of cookies to send with the request. Default empty array.
63          *     @type string|array $body                Body to send with the request. Default null.
64          *     @type bool         $compress            Whether to compress the $body when sending the request.
65          *                                             Default false.
66          *     @type bool         $decompress          Whether to decompress a compressed response. If set to false and
67          *                                             compressed content is returned in the response anyway, it will
68          *                                             need to be separately decompressed. Default true.
69          *     @type bool         $sslverify           Whether to verify SSL for the request. Default true.
70          *     @type string       sslcertificates      Absolute path to an SSL certificate .crt file.
71          *                                             Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
72          *     @type bool         $stream              Whether to stream to a file. If set to true and no filename was
73          *                                             given, it will be droped it in the WP temp dir and its name will
74          *                                             be set using the basename of the URL. Default false.
75          *     @type string       $filename            Filename of the file to write to when streaming. $stream must be
76          *                                             set to true. Default null.
77          *     @type int          $limit_response_size Size in bytes to limit the response to. Default null.
78          *
79          * }
80          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
81          *                        A WP_Error instance upon error.
82          */
83         public function request( $url, $args = array() ) {
84                 global $wp_version;
85
86                 $defaults = array(
87                         'method' => 'GET',
88                         /**
89                          * Filter the timeout value for an HTTP request.
90                          *
91                          * @since 2.7.0
92                          *
93                          * @param int $timeout_value Time in seconds until a request times out.
94                          *                           Default 5.
95                          */
96                         'timeout' => apply_filters( 'http_request_timeout', 5 ),
97                         /**
98                          * Filter the number of redirects allowed during an HTTP request.
99                          *
100                          * @since 2.7.0
101                          *
102                          * @param int $redirect_count Number of redirects allowed. Default 5.
103                          */
104                         'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
105                         /**
106                          * Filter the version of the HTTP protocol used in a request.
107                          *
108                          * @since 2.7.0
109                          *
110                          * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
111                          *                        Default '1.0'.
112                          */
113                         'httpversion' => apply_filters( 'http_request_version', '1.0' ),
114                         /**
115                          * Filter the user agent value sent with an HTTP request.
116                          *
117                          * @since 2.7.0
118                          *
119                          * @param string $user_agent WordPress user agent string.
120                          */
121                         'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
122                         /**
123                          * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
124                          *
125                          * @since 3.6.0
126                          *
127                          * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
128                          *                       Default false.
129                          */
130                         'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
131                         'blocking' => true,
132                         'headers' => array(),
133                         'cookies' => array(),
134                         'body' => null,
135                         'compress' => false,
136                         'decompress' => true,
137                         'sslverify' => true,
138                         'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
139                         'stream' => false,
140                         'filename' => null,
141                         'limit_response_size' => null,
142                 );
143
144                 // Pre-parse for the HEAD checks.
145                 $args = wp_parse_args( $args );
146
147                 // By default, Head requests do not cause redirections.
148                 if ( isset($args['method']) && 'HEAD' == $args['method'] )
149                         $defaults['redirection'] = 0;
150
151                 $r = wp_parse_args( $args, $defaults );
152                 /**
153                  * Filter the arguments used in an HTTP request.
154                  *
155                  * @since 2.7.0
156                  *
157                  * @param array  $r   An array of HTTP request arguments.
158                  * @param string $url The request URL.
159                  */
160                 $r = apply_filters( 'http_request_args', $r, $url );
161
162                 // The transports decrement this, store a copy of the original value for loop purposes.
163                 if ( ! isset( $r['_redirection'] ) )
164                         $r['_redirection'] = $r['redirection'];
165
166                 /**
167                  * Filter whether to preempt an HTTP request's return.
168                  *
169                  * Returning a truthy value to the filter will short-circuit
170                  * the HTTP request and return early with that value.
171                  *
172                  * @since 2.9.0
173                  *
174                  * @param bool   $preempt Whether to preempt an HTTP request return. Default false.
175                  * @param array  $r       HTTP request arguments.
176                  * @param string $url     The request URL.
177                  */
178                 $pre = apply_filters( 'pre_http_request', false, $r, $url );
179                 if ( false !== $pre )
180                         return $pre;
181
182                 if ( function_exists( 'wp_kses_bad_protocol' ) ) {
183                         if ( $r['reject_unsafe_urls'] )
184                                 $url = wp_http_validate_url( $url );
185                         $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
186                 }
187
188                 $arrURL = @parse_url( $url );
189
190                 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
191                         return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
192
193                 if ( $this->block_request( $url ) )
194                         return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
195
196                 /*
197                  * Determine if this is a https call and pass that on to the transport functions
198                  * so that we can blacklist the transports that do not support ssl verification
199                  */
200                 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
201
202                 // Determine if this request is to OUR install of WordPress.
203                 $homeURL = parse_url( get_bloginfo( 'url' ) );
204                 $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
205                 unset( $homeURL );
206
207                 /*
208                  * If we are streaming to a file but no filename was given drop it in the WP temp dir
209                  * and pick its name using the basename of the $url.
210                  */
211                 if ( $r['stream']  && empty( $r['filename'] ) ) {
212                         $r['filename'] = wp_unique_filename( get_temp_dir(), basename( $url ) );
213                 }
214
215                 /*
216                  * Force some settings if we are streaming to a file and check for existence and perms
217                  * of destination directory.
218                  */
219                 if ( $r['stream'] ) {
220                         $r['blocking'] = true;
221                         if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
222                                 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
223                 }
224
225                 if ( is_null( $r['headers'] ) )
226                         $r['headers'] = array();
227
228                 if ( ! is_array( $r['headers'] ) ) {
229                         $processedHeaders = WP_Http::processHeaders( $r['headers'], $url );
230                         $r['headers'] = $processedHeaders['headers'];
231                 }
232
233                 if ( isset( $r['headers']['User-Agent'] ) ) {
234                         $r['user-agent'] = $r['headers']['User-Agent'];
235                         unset( $r['headers']['User-Agent'] );
236                 }
237
238                 if ( isset( $r['headers']['user-agent'] ) ) {
239                         $r['user-agent'] = $r['headers']['user-agent'];
240                         unset( $r['headers']['user-agent'] );
241                 }
242
243                 if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
244                         $r['headers']['connection'] = 'close';
245                 }
246
247                 // Construct Cookie: header if any cookies are set.
248                 WP_Http::buildCookieHeader( $r );
249
250                 // Avoid issues where mbstring.func_overload is enabled.
251                 mbstring_binary_safe_encoding();
252
253                 if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
254                         if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
255                                 $r['headers']['Accept-Encoding'] = $encoding;
256                 }
257
258                 if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
259                         if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
260                                 $r['body'] = http_build_query( $r['body'], null, '&' );
261
262                                 if ( ! isset( $r['headers']['Content-Type'] ) )
263                                         $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
264                         }
265
266                         if ( '' === $r['body'] )
267                                 $r['body'] = null;
268
269                         if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
270                                 $r['headers']['Content-Length'] = strlen( $r['body'] );
271                 }
272
273                 $response = $this->_dispatch_request( $url, $r );
274
275                 reset_mbstring_encoding();
276
277                 if ( is_wp_error( $response ) )
278                         return $response;
279
280                 // Append cookies that were used in this request to the response
281                 if ( ! empty( $r['cookies'] ) ) {
282                         $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
283                         foreach ( $r['cookies'] as $cookie ) {
284                                 if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
285                                         $response['cookies'][] = $cookie;
286                                 }
287                         }
288                 }
289
290                 return $response;
291         }
292
293         /**
294          * Tests which transports are capable of supporting the request.
295          *
296          * @since 3.2.0
297          * @access private
298          *
299          * @param array $args Request arguments
300          * @param string $url URL to Request
301          *
302          * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
303          */
304         public function _get_first_available_transport( $args, $url = null ) {
305                 /**
306                  * Filter which HTTP transports are available and in what order.
307                  *
308                  * @since 3.7.0
309                  *
310                  * @param array  $value Array of HTTP transports to check. Default array contains
311                  *                      'curl', and 'streams', in that order.
312                  * @param array  $args  HTTP request arguments.
313                  * @param string $url   The URL to request.
314                  */
315                 $request_order = apply_filters( 'http_api_transports', array( 'curl', 'streams' ), $args, $url );
316
317                 // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
318                 foreach ( $request_order as $transport ) {
319                         $class = 'WP_HTTP_' . $transport;
320
321                         // Check to see if this transport is a possibility, calls the transport statically.
322                         if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
323                                 continue;
324
325                         return $class;
326                 }
327
328                 return false;
329         }
330
331         /**
332          * Dispatches a HTTP request to a supporting transport.
333          *
334          * Tests each transport in order to find a transport which matches the request arguments.
335          * Also caches the transport instance to be used later.
336          *
337          * The order for requests is cURL, and then PHP Streams.
338          *
339          * @since 3.2.0
340          * @access private
341          *
342          * @param string $url URL to Request
343          * @param array $args Request arguments
344          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
345          */
346         private function _dispatch_request( $url, $args ) {
347                 static $transports = array();
348
349                 $class = $this->_get_first_available_transport( $args, $url );
350                 if ( !$class )
351                         return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
352
353                 // Transport claims to support request, instantiate it and give it a whirl.
354                 if ( empty( $transports[$class] ) )
355                         $transports[$class] = new $class;
356
357                 $response = $transports[$class]->request( $url, $args );
358
359                 /**
360                  * Fires after an HTTP API response is received and before the response is returned.
361                  *
362                  * @since 2.8.0
363                  *
364                  * @param array|WP_Error $response HTTP response or WP_Error object.
365                  * @param string         $context  Context under which the hook is fired.
366                  * @param string         $class    HTTP transport used.
367                  * @param array          $args     HTTP request arguments.
368                  * @param string         $url      The request URL.
369                  */
370                 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
371
372                 if ( is_wp_error( $response ) )
373                         return $response;
374
375                 /**
376                  * Filter the HTTP API response immediately before the response is returned.
377                  *
378                  * @since 2.9.0
379                  *
380                  * @param array  $response HTTP response.
381                  * @param array  $args     HTTP request arguments.
382                  * @param string $url      The request URL.
383                  */
384                 return apply_filters( 'http_response', $response, $args, $url );
385         }
386
387         /**
388          * Uses the POST HTTP method.
389          *
390          * Used for sending data that is expected to be in the body.
391          *
392          * @access public
393          * @since 2.7.0
394          *
395          * @param string       $url  The request URL.
396          * @param string|array $args Optional. Override the defaults.
397          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
398          */
399         public function post($url, $args = array()) {
400                 $defaults = array('method' => 'POST');
401                 $r = wp_parse_args( $args, $defaults );
402                 return $this->request($url, $r);
403         }
404
405         /**
406          * Uses the GET HTTP method.
407          *
408          * Used for sending data that is expected to be in the body.
409          *
410          * @access public
411          * @since 2.7.0
412          *
413          * @param string $url The request URL.
414          * @param string|array $args Optional. Override the defaults.
415          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
416          */
417         public function get($url, $args = array()) {
418                 $defaults = array('method' => 'GET');
419                 $r = wp_parse_args( $args, $defaults );
420                 return $this->request($url, $r);
421         }
422
423         /**
424          * Uses the HEAD HTTP method.
425          *
426          * Used for sending data that is expected to be in the body.
427          *
428          * @access public
429          * @since 2.7.0
430          *
431          * @param string $url The request URL.
432          * @param string|array $args Optional. Override the defaults.
433          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
434          */
435         public function head($url, $args = array()) {
436                 $defaults = array('method' => 'HEAD');
437                 $r = wp_parse_args( $args, $defaults );
438                 return $this->request($url, $r);
439         }
440
441         /**
442          * Parses the responses and splits the parts into headers and body.
443          *
444          * @access public
445          * @static
446          * @since 2.7.0
447          *
448          * @param string $strResponse The full response string
449          * @return array Array with 'headers' and 'body' keys.
450          */
451         public static function processResponse($strResponse) {
452                 $res = explode("\r\n\r\n", $strResponse, 2);
453
454                 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
455         }
456
457         /**
458          * Transform header string into an array.
459          *
460          * If an array is given then it is assumed to be raw header data with numeric keys with the
461          * headers as the values. No headers must be passed that were already processed.
462          *
463          * @access public
464          * @static
465          * @since 2.7.0
466          *
467          * @param string|array $headers
468          * @param string $url The URL that was requested
469          * @return array Processed string headers. If duplicate headers are encountered,
470          *                                      Then a numbered array is returned as the value of that header-key.
471          */
472         public static function processHeaders( $headers, $url = '' ) {
473                 // Split headers, one per array element.
474                 if ( is_string($headers) ) {
475                         // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
476                         $headers = str_replace("\r\n", "\n", $headers);
477                         /*
478                          * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
479                          * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
480                          */
481                         $headers = preg_replace('/\n[ \t]/', ' ', $headers);
482                         // Create the headers array.
483                         $headers = explode("\n", $headers);
484                 }
485
486                 $response = array('code' => 0, 'message' => '');
487
488                 /*
489                  * If a redirection has taken place, The headers for each page request may have been passed.
490                  * In this case, determine the final HTTP header and parse from there.
491                  */
492                 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
493                         if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
494                                 $headers = array_splice($headers, $i);
495                                 break;
496                         }
497                 }
498
499                 $cookies = array();
500                 $newheaders = array();
501                 foreach ( (array) $headers as $tempheader ) {
502                         if ( empty($tempheader) )
503                                 continue;
504
505                         if ( false === strpos($tempheader, ':') ) {
506                                 $stack = explode(' ', $tempheader, 3);
507                                 $stack[] = '';
508                                 list( , $response['code'], $response['message']) = $stack;
509                                 continue;
510                         }
511
512                         list($key, $value) = explode(':', $tempheader, 2);
513
514                         $key = strtolower( $key );
515                         $value = trim( $value );
516
517                         if ( isset( $newheaders[ $key ] ) ) {
518                                 if ( ! is_array( $newheaders[ $key ] ) )
519                                         $newheaders[$key] = array( $newheaders[ $key ] );
520                                 $newheaders[ $key ][] = $value;
521                         } else {
522                                 $newheaders[ $key ] = $value;
523                         }
524                         if ( 'set-cookie' == $key )
525                                 $cookies[] = new WP_Http_Cookie( $value, $url );
526                 }
527
528                 // Cast the Response Code to an int
529                 $response['code'] = intval( $response['code'] );
530
531                 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
532         }
533
534         /**
535          * Takes the arguments for a ::request() and checks for the cookie array.
536          *
537          * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
538          * which are each parsed into strings and added to the Cookie: header (within the arguments array).
539          * Edits the array by reference.
540          *
541          * @access public
542          * @version 2.8.0
543          * @static
544          *
545          * @param array $r Full array of args passed into ::request()
546          */
547         public static function buildCookieHeader( &$r ) {
548                 if ( ! empty($r['cookies']) ) {
549                         // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
550                         foreach ( $r['cookies'] as $name => $value ) {
551                                 if ( ! is_object( $value ) )
552                                         $r['cookies'][ $name ] = new WP_HTTP_Cookie( array( 'name' => $name, 'value' => $value ) );
553                         }
554
555                         $cookies_header = '';
556                         foreach ( (array) $r['cookies'] as $cookie ) {
557                                 $cookies_header .= $cookie->getHeaderValue() . '; ';
558                         }
559
560                         $cookies_header = substr( $cookies_header, 0, -2 );
561                         $r['headers']['cookie'] = $cookies_header;
562                 }
563         }
564
565         /**
566          * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
567          *
568          * Based off the HTTP http_encoding_dechunk function.
569          *
570          * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
571          *
572          * @access public
573          * @since 2.7.0
574          * @static
575          *
576          * @param string $body Body content
577          * @return string Chunked decoded body on success or raw body on failure.
578          */
579         public static function chunkTransferDecode( $body ) {
580                 // The body is not chunked encoded or is malformed.
581                 if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
582                         return $body;
583
584                 $parsed_body = '';
585
586                 // We'll be altering $body, so need a backup in case of error.
587                 $body_original = $body;
588
589                 while ( true ) {
590                         $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
591                         if ( ! $has_chunk || empty( $match[1] ) )
592                                 return $body_original;
593
594                         $length = hexdec( $match[1] );
595                         $chunk_length = strlen( $match[0] );
596
597                         // Parse out the chunk of data.
598                         $parsed_body .= substr( $body, $chunk_length, $length );
599
600                         // Remove the chunk from the raw data.
601                         $body = substr( $body, $length + $chunk_length );
602
603                         // End of the document.
604                         if ( '0' === trim( $body ) )
605                                 return $parsed_body;
606                 }
607         }
608
609         /**
610          * Block requests through the proxy.
611          *
612          * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
613          * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
614          *
615          * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
616          * file and this will only allow localhost and your blog to make requests. The constant
617          * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
618          * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
619          * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
620          *
621          * @since 2.8.0
622          * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
623          * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
624          *
625          * @param string $uri URI of url.
626          * @return bool True to block, false to allow.
627          */
628         public function block_request($uri) {
629                 // We don't need to block requests, because nothing is blocked.
630                 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
631                         return false;
632
633                 $check = parse_url($uri);
634                 if ( ! $check )
635                         return true;
636
637                 $home = parse_url( get_option('siteurl') );
638
639                 // Don't block requests back to ourselves by default.
640                 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
641                         /**
642                          * Filter whether to block local requests through the proxy.
643                          *
644                          * @since 2.8.0
645                          *
646                          * @param bool $block Whether to block local requests through proxy.
647                          *                    Default false.
648                          */
649                         return apply_filters( 'block_local_requests', false );
650                 }
651
652                 if ( !defined('WP_ACCESSIBLE_HOSTS') )
653                         return true;
654
655                 static $accessible_hosts;
656                 static $wildcard_regex = false;
657                 if ( null == $accessible_hosts ) {
658                         $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
659
660                         if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
661                                 $wildcard_regex = array();
662                                 foreach ( $accessible_hosts as $host )
663                                         $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
664                                 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
665                         }
666                 }
667
668                 if ( !empty($wildcard_regex) )
669                         return !preg_match($wildcard_regex, $check['host']);
670                 else
671                         return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
672
673         }
674
675         /**
676          * A wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7
677          *
678          * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including
679          * schemeless and relative url's with :// in the path, this works around those
680          * limitations providing a standard output on PHP 5.2~5.4+.
681          *
682          * Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated
683          * when URL parsing failed.
684          *
685          * @since 4.1.0
686          * @access protected
687          *
688          * @param string $url The URL to parse.
689          * @return bool|array False on failure; Array of URL components on success;
690          *                    See parse_url()'s return values.
691          */
692         protected static function parse_url( $url ) {
693                 $parts = @parse_url( $url );
694                 if ( ! $parts ) {
695                         // < PHP 5.4.7 compat, trouble with relative paths including a scheme break in the path
696                         if ( '/' == $url[0] && false !== strpos( $url, '://' ) ) {
697                                 // Since we know it's a relative path, prefix with a scheme/host placeholder and try again
698                                 if ( ! $parts = @parse_url( 'placeholder://placeholder' . $url ) ) {
699                                         return $parts;
700                                 }
701                                 // Remove the placeholder values
702                                 unset( $parts['scheme'], $parts['host'] );
703                         } else {
704                                 return $parts;
705                         }
706                 }
707
708                 // < PHP 5.4.7 compat, doesn't detect schemeless URL's host field
709                 if ( '//' == substr( $url, 0, 2 ) && ! isset( $parts['host'] ) ) {
710                         list( $parts['host'], $slashless_path ) = explode( '/', substr( $parts['path'], 2 ), 2 );
711                         $parts['path'] = "/{$slashless_path}";
712                 }
713
714                 return $parts;
715         }
716
717         /**
718          * Converts a relative URL to an absolute URL relative to a given URL.
719          *
720          * If an Absolute URL is provided, no processing of that URL is done.
721          *
722          * @since 3.4.0
723          *
724          * @access public
725          * @param string $maybe_relative_path The URL which might be relative
726          * @param string $url                 The URL which $maybe_relative_path is relative to
727          * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
728          */
729         public static function make_absolute_url( $maybe_relative_path, $url ) {
730                 if ( empty( $url ) )
731                         return $maybe_relative_path;
732
733                 if ( ! $url_parts = WP_HTTP::parse_url( $url ) ) {
734                         return $maybe_relative_path;
735                 }
736
737                 if ( ! $relative_url_parts = WP_HTTP::parse_url( $maybe_relative_path ) ) {
738                         return $maybe_relative_path;
739                 }
740
741                 // Check for a scheme on the 'relative' url
742                 if ( ! empty( $relative_url_parts['scheme'] ) ) {
743                         return $maybe_relative_path;
744                 }
745
746                 $absolute_path = $url_parts['scheme'] . '://';
747
748                 // Schemeless URL's will make it this far, so we check for a host in the relative url and convert it to a protocol-url
749                 if ( isset( $relative_url_parts['host'] ) ) {
750                         $absolute_path .= $relative_url_parts['host'];
751                         if ( isset( $relative_url_parts['port'] ) )
752                                 $absolute_path .= ':' . $relative_url_parts['port'];
753                 } else {
754                         $absolute_path .= $url_parts['host'];
755                         if ( isset( $url_parts['port'] ) )
756                                 $absolute_path .= ':' . $url_parts['port'];
757                 }
758
759                 // Start off with the Absolute URL path.
760                 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
761
762                 // If it's a root-relative path, then great.
763                 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
764                         $path = $relative_url_parts['path'];
765
766                 // Else it's a relative path.
767                 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
768                         // Strip off any file components from the absolute path.
769                         $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
770
771                         // Build the new path.
772                         $path .= $relative_url_parts['path'];
773
774                         // Strip all /path/../ out of the path.
775                         while ( strpos( $path, '../' ) > 1 ) {
776                                 $path = preg_replace( '![^/]+/\.\./!', '', $path );
777                         }
778
779                         // Strip any final leading ../ from the path.
780                         $path = preg_replace( '!^/(\.\./)+!', '', $path );
781                 }
782
783                 // Add the Query string.
784                 if ( ! empty( $relative_url_parts['query'] ) )
785                         $path .= '?' . $relative_url_parts['query'];
786
787                 return $absolute_path . '/' . ltrim( $path, '/' );
788         }
789
790         /**
791          * Handles HTTP Redirects and follows them if appropriate.
792          *
793          * @since 3.7.0
794          *
795          * @param string $url The URL which was requested.
796          * @param array $args The Arguments which were used to make the request.
797          * @param array $response The Response of the HTTP request.
798          * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
799          */
800         public static function handle_redirects( $url, $args, $response ) {
801                 // If no redirects are present, or, redirects were not requested, perform no action.
802                 if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
803                         return false;
804
805                 // Only perform redirections on redirection http codes.
806                 if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
807                         return false;
808
809                 // Don't redirect if we've run out of redirects.
810                 if ( $args['redirection']-- <= 0 )
811                         return new WP_Error( 'http_request_failed', __('Too many redirects.') );
812
813                 $redirect_location = $response['headers']['location'];
814
815                 // If there were multiple Location headers, use the last header specified.
816                 if ( is_array( $redirect_location ) )
817                         $redirect_location = array_pop( $redirect_location );
818
819                 $redirect_location = WP_HTTP::make_absolute_url( $redirect_location, $url );
820
821                 // POST requests should not POST to a redirected location.
822                 if ( 'POST' == $args['method'] ) {
823                         if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
824                                 $args['method'] = 'GET';
825                 }
826
827                 // Include valid cookies in the redirect process.
828                 if ( ! empty( $response['cookies'] ) ) {
829                         foreach ( $response['cookies'] as $cookie ) {
830                                 if ( $cookie->test( $redirect_location ) )
831                                         $args['cookies'][] = $cookie;
832                         }
833                 }
834
835                 return wp_remote_request( $redirect_location, $args );
836         }
837
838         /**
839          * Determines if a specified string represents an IP address or not.
840          *
841          * This function also detects the type of the IP address, returning either
842          * '4' or '6' to represent a IPv4 and IPv6 address respectively.
843          * This does not verify if the IP is a valid IP, only that it appears to be
844          * an IP address.
845          *
846          * @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
847          *
848          * @since 3.7.0
849          * @static
850          *
851          * @param string $maybe_ip A suspected IP address
852          * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
853          */
854         public static function is_ip_address( $maybe_ip ) {
855                 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
856                         return 4;
857
858                 if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) )
859                         return 6;
860
861                 return false;
862         }
863
864 }
865
866 /**
867  * HTTP request method uses PHP Streams to retrieve the url.
868  *
869  * @since 2.7.0
870  * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
871  */
872 class WP_Http_Streams {
873         /**
874          * Send a HTTP request to a URI using PHP Streams.
875          *
876          * @see WP_Http::request For default options descriptions.
877          *
878          * @since 2.7.0
879          * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
880          *
881          * @access public
882          * @param string $url The request URL.
883          * @param string|array $args Optional. Override the defaults.
884          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
885          */
886         public function request($url, $args = array()) {
887                 $defaults = array(
888                         'method' => 'GET', 'timeout' => 5,
889                         'redirection' => 5, 'httpversion' => '1.0',
890                         'blocking' => true,
891                         'headers' => array(), 'body' => null, 'cookies' => array()
892                 );
893
894                 $r = wp_parse_args( $args, $defaults );
895
896                 if ( isset($r['headers']['User-Agent']) ) {
897                         $r['user-agent'] = $r['headers']['User-Agent'];
898                         unset($r['headers']['User-Agent']);
899                 } else if ( isset($r['headers']['user-agent']) ) {
900                         $r['user-agent'] = $r['headers']['user-agent'];
901                         unset($r['headers']['user-agent']);
902                 }
903
904                 // Construct Cookie: header if any cookies are set.
905                 WP_Http::buildCookieHeader( $r );
906
907                 $arrURL = parse_url($url);
908
909                 $connect_host = $arrURL['host'];
910
911                 $secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
912                 if ( ! isset( $arrURL['port'] ) ) {
913                         if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
914                                 $arrURL['port'] = 443;
915                                 $secure_transport = true;
916                         } else {
917                                 $arrURL['port'] = 80;
918                         }
919                 }
920
921                 // Always pass a Path, defaulting to the root in cases such as http://example.com
922                 if ( ! isset( $arrURL['path'] ) ) {
923                         $arrURL['path'] = '/';
924                 }
925
926                 if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
927                         if ( isset( $r['headers']['Host'] ) )
928                                 $arrURL['host'] = $r['headers']['Host'];
929                         else
930                                 $arrURL['host'] = $r['headers']['host'];
931                         unset( $r['headers']['Host'], $r['headers']['host'] );
932                 }
933
934                 /*
935                  * Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
936                  * to ::1, which fails when the server is not set up for it. For compatibility, always
937                  * connect to the IPv4 address.
938                  */
939                 if ( 'localhost' == strtolower( $connect_host ) )
940                         $connect_host = '127.0.0.1';
941
942                 $connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
943
944                 $is_local = isset( $r['local'] ) && $r['local'];
945                 $ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
946                 if ( $is_local ) {
947                         /**
948                          * Filter whether SSL should be verified for local requests.
949                          *
950                          * @since 2.8.0
951                          *
952                          * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
953                          */
954                         $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
955                 } elseif ( ! $is_local ) {
956                         /**
957                          * Filter whether SSL should be verified for non-local requests.
958                          *
959                          * @since 2.8.0
960                          *
961                          * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
962                          */
963                         $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
964                 }
965
966                 $proxy = new WP_HTTP_Proxy();
967
968                 $context = stream_context_create( array(
969                         'ssl' => array(
970                                 'verify_peer' => $ssl_verify,
971                                 //'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
972                                 'capture_peer_cert' => $ssl_verify,
973                                 'SNI_enabled' => true,
974                                 'cafile' => $r['sslcertificates'],
975                                 'allow_self_signed' => ! $ssl_verify,
976                         )
977                 ) );
978
979                 $timeout = (int) floor( $r['timeout'] );
980                 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
981                 $connect_timeout = max( $timeout, 1 );
982
983                 // Store error number.
984                 $connection_error = null;
985
986                 // Store error string.
987                 $connection_error_str = null;
988
989                 if ( !WP_DEBUG ) {
990                         // In the event that the SSL connection fails, silence the many PHP Warnings.
991                         if ( $secure_transport )
992                                 $error_reporting = error_reporting(0);
993
994                         if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
995                                 $handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
996                         else
997                                 $handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
998
999                         if ( $secure_transport )
1000                                 error_reporting( $error_reporting );
1001
1002                 } else {
1003                         if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
1004                                 $handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1005                         else
1006                                 $handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1007                 }
1008
1009                 if ( false === $handle ) {
1010                         // SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
1011                         if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
1012                                 return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1013
1014                         return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
1015                 }
1016
1017                 // Verify that the SSL certificate is valid for this request.
1018                 if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
1019                         if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
1020                                 return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1021                 }
1022
1023                 stream_set_timeout( $handle, $timeout, $utimeout );
1024
1025                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
1026                         $requestPath = $url;
1027                 else
1028                         $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
1029
1030                 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
1031
1032                 $include_port_in_host_header = (
1033                         ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) ||
1034                         ( 'http'  == $arrURL['scheme'] && 80  != $arrURL['port'] ) ||
1035                         ( 'https' == $arrURL['scheme'] && 443 != $arrURL['port'] )
1036                 );
1037
1038                 if ( $include_port_in_host_header ) {
1039                         $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
1040                 } else {
1041                         $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
1042                 }
1043
1044                 if ( isset($r['user-agent']) )
1045                         $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
1046
1047                 if ( is_array($r['headers']) ) {
1048                         foreach ( (array) $r['headers'] as $header => $headerValue )
1049                                 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
1050                 } else {
1051                         $strHeaders .= $r['headers'];
1052                 }
1053
1054                 if ( $proxy->use_authentication() )
1055                         $strHeaders .= $proxy->authentication_header() . "\r\n";
1056
1057                 $strHeaders .= "\r\n";
1058
1059                 if ( ! is_null($r['body']) )
1060                         $strHeaders .= $r['body'];
1061
1062                 fwrite($handle, $strHeaders);
1063
1064                 if ( ! $r['blocking'] ) {
1065                         stream_set_blocking( $handle, 0 );
1066                         fclose( $handle );
1067                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1068                 }
1069
1070                 $strResponse = '';
1071                 $bodyStarted = false;
1072                 $keep_reading = true;
1073                 $block_size = 4096;
1074                 if ( isset( $r['limit_response_size'] ) )
1075                         $block_size = min( $block_size, $r['limit_response_size'] );
1076
1077                 // If streaming to a file setup the file handle.
1078                 if ( $r['stream'] ) {
1079                         if ( ! WP_DEBUG )
1080                                 $stream_handle = @fopen( $r['filename'], 'w+' );
1081                         else
1082                                 $stream_handle = fopen( $r['filename'], 'w+' );
1083                         if ( ! $stream_handle )
1084                                 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1085
1086                         $bytes_written = 0;
1087                         while ( ! feof($handle) && $keep_reading ) {
1088                                 $block = fread( $handle, $block_size );
1089                                 if ( ! $bodyStarted ) {
1090                                         $strResponse .= $block;
1091                                         if ( strpos( $strResponse, "\r\n\r\n" ) ) {
1092                                                 $process = WP_Http::processResponse( $strResponse );
1093                                                 $bodyStarted = true;
1094                                                 $block = $process['body'];
1095                                                 unset( $strResponse );
1096                                                 $process['body'] = '';
1097                                         }
1098                                 }
1099
1100                                 $this_block_size = strlen( $block );
1101
1102                                 if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] ) {
1103                                         $this_block_size = ( $r['limit_response_size'] - $bytes_written );
1104                                         $block = substr( $block, 0, $this_block_size );
1105                                 }
1106
1107                                 $bytes_written_to_file = fwrite( $stream_handle, $block );
1108
1109                                 if ( $bytes_written_to_file != $this_block_size ) {
1110                                         fclose( $handle );
1111                                         fclose( $stream_handle );
1112                                         return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1113                                 }
1114
1115                                 $bytes_written += $bytes_written_to_file;
1116
1117                                 $keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
1118                         }
1119
1120                         fclose( $stream_handle );
1121
1122                 } else {
1123                         $header_length = 0;
1124                         while ( ! feof( $handle ) && $keep_reading ) {
1125                                 $block = fread( $handle, $block_size );
1126                                 $strResponse .= $block;
1127                                 if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
1128                                         $header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
1129                                         $bodyStarted = true;
1130                                 }
1131                                 $keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
1132                         }
1133
1134                         $process = WP_Http::processResponse( $strResponse );
1135                         unset( $strResponse );
1136
1137                 }
1138
1139                 fclose( $handle );
1140
1141                 $arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
1142
1143                 $response = array(
1144                         'headers' => $arrHeaders['headers'],
1145                         // Not yet processed.
1146                         'body' => null,
1147                         'response' => $arrHeaders['response'],
1148                         'cookies' => $arrHeaders['cookies'],
1149                         'filename' => $r['filename']
1150                 );
1151
1152                 // Handle redirects.
1153                 if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1154                         return $redirect_response;
1155
1156                 // If the body was chunk encoded, then decode it.
1157                 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
1158                         $process['body'] = WP_Http::chunkTransferDecode($process['body']);
1159
1160                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
1161                         $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
1162
1163                 if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
1164                         $process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
1165
1166                 $response['body'] = $process['body'];
1167
1168                 return $response;
1169         }
1170
1171         /**
1172          * Verifies the received SSL certificate against it's Common Names and subjectAltName fields
1173          *
1174          * PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
1175          * the certificate is valid for the hostname which was requested.
1176          * This function verifies the requested hostname against certificate's subjectAltName field,
1177          * if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
1178          *
1179          * IP Address support is included if the request is being made to an IP address.
1180          *
1181          * @since 3.7.0
1182          * @static
1183          *
1184          * @param stream $stream The PHP Stream which the SSL request is being made over
1185          * @param string $host The hostname being requested
1186          * @return bool If the cerficiate presented in $stream is valid for $host
1187          */
1188         public static function verify_ssl_certificate( $stream, $host ) {
1189                 $context_options = stream_context_get_options( $stream );
1190
1191                 if ( empty( $context_options['ssl']['peer_certificate'] ) )
1192                         return false;
1193
1194                 $cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
1195                 if ( ! $cert )
1196                         return false;
1197
1198                 /*
1199                  * If the request is being made to an IP address, we'll validate against IP fields
1200                  * in the cert (if they exist)
1201                  */
1202                 $host_type = ( WP_HTTP::is_ip_address( $host ) ? 'ip' : 'dns' );
1203
1204                 $certificate_hostnames = array();
1205                 if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
1206                         $match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
1207                         foreach ( $match_against as $match ) {
1208                                 list( $match_type, $match_host ) = explode( ':', $match );
1209                                 if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
1210                                         $certificate_hostnames[] = strtolower( trim( $match_host ) );
1211                         }
1212                 } elseif ( !empty( $cert['subject']['CN'] ) ) {
1213                         // Only use the CN when the certificate includes no subjectAltName extension.
1214                         $certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
1215                 }
1216
1217                 // Exact hostname/IP matches.
1218                 if ( in_array( strtolower( $host ), $certificate_hostnames ) )
1219                         return true;
1220
1221                 // IP's can't be wildcards, Stop processing.
1222                 if ( 'ip' == $host_type )
1223                         return false;
1224
1225                 // Test to see if the domain is at least 2 deep for wildcard support.
1226                 if ( substr_count( $host, '.' ) < 2 )
1227                         return false;
1228
1229                 // Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
1230                 $wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
1231
1232                 return in_array( strtolower( $wildcard_host ), $certificate_hostnames );
1233         }
1234
1235         /**
1236          * Whether this class can be used for retrieving a URL.
1237          *
1238          * @static
1239          * @access public
1240          * @since 2.7.0
1241          * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
1242          *
1243          * @return boolean False means this class can not be used, true means it can.
1244          */
1245         public static function test( $args = array() ) {
1246                 if ( ! function_exists( 'stream_socket_client' ) )
1247                         return false;
1248
1249                 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1250
1251                 if ( $is_ssl ) {
1252                         if ( ! extension_loaded( 'openssl' ) )
1253                                 return false;
1254                         if ( ! function_exists( 'openssl_x509_parse' ) )
1255                                 return false;
1256                 }
1257
1258                 /**
1259                  * Filter whether streams can be used as a transport for retrieving a URL.
1260                  *
1261                  * @since 2.7.0
1262                  *
1263                  * @param bool  $use_class Whether the class can be used. Default true.
1264                  * @param array $args      Request arguments.
1265                  */
1266                 return apply_filters( 'use_streams_transport', true, $args );
1267         }
1268 }
1269
1270 /**
1271  * Deprecated HTTP Transport method which used fsockopen.
1272  *
1273  * This class is not used, and is included for backwards compatibility only.
1274  * All code should make use of WP_HTTP directly through it's API.
1275  *
1276  * @see WP_HTTP::request
1277  *
1278  * @since 2.7.0
1279  * @deprecated 3.7.0 Please use WP_HTTP::request() directly
1280  */
1281 class WP_HTTP_Fsockopen extends WP_HTTP_Streams {
1282         // For backwards compatibility for users who are using the class directly.
1283 }
1284
1285 /**
1286  * HTTP request method uses Curl extension to retrieve the url.
1287  *
1288  * Requires the Curl extension to be installed.
1289  *
1290  * @package WordPress
1291  * @subpackage HTTP
1292  * @since 2.7.0
1293  */
1294 class WP_Http_Curl {
1295
1296         /**
1297          * Temporary header storage for during requests.
1298          *
1299          * @since 3.2.0
1300          * @access private
1301          * @var string
1302          */
1303         private $headers = '';
1304
1305         /**
1306          * Temporary body storage for during requests.
1307          *
1308          * @since 3.6.0
1309          * @access private
1310          * @var string
1311          */
1312         private $body = '';
1313
1314         /**
1315          * The maximum amount of data to receive from the remote server.
1316          *
1317          * @since 3.6.0
1318          * @access private
1319          * @var int
1320          */
1321         private $max_body_length = false;
1322
1323         /**
1324          * The file resource used for streaming to file.
1325          *
1326          * @since 3.6.0
1327          * @access private
1328          * @var resource
1329          */
1330         private $stream_handle = false;
1331
1332         /**
1333          * The total bytes written in the current request.
1334          *
1335          * @since 4.1.0
1336          * @access private
1337          * @var int
1338          */
1339         private $bytes_written_total = 0;
1340
1341         /**
1342          * Send a HTTP request to a URI using cURL extension.
1343          *
1344          * @access public
1345          * @since 2.7.0
1346          *
1347          * @param string $url The request URL.
1348          * @param string|array $args Optional. Override the defaults.
1349          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
1350          */
1351         public function request($url, $args = array()) {
1352                 $defaults = array(
1353                         'method' => 'GET', 'timeout' => 5,
1354                         'redirection' => 5, 'httpversion' => '1.0',
1355                         'blocking' => true,
1356                         'headers' => array(), 'body' => null, 'cookies' => array()
1357                 );
1358
1359                 $r = wp_parse_args( $args, $defaults );
1360
1361                 if ( isset($r['headers']['User-Agent']) ) {
1362                         $r['user-agent'] = $r['headers']['User-Agent'];
1363                         unset($r['headers']['User-Agent']);
1364                 } else if ( isset($r['headers']['user-agent']) ) {
1365                         $r['user-agent'] = $r['headers']['user-agent'];
1366                         unset($r['headers']['user-agent']);
1367                 }
1368
1369                 // Construct Cookie: header if any cookies are set.
1370                 WP_Http::buildCookieHeader( $r );
1371
1372                 $handle = curl_init();
1373
1374                 // cURL offers really easy proxy support.
1375                 $proxy = new WP_HTTP_Proxy();
1376
1377                 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1378
1379                         curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1380                         curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1381                         curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1382
1383                         if ( $proxy->use_authentication() ) {
1384                                 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1385                                 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1386                         }
1387                 }
1388
1389                 $is_local = isset($r['local']) && $r['local'];
1390                 $ssl_verify = isset($r['sslverify']) && $r['sslverify'];
1391                 if ( $is_local ) {
1392                         /** This filter is documented in wp-includes/class-http.php */
1393                         $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
1394                 } elseif ( ! $is_local ) {
1395                         /** This filter is documented in wp-includes/class-http.php */
1396                         $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
1397                 }
1398
1399                 /*
1400                  * CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
1401                  * a value of 0 will allow an unlimited timeout.
1402                  */
1403                 $timeout = (int) ceil( $r['timeout'] );
1404                 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1405                 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1406
1407                 curl_setopt( $handle, CURLOPT_URL, $url);
1408                 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1409                 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
1410                 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1411                 curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
1412                 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1413
1414                 /*
1415                  * The option doesn't work with safe mode or when open_basedir is set, and there's
1416                  * a bug #17490 with redirected POST requests, so handle redirections outside Curl.
1417                  */
1418                 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
1419                 if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
1420                         curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
1421
1422                 switch ( $r['method'] ) {
1423                         case 'HEAD':
1424                                 curl_setopt( $handle, CURLOPT_NOBODY, true );
1425                                 break;
1426                         case 'POST':
1427                                 curl_setopt( $handle, CURLOPT_POST, true );
1428                                 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1429                                 break;
1430                         case 'PUT':
1431                                 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1432                                 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1433                                 break;
1434                         default:
1435                                 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
1436                                 if ( ! is_null( $r['body'] ) )
1437                                         curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1438                                 break;
1439                 }
1440
1441                 if ( true === $r['blocking'] ) {
1442                         curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
1443                         curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
1444                 }
1445
1446                 curl_setopt( $handle, CURLOPT_HEADER, false );
1447
1448                 if ( isset( $r['limit_response_size'] ) )
1449                         $this->max_body_length = intval( $r['limit_response_size'] );
1450                 else
1451                         $this->max_body_length = false;
1452
1453                 // If streaming to a file open a file handle, and setup our curl streaming handler.
1454                 if ( $r['stream'] ) {
1455                         if ( ! WP_DEBUG )
1456                                 $this->stream_handle = @fopen( $r['filename'], 'w+' );
1457                         else
1458                                 $this->stream_handle = fopen( $r['filename'], 'w+' );
1459                         if ( ! $this->stream_handle )
1460                                 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1461                 } else {
1462                         $this->stream_handle = false;
1463                 }
1464
1465                 if ( !empty( $r['headers'] ) ) {
1466                         // cURL expects full header strings in each element.
1467                         $headers = array();
1468                         foreach ( $r['headers'] as $name => $value ) {
1469                                 $headers[] = "{$name}: $value";
1470                         }
1471                         curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1472                 }
1473
1474                 if ( $r['httpversion'] == '1.0' )
1475                         curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1476                 else
1477                         curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1478
1479                 /**
1480                  * Fires before the cURL request is executed.
1481                  *
1482                  * Cookies are not currently handled by the HTTP API. This action allows
1483                  * plugins to handle cookies themselves.
1484                  *
1485                  * @since 2.8.0
1486                  *
1487                  * @param resource &$handle The cURL handle returned by curl_init().
1488                  * @param array    $r       The HTTP request arguments.
1489                  * @param string   $url     The request URL.
1490                  */
1491                 do_action_ref_array( 'http_api_curl', array( &$handle, $r, $url ) );
1492
1493                 // We don't need to return the body, so don't. Just execute request and return.
1494                 if ( ! $r['blocking'] ) {
1495                         curl_exec( $handle );
1496
1497                         if ( $curl_error = curl_error( $handle ) ) {
1498                                 curl_close( $handle );
1499                                 return new WP_Error( 'http_request_failed', $curl_error );
1500                         }
1501                         if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1502                                 curl_close( $handle );
1503                                 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1504                         }
1505
1506                         curl_close( $handle );
1507                         return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1508                 }
1509
1510                 curl_exec( $handle );
1511                 $theHeaders = WP_Http::processHeaders( $this->headers, $url );
1512                 $theBody = $this->body;
1513                 $bytes_written_total = $this->bytes_written_total;
1514
1515                 $this->headers = '';
1516                 $this->body = '';
1517                 $this->bytes_written_total = 0;
1518
1519                 $curl_error = curl_errno( $handle );
1520
1521                 // If an error occurred, or, no response.
1522                 if ( $curl_error || ( 0 == strlen( $theBody ) && empty( $theHeaders['headers'] ) ) ) {
1523                         if ( CURLE_WRITE_ERROR /* 23 */ == $curl_error && $r['stream'] ) {
1524                                 if ( ! $this->max_body_length || $this->max_body_length != $bytes_written_total ) {
1525                                         fclose( $this->stream_handle );
1526                                         return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1527                                 }
1528                         } else {
1529                                 if ( $curl_error = curl_error( $handle ) ) {
1530                                         curl_close( $handle );
1531                                         return new WP_Error( 'http_request_failed', $curl_error );
1532                                 }
1533                         }
1534                         if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1535                                 curl_close( $handle );
1536                                 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1537                         }
1538                 }
1539
1540                 curl_close( $handle );
1541
1542                 if ( $r['stream'] )
1543                         fclose( $this->stream_handle );
1544
1545                 $response = array(
1546                         'headers' => $theHeaders['headers'],
1547                         'body' => null,
1548                         'response' => $theHeaders['response'],
1549                         'cookies' => $theHeaders['cookies'],
1550                         'filename' => $r['filename']
1551                 );
1552
1553                 // Handle redirects.
1554                 if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1555                         return $redirect_response;
1556
1557                 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1558                         $theBody = WP_Http_Encoding::decompress( $theBody );
1559
1560                 $response['body'] = $theBody;
1561
1562                 return $response;
1563         }
1564
1565         /**
1566          * Grab the headers of the cURL request
1567          *
1568          * Each header is sent individually to this callback, so we append to the $header property for temporary storage
1569          *
1570          * @since 3.2.0
1571          * @access private
1572          * @return int
1573          */
1574         private function stream_headers( $handle, $headers ) {
1575                 $this->headers .= $headers;
1576                 return strlen( $headers );
1577         }
1578
1579         /**
1580          * Grab the body of the cURL request
1581          *
1582          * The contents of the document are passed in chunks, so we append to the $body property for temporary storage.
1583          * Returning a length shorter than the length of $data passed in will cause cURL to abort the request with CURLE_WRITE_ERROR
1584          *
1585          * @since 3.6.0
1586          * @access private
1587          * @return int
1588          */
1589         private function stream_body( $handle, $data ) {
1590                 $data_length = strlen( $data );
1591
1592                 if ( $this->max_body_length && ( $this->bytes_written_total + $data_length ) > $this->max_body_length ) {
1593                         $data_length = ( $this->max_body_length - $this->bytes_written_total );
1594                         $data = substr( $data, 0, $data_length );
1595                 }
1596
1597                 if ( $this->stream_handle ) {
1598                         $bytes_written = fwrite( $this->stream_handle, $data );
1599                 } else {
1600                         $this->body .= $data;
1601                         $bytes_written = $data_length;
1602                 }
1603
1604                 $this->bytes_written_total += $bytes_written;
1605
1606                 // Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR.
1607                 return $bytes_written;
1608         }
1609
1610         /**
1611          * Whether this class can be used for retrieving an URL.
1612          *
1613          * @static
1614          * @since 2.7.0
1615          *
1616          * @return boolean False means this class can not be used, true means it can.
1617          */
1618         public static function test( $args = array() ) {
1619                 if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
1620                         return false;
1621
1622                 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1623
1624                 if ( $is_ssl ) {
1625                         $curl_version = curl_version();
1626                         // Check whether this cURL version support SSL requests.
1627                         if ( ! (CURL_VERSION_SSL & $curl_version['features']) )
1628                                 return false;
1629                 }
1630
1631                 /**
1632                  * Filter whether cURL can be used as a transport for retrieving a URL.
1633                  *
1634                  * @since 2.7.0
1635                  *
1636                  * @param bool  $use_class Whether the class can be used. Default true.
1637                  * @param array $args      An array of request arguments.
1638                  */
1639                 return apply_filters( 'use_curl_transport', true, $args );
1640         }
1641 }
1642
1643 /**
1644  * Adds Proxy support to the WordPress HTTP API.
1645  *
1646  * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1647  * enable proxy support. There are also a few filters that plugins can hook into for some of the
1648  * constants.
1649  *
1650  * Please note that only BASIC authentication is supported by most transports.
1651  * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
1652  *
1653  * The constants are as follows:
1654  * <ol>
1655  * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1656  * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1657  * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1658  * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1659  * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1660  * You do not need to have localhost and the blog host in this list, because they will not be passed
1661  * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1662  * </ol>
1663  *
1664  * An example can be as seen below.
1665  *
1666  *     define('WP_PROXY_HOST', '192.168.84.101');
1667  *     define('WP_PROXY_PORT', '8080');
1668  *     define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1669  *
1670  * @link https://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1671  * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1672  * @since 2.8.0
1673  */
1674 class WP_HTTP_Proxy {
1675
1676         /**
1677          * Whether proxy connection should be used.
1678          *
1679          * @since 2.8.0
1680          *
1681          * @use WP_PROXY_HOST
1682          * @use WP_PROXY_PORT
1683          *
1684          * @return bool
1685          */
1686         public function is_enabled() {
1687                 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1688         }
1689
1690         /**
1691          * Whether authentication should be used.
1692          *
1693          * @since 2.8.0
1694          *
1695          * @use WP_PROXY_USERNAME
1696          * @use WP_PROXY_PASSWORD
1697          *
1698          * @return bool
1699          */
1700         public function use_authentication() {
1701                 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1702         }
1703
1704         /**
1705          * Retrieve the host for the proxy server.
1706          *
1707          * @since 2.8.0
1708          *
1709          * @return string
1710          */
1711         public function host() {
1712                 if ( defined('WP_PROXY_HOST') )
1713                         return WP_PROXY_HOST;
1714
1715                 return '';
1716         }
1717
1718         /**
1719          * Retrieve the port for the proxy server.
1720          *
1721          * @since 2.8.0
1722          *
1723          * @return string
1724          */
1725         public function port() {
1726                 if ( defined('WP_PROXY_PORT') )
1727                         return WP_PROXY_PORT;
1728
1729                 return '';
1730         }
1731
1732         /**
1733          * Retrieve the username for proxy authentication.
1734          *
1735          * @since 2.8.0
1736          *
1737          * @return string
1738          */
1739         public function username() {
1740                 if ( defined('WP_PROXY_USERNAME') )
1741                         return WP_PROXY_USERNAME;
1742
1743                 return '';
1744         }
1745
1746         /**
1747          * Retrieve the password for proxy authentication.
1748          *
1749          * @since 2.8.0
1750          *
1751          * @return string
1752          */
1753         public function password() {
1754                 if ( defined('WP_PROXY_PASSWORD') )
1755                         return WP_PROXY_PASSWORD;
1756
1757                 return '';
1758         }
1759
1760         /**
1761          * Retrieve authentication string for proxy authentication.
1762          *
1763          * @since 2.8.0
1764          *
1765          * @return string
1766          */
1767         public function authentication() {
1768                 return $this->username() . ':' . $this->password();
1769         }
1770
1771         /**
1772          * Retrieve header string for proxy authentication.
1773          *
1774          * @since 2.8.0
1775          *
1776          * @return string
1777          */
1778         public function authentication_header() {
1779                 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1780         }
1781
1782         /**
1783          * Whether URL should be sent through the proxy server.
1784          *
1785          * We want to keep localhost and the blog URL from being sent through the proxy server, because
1786          * some proxies can not handle this. We also have the constant available for defining other
1787          * hosts that won't be sent through the proxy.
1788          *
1789          * @since 2.8.0
1790          *
1791          * @param string $uri URI to check.
1792          * @return bool True, to send through the proxy and false if, the proxy should not be used.
1793          */
1794         public function send_through_proxy( $uri ) {
1795                 /*
1796                  * parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1797                  * This will be displayed on blogs, which is not reasonable.
1798                  */
1799                 $check = @parse_url($uri);
1800
1801                 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1802                 if ( $check === false )
1803                         return true;
1804
1805                 $home = parse_url( get_option('siteurl') );
1806
1807                 /**
1808                  * Filter whether to preempt sending the request through the proxy server.
1809                  *
1810                  * Returning false will bypass the proxy; returning true will send
1811                  * the request through the proxy. Returning null bypasses the filter.
1812                  *
1813                  * @since 3.5.0
1814                  *
1815                  * @param null   $override Whether to override the request result. Default null.
1816                  * @param string $uri      URL to check.
1817                  * @param array  $check    Associative array result of parsing the URI.
1818                  * @param array  $home     Associative array result of parsing the site URL.
1819                  */
1820                 $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
1821                 if ( ! is_null( $result ) )
1822                         return $result;
1823
1824                 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) )
1825                         return false;
1826
1827                 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1828                         return true;
1829
1830                 static $bypass_hosts;
1831                 static $wildcard_regex = false;
1832                 if ( null == $bypass_hosts ) {
1833                         $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1834
1835                         if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1836                                 $wildcard_regex = array();
1837                                 foreach ( $bypass_hosts as $host )
1838                                         $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
1839                                 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1840                         }
1841                 }
1842
1843                 if ( !empty($wildcard_regex) )
1844                         return !preg_match($wildcard_regex, $check['host']);
1845                 else
1846                         return !in_array( $check['host'], $bypass_hosts );
1847         }
1848 }
1849 /**
1850  * Internal representation of a single cookie.
1851  *
1852  * Returned cookies are represented using this class, and when cookies are set, if they are not
1853  * already a WP_Http_Cookie() object, then they are turned into one.
1854  *
1855  * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1856  * names. Need to switch to use underscores instead for the methods.
1857  *
1858  * @package WordPress
1859  * @subpackage HTTP
1860  * @since 2.8.0
1861  */
1862 class WP_Http_Cookie {
1863
1864         /**
1865          * Cookie name.
1866          *
1867          * @since 2.8.0
1868          * @var string
1869          */
1870         public $name;
1871
1872         /**
1873          * Cookie value.
1874          *
1875          * @since 2.8.0
1876          * @var string
1877          */
1878         public $value;
1879
1880         /**
1881          * When the cookie expires.
1882          *
1883          * @since 2.8.0
1884          * @var string
1885          */
1886         public $expires;
1887
1888         /**
1889          * Cookie URL path.
1890          *
1891          * @since 2.8.0
1892          * @var string
1893          */
1894         public $path;
1895
1896         /**
1897          * Cookie Domain.
1898          *
1899          * @since 2.8.0
1900          * @var string
1901          */
1902         public $domain;
1903
1904         /**
1905          * Sets up this cookie object.
1906          *
1907          * The parameter $data should be either an associative array containing the indices names below
1908          * or a header string detailing it.
1909          *
1910          * @since 2.8.0
1911          * @access public
1912          *
1913          * @param string|array $data {
1914          *     Raw cookie data as header string or data array.
1915          *
1916          *     @type string     $name    Cookie name.
1917          *     @type mixed      $value   Value. Should NOT already be urlencoded.
1918          *     @type string|int $expires Optional. Unix timestamp or formatted date. Default null.
1919          *     @type string     $path    Optional. Path. Default '/'.
1920          *     @type string     $domain  Optional. Domain. Default host of parsed $requested_url.
1921          *     @type int        $port    Optional. Port. Default null.
1922          * }
1923          * @param string       $requested_url The URL which the cookie was set on, used for default $domain
1924          *                                    and $port values.
1925          */
1926         public function __construct( $data, $requested_url = '' ) {
1927                 if ( $requested_url )
1928                         $arrURL = @parse_url( $requested_url );
1929                 if ( isset( $arrURL['host'] ) )
1930                         $this->domain = $arrURL['host'];
1931                 $this->path = isset( $arrURL['path'] ) ? $arrURL['path'] : '/';
1932                 if (  '/' != substr( $this->path, -1 ) )
1933                         $this->path = dirname( $this->path ) . '/';
1934
1935                 if ( is_string( $data ) ) {
1936                         // Assume it's a header string direct from a previous request.
1937                         $pairs = explode( ';', $data );
1938
1939                         // Special handling for first pair; name=value. Also be careful of "=" in value.
1940                         $name  = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1941                         $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1942                         $this->name  = $name;
1943                         $this->value = urldecode( $value );
1944
1945                         // Removes name=value from items.
1946                         array_shift( $pairs );
1947
1948                         // Set everything else as a property.
1949                         foreach ( $pairs as $pair ) {
1950                                 $pair = rtrim($pair);
1951
1952                                 // Handle the cookie ending in ; which results in a empty final pair.
1953                                 if ( empty($pair) )
1954                                         continue;
1955
1956                                 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1957                                 $key = strtolower( trim( $key ) );
1958                                 if ( 'expires' == $key )
1959                                         $val = strtotime( $val );
1960                                 $this->$key = $val;
1961                         }
1962                 } else {
1963                         if ( !isset( $data['name'] ) )
1964                                 return false;
1965
1966                         // Set properties based directly on parameters.
1967                         foreach ( array( 'name', 'value', 'path', 'domain', 'port' ) as $field ) {
1968                                 if ( isset( $data[ $field ] ) )
1969                                         $this->$field = $data[ $field ];
1970                         }
1971
1972                         if ( isset( $data['expires'] ) )
1973                                 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1974                         else
1975                                 $this->expires = null;
1976                 }
1977         }
1978
1979         /**
1980          * Confirms that it's OK to send this cookie to the URL checked against.
1981          *
1982          * Decision is based on RFC 2109/2965, so look there for details on validity.
1983          *
1984          * @access public
1985          * @since 2.8.0
1986          *
1987          * @param string $url URL you intend to send this cookie to
1988          * @return boolean true if allowed, false otherwise.
1989          */
1990         public function test( $url ) {
1991                 if ( is_null( $this->name ) )
1992                         return false;
1993
1994                 // Expires - if expired then nothing else matters.
1995                 if ( isset( $this->expires ) && time() > $this->expires )
1996                         return false;
1997
1998                 // Get details on the URL we're thinking about sending to.
1999                 $url = parse_url( $url );
2000                 $url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' == $url['scheme'] ? 443 : 80 );
2001                 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
2002
2003                 // Values to use for comparison against the URL.
2004                 $path   = isset( $this->path )   ? $this->path   : '/';
2005                 $port   = isset( $this->port )   ? $this->port   : null;
2006                 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
2007                 if ( false === stripos( $domain, '.' ) )
2008                         $domain .= '.local';
2009
2010                 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
2011                 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
2012                 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
2013                         return false;
2014
2015                 // Port - supports "port-lists" in the format: "80,8000,8080".
2016                 if ( !empty( $port ) && !in_array( $url['port'], explode( ',', $port) ) )
2017                         return false;
2018
2019                 // Path - request path must start with path restriction.
2020                 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
2021                         return false;
2022
2023                 return true;
2024         }
2025
2026         /**
2027          * Convert cookie name and value back to header string.
2028          *
2029          * @access public
2030          * @since 2.8.0
2031          *
2032          * @return string Header encoded cookie name and value.
2033          */
2034         public function getHeaderValue() {
2035                 if ( ! isset( $this->name ) || ! isset( $this->value ) )
2036                         return '';
2037
2038                 /**
2039                  * Filter the header-encoded cookie value.
2040                  *
2041                  * @since 3.4.0
2042                  *
2043                  * @param string $value The cookie value.
2044                  * @param string $name  The cookie name.
2045                  */
2046                 return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
2047         }
2048
2049         /**
2050          * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
2051          *
2052          * @access public
2053          * @since 2.8.0
2054          *
2055          * @return string
2056          */
2057         public function getFullHeader() {
2058                 return 'Cookie: ' . $this->getHeaderValue();
2059         }
2060 }
2061
2062 /**
2063  * Implementation for deflate and gzip transfer encodings.
2064  *
2065  * Includes RFC 1950, RFC 1951, and RFC 1952.
2066  *
2067  * @since 2.8.0
2068  * @package WordPress
2069  * @subpackage HTTP
2070  */
2071 class WP_Http_Encoding {
2072
2073         /**
2074          * Compress raw string using the deflate format.
2075          *
2076          * Supports the RFC 1951 standard.
2077          *
2078          * @since 2.8.0
2079          *
2080          * @param string $raw String to compress.
2081          * @param int $level Optional, default is 9. Compression level, 9 is highest.
2082          * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
2083          * @return string|false False on failure.
2084          */
2085         public static function compress( $raw, $level = 9, $supports = null ) {
2086                 return gzdeflate( $raw, $level );
2087         }
2088
2089         /**
2090          * Decompression of deflated string.
2091          *
2092          * Will attempt to decompress using the RFC 1950 standard, and if that fails
2093          * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
2094          * 1952 standard gzip decode will be attempted. If all fail, then the
2095          * original compressed string will be returned.
2096          *
2097          * @since 2.8.0
2098          *
2099          * @param string $compressed String to decompress.
2100          * @param int $length The optional length of the compressed data.
2101          * @return string|bool False on failure.
2102          */
2103         public static function decompress( $compressed, $length = null ) {
2104
2105                 if ( empty($compressed) )
2106                         return $compressed;
2107
2108                 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
2109                         return $decompressed;
2110
2111                 if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
2112                         return $decompressed;
2113
2114                 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
2115                         return $decompressed;
2116
2117                 if ( function_exists('gzdecode') ) {
2118                         $decompressed = @gzdecode( $compressed );
2119
2120                         if ( false !== $decompressed )
2121                                 return $decompressed;
2122                 }
2123
2124                 return $compressed;
2125         }
2126
2127         /**
2128          * Decompression of deflated string while staying compatible with the majority of servers.
2129          *
2130          * Certain Servers will return deflated data with headers which PHP's gzinflate()
2131          * function cannot handle out of the box. The following function has been created from
2132          * various snippets on the gzinflate() PHP documentation.
2133          *
2134          * Warning: Magic numbers within. Due to the potential different formats that the compressed
2135          * data may be returned in, some "magic offsets" are needed to ensure proper decompression
2136          * takes place. For a simple progmatic way to determine the magic offset in use, see:
2137          * https://core.trac.wordpress.org/ticket/18273
2138          *
2139          * @since 2.8.1
2140          * @link https://core.trac.wordpress.org/ticket/18273
2141          * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
2142          * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
2143          *
2144          * @param string $gzData String to decompress.
2145          * @return string|bool False on failure.
2146          */
2147         public static function compatible_gzinflate($gzData) {
2148
2149                 // Compressed data might contain a full header, if so strip it for gzinflate().
2150                 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
2151                         $i = 10;
2152                         $flg = ord( substr($gzData, 3, 1) );
2153                         if ( $flg > 0 ) {
2154                                 if ( $flg & 4 ) {
2155                                         list($xlen) = unpack('v', substr($gzData, $i, 2) );
2156                                         $i = $i + 2 + $xlen;
2157                                 }
2158                                 if ( $flg & 8 )
2159                                         $i = strpos($gzData, "\0", $i) + 1;
2160                                 if ( $flg & 16 )
2161                                         $i = strpos($gzData, "\0", $i) + 1;
2162                                 if ( $flg & 2 )
2163                                         $i = $i + 2;
2164                         }
2165                         $decompressed = @gzinflate( substr($gzData, $i, -8) );
2166                         if ( false !== $decompressed )
2167                                 return $decompressed;
2168                 }
2169
2170                 // Compressed data from java.util.zip.Deflater amongst others.
2171                 $decompressed = @gzinflate( substr($gzData, 2) );
2172                 if ( false !== $decompressed )
2173                         return $decompressed;
2174
2175                 return false;
2176         }
2177
2178         /**
2179          * What encoding types to accept and their priority values.
2180          *
2181          * @since 2.8.0
2182          *
2183          * @param string $url
2184          * @param array  $args
2185          * @return string Types of encoding to accept.
2186          */
2187         public static function accept_encoding( $url, $args ) {
2188                 $type = array();
2189                 $compression_enabled = WP_Http_Encoding::is_available();
2190
2191                 if ( ! $args['decompress'] ) // Decompression specifically disabled.
2192                         $compression_enabled = false;
2193                 elseif ( $args['stream'] ) // Disable when streaming to file.
2194                         $compression_enabled = false;
2195                 elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it.
2196                         $compression_enabled = false;
2197
2198                 if ( $compression_enabled ) {
2199                         if ( function_exists( 'gzinflate' ) )
2200                                 $type[] = 'deflate;q=1.0';
2201
2202                         if ( function_exists( 'gzuncompress' ) )
2203                                 $type[] = 'compress;q=0.5';
2204
2205                         if ( function_exists( 'gzdecode' ) )
2206                                 $type[] = 'gzip;q=0.5';
2207                 }
2208
2209                 /**
2210                  * Filter the allowed encoding types.
2211                  *
2212                  * @since 3.6.0
2213                  *
2214                  * @param array  $type Encoding types allowed. Accepts 'gzinflate',
2215                  *                     'gzuncompress', 'gzdecode'.
2216                  * @param string $url  URL of the HTTP request.
2217                  * @param array  $args HTTP request arguments.
2218                  */
2219                 $type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
2220
2221                 return implode(', ', $type);
2222         }
2223
2224         /**
2225          * What encoding the content used when it was compressed to send in the headers.
2226          *
2227          * @since 2.8.0
2228          *
2229          * @return string Content-Encoding string to send in the header.
2230          */
2231         public static function content_encoding() {
2232                 return 'deflate';
2233         }
2234
2235         /**
2236          * Whether the content be decoded based on the headers.
2237          *
2238          * @since 2.8.0
2239          *
2240          * @param array|string $headers All of the available headers.
2241          * @return bool
2242          */
2243         public static function should_decode($headers) {
2244                 if ( is_array( $headers ) ) {
2245                         if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
2246                                 return true;
2247                 } else if ( is_string( $headers ) ) {
2248                         return ( stripos($headers, 'content-encoding:') !== false );
2249                 }
2250
2251                 return false;
2252         }
2253
2254         /**
2255          * Whether decompression and compression are supported by the PHP version.
2256          *
2257          * Each function is tested instead of checking for the zlib extension, to
2258          * ensure that the functions all exist in the PHP version and aren't
2259          * disabled.
2260          *
2261          * @since 2.8.0
2262          *
2263          * @return bool
2264          */
2265         public static function is_available() {
2266                 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
2267         }
2268 }