]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request2/Response.php
96682d795ba81f3006b83bdf8bbcebe36ebd13ee
[quix0rs-gnu-social.git] / extlib / HTTP / Request2 / Response.php
1 <?php\r
2 /**\r
3  * Class representing a HTTP response\r
4  *\r
5  * PHP version 5\r
6  *\r
7  * LICENSE:\r
8  *\r
9  * Copyright (c) 2008-2012, Alexey Borzov <avb@php.net>\r
10  * All rights reserved.\r
11  *\r
12  * Redistribution and use in source and binary forms, with or without\r
13  * modification, are permitted provided that the following conditions\r
14  * are met:\r
15  *\r
16  *     * Redistributions of source code must retain the above copyright\r
17  *      notice, this list of conditions and the following disclaimer.\r
18  *     * Redistributions in binary form must reproduce the above copyright\r
19  *      notice, this list of conditions and the following disclaimer in the\r
20  *      documentation and/or other materials provided with the distribution.\r
21  *     * The names of the authors may not be used to endorse or promote products\r
22  *      derived from this software without specific prior written permission.\r
23  *\r
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\r
25  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r
26  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
27  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r
28  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
30  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r
31  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
32  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
33  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
34  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
35  *\r
36  * @category HTTP\r
37  * @package  HTTP_Request2\r
38  * @author   Alexey Borzov <avb@php.net>\r
39  * @license  http://opensource.org/licenses/bsd-license.php New BSD License\r
40  * @version  SVN: $Id: Response.php 324936 2012-04-07 07:49:03Z avb $\r
41  * @link     http://pear.php.net/package/HTTP_Request2\r
42  */\r
43 \r
44 /**\r
45  * Exception class for HTTP_Request2 package\r
46  */\r
47 require_once 'HTTP/Request2/Exception.php';\r
48 \r
49 /**\r
50  * Class representing a HTTP response\r
51  *\r
52  * The class is designed to be used in "streaming" scenario, building the\r
53  * response as it is being received:\r
54  * <code>\r
55  * $statusLine = read_status_line();\r
56  * $response = new HTTP_Request2_Response($statusLine);\r
57  * do {\r
58  *     $headerLine = read_header_line();\r
59  *     $response->parseHeaderLine($headerLine);\r
60  * } while ($headerLine != '');\r
61  *\r
62  * while ($chunk = read_body()) {\r
63  *     $response->appendBody($chunk);\r
64  * }\r
65  *\r
66  * var_dump($response->getHeader(), $response->getCookies(), $response->getBody());\r
67  * </code>\r
68  *\r
69  * @category HTTP\r
70  * @package  HTTP_Request2\r
71  * @author   Alexey Borzov <avb@php.net>\r
72  * @license  http://opensource.org/licenses/bsd-license.php New BSD License\r
73  * @version  Release: 2.1.1\r
74  * @link     http://pear.php.net/package/HTTP_Request2\r
75  * @link     http://tools.ietf.org/html/rfc2616#section-6\r
76  */\r
77 class HTTP_Request2_Response\r
78 {\r
79     /**\r
80      * HTTP protocol version (e.g. 1.0, 1.1)\r
81      * @var  string\r
82      */\r
83     protected $version;\r
84 \r
85     /**\r
86      * Status code\r
87      * @var  integer\r
88      * @link http://tools.ietf.org/html/rfc2616#section-6.1.1\r
89      */\r
90     protected $code;\r
91 \r
92     /**\r
93      * Reason phrase\r
94      * @var  string\r
95      * @link http://tools.ietf.org/html/rfc2616#section-6.1.1\r
96      */\r
97     protected $reasonPhrase;\r
98 \r
99     /**\r
100      * Effective URL (may be different from original request URL in case of redirects)\r
101      * @var  string\r
102      */\r
103     protected $effectiveUrl;\r
104 \r
105     /**\r
106      * Associative array of response headers\r
107      * @var  array\r
108      */\r
109     protected $headers = array();\r
110 \r
111     /**\r
112      * Cookies set in the response\r
113      * @var  array\r
114      */\r
115     protected $cookies = array();\r
116 \r
117     /**\r
118      * Name of last header processed by parseHederLine()\r
119      *\r
120      * Used to handle the headers that span multiple lines\r
121      *\r
122      * @var  string\r
123      */\r
124     protected $lastHeader = null;\r
125 \r
126     /**\r
127      * Response body\r
128      * @var  string\r
129      */\r
130     protected $body = '';\r
131 \r
132     /**\r
133      * Whether the body is still encoded by Content-Encoding\r
134      *\r
135      * cURL provides the decoded body to the callback; if we are reading from\r
136      * socket the body is still gzipped / deflated\r
137      *\r
138      * @var  bool\r
139      */\r
140     protected $bodyEncoded;\r
141 \r
142     /**\r
143      * Associative array of HTTP status code / reason phrase.\r
144      *\r
145      * @var  array\r
146      * @link http://tools.ietf.org/html/rfc2616#section-10\r
147      */\r
148     protected static $phrases = array(\r
149 \r
150         // 1xx: Informational - Request received, continuing process\r
151         100 => 'Continue',\r
152         101 => 'Switching Protocols',\r
153 \r
154         // 2xx: Success - The action was successfully received, understood and\r
155         // accepted\r
156         200 => 'OK',\r
157         201 => 'Created',\r
158         202 => 'Accepted',\r
159         203 => 'Non-Authoritative Information',\r
160         204 => 'No Content',\r
161         205 => 'Reset Content',\r
162         206 => 'Partial Content',\r
163 \r
164         // 3xx: Redirection - Further action must be taken in order to complete\r
165         // the request\r
166         300 => 'Multiple Choices',\r
167         301 => 'Moved Permanently',\r
168         302 => 'Found',  // 1.1\r
169         303 => 'See Other',\r
170         304 => 'Not Modified',\r
171         305 => 'Use Proxy',\r
172         307 => 'Temporary Redirect',\r
173 \r
174         // 4xx: Client Error - The request contains bad syntax or cannot be\r
175         // fulfilled\r
176         400 => 'Bad Request',\r
177         401 => 'Unauthorized',\r
178         402 => 'Payment Required',\r
179         403 => 'Forbidden',\r
180         404 => 'Not Found',\r
181         405 => 'Method Not Allowed',\r
182         406 => 'Not Acceptable',\r
183         407 => 'Proxy Authentication Required',\r
184         408 => 'Request Timeout',\r
185         409 => 'Conflict',\r
186         410 => 'Gone',\r
187         411 => 'Length Required',\r
188         412 => 'Precondition Failed',\r
189         413 => 'Request Entity Too Large',\r
190         414 => 'Request-URI Too Long',\r
191         415 => 'Unsupported Media Type',\r
192         416 => 'Requested Range Not Satisfiable',\r
193         417 => 'Expectation Failed',\r
194 \r
195         // 5xx: Server Error - The server failed to fulfill an apparently\r
196         // valid request\r
197         500 => 'Internal Server Error',\r
198         501 => 'Not Implemented',\r
199         502 => 'Bad Gateway',\r
200         503 => 'Service Unavailable',\r
201         504 => 'Gateway Timeout',\r
202         505 => 'HTTP Version Not Supported',\r
203         509 => 'Bandwidth Limit Exceeded',\r
204 \r
205     );\r
206 \r
207     /**\r
208      * Returns the default reason phrase for the given code or all reason phrases\r
209      *\r
210      * @param int $code Response code\r
211      *\r
212      * @return string|array|null Default reason phrase for $code if $code is given\r
213      *                           (null if no phrase is available), array of all\r
214      *                           reason phrases if $code is null\r
215      * @link   http://pear.php.net/bugs/18716\r
216      */\r
217     public static function getDefaultReasonPhrase($code = null)\r
218     {\r
219         if (null === $code) {\r
220             return self::$phrases;\r
221         } else {\r
222             return isset(self::$phrases[$code]) ? self::$phrases[$code] : null;\r
223         }\r
224     }\r
225 \r
226     /**\r
227      * Constructor, parses the response status line\r
228      *\r
229      * @param string $statusLine   Response status line (e.g. "HTTP/1.1 200 OK")\r
230      * @param bool   $bodyEncoded  Whether body is still encoded by Content-Encoding\r
231      * @param string $effectiveUrl Effective URL of the response\r
232      *\r
233      * @throws   HTTP_Request2_MessageException if status line is invalid according to spec\r
234      */\r
235     public function __construct($statusLine, $bodyEncoded = true, $effectiveUrl = null)\r
236     {\r
237         if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {\r
238             throw new HTTP_Request2_MessageException(\r
239                 "Malformed response: {$statusLine}",\r
240                 HTTP_Request2_Exception::MALFORMED_RESPONSE\r
241             );\r
242         }\r
243         $this->version      = $m[1];\r
244         $this->code         = intval($m[2]);\r
245         $this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);\r
246         $this->bodyEncoded  = (bool)$bodyEncoded;\r
247         $this->effectiveUrl = (string)$effectiveUrl;\r
248     }\r
249 \r
250     /**\r
251      * Parses the line from HTTP response filling $headers array\r
252      *\r
253      * The method should be called after reading the line from socket or receiving\r
254      * it into cURL callback. Passing an empty string here indicates the end of\r
255      * response headers and triggers additional processing, so be sure to pass an\r
256      * empty string in the end.\r
257      *\r
258      * @param string $headerLine Line from HTTP response\r
259      */\r
260     public function parseHeaderLine($headerLine)\r
261     {\r
262         $headerLine = trim($headerLine, "\r\n");\r
263 \r
264         if ('' == $headerLine) {\r
265             // empty string signals the end of headers, process the received ones\r
266             if (!empty($this->headers['set-cookie'])) {\r
267                 $cookies = is_array($this->headers['set-cookie'])?\r
268                            $this->headers['set-cookie']:\r
269                            array($this->headers['set-cookie']);\r
270                 foreach ($cookies as $cookieString) {\r
271                     $this->parseCookie($cookieString);\r
272                 }\r
273                 unset($this->headers['set-cookie']);\r
274             }\r
275             foreach (array_keys($this->headers) as $k) {\r
276                 if (is_array($this->headers[$k])) {\r
277                     $this->headers[$k] = implode(', ', $this->headers[$k]);\r
278                 }\r
279             }\r
280 \r
281         } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {\r
282             // string of the form header-name: header value\r
283             $name  = strtolower($m[1]);\r
284             $value = trim($m[2]);\r
285             if (empty($this->headers[$name])) {\r
286                 $this->headers[$name] = $value;\r
287             } else {\r
288                 if (!is_array($this->headers[$name])) {\r
289                     $this->headers[$name] = array($this->headers[$name]);\r
290                 }\r
291                 $this->headers[$name][] = $value;\r
292             }\r
293             $this->lastHeader = $name;\r
294 \r
295         } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {\r
296             // continuation of a previous header\r
297             if (!is_array($this->headers[$this->lastHeader])) {\r
298                 $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);\r
299             } else {\r
300                 $key = count($this->headers[$this->lastHeader]) - 1;\r
301                 $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);\r
302             }\r
303         }\r
304     }\r
305 \r
306     /**\r
307      * Parses a Set-Cookie header to fill $cookies array\r
308      *\r
309      * @param string $cookieString value of Set-Cookie header\r
310      *\r
311      * @link     http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html\r
312      */\r
313     protected function parseCookie($cookieString)\r
314     {\r
315         $cookie = array(\r
316             'expires' => null,\r
317             'domain'  => null,\r
318             'path'    => null,\r
319             'secure'  => false\r
320         );\r
321 \r
322         if (!strpos($cookieString, ';')) {\r
323             // Only a name=value pair\r
324             $pos = strpos($cookieString, '=');\r
325             $cookie['name']  = trim(substr($cookieString, 0, $pos));\r
326             $cookie['value'] = trim(substr($cookieString, $pos + 1));\r
327 \r
328         } else {\r
329             // Some optional parameters are supplied\r
330             $elements = explode(';', $cookieString);\r
331             $pos = strpos($elements[0], '=');\r
332             $cookie['name']  = trim(substr($elements[0], 0, $pos));\r
333             $cookie['value'] = trim(substr($elements[0], $pos + 1));\r
334 \r
335             for ($i = 1; $i < count($elements); $i++) {\r
336                 if (false === strpos($elements[$i], '=')) {\r
337                     $elName  = trim($elements[$i]);\r
338                     $elValue = null;\r
339                 } else {\r
340                     list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));\r
341                 }\r
342                 $elName = strtolower($elName);\r
343                 if ('secure' == $elName) {\r
344                     $cookie['secure'] = true;\r
345                 } elseif ('expires' == $elName) {\r
346                     $cookie['expires'] = str_replace('"', '', $elValue);\r
347                 } elseif ('path' == $elName || 'domain' == $elName) {\r
348                     $cookie[$elName] = urldecode($elValue);\r
349                 } else {\r
350                     $cookie[$elName] = $elValue;\r
351                 }\r
352             }\r
353         }\r
354         $this->cookies[] = $cookie;\r
355     }\r
356 \r
357     /**\r
358      * Appends a string to the response body\r
359      *\r
360      * @param string $bodyChunk part of response body\r
361      */\r
362     public function appendBody($bodyChunk)\r
363     {\r
364         $this->body .= $bodyChunk;\r
365     }\r
366 \r
367     /**\r
368      * Returns the effective URL of the response\r
369      *\r
370      * This may be different from the request URL if redirects were followed.\r
371      *\r
372      * @return string\r
373      * @link   http://pear.php.net/bugs/bug.php?id=18412\r
374      */\r
375     public function getEffectiveUrl()\r
376     {\r
377         return $this->effectiveUrl;\r
378     }\r
379 \r
380     /**\r
381      * Returns the status code\r
382      *\r
383      * @return   integer\r
384      */\r
385     public function getStatus()\r
386     {\r
387         return $this->code;\r
388     }\r
389 \r
390     /**\r
391      * Returns the reason phrase\r
392      *\r
393      * @return   string\r
394      */\r
395     public function getReasonPhrase()\r
396     {\r
397         return $this->reasonPhrase;\r
398     }\r
399 \r
400     /**\r
401      * Whether response is a redirect that can be automatically handled by HTTP_Request2\r
402      *\r
403      * @return   bool\r
404      */\r
405     public function isRedirect()\r
406     {\r
407         return in_array($this->code, array(300, 301, 302, 303, 307))\r
408                && isset($this->headers['location']);\r
409     }\r
410 \r
411     /**\r
412      * Returns either the named header or all response headers\r
413      *\r
414      * @param string $headerName Name of header to return\r
415      *\r
416      * @return   string|array    Value of $headerName header (null if header is\r
417      *                           not present), array of all response headers if\r
418      *                           $headerName is null\r
419      */\r
420     public function getHeader($headerName = null)\r
421     {\r
422         if (null === $headerName) {\r
423             return $this->headers;\r
424         } else {\r
425             $headerName = strtolower($headerName);\r
426             return isset($this->headers[$headerName])? $this->headers[$headerName]: null;\r
427         }\r
428     }\r
429 \r
430     /**\r
431      * Returns cookies set in response\r
432      *\r
433      * @return   array\r
434      */\r
435     public function getCookies()\r
436     {\r
437         return $this->cookies;\r
438     }\r
439 \r
440     /**\r
441      * Returns the body of the response\r
442      *\r
443      * @return   string\r
444      * @throws   HTTP_Request2_Exception if body cannot be decoded\r
445      */\r
446     public function getBody()\r
447     {\r
448         if (0 == strlen($this->body) || !$this->bodyEncoded\r
449             || !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))\r
450         ) {\r
451             return $this->body;\r
452 \r
453         } else {\r
454             if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {\r
455                 $oldEncoding = mb_internal_encoding();\r
456                 mb_internal_encoding('8bit');\r
457             }\r
458 \r
459             try {\r
460                 switch (strtolower($this->getHeader('content-encoding'))) {\r
461                 case 'gzip':\r
462                     $decoded = self::decodeGzip($this->body);\r
463                     break;\r
464                 case 'deflate':\r
465                     $decoded = self::decodeDeflate($this->body);\r
466                 }\r
467             } catch (Exception $e) {\r
468             }\r
469 \r
470             if (!empty($oldEncoding)) {\r
471                 mb_internal_encoding($oldEncoding);\r
472             }\r
473             if (!empty($e)) {\r
474                 throw $e;\r
475             }\r
476             return $decoded;\r
477         }\r
478     }\r
479 \r
480     /**\r
481      * Get the HTTP version of the response\r
482      *\r
483      * @return   string\r
484      */\r
485     public function getVersion()\r
486     {\r
487         return $this->version;\r
488     }\r
489 \r
490     /**\r
491      * Decodes the message-body encoded by gzip\r
492      *\r
493      * The real decoding work is done by gzinflate() built-in function, this\r
494      * method only parses the header and checks data for compliance with\r
495      * RFC 1952\r
496      *\r
497      * @param string $data gzip-encoded data\r
498      *\r
499      * @return   string  decoded data\r
500      * @throws   HTTP_Request2_LogicException\r
501      * @throws   HTTP_Request2_MessageException\r
502      * @link     http://tools.ietf.org/html/rfc1952\r
503      */\r
504     public static function decodeGzip($data)\r
505     {\r
506         $length = strlen($data);\r
507         // If it doesn't look like gzip-encoded data, don't bother\r
508         if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {\r
509             return $data;\r
510         }\r
511         if (!function_exists('gzinflate')) {\r
512             throw new HTTP_Request2_LogicException(\r
513                 'Unable to decode body: gzip extension not available',\r
514                 HTTP_Request2_Exception::MISCONFIGURATION\r
515             );\r
516         }\r
517         $method = ord(substr($data, 2, 1));\r
518         if (8 != $method) {\r
519             throw new HTTP_Request2_MessageException(\r
520                 'Error parsing gzip header: unknown compression method',\r
521                 HTTP_Request2_Exception::DECODE_ERROR\r
522             );\r
523         }\r
524         $flags = ord(substr($data, 3, 1));\r
525         if ($flags & 224) {\r
526             throw new HTTP_Request2_MessageException(\r
527                 'Error parsing gzip header: reserved bits are set',\r
528                 HTTP_Request2_Exception::DECODE_ERROR\r
529             );\r
530         }\r
531 \r
532         // header is 10 bytes minimum. may be longer, though.\r
533         $headerLength = 10;\r
534         // extra fields, need to skip 'em\r
535         if ($flags & 4) {\r
536             if ($length - $headerLength - 2 < 8) {\r
537                 throw new HTTP_Request2_MessageException(\r
538                     'Error parsing gzip header: data too short',\r
539                     HTTP_Request2_Exception::DECODE_ERROR\r
540                 );\r
541             }\r
542             $extraLength = unpack('v', substr($data, 10, 2));\r
543             if ($length - $headerLength - 2 - $extraLength[1] < 8) {\r
544                 throw new HTTP_Request2_MessageException(\r
545                     'Error parsing gzip header: data too short',\r
546                     HTTP_Request2_Exception::DECODE_ERROR\r
547                 );\r
548             }\r
549             $headerLength += $extraLength[1] + 2;\r
550         }\r
551         // file name, need to skip that\r
552         if ($flags & 8) {\r
553             if ($length - $headerLength - 1 < 8) {\r
554                 throw new HTTP_Request2_MessageException(\r
555                     'Error parsing gzip header: data too short',\r
556                     HTTP_Request2_Exception::DECODE_ERROR\r
557                 );\r
558             }\r
559             $filenameLength = strpos(substr($data, $headerLength), chr(0));\r
560             if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {\r
561                 throw new HTTP_Request2_MessageException(\r
562                     'Error parsing gzip header: data too short',\r
563                     HTTP_Request2_Exception::DECODE_ERROR\r
564                 );\r
565             }\r
566             $headerLength += $filenameLength + 1;\r
567         }\r
568         // comment, need to skip that also\r
569         if ($flags & 16) {\r
570             if ($length - $headerLength - 1 < 8) {\r
571                 throw new HTTP_Request2_MessageException(\r
572                     'Error parsing gzip header: data too short',\r
573                     HTTP_Request2_Exception::DECODE_ERROR\r
574                 );\r
575             }\r
576             $commentLength = strpos(substr($data, $headerLength), chr(0));\r
577             if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {\r
578                 throw new HTTP_Request2_MessageException(\r
579                     'Error parsing gzip header: data too short',\r
580                     HTTP_Request2_Exception::DECODE_ERROR\r
581                 );\r
582             }\r
583             $headerLength += $commentLength + 1;\r
584         }\r
585         // have a CRC for header. let's check\r
586         if ($flags & 2) {\r
587             if ($length - $headerLength - 2 < 8) {\r
588                 throw new HTTP_Request2_MessageException(\r
589                     'Error parsing gzip header: data too short',\r
590                     HTTP_Request2_Exception::DECODE_ERROR\r
591                 );\r
592             }\r
593             $crcReal   = 0xffff & crc32(substr($data, 0, $headerLength));\r
594             $crcStored = unpack('v', substr($data, $headerLength, 2));\r
595             if ($crcReal != $crcStored[1]) {\r
596                 throw new HTTP_Request2_MessageException(\r
597                     'Header CRC check failed',\r
598                     HTTP_Request2_Exception::DECODE_ERROR\r
599                 );\r
600             }\r
601             $headerLength += 2;\r
602         }\r
603         // unpacked data CRC and size at the end of encoded data\r
604         $tmp = unpack('V2', substr($data, -8));\r
605         $dataCrc  = $tmp[1];\r
606         $dataSize = $tmp[2];\r
607 \r
608         // finally, call the gzinflate() function\r
609         // don't pass $dataSize to gzinflate, see bugs #13135, #14370\r
610         $unpacked = gzinflate(substr($data, $headerLength, -8));\r
611         if (false === $unpacked) {\r
612             throw new HTTP_Request2_MessageException(\r
613                 'gzinflate() call failed',\r
614                 HTTP_Request2_Exception::DECODE_ERROR\r
615             );\r
616         } elseif ($dataSize != strlen($unpacked)) {\r
617             throw new HTTP_Request2_MessageException(\r
618                 'Data size check failed',\r
619                 HTTP_Request2_Exception::DECODE_ERROR\r
620             );\r
621         } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {\r
622             throw new HTTP_Request2_Exception(\r
623                 'Data CRC check failed',\r
624                 HTTP_Request2_Exception::DECODE_ERROR\r
625             );\r
626         }\r
627         return $unpacked;\r
628     }\r
629 \r
630     /**\r
631      * Decodes the message-body encoded by deflate\r
632      *\r
633      * @param string $data deflate-encoded data\r
634      *\r
635      * @return   string  decoded data\r
636      * @throws   HTTP_Request2_LogicException\r
637      */\r
638     public static function decodeDeflate($data)\r
639     {\r
640         if (!function_exists('gzuncompress')) {\r
641             throw new HTTP_Request2_LogicException(\r
642                 'Unable to decode body: gzip extension not available',\r
643                 HTTP_Request2_Exception::MISCONFIGURATION\r
644             );\r
645         }\r
646         // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,\r
647         // while many applications send raw deflate stream from RFC 1951.\r
648         // We should check for presence of zlib header and use gzuncompress() or\r
649         // gzinflate() as needed. See bug #15305\r
650         $header = unpack('n', substr($data, 0, 2));\r
651         return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);\r
652     }\r
653 }\r
654 ?>