]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-http.php
WordPress 4.4.2
[autoinstalls/wordpress.git] / wp-includes / class-http.php
1 <?php
2 /**
3  * HTTP API: WP_Http class
4  *
5  * @package WordPress
6  * @subpackage HTTP
7  * @since 2.7.0
8  */
9
10 /**
11  * Core class used for managing HTTP transports and making HTTP requests.
12  *
13  * This class is used to consistently make outgoing HTTP requests easy for developers
14  * while still being compatible with the many PHP configurations under which
15  * WordPress runs.
16  *
17  * Debugging includes several actions, which pass different variables for debugging the HTTP API.
18  *
19  * @since 2.7.0
20  */
21 class WP_Http {
22
23         /**
24          * Send an HTTP request to a URI.
25          *
26          * Please note: The only URI that are supported in the HTTP Transport implementation
27          * are the HTTP and HTTPS protocols.
28          *
29          * @access public
30          * @since 2.7.0
31          *
32          * @global string $wp_version
33          *
34          * @param string       $url  The request URL.
35          * @param string|array $args {
36          *     Optional. Array or string of HTTP request arguments.
37          *
38          *     @type string       $method              Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
39          *                                             Some transports technically allow others, but should not be
40          *                                             assumed. Default 'GET'.
41          *     @type int          $timeout             How long the connection should stay open in seconds. Default 5.
42          *     @type int          $redirection         Number of allowed redirects. Not supported by all transports
43          *                                             Default 5.
44          *     @type string       $httpversion         Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
45          *                                             Default '1.0'.
46          *     @type string       $user-agent          User-agent value sent.
47          *                                             Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
48          *     @type bool         $reject_unsafe_urls  Whether to pass URLs through {@see wp_http_validate_url()}.
49          *                                             Default false.
50          *     @type bool         $blocking            Whether the calling code requires the result of the request.
51          *                                             If set to false, the request will be sent to the remote server,
52          *                                             and processing returned to the calling code immediately, the caller
53          *                                             will know if the request succeeded or failed, but will not receive
54          *                                             any response from the remote server. Default true.
55          *     @type string|array $headers             Array or string of headers to send with the request.
56          *                                             Default empty array.
57          *     @type array        $cookies             List of cookies to send with the request. Default empty array.
58          *     @type string|array $body                Body to send with the request. Default null.
59          *     @type bool         $compress            Whether to compress the $body when sending the request.
60          *                                             Default false.
61          *     @type bool         $decompress          Whether to decompress a compressed response. If set to false and
62          *                                             compressed content is returned in the response anyway, it will
63          *                                             need to be separately decompressed. Default true.
64          *     @type bool         $sslverify           Whether to verify SSL for the request. Default true.
65          *     @type string       sslcertificates      Absolute path to an SSL certificate .crt file.
66          *                                             Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
67          *     @type bool         $stream              Whether to stream to a file. If set to true and no filename was
68          *                                             given, it will be droped it in the WP temp dir and its name will
69          *                                             be set using the basename of the URL. Default false.
70          *     @type string       $filename            Filename of the file to write to when streaming. $stream must be
71          *                                             set to true. Default null.
72          *     @type int          $limit_response_size Size in bytes to limit the response to. Default null.
73          *
74          * }
75          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
76          *                        A WP_Error instance upon error.
77          */
78         public function request( $url, $args = array() ) {
79                 global $wp_version;
80
81                 $defaults = array(
82                         'method' => 'GET',
83                         /**
84                          * Filter the timeout value for an HTTP request.
85                          *
86                          * @since 2.7.0
87                          *
88                          * @param int $timeout_value Time in seconds until a request times out.
89                          *                           Default 5.
90                          */
91                         'timeout' => apply_filters( 'http_request_timeout', 5 ),
92                         /**
93                          * Filter the number of redirects allowed during an HTTP request.
94                          *
95                          * @since 2.7.0
96                          *
97                          * @param int $redirect_count Number of redirects allowed. Default 5.
98                          */
99                         'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
100                         /**
101                          * Filter the version of the HTTP protocol used in a request.
102                          *
103                          * @since 2.7.0
104                          *
105                          * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
106                          *                        Default '1.0'.
107                          */
108                         'httpversion' => apply_filters( 'http_request_version', '1.0' ),
109                         /**
110                          * Filter the user agent value sent with an HTTP request.
111                          *
112                          * @since 2.7.0
113                          *
114                          * @param string $user_agent WordPress user agent string.
115                          */
116                         'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
117                         /**
118                          * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
119                          *
120                          * @since 3.6.0
121                          *
122                          * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
123                          *                       Default false.
124                          */
125                         'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
126                         'blocking' => true,
127                         'headers' => array(),
128                         'cookies' => array(),
129                         'body' => null,
130                         'compress' => false,
131                         'decompress' => true,
132                         'sslverify' => true,
133                         'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
134                         'stream' => false,
135                         'filename' => null,
136                         'limit_response_size' => null,
137                 );
138
139                 // Pre-parse for the HEAD checks.
140                 $args = wp_parse_args( $args );
141
142                 // By default, Head requests do not cause redirections.
143                 if ( isset($args['method']) && 'HEAD' == $args['method'] )
144                         $defaults['redirection'] = 0;
145
146                 $r = wp_parse_args( $args, $defaults );
147                 /**
148                  * Filter the arguments used in an HTTP request.
149                  *
150                  * @since 2.7.0
151                  *
152                  * @param array  $r   An array of HTTP request arguments.
153                  * @param string $url The request URL.
154                  */
155                 $r = apply_filters( 'http_request_args', $r, $url );
156
157                 // The transports decrement this, store a copy of the original value for loop purposes.
158                 if ( ! isset( $r['_redirection'] ) )
159                         $r['_redirection'] = $r['redirection'];
160
161                 /**
162                  * Filter whether to preempt an HTTP request's return value.
163                  *
164                  * Returning a non-false value from the filter will short-circuit the HTTP request and return
165                  * early with that value. A filter should return either:
166                  *
167                  *  - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
168                  *  - A WP_Error instance
169                  *  - boolean false (to avoid short-circuiting the response)
170                  *
171                  * Returning any other value may result in unexpected behaviour.
172                  *
173                  * @since 2.9.0
174                  *
175                  * @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value. Default false.
176                  * @param array               $r        HTTP request arguments.
177                  * @param string              $url      The request URL.
178                  */
179                 $pre = apply_filters( 'pre_http_request', false, $r, $url );
180
181                 if ( false !== $pre )
182                         return $pre;
183
184                 if ( function_exists( 'wp_kses_bad_protocol' ) ) {
185                         if ( $r['reject_unsafe_urls'] )
186                                 $url = wp_http_validate_url( $url );
187                         if ( $url ) {
188                                 $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
189                         }
190                 }
191
192                 $arrURL = @parse_url( $url );
193
194                 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
195                         return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
196
197                 if ( $this->block_request( $url ) )
198                         return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
199
200                 /*
201                  * Determine if this is a https call and pass that on to the transport functions
202                  * so that we can blacklist the transports that do not support ssl verification
203                  */
204                 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
205
206                 // Determine if this request is to OUR install of WordPress.
207                 $homeURL = parse_url( get_bloginfo( 'url' ) );
208                 $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
209                 unset( $homeURL );
210
211                 /*
212                  * If we are streaming to a file but no filename was given drop it in the WP temp dir
213                  * and pick its name using the basename of the $url.
214                  */
215                 if ( $r['stream']  && empty( $r['filename'] ) ) {
216                         $r['filename'] = get_temp_dir() . wp_unique_filename( get_temp_dir(), basename( $url ) );
217                 }
218
219                 /*
220                  * Force some settings if we are streaming to a file and check for existence and perms
221                  * of destination directory.
222                  */
223                 if ( $r['stream'] ) {
224                         $r['blocking'] = true;
225                         if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
226                                 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
227                 }
228
229                 if ( is_null( $r['headers'] ) )
230                         $r['headers'] = array();
231
232                 if ( ! is_array( $r['headers'] ) ) {
233                         $processedHeaders = self::processHeaders( $r['headers'], $url );
234                         $r['headers'] = $processedHeaders['headers'];
235                 }
236
237                 if ( isset( $r['headers']['User-Agent'] ) ) {
238                         $r['user-agent'] = $r['headers']['User-Agent'];
239                         unset( $r['headers']['User-Agent'] );
240                 }
241
242                 if ( isset( $r['headers']['user-agent'] ) ) {
243                         $r['user-agent'] = $r['headers']['user-agent'];
244                         unset( $r['headers']['user-agent'] );
245                 }
246
247                 if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
248                         $r['headers']['connection'] = 'close';
249                 }
250
251                 // Construct Cookie: header if any cookies are set.
252                 self::buildCookieHeader( $r );
253
254                 // Avoid issues where mbstring.func_overload is enabled.
255                 mbstring_binary_safe_encoding();
256
257                 if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
258                         if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
259                                 $r['headers']['Accept-Encoding'] = $encoding;
260                 }
261
262                 if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
263                         if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
264                                 $r['body'] = http_build_query( $r['body'], null, '&' );
265
266                                 if ( ! isset( $r['headers']['Content-Type'] ) )
267                                         $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
268                         }
269
270                         if ( '' === $r['body'] )
271                                 $r['body'] = null;
272
273                         if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
274                                 $r['headers']['Content-Length'] = strlen( $r['body'] );
275                 }
276
277                 $response = $this->_dispatch_request( $url, $r );
278
279                 reset_mbstring_encoding();
280
281                 if ( is_wp_error( $response ) )
282                         return $response;
283
284                 // Append cookies that were used in this request to the response
285                 if ( ! empty( $r['cookies'] ) ) {
286                         $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
287                         foreach ( $r['cookies'] as $cookie ) {
288                                 if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
289                                         $response['cookies'][] = $cookie;
290                                 }
291                         }
292                 }
293
294                 return $response;
295         }
296
297         /**
298          * Tests which transports are capable of supporting the request.
299          *
300          * @since 3.2.0
301          * @access private
302          *
303          * @param array $args Request arguments
304          * @param string $url URL to Request
305          *
306          * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
307          */
308         public function _get_first_available_transport( $args, $url = null ) {
309                 $transports = array( 'curl', 'streams' );
310                 /**
311                  * Filter which HTTP transports are available and in what order.
312                  *
313                  * @since 3.7.0
314                  *
315                  * @param array  $transports Array of HTTP transports to check. Default array contains
316                  *                           'curl', and 'streams', in that order.
317                  * @param array  $args       HTTP request arguments.
318                  * @param string $url        The URL to request.
319                  */
320                 $request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
321
322                 // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
323                 foreach ( $request_order as $transport ) {
324                         if ( in_array( $transport, $transports ) ) {
325                                 $transport = ucfirst( $transport );
326                         }
327                         $class = 'WP_Http_' . $transport;
328
329                         // Check to see if this transport is a possibility, calls the transport statically.
330                         if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
331                                 continue;
332
333                         return $class;
334                 }
335
336                 return false;
337         }
338
339         /**
340          * Dispatches a HTTP request to a supporting transport.
341          *
342          * Tests each transport in order to find a transport which matches the request arguments.
343          * Also caches the transport instance to be used later.
344          *
345          * The order for requests is cURL, and then PHP Streams.
346          *
347          * @since 3.2.0
348          *
349          * @static
350          * @access private
351          *
352          * @param string $url URL to Request
353          * @param array $args Request arguments
354          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
355          */
356         private function _dispatch_request( $url, $args ) {
357                 static $transports = array();
358
359                 $class = $this->_get_first_available_transport( $args, $url );
360                 if ( !$class )
361                         return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
362
363                 // Transport claims to support request, instantiate it and give it a whirl.
364                 if ( empty( $transports[$class] ) )
365                         $transports[$class] = new $class;
366
367                 $response = $transports[$class]->request( $url, $args );
368
369                 /**
370                  * Fires after an HTTP API response is received and before the response is returned.
371                  *
372                  * @since 2.8.0
373                  *
374                  * @param array|WP_Error $response HTTP response or WP_Error object.
375                  * @param string         $context  Context under which the hook is fired.
376                  * @param string         $class    HTTP transport used.
377                  * @param array          $args     HTTP request arguments.
378                  * @param string         $url      The request URL.
379                  */
380                 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
381
382                 if ( is_wp_error( $response ) )
383                         return $response;
384
385                 /**
386                  * Filter the HTTP API response immediately before the response is returned.
387                  *
388                  * @since 2.9.0
389                  *
390                  * @param array  $response HTTP response.
391                  * @param array  $args     HTTP request arguments.
392                  * @param string $url      The request URL.
393                  */
394                 return apply_filters( 'http_response', $response, $args, $url );
395         }
396
397         /**
398          * Uses the POST HTTP method.
399          *
400          * Used for sending data that is expected to be in the body.
401          *
402          * @access public
403          * @since 2.7.0
404          *
405          * @param string       $url  The request URL.
406          * @param string|array $args Optional. Override the defaults.
407          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
408          */
409         public function post($url, $args = array()) {
410                 $defaults = array('method' => 'POST');
411                 $r = wp_parse_args( $args, $defaults );
412                 return $this->request($url, $r);
413         }
414
415         /**
416          * Uses the GET HTTP method.
417          *
418          * Used for sending data that is expected to be in the body.
419          *
420          * @access public
421          * @since 2.7.0
422          *
423          * @param string $url The request URL.
424          * @param string|array $args Optional. Override the defaults.
425          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
426          */
427         public function get($url, $args = array()) {
428                 $defaults = array('method' => 'GET');
429                 $r = wp_parse_args( $args, $defaults );
430                 return $this->request($url, $r);
431         }
432
433         /**
434          * Uses the HEAD HTTP method.
435          *
436          * Used for sending data that is expected to be in the body.
437          *
438          * @access public
439          * @since 2.7.0
440          *
441          * @param string $url The request URL.
442          * @param string|array $args Optional. Override the defaults.
443          * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
444          */
445         public function head($url, $args = array()) {
446                 $defaults = array('method' => 'HEAD');
447                 $r = wp_parse_args( $args, $defaults );
448                 return $this->request($url, $r);
449         }
450
451         /**
452          * Parses the responses and splits the parts into headers and body.
453          *
454          * @access public
455          * @static
456          * @since 2.7.0
457          *
458          * @param string $strResponse The full response string
459          * @return array Array with 'headers' and 'body' keys.
460          */
461         public static function processResponse($strResponse) {
462                 $res = explode("\r\n\r\n", $strResponse, 2);
463
464                 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
465         }
466
467         /**
468          * Transform header string into an array.
469          *
470          * If an array is given then it is assumed to be raw header data with numeric keys with the
471          * headers as the values. No headers must be passed that were already processed.
472          *
473          * @access public
474          * @static
475          * @since 2.7.0
476          *
477          * @param string|array $headers
478          * @param string $url The URL that was requested
479          * @return array Processed string headers. If duplicate headers are encountered,
480          *                                      Then a numbered array is returned as the value of that header-key.
481          */
482         public static function processHeaders( $headers, $url = '' ) {
483                 // Split headers, one per array element.
484                 if ( is_string($headers) ) {
485                         // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
486                         $headers = str_replace("\r\n", "\n", $headers);
487                         /*
488                          * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
489                          * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
490                          */
491                         $headers = preg_replace('/\n[ \t]/', ' ', $headers);
492                         // Create the headers array.
493                         $headers = explode("\n", $headers);
494                 }
495
496                 $response = array('code' => 0, 'message' => '');
497
498                 /*
499                  * If a redirection has taken place, The headers for each page request may have been passed.
500                  * In this case, determine the final HTTP header and parse from there.
501                  */
502                 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
503                         if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
504                                 $headers = array_splice($headers, $i);
505                                 break;
506                         }
507                 }
508
509                 $cookies = array();
510                 $newheaders = array();
511                 foreach ( (array) $headers as $tempheader ) {
512                         if ( empty($tempheader) )
513                                 continue;
514
515                         if ( false === strpos($tempheader, ':') ) {
516                                 $stack = explode(' ', $tempheader, 3);
517                                 $stack[] = '';
518                                 list( , $response['code'], $response['message']) = $stack;
519                                 continue;
520                         }
521
522                         list($key, $value) = explode(':', $tempheader, 2);
523
524                         $key = strtolower( $key );
525                         $value = trim( $value );
526
527                         if ( isset( $newheaders[ $key ] ) ) {
528                                 if ( ! is_array( $newheaders[ $key ] ) )
529                                         $newheaders[$key] = array( $newheaders[ $key ] );
530                                 $newheaders[ $key ][] = $value;
531                         } else {
532                                 $newheaders[ $key ] = $value;
533                         }
534                         if ( 'set-cookie' == $key )
535                                 $cookies[] = new WP_Http_Cookie( $value, $url );
536                 }
537
538                 // Cast the Response Code to an int
539                 $response['code'] = intval( $response['code'] );
540
541                 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
542         }
543
544         /**
545          * Takes the arguments for a ::request() and checks for the cookie array.
546          *
547          * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
548          * which are each parsed into strings and added to the Cookie: header (within the arguments array).
549          * Edits the array by reference.
550          *
551          * @access public
552          * @version 2.8.0
553          * @static
554          *
555          * @param array $r Full array of args passed into ::request()
556          */
557         public static function buildCookieHeader( &$r ) {
558                 if ( ! empty($r['cookies']) ) {
559                         // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
560                         foreach ( $r['cookies'] as $name => $value ) {
561                                 if ( ! is_object( $value ) )
562                                         $r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
563                         }
564
565                         $cookies_header = '';
566                         foreach ( (array) $r['cookies'] as $cookie ) {
567                                 $cookies_header .= $cookie->getHeaderValue() . '; ';
568                         }
569
570                         $cookies_header = substr( $cookies_header, 0, -2 );
571                         $r['headers']['cookie'] = $cookies_header;
572                 }
573         }
574
575         /**
576          * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
577          *
578          * Based off the HTTP http_encoding_dechunk function.
579          *
580          * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
581          *
582          * @access public
583          * @since 2.7.0
584          * @static
585          *
586          * @param string $body Body content
587          * @return string Chunked decoded body on success or raw body on failure.
588          */
589         public static function chunkTransferDecode( $body ) {
590                 // The body is not chunked encoded or is malformed.
591                 if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
592                         return $body;
593
594                 $parsed_body = '';
595
596                 // We'll be altering $body, so need a backup in case of error.
597                 $body_original = $body;
598
599                 while ( true ) {
600                         $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
601                         if ( ! $has_chunk || empty( $match[1] ) )
602                                 return $body_original;
603
604                         $length = hexdec( $match[1] );
605                         $chunk_length = strlen( $match[0] );
606
607                         // Parse out the chunk of data.
608                         $parsed_body .= substr( $body, $chunk_length, $length );
609
610                         // Remove the chunk from the raw data.
611                         $body = substr( $body, $length + $chunk_length );
612
613                         // End of the document.
614                         if ( '0' === trim( $body ) )
615                                 return $parsed_body;
616                 }
617         }
618
619         /**
620          * Block requests through the proxy.
621          *
622          * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
623          * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
624          *
625          * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
626          * file and this will only allow localhost and your blog to make requests. The constant
627          * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
628          * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
629          * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
630          *
631          * @since 2.8.0
632          * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
633          * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
634          *
635          * @staticvar array|null $accessible_hosts
636          * @staticvar array      $wildcard_regex
637          *
638          * @param string $uri URI of url.
639          * @return bool True to block, false to allow.
640          */
641         public function block_request($uri) {
642                 // We don't need to block requests, because nothing is blocked.
643                 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
644                         return false;
645
646                 $check = parse_url($uri);
647                 if ( ! $check )
648                         return true;
649
650                 $home = parse_url( get_option('siteurl') );
651
652                 // Don't block requests back to ourselves by default.
653                 if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
654                         /**
655                          * Filter whether to block local requests through the proxy.
656                          *
657                          * @since 2.8.0
658                          *
659                          * @param bool $block Whether to block local requests through proxy.
660                          *                    Default false.
661                          */
662                         return apply_filters( 'block_local_requests', false );
663                 }
664
665                 if ( !defined('WP_ACCESSIBLE_HOSTS') )
666                         return true;
667
668                 static $accessible_hosts = null;
669                 static $wildcard_regex = array();
670                 if ( null === $accessible_hosts ) {
671                         $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
672
673                         if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
674                                 $wildcard_regex = array();
675                                 foreach ( $accessible_hosts as $host )
676                                         $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
677                                 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
678                         }
679                 }
680
681                 if ( !empty($wildcard_regex) )
682                         return !preg_match($wildcard_regex, $check['host']);
683                 else
684                         return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
685
686         }
687
688         /**
689          * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
690          *
691          * @access protected
692          * @deprecated 4.4.0 Use wp_parse_url()
693          * @see wp_parse_url()
694          *
695          * @param string $url The URL to parse.
696          * @return bool|array False on failure; Array of URL components on success;
697          *                    See parse_url()'s return values.
698          */
699         protected static function parse_url( $url ) {
700                 _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
701                 return wp_parse_url( $url );
702         }
703
704         /**
705          * Converts a relative URL to an absolute URL relative to a given URL.
706          *
707          * If an Absolute URL is provided, no processing of that URL is done.
708          *
709          * @since 3.4.0
710          *
711          * @static
712          * @access public
713          *
714          * @param string $maybe_relative_path The URL which might be relative
715          * @param string $url                 The URL which $maybe_relative_path is relative to
716          * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
717          */
718         public static function make_absolute_url( $maybe_relative_path, $url ) {
719                 if ( empty( $url ) )
720                         return $maybe_relative_path;
721
722                 if ( ! $url_parts = wp_parse_url( $url ) ) {
723                         return $maybe_relative_path;
724                 }
725
726                 if ( ! $relative_url_parts = wp_parse_url( $maybe_relative_path ) ) {
727                         return $maybe_relative_path;
728                 }
729
730                 // Check for a scheme on the 'relative' url
731                 if ( ! empty( $relative_url_parts['scheme'] ) ) {
732                         return $maybe_relative_path;
733                 }
734
735                 $absolute_path = $url_parts['scheme'] . '://';
736
737                 // 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
738                 if ( isset( $relative_url_parts['host'] ) ) {
739                         $absolute_path .= $relative_url_parts['host'];
740                         if ( isset( $relative_url_parts['port'] ) )
741                                 $absolute_path .= ':' . $relative_url_parts['port'];
742                 } else {
743                         $absolute_path .= $url_parts['host'];
744                         if ( isset( $url_parts['port'] ) )
745                                 $absolute_path .= ':' . $url_parts['port'];
746                 }
747
748                 // Start off with the Absolute URL path.
749                 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
750
751                 // If it's a root-relative path, then great.
752                 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
753                         $path = $relative_url_parts['path'];
754
755                 // Else it's a relative path.
756                 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
757                         // Strip off any file components from the absolute path.
758                         $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
759
760                         // Build the new path.
761                         $path .= $relative_url_parts['path'];
762
763                         // Strip all /path/../ out of the path.
764                         while ( strpos( $path, '../' ) > 1 ) {
765                                 $path = preg_replace( '![^/]+/\.\./!', '', $path );
766                         }
767
768                         // Strip any final leading ../ from the path.
769                         $path = preg_replace( '!^/(\.\./)+!', '', $path );
770                 }
771
772                 // Add the Query string.
773                 if ( ! empty( $relative_url_parts['query'] ) )
774                         $path .= '?' . $relative_url_parts['query'];
775
776                 return $absolute_path . '/' . ltrim( $path, '/' );
777         }
778
779         /**
780          * Handles HTTP Redirects and follows them if appropriate.
781          *
782          * @since 3.7.0
783          *
784          * @static
785          *
786          * @param string $url The URL which was requested.
787          * @param array $args The Arguments which were used to make the request.
788          * @param array $response The Response of the HTTP request.
789          * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
790          */
791         public static function handle_redirects( $url, $args, $response ) {
792                 // If no redirects are present, or, redirects were not requested, perform no action.
793                 if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
794                         return false;
795
796                 // Only perform redirections on redirection http codes.
797                 if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
798                         return false;
799
800                 // Don't redirect if we've run out of redirects.
801                 if ( $args['redirection']-- <= 0 )
802                         return new WP_Error( 'http_request_failed', __('Too many redirects.') );
803
804                 $redirect_location = $response['headers']['location'];
805
806                 // If there were multiple Location headers, use the last header specified.
807                 if ( is_array( $redirect_location ) )
808                         $redirect_location = array_pop( $redirect_location );
809
810                 $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
811
812                 // POST requests should not POST to a redirected location.
813                 if ( 'POST' == $args['method'] ) {
814                         if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
815                                 $args['method'] = 'GET';
816                 }
817
818                 // Include valid cookies in the redirect process.
819                 if ( ! empty( $response['cookies'] ) ) {
820                         foreach ( $response['cookies'] as $cookie ) {
821                                 if ( $cookie->test( $redirect_location ) )
822                                         $args['cookies'][] = $cookie;
823                         }
824                 }
825
826                 return wp_remote_request( $redirect_location, $args );
827         }
828
829         /**
830          * Determines if a specified string represents an IP address or not.
831          *
832          * This function also detects the type of the IP address, returning either
833          * '4' or '6' to represent a IPv4 and IPv6 address respectively.
834          * This does not verify if the IP is a valid IP, only that it appears to be
835          * an IP address.
836          *
837          * @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
838          *
839          * @since 3.7.0
840          * @static
841          *
842          * @param string $maybe_ip A suspected IP address
843          * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
844          */
845         public static function is_ip_address( $maybe_ip ) {
846                 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
847                         return 4;
848
849                 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, ' []' ) ) )
850                         return 6;
851
852                 return false;
853         }
854
855 }