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