]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/Requests/Requests.php
Sync with recent Requests commits. Fixes #1796
[Github/YOURLS.git] / includes / Requests / Requests.php
1 <?php
2 /**
3  * Requests for PHP
4  *
5  * Inspired by Requests for Python.
6  *
7  * Based on concepts from SimplePie_File, RequestCore and WP_Http.
8  *
9  * @package Requests
10  */
11
12 /**
13  * Requests for PHP
14  *
15  * Inspired by Requests for Python.
16  *
17  * Based on concepts from SimplePie_File, RequestCore and WP_Http.
18  *
19  * @package Requests
20  */
21 class Requests {
22         /**
23          * POST method
24          *
25          * @var string
26          */
27         const POST = 'POST';
28
29         /**
30          * PUT method
31          *
32          * @var string
33          */
34         const PUT = 'PUT';
35
36         /**
37          * GET method
38          *
39          * @var string
40          */
41         const GET = 'GET';
42
43         /**
44          * HEAD method
45          *
46          * @var string
47          */
48         const HEAD = 'HEAD';
49
50         /**
51          * DELETE method
52          *
53          * @var string
54          */
55         const DELETE = 'DELETE';
56
57         /**
58          * PATCH method
59          *
60          * @link http://tools.ietf.org/html/rfc5789
61          * @var string
62          */
63         const PATCH = 'PATCH';
64
65         /**
66          * Current version of Requests
67          *
68          * @var string
69          */
70         const VERSION = '1.6';
71
72         /**
73          * Registered transport classes
74          *
75          * @var array
76          */
77         protected static $transports = array();
78
79         /**
80          * Selected transport name
81          *
82          * Use {@see get_transport()} instead
83          *
84          * @var array
85          */
86         public static $transport = array();
87
88         /**
89          * This is a static class, do not instantiate it
90          *
91          * @codeCoverageIgnore
92          */
93         private function __construct() {}
94
95         /**
96          * Autoloader for Requests
97          *
98          * Register this with {@see register_autoloader()} if you'd like to avoid
99          * having to create your own.
100          *
101          * (You can also use `spl_autoload_register` directly if you'd prefer.)
102          *
103          * @codeCoverageIgnore
104          *
105          * @param string $class Class name to load
106          */
107         public static function autoloader($class) {
108                 // Check that the class starts with "Requests"
109                 if (strpos($class, 'Requests') !== 0) {
110                         return;
111                 }
112
113                 $file = str_replace('_', '/', $class);
114                 if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
115                         require_once(dirname(__FILE__) . '/' . $file . '.php');
116                 }
117         }
118
119         /**
120          * Register the built-in autoloader
121          *
122          * @codeCoverageIgnore
123          */
124         public static function register_autoloader() {
125                 spl_autoload_register(array('Requests', 'autoloader'));
126         }
127
128         /**
129          * Register a transport
130          *
131          * @param string $transport Transport class to add, must support the Requests_Transport interface
132          */
133         public static function add_transport($transport) {
134                 if (empty(self::$transports)) {
135                         self::$transports = array(
136                                 'Requests_Transport_cURL',
137                                 'Requests_Transport_fsockopen',
138                         );
139                 }
140
141                 self::$transports = array_merge(self::$transports, array($transport));
142         }
143
144         /**
145          * Get a working transport
146          *
147          * @throws Requests_Exception If no valid transport is found (`notransport`)
148          * @return Requests_Transport
149          */
150         protected static function get_transport($capabilities = array()) {
151                 // Caching code, don't bother testing coverage
152                 // @codeCoverageIgnoreStart
153                 // array of capabilities as a string to be used as an array key
154                 ksort($capabilities);
155                 $cap_string = serialize($capabilities);
156
157                 // Don't search for a transport if it's already been done for these $capabilities
158                 if (isset(self::$transport[$cap_string]) && self::$transport[$cap_string] !== null) {
159                         return new self::$transport[$cap_string]();
160                 }
161                 // @codeCoverageIgnoreEnd
162
163                 if (empty(self::$transports)) {
164                         self::$transports = array(
165                                 'Requests_Transport_cURL',
166                                 'Requests_Transport_fsockopen',
167                         );
168                 }
169
170                 // Find us a working transport
171                 foreach (self::$transports as $class) {
172                         if (!class_exists($class))
173                                 continue;
174
175                         $result = call_user_func(array($class, 'test'), $capabilities);
176                         if ($result) {
177                                 self::$transport[$cap_string] = $class;
178                                 break;
179                         }
180                 }
181                 if (self::$transport[$cap_string] === null) {
182                         throw new Requests_Exception('No working transports found', 'notransport', self::$transports);
183                 }
184                 
185                 return new self::$transport[$cap_string]();
186         }
187
188         /**#@+
189          * @see request()
190          * @param string $url
191          * @param array $headers
192          * @param array $options
193          * @return Requests_Response
194          */
195         /**
196          * Send a GET request
197          */
198         public static function get($url, $headers = array(), $options = array()) {
199                 return self::request($url, $headers, null, self::GET, $options);
200         }
201
202         /**
203          * Send a HEAD request
204          */
205         public static function head($url, $headers = array(), $options = array()) {
206                 return self::request($url, $headers, null, self::HEAD, $options);
207         }
208
209         /**
210          * Send a DELETE request
211          */
212         public static function delete($url, $headers = array(), $options = array()) {
213                 return self::request($url, $headers, null, self::DELETE, $options);
214         }
215         /**#@-*/
216
217         /**#@+
218          * @see request()
219          * @param string $url
220          * @param array $headers
221          * @param array $data
222          * @param array $options
223          * @return Requests_Response
224          */
225         /**
226          * Send a POST request
227          */
228         public static function post($url, $headers = array(), $data = array(), $options = array()) {
229                 return self::request($url, $headers, $data, self::POST, $options);
230         }
231         /**
232          * Send a PUT request
233          */
234         public static function put($url, $headers = array(), $data = array(), $options = array()) {
235                 return self::request($url, $headers, $data, self::PUT, $options);
236         }
237
238         /**
239          * Send a PATCH request
240          *
241          * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the
242          * specification recommends that should send an ETag
243          *
244          * @link http://tools.ietf.org/html/rfc5789
245          */
246         public static function patch($url, $headers, $data = array(), $options = array()) {
247                 return self::request($url, $headers, $data, self::PATCH, $options);
248         }
249         /**#@-*/
250
251         /**
252          * Main interface for HTTP requests
253          *
254          * This method initiates a request and sends it via a transport before
255          * parsing.
256          *
257          * The `$options` parameter takes an associative array with the following
258          * options:
259          *
260          * - `timeout`: How long should we wait for a response?
261          *    (float, seconds with a millisecond precision, default: 10, example: 0.01)
262          * - `connect_timeout`: How long should we wait while trying to connect?
263          *    (float, seconds with a millisecond precision, default: 10, example: 0.01)
264          * - `useragent`: Useragent to send to the server
265          *    (string, default: php-requests/$version)
266          * - `follow_redirects`: Should we follow 3xx redirects?
267          *    (boolean, default: true)
268          * - `redirects`: How many times should we redirect before erroring?
269          *    (integer, default: 10)
270          * - `blocking`: Should we block processing on this request?
271          *    (boolean, default: true)
272          * - `filename`: File to stream the body to instead.
273          *    (string|boolean, default: false)
274          * - `auth`: Authentication handler or array of user/password details to use
275          *    for Basic authentication
276          *    (Requests_Auth|array|boolean, default: false)
277          * - `proxy`: Proxy details to use for proxy by-passing and authentication
278          *    (Requests_Proxy|array|boolean, default: false)
279          * - `idn`: Enable IDN parsing
280          *    (boolean, default: true)
281          * - `transport`: Custom transport. Either a class name, or a
282          *    transport object. Defaults to the first working transport from
283          *    {@see getTransport()}
284          *    (string|Requests_Transport, default: {@see getTransport()})
285          * - `hooks`: Hooks handler.
286          *    (Requests_Hooker, default: new Requests_Hooks())
287          * - `verify`: Should we verify SSL certificates? Allows passing in a custom
288          *    certificate file as a string. (Using true uses the system-wide root
289          *    certificate store instead, but this may have different behaviour
290          *    across transports.)
291          *    (string|boolean, default: library/Requests/Transport/cacert.pem)
292          * - `verifyname`: Should we verify the common name in the SSL certificate?
293          *    (boolean: default, true)
294          *
295          * @throws Requests_Exception On invalid URLs (`nonhttp`)
296          *
297          * @param string $url URL to request
298          * @param array $headers Extra headers to send with the request
299          * @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
300          * @param string $type HTTP request type (use Requests constants)
301          * @param array $options Options for the request (see description for more information)
302          * @return Requests_Response
303          */
304         public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) {
305                 if (empty($options['type'])) {
306                         $options['type'] = $type;
307                 }
308                 $options = array_merge(self::get_default_options(), $options);
309
310                 self::set_defaults($url, $headers, $data, $type, $options);
311
312                 $options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options));
313
314                 if (!empty($options['transport'])) {
315                         $transport = $options['transport'];
316
317                         if (is_string($options['transport'])) {
318                                 $transport = new $transport();
319                         }
320                 } else {
321                         $need_ssl = (0 === stripos($url, 'https://'));
322                         $capabilities = array('ssl' => $need_ssl);
323                         $transport = self::get_transport($capabilities);
324                 }
325                 $response = $transport->request($url, $headers, $data, $options);
326
327                 $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
328
329                 return self::parse_response($response, $url, $headers, $data, $options);
330         }
331
332         /**
333          * Send multiple HTTP requests simultaneously
334          *
335          * The `$requests` parameter takes an associative or indexed array of
336          * request fields. The key of each request can be used to match up the
337          * request with the returned data, or with the request passed into your
338          * `multiple.request.complete` callback.
339          *
340          * The request fields value is an associative array with the following keys:
341          *
342          * - `url`: Request URL Same as the `$url` parameter to
343          *    {@see Requests::request}
344          *    (string, required)
345          * - `headers`: Associative array of header fields. Same as the `$headers`
346          *    parameter to {@see Requests::request}
347          *    (array, default: `array()`)
348          * - `data`: Associative array of data fields or a string. Same as the
349          *    `$data` parameter to {@see Requests::request}
350          *    (array|string, default: `array()`)
351          * - `type`: HTTP request type (use Requests constants). Same as the `$type`
352          *    parameter to {@see Requests::request}
353          *    (string, default: `Requests::GET`)
354          * - `cookies`: Associative array of cookie name to value, or cookie jar.
355          *    (array|Requests_Cookie_Jar)
356          *
357          * If the `$options` parameter is specified, individual requests will
358          * inherit options from it. This can be used to use a single hooking system,
359          * or set all the types to `Requests::POST`, for example.
360          *
361          * In addition, the `$options` parameter takes the following global options:
362          *
363          * - `complete`: A callback for when a request is complete. Takes two
364          *    parameters, a Requests_Response/Requests_Exception reference, and the
365          *    ID from the request array (Note: this can also be overridden on a
366          *    per-request basis, although that's a little silly)
367          *    (callback)
368          *
369          * @param array $requests Requests data (see description for more information)
370          * @param array $options Global and default options (see {@see Requests::request})
371          * @return array Responses (either Requests_Response or a Requests_Exception object)
372          */
373         public static function request_multiple($requests, $options = array()) {
374                 $options = array_merge(self::get_default_options(true), $options);
375
376                 if (!empty($options['hooks'])) {
377                         $options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
378                         if (!empty($options['complete'])) {
379                                 $options['hooks']->register('multiple.request.complete', $options['complete']);
380                         }
381                 }
382
383                 foreach ($requests as $id => &$request) {
384                         if (!isset($request['headers'])) {
385                                 $request['headers'] = array();
386                         }
387                         if (!isset($request['data'])) {
388                                 $request['data'] = array();
389                         }
390                         if (!isset($request['type'])) {
391                                 $request['type'] = self::GET;
392                         }
393                         if (!isset($request['options'])) {
394                                 $request['options'] = $options;
395                                 $request['options']['type'] = $request['type'];
396                         }
397                         else {
398                                 if (empty($request['options']['type'])) {
399                                         $request['options']['type'] = $request['type'];
400                                 }
401                                 $request['options'] = array_merge($options, $request['options']);
402                         }
403
404                         self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
405
406                         // Ensure we only hook in once
407                         if ($request['options']['hooks'] !== $options['hooks']) {
408                                 $request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
409                                 if (!empty($request['options']['complete'])) {
410                                         $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
411                                 }
412                         }
413                 }
414                 unset($request);
415
416                 if (!empty($options['transport'])) {
417                         $transport = $options['transport'];
418
419                         if (is_string($options['transport'])) {
420                                 $transport = new $transport();
421                         }
422                 }
423                 else {
424                         $transport = self::get_transport();
425                 }
426                 $responses = $transport->request_multiple($requests, $options);
427
428                 foreach ($responses as $id => &$response) {
429                         // If our hook got messed with somehow, ensure we end up with the
430                         // correct response
431                         if (is_string($response)) {
432                                 $request = $requests[$id];
433                                 self::parse_multiple($response, $request);
434                                 $request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id));
435                         }
436                 }
437
438                 return $responses;
439         }
440
441         /**
442          * Get the default options
443          *
444          * @see Requests::request() for values returned by this method
445          * @param boolean $multirequest Is this a multirequest?
446          * @return array Default option values
447          */
448         protected static function get_default_options($multirequest = false) {
449                 $defaults = array(
450                         'timeout' => 10,
451                         'connect_timeout' => 10,
452                         'useragent' => 'php-requests/' . self::VERSION,
453                         'redirected' => 0,
454                         'redirects' => 10,
455                         'follow_redirects' => true,
456                         'blocking' => true,
457                         'type' => self::GET,
458                         'filename' => false,
459                         'auth' => false,
460                         'proxy' => false,
461                         'cookies' => false,
462                         'idn' => true,
463                         'hooks' => null,
464                         'transport' => null,
465                         'verify' => dirname( __FILE__ ) . '/Requests/Transport/cacert.pem',
466                         'verifyname' => true,
467                 );
468                 if ($multirequest !== false) {
469                         $defaults['complete'] = null;
470                 }
471                 return $defaults;
472         }
473
474         /**
475          * Set the default values
476          *
477          * @param string $url URL to request
478          * @param array $headers Extra headers to send with the request
479          * @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
480          * @param string $type HTTP request type
481          * @param array $options Options for the request
482          * @return array $options
483          */
484         protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
485                 if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
486                         throw new Requests_Exception('Only HTTP requests are handled.', 'nonhttp', $url);
487                 }
488
489                 if (empty($options['hooks'])) {
490                         $options['hooks'] = new Requests_Hooks();
491                 }
492
493                 if (is_array($options['auth'])) {
494                         $options['auth'] = new Requests_Auth_Basic($options['auth']);
495                 }
496                 if ($options['auth'] !== false) {
497                         $options['auth']->register($options['hooks']);
498                 }
499
500                 if (!empty($options['proxy'])) {
501                         $options['proxy'] = new Requests_Proxy_HTTP($options['proxy']);
502                 }
503                 if ($options['proxy'] !== false) {
504                         $options['proxy']->register($options['hooks']);
505                 }
506
507                 if (is_array($options['cookies'])) {
508                         $options['cookies'] = new Requests_Cookie_Jar($options['cookies']);
509                 }
510                 elseif (empty($options['cookies'])) {
511                         $options['cookies'] = new Requests_Cookie_Jar();
512                 }
513                 if ($options['cookies'] !== false) {
514                         $options['cookies']->register($options['hooks']);
515                 }
516
517                 if ($options['idn'] !== false) {
518                         $iri = new Requests_IRI($url);
519                         $iri->host = Requests_IDNAEncoder::encode($iri->ihost);
520                         $url = $iri->uri;
521                 }
522         }
523
524         /**
525          * HTTP response parser
526          *
527          * @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`)
528          * @throws Requests_Exception On missing head/body separator (`noversion`)
529          * @throws Requests_Exception On missing head/body separator (`toomanyredirects`)
530          *
531          * @param string $headers Full response text including headers and body
532          * @param string $url Original request URL
533          * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
534          * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
535          * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
536          * @return Requests_Response
537          */
538         protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
539                 $return = new Requests_Response();
540                 if (!$options['blocking']) {
541                         return $return;
542                 }
543
544                 $return->raw = $headers;
545                 $return->url = $url;
546
547                 if (!$options['filename']) {
548                         if (($pos = strpos($headers, "\r\n\r\n")) === false) {
549                                 // Crap!
550                                 throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator');
551                         }
552
553                         $headers = substr($return->raw, 0, $pos);
554                         $return->body = substr($return->raw, $pos + strlen("\n\r\n\r"));
555                 }
556                 else {
557                         $return->body = '';
558                 }
559                 // Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
560                 $headers = str_replace("\r\n", "\n", $headers);
561                 // Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
562                 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
563                 $headers = explode("\n", $headers);
564                 preg_match('#^HTTP/1\.\d[ \t]+(\d+)#i', array_shift($headers), $matches);
565                 if (empty($matches)) {
566                         throw new Requests_Exception('Response could not be parsed', 'noversion', $headers);
567                 }
568                 $return->status_code = (int) $matches[1];
569                 if ($return->status_code >= 200 && $return->status_code < 300) {
570                         $return->success = true;
571                 }
572
573                 foreach ($headers as $header) {
574                         list($key, $value) = explode(':', $header, 2);
575                         $value = trim($value);
576                         preg_replace('#(\s+)#i', ' ', $value);
577                         $return->headers[$key] = $value;
578                 }
579                 if (isset($return->headers['transfer-encoding'])) {
580                         $return->body = self::decode_chunked($return->body);
581                         unset($return->headers['transfer-encoding']);
582                 }
583                 if (isset($return->headers['content-encoding'])) {
584                         $return->body = self::decompress($return->body);
585                 }
586
587                 //fsockopen and cURL compatibility
588                 if (isset($return->headers['connection'])) {
589                         unset($return->headers['connection']);
590                 }
591
592                 $options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options));
593
594                 if ((in_array($return->status_code, array(300, 301, 302, 303, 307)) || $return->status_code > 307 && $return->status_code < 400) && $options['follow_redirects'] === true) {
595                         if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
596                                 if ($return->status_code === 303) {
597                                         $options['type'] = Requests::GET;
598                                 }
599                                 $options['redirected']++;
600                                 $location = $return->headers['location'];
601                                 if (strpos ($location, 'http://') !== 0 && strpos ($location, 'https://') !== 0) {
602                                         // relative redirect, for compatibility make it absolute
603                                         $location = Requests_IRI::absolutize($url, $location);
604                                         $location = $location->uri;
605                                 }
606                                 $redirected = self::request($location, $req_headers, $req_data, false, $options);
607                                 $redirected->history[] = $return;
608                                 return $redirected;
609                         }
610                         elseif ($options['redirected'] >= $options['redirects']) {
611                                 throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return);
612                         }
613                 }
614
615                 $return->redirects = $options['redirected'];
616
617                 $options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options));
618                 return $return;
619         }
620
621         /**
622          * Callback for `transport.internal.parse_response`
623          *
624          * Internal use only. Converts a raw HTTP response to a Requests_Response
625          * while still executing a multiple request.
626          *
627          * @param string $headers Full response text including headers and body
628          * @param array $request Request data as passed into {@see Requests::request_multiple()}
629          * @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object
630          */
631         public static function parse_multiple(&$response, $request) {
632                 try {
633                         $response = self::parse_response($response, $request['url'], $request['headers'], $request['data'], $request['options']);
634                 }
635                 catch (Requests_Exception $e) {
636                         $response = $e;
637                 }
638         }
639
640         /**
641          * Decoded a chunked body as per RFC 2616
642          *
643          * @see http://tools.ietf.org/html/rfc2616#section-3.6.1
644          * @param string $data Chunked body
645          * @return string Decoded body
646          */
647         protected static function decode_chunked($data) {
648                 if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($data))) {
649                         return $data;
650                 }
651
652                 $decoded = '';
653                 $encoded = $data;
654
655                 while (true) {
656                         $is_chunked = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches );
657                         if (!$is_chunked) {
658                                 // Looks like it's not chunked after all
659                                 return $data;
660                         }
661
662                         $length = hexdec(trim($matches[1]));
663                         if ($length === 0) {
664                                 // Ignore trailer headers
665                                 return $decoded;
666                         }
667
668                         $chunk_length = strlen($matches[0]);
669                         $decoded .= $part = substr($encoded, $chunk_length, $length);
670                         $encoded = substr($encoded, $chunk_length + $length + 2);
671
672                         if (trim($encoded) === '0' || empty($encoded)) {
673                                 return $decoded;
674                         }
675                 }
676
677                 // We'll never actually get down here
678                 // @codeCoverageIgnoreStart
679         }
680         // @codeCoverageIgnoreEnd
681
682         /**
683          * Convert a key => value array to a 'key: value' array for headers
684          *
685          * @param array $array Dictionary of header values
686          * @return array List of headers
687          */
688         public static function flatten($array) {
689                 $return = array();
690                 foreach ($array as $key => $value) {
691                         $return[] = "$key: $value";
692                 }
693                 return $return;
694         }
695
696         /**
697          * Convert a key => value array to a 'key: value' array for headers
698          *
699          * @deprecated Misspelling of {@see Requests::flatten}
700          * @param array $array Dictionary of header values
701          * @return array List of headers
702          */
703         public static function flattern($array) {
704                 return self::flatten($array);
705         }
706
707         /**
708          * Decompress an encoded body
709          *
710          * Implements gzip, compress and deflate. Guesses which it is by attempting
711          * to decode.
712          *
713          * @todo Make this smarter by defaulting to whatever the headers say first
714          * @param string $data Compressed data in one of the above formats
715          * @return string Decompressed string
716          */
717         public static function decompress($data) {
718                 if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") {
719                         // Not actually compressed. Probably cURL ruining this for us.
720                         return $data;
721                 }
722
723                 if (function_exists('gzdecode') && ($decoded = @gzdecode($data)) !== false) {
724                         return $decoded;
725                 }
726                 elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) {
727                         return $decoded;
728                 }
729                 elseif (($decoded = self::compatible_gzinflate($data)) !== false) {
730                         return $decoded;
731                 }
732                 elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) {
733                         return $decoded;
734                 }
735
736                 return $data;
737         }
738
739         /**
740          * Decompression of deflated string while staying compatible with the majority of servers.
741          *
742          * Certain Servers will return deflated data with headers which PHP's gzinflate()
743          * function cannot handle out of the box. The following function has been created from
744          * various snippets on the gzinflate() PHP documentation.
745          *
746          * Warning: Magic numbers within. Due to the potential different formats that the compressed
747          * data may be returned in, some "magic offsets" are needed to ensure proper decompression
748          * takes place. For a simple progmatic way to determine the magic offset in use, see:
749          * http://core.trac.wordpress.org/ticket/18273
750          *
751          * @since 2.8.1
752          * @link http://core.trac.wordpress.org/ticket/18273
753          * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
754          * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
755          *
756          * @param string $gzData String to decompress.
757          * @return string|bool False on failure.
758          */
759         public static function compatible_gzinflate($gzData) {
760                 // Compressed data might contain a full zlib header, if so strip it for
761                 // gzinflate()
762                 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
763                         $i = 10;
764                         $flg = ord( substr($gzData, 3, 1) );
765                         if ( $flg > 0 ) {
766                                 if ( $flg & 4 ) {
767                                         list($xlen) = unpack('v', substr($gzData, $i, 2) );
768                                         $i = $i + 2 + $xlen;
769                                 }
770                                 if ( $flg & 8 )
771                                         $i = strpos($gzData, "\0", $i) + 1;
772                                 if ( $flg & 16 )
773                                         $i = strpos($gzData, "\0", $i) + 1;
774                                 if ( $flg & 2 )
775                                         $i = $i + 2;
776                         }
777                         $decompressed = self::compatible_gzinflate( substr( $gzData, $i ) );
778                         if ( false !== $decompressed ) {
779                                 return $decompressed;
780                         }
781                 }
782
783                 // If the data is Huffman Encoded, we must first strip the leading 2
784                 // byte Huffman marker for gzinflate()
785                 // The response is Huffman coded by many compressors such as
786                 // java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's
787                 // System.IO.Compression.DeflateStream.
788                 //
789                 // See http://decompres.blogspot.com/ for a quick explanation of this
790                 // data type
791                 $huffman_encoded = false;
792
793                 // low nibble of first byte should be 0x08
794                 list( , $first_nibble )    = unpack( 'h', $gzData );
795
796                 // First 2 bytes should be divisible by 0x1F
797                 list( , $first_two_bytes ) = unpack( 'n', $gzData );
798
799                 if ( 0x08 == $first_nibble && 0 == ( $first_two_bytes % 0x1F ) )
800                         $huffman_encoded = true;
801
802                 if ( $huffman_encoded ) {
803                         if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 2 ) ) ) )
804                                 return $decompressed;
805                 }
806
807                 if ( "\x50\x4b\x03\x04" == substr( $gzData, 0, 4 ) ) {
808                         // ZIP file format header
809                         // Offset 6: 2 bytes, General-purpose field
810                         // Offset 26: 2 bytes, filename length
811                         // Offset 28: 2 bytes, optional field length
812                         // Offset 30: Filename field, followed by optional field, followed
813                         // immediately by data
814                         list( , $general_purpose_flag ) = unpack( 'v', substr( $gzData, 6, 2 ) );
815
816                         // If the file has been compressed on the fly, 0x08 bit is set of
817                         // the general purpose field. We can use this to differentiate
818                         // between a compressed document, and a ZIP file
819                         $zip_compressed_on_the_fly = ( 0x08 == (0x08 & $general_purpose_flag ) );
820
821                         if ( ! $zip_compressed_on_the_fly ) {
822                                 // Don't attempt to decode a compressed zip file
823                                 return $gzData;
824                         }
825
826                         // Determine the first byte of data, based on the above ZIP header
827                         // offsets:
828                         $first_file_start = array_sum( unpack( 'v2', substr( $gzData, 26, 4 ) ) );
829                         if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 30 + $first_file_start ) ) ) ) {
830                                 return $decompressed;
831                         }
832                         return false;
833                 }
834
835                 // Finally fall back to straight gzinflate
836                 if ( false !== ( $decompressed = @gzinflate( $gzData ) ) ) {
837                         return $decompressed;
838                 }
839
840                 // Fallback for all above failing, not expected, but included for
841                 // debugging and preventing regressions and to track stats
842                 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 2 ) ) ) ) {
843                         return $decompressed;
844                 }
845
846                 return false;
847         }
848
849         public static function match_domain($host, $reference) {
850                 // Check for a direct match
851                 if ($host === $reference) {
852                         return true;
853                 }
854
855                 // Calculate the valid wildcard match if the host is not an IP address
856                 // Also validates that the host has 3 parts or more, as per Firefox's
857                 // ruleset.
858                 $parts = explode('.', $host);
859                 if (ip2long($host) === false && count($parts) >= 3) {
860                         $parts[0] = '*';
861                         $wildcard = implode('.', $parts);
862                         if ($wildcard === $reference) {
863                                 return true;
864                         }
865                 }
866
867                 return false;
868         }
869 }