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