--- /dev/null
+<?php\r
+/**\r
+ * Class representing a HTTP response\r
+ *\r
+ * PHP version 5\r
+ *\r
+ * LICENSE:\r
+ *\r
+ * Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ *\r
+ * * Redistributions of source code must retain the above copyright\r
+ * notice, this list of conditions and the following disclaimer.\r
+ * * Redistributions in binary form must reproduce the above copyright\r
+ * notice, this list of conditions and the following disclaimer in the\r
+ * documentation and/or other materials provided with the distribution.\r
+ * * The names of the authors may not be used to endorse or promote products\r
+ * derived from this software without specific prior written permission.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\r
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+ *\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License\r
+ * @version CVS: $Id: Response.php 287948 2009-09-01 17:12:18Z avb $\r
+ * @link http://pear.php.net/package/HTTP_Request2\r
+ */\r
+\r
+/**\r
+ * Exception class for HTTP_Request2 package\r
+ */ \r
+require_once 'HTTP/Request2/Exception.php';\r
+\r
+/**\r
+ * Class representing a HTTP response\r
+ *\r
+ * The class is designed to be used in "streaming" scenario, building the\r
+ * response as it is being received:\r
+ * <code>\r
+ * $statusLine = read_status_line();\r
+ * $response = new HTTP_Request2_Response($statusLine);\r
+ * do {\r
+ * $headerLine = read_header_line();\r
+ * $response->parseHeaderLine($headerLine);\r
+ * } while ($headerLine != '');\r
+ * \r
+ * while ($chunk = read_body()) {\r
+ * $response->appendBody($chunk);\r
+ * }\r
+ * \r
+ * var_dump($response->getHeader(), $response->getCookies(), $response->getBody());\r
+ * </code>\r
+ *\r
+ *\r
+ * @category HTTP\r
+ * @package HTTP_Request2\r
+ * @author Alexey Borzov <avb@php.net>\r
+ * @version Release: 0.4.1\r
+ * @link http://tools.ietf.org/html/rfc2616#section-6\r
+ */\r
+class HTTP_Request2_Response\r
+{\r
+ /**\r
+ * HTTP protocol version (e.g. 1.0, 1.1)\r
+ * @var string\r
+ */\r
+ protected $version;\r
+\r
+ /**\r
+ * Status code\r
+ * @var integer\r
+ * @link http://tools.ietf.org/html/rfc2616#section-6.1.1\r
+ */\r
+ protected $code;\r
+\r
+ /**\r
+ * Reason phrase\r
+ * @var string\r
+ * @link http://tools.ietf.org/html/rfc2616#section-6.1.1\r
+ */\r
+ protected $reasonPhrase;\r
+\r
+ /**\r
+ * Associative array of response headers\r
+ * @var array\r
+ */\r
+ protected $headers = array();\r
+\r
+ /**\r
+ * Cookies set in the response\r
+ * @var array\r
+ */\r
+ protected $cookies = array();\r
+\r
+ /**\r
+ * Name of last header processed by parseHederLine()\r
+ *\r
+ * Used to handle the headers that span multiple lines\r
+ *\r
+ * @var string\r
+ */\r
+ protected $lastHeader = null;\r
+\r
+ /**\r
+ * Response body\r
+ * @var string\r
+ */\r
+ protected $body = '';\r
+\r
+ /**\r
+ * Whether the body is still encoded by Content-Encoding\r
+ *\r
+ * cURL provides the decoded body to the callback; if we are reading from\r
+ * socket the body is still gzipped / deflated\r
+ *\r
+ * @var bool\r
+ */\r
+ protected $bodyEncoded;\r
+\r
+ /**\r
+ * Associative array of HTTP status code / reason phrase.\r
+ *\r
+ * @var array\r
+ * @link http://tools.ietf.org/html/rfc2616#section-10\r
+ */\r
+ protected static $phrases = array(\r
+\r
+ // 1xx: Informational - Request received, continuing process\r
+ 100 => 'Continue',\r
+ 101 => 'Switching Protocols',\r
+\r
+ // 2xx: Success - The action was successfully received, understood and\r
+ // accepted\r
+ 200 => 'OK',\r
+ 201 => 'Created',\r
+ 202 => 'Accepted',\r
+ 203 => 'Non-Authoritative Information',\r
+ 204 => 'No Content',\r
+ 205 => 'Reset Content',\r
+ 206 => 'Partial Content',\r
+\r
+ // 3xx: Redirection - Further action must be taken in order to complete\r
+ // the request\r
+ 300 => 'Multiple Choices',\r
+ 301 => 'Moved Permanently',\r
+ 302 => 'Found', // 1.1\r
+ 303 => 'See Other',\r
+ 304 => 'Not Modified',\r
+ 305 => 'Use Proxy',\r
+ 307 => 'Temporary Redirect',\r
+\r
+ // 4xx: Client Error - The request contains bad syntax or cannot be \r
+ // fulfilled\r
+ 400 => 'Bad Request',\r
+ 401 => 'Unauthorized',\r
+ 402 => 'Payment Required',\r
+ 403 => 'Forbidden',\r
+ 404 => 'Not Found',\r
+ 405 => 'Method Not Allowed',\r
+ 406 => 'Not Acceptable',\r
+ 407 => 'Proxy Authentication Required',\r
+ 408 => 'Request Timeout',\r
+ 409 => 'Conflict',\r
+ 410 => 'Gone',\r
+ 411 => 'Length Required',\r
+ 412 => 'Precondition Failed',\r
+ 413 => 'Request Entity Too Large',\r
+ 414 => 'Request-URI Too Long',\r
+ 415 => 'Unsupported Media Type',\r
+ 416 => 'Requested Range Not Satisfiable',\r
+ 417 => 'Expectation Failed',\r
+\r
+ // 5xx: Server Error - The server failed to fulfill an apparently\r
+ // valid request\r
+ 500 => 'Internal Server Error',\r
+ 501 => 'Not Implemented',\r
+ 502 => 'Bad Gateway',\r
+ 503 => 'Service Unavailable',\r
+ 504 => 'Gateway Timeout',\r
+ 505 => 'HTTP Version Not Supported',\r
+ 509 => 'Bandwidth Limit Exceeded',\r
+\r
+ );\r
+\r
+ /**\r
+ * Constructor, parses the response status line\r
+ *\r
+ * @param string Response status line (e.g. "HTTP/1.1 200 OK")\r
+ * @param bool Whether body is still encoded by Content-Encoding\r
+ * @throws HTTP_Request2_Exception if status line is invalid according to spec\r
+ */\r
+ public function __construct($statusLine, $bodyEncoded = true)\r
+ {\r
+ if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {\r
+ throw new HTTP_Request2_Exception("Malformed response: {$statusLine}");\r
+ }\r
+ $this->version = $m[1];\r
+ $this->code = intval($m[2]);\r
+ if (!empty($m[3])) {\r
+ $this->reasonPhrase = trim($m[3]);\r
+ } elseif (!empty(self::$phrases[$this->code])) {\r
+ $this->reasonPhrase = self::$phrases[$this->code];\r
+ }\r
+ $this->bodyEncoded = (bool)$bodyEncoded;\r
+ }\r
+\r
+ /**\r
+ * Parses the line from HTTP response filling $headers array\r
+ *\r
+ * The method should be called after reading the line from socket or receiving \r
+ * it into cURL callback. Passing an empty string here indicates the end of\r
+ * response headers and triggers additional processing, so be sure to pass an\r
+ * empty string in the end.\r
+ *\r
+ * @param string Line from HTTP response\r
+ */\r
+ public function parseHeaderLine($headerLine)\r
+ {\r
+ $headerLine = trim($headerLine, "\r\n");\r
+\r
+ // empty string signals the end of headers, process the received ones\r
+ if ('' == $headerLine) {\r
+ if (!empty($this->headers['set-cookie'])) {\r
+ $cookies = is_array($this->headers['set-cookie'])?\r
+ $this->headers['set-cookie']:\r
+ array($this->headers['set-cookie']);\r
+ foreach ($cookies as $cookieString) {\r
+ $this->parseCookie($cookieString);\r
+ }\r
+ unset($this->headers['set-cookie']);\r
+ }\r
+ foreach (array_keys($this->headers) as $k) {\r
+ if (is_array($this->headers[$k])) {\r
+ $this->headers[$k] = implode(', ', $this->headers[$k]);\r
+ }\r
+ }\r
+\r
+ // string of the form header-name: header value\r
+ } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {\r
+ $name = strtolower($m[1]);\r
+ $value = trim($m[2]);\r
+ if (empty($this->headers[$name])) {\r
+ $this->headers[$name] = $value;\r
+ } else {\r
+ if (!is_array($this->headers[$name])) {\r
+ $this->headers[$name] = array($this->headers[$name]);\r
+ }\r
+ $this->headers[$name][] = $value;\r
+ }\r
+ $this->lastHeader = $name;\r
+\r
+ // string \r
+ } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {\r
+ if (!is_array($this->headers[$this->lastHeader])) {\r
+ $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);\r
+ } else {\r
+ $key = count($this->headers[$this->lastHeader]) - 1;\r
+ $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);\r
+ }\r
+ }\r
+ } \r
+\r
+ /**\r
+ * Parses a Set-Cookie header to fill $cookies array\r
+ *\r
+ * @param string value of Set-Cookie header\r
+ * @link http://cgi.netscape.com/newsref/std/cookie_spec.html\r
+ */\r
+ protected function parseCookie($cookieString)\r
+ {\r
+ $cookie = array(\r
+ 'expires' => null,\r
+ 'domain' => null,\r
+ 'path' => null,\r
+ 'secure' => false\r
+ );\r
+\r
+ // Only a name=value pair\r
+ if (!strpos($cookieString, ';')) {\r
+ $pos = strpos($cookieString, '=');\r
+ $cookie['name'] = trim(substr($cookieString, 0, $pos));\r
+ $cookie['value'] = trim(substr($cookieString, $pos + 1));\r
+\r
+ // Some optional parameters are supplied\r
+ } else {\r
+ $elements = explode(';', $cookieString);\r
+ $pos = strpos($elements[0], '=');\r
+ $cookie['name'] = trim(substr($elements[0], 0, $pos));\r
+ $cookie['value'] = trim(substr($elements[0], $pos + 1));\r
+\r
+ for ($i = 1; $i < count($elements); $i++) {\r
+ if (false === strpos($elements[$i], '=')) {\r
+ $elName = trim($elements[$i]);\r
+ $elValue = null;\r
+ } else {\r
+ list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));\r
+ }\r
+ $elName = strtolower($elName);\r
+ if ('secure' == $elName) {\r
+ $cookie['secure'] = true;\r
+ } elseif ('expires' == $elName) {\r
+ $cookie['expires'] = str_replace('"', '', $elValue);\r
+ } elseif ('path' == $elName || 'domain' == $elName) {\r
+ $cookie[$elName] = urldecode($elValue);\r
+ } else {\r
+ $cookie[$elName] = $elValue;\r
+ }\r
+ }\r
+ }\r
+ $this->cookies[] = $cookie;\r
+ }\r
+\r
+ /**\r
+ * Appends a string to the response body\r
+ * @param string\r
+ */\r
+ public function appendBody($bodyChunk)\r
+ {\r
+ $this->body .= $bodyChunk;\r
+ }\r
+\r
+ /**\r
+ * Returns the status code\r
+ * @return integer \r
+ */\r
+ public function getStatus()\r
+ {\r
+ return $this->code;\r
+ }\r
+\r
+ /**\r
+ * Returns the reason phrase\r
+ * @return string\r
+ */\r
+ public function getReasonPhrase()\r
+ {\r
+ return $this->reasonPhrase;\r
+ }\r
+\r
+ /**\r
+ * Returns either the named header or all response headers\r
+ *\r
+ * @param string Name of header to return\r
+ * @return string|array Value of $headerName header (null if header is\r
+ * not present), array of all response headers if\r
+ * $headerName is null\r
+ */\r
+ public function getHeader($headerName = null)\r
+ {\r
+ if (null === $headerName) {\r
+ return $this->headers;\r
+ } else {\r
+ $headerName = strtolower($headerName);\r
+ return isset($this->headers[$headerName])? $this->headers[$headerName]: null;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Returns cookies set in response\r
+ *\r
+ * @return array\r
+ */\r
+ public function getCookies()\r
+ {\r
+ return $this->cookies;\r
+ }\r
+\r
+ /**\r
+ * Returns the body of the response\r
+ *\r
+ * @return string\r
+ * @throws HTTP_Request2_Exception if body cannot be decoded\r
+ */\r
+ public function getBody()\r
+ {\r
+ if (!$this->bodyEncoded ||\r
+ !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))\r
+ ) {\r
+ return $this->body;\r
+\r
+ } else {\r
+ if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {\r
+ $oldEncoding = mb_internal_encoding();\r
+ mb_internal_encoding('iso-8859-1');\r
+ }\r
+\r
+ try {\r
+ switch (strtolower($this->getHeader('content-encoding'))) {\r
+ case 'gzip':\r
+ $decoded = self::decodeGzip($this->body);\r
+ break;\r
+ case 'deflate':\r
+ $decoded = self::decodeDeflate($this->body);\r
+ }\r
+ } catch (Exception $e) {\r
+ }\r
+\r
+ if (!empty($oldEncoding)) {\r
+ mb_internal_encoding($oldEncoding);\r
+ }\r
+ if (!empty($e)) {\r
+ throw $e;\r
+ }\r
+ return $decoded;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Get the HTTP version of the response\r
+ *\r
+ * @return string\r
+ */ \r
+ public function getVersion()\r
+ {\r
+ return $this->version;\r
+ }\r
+\r
+ /**\r
+ * Decodes the message-body encoded by gzip\r
+ *\r
+ * The real decoding work is done by gzinflate() built-in function, this\r
+ * method only parses the header and checks data for compliance with\r
+ * RFC 1952\r
+ *\r
+ * @param string gzip-encoded data\r
+ * @return string decoded data\r
+ * @throws HTTP_Request2_Exception\r
+ * @link http://tools.ietf.org/html/rfc1952\r
+ */\r
+ public static function decodeGzip($data)\r
+ {\r
+ $length = strlen($data);\r
+ // If it doesn't look like gzip-encoded data, don't bother\r
+ if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {\r
+ return $data;\r
+ }\r
+ if (!function_exists('gzinflate')) {\r
+ throw new HTTP_Request2_Exception('Unable to decode body: gzip extension not available');\r
+ }\r
+ $method = ord(substr($data, 2, 1));\r
+ if (8 != $method) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: unknown compression method');\r
+ }\r
+ $flags = ord(substr($data, 3, 1));\r
+ if ($flags & 224) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: reserved bits are set');\r
+ }\r
+\r
+ // header is 10 bytes minimum. may be longer, though.\r
+ $headerLength = 10;\r
+ // extra fields, need to skip 'em\r
+ if ($flags & 4) {\r
+ if ($length - $headerLength - 2 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $extraLength = unpack('v', substr($data, 10, 2));\r
+ if ($length - $headerLength - 2 - $extraLength[1] < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $headerLength += $extraLength[1] + 2;\r
+ }\r
+ // file name, need to skip that\r
+ if ($flags & 8) {\r
+ if ($length - $headerLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $filenameLength = strpos(substr($data, $headerLength), chr(0));\r
+ if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $headerLength += $filenameLength + 1;\r
+ }\r
+ // comment, need to skip that also\r
+ if ($flags & 16) {\r
+ if ($length - $headerLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $commentLength = strpos(substr($data, $headerLength), chr(0));\r
+ if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $headerLength += $commentLength + 1;\r
+ }\r
+ // have a CRC for header. let's check\r
+ if ($flags & 2) {\r
+ if ($length - $headerLength - 2 < 8) {\r
+ throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');\r
+ }\r
+ $crcReal = 0xffff & crc32(substr($data, 0, $headerLength));\r
+ $crcStored = unpack('v', substr($data, $headerLength, 2));\r
+ if ($crcReal != $crcStored[1]) {\r
+ throw new HTTP_Request2_Exception('Header CRC check failed');\r
+ }\r
+ $headerLength += 2;\r
+ }\r
+ // unpacked data CRC and size at the end of encoded data\r
+ $tmp = unpack('V2', substr($data, -8));\r
+ $dataCrc = $tmp[1];\r
+ $dataSize = $tmp[2];\r
+\r
+ // finally, call the gzinflate() function\r
+ // don't pass $dataSize to gzinflate, see bugs #13135, #14370\r
+ $unpacked = gzinflate(substr($data, $headerLength, -8));\r
+ if (false === $unpacked) {\r
+ throw new HTTP_Request2_Exception('gzinflate() call failed');\r
+ } elseif ($dataSize != strlen($unpacked)) {\r
+ throw new HTTP_Request2_Exception('Data size check failed');\r
+ } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {\r
+ throw new HTTP_Request2_Exception('Data CRC check failed');\r
+ }\r
+ return $unpacked;\r
+ }\r
+\r
+ /**\r
+ * Decodes the message-body encoded by deflate\r
+ *\r
+ * @param string deflate-encoded data\r
+ * @return string decoded data\r
+ * @throws HTTP_Request2_Exception\r
+ */\r
+ public static function decodeDeflate($data)\r
+ {\r
+ if (!function_exists('gzuncompress')) {\r
+ throw new HTTP_Request2_Exception('Unable to decode body: gzip extension not available');\r
+ }\r
+ // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,\r
+ // while many applications send raw deflate stream from RFC 1951.\r
+ // We should check for presence of zlib header and use gzuncompress() or\r
+ // gzinflate() as needed. See bug #15305\r
+ $header = unpack('n', substr($data, 0, 2));\r
+ return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);\r
+ }\r
+}\r
+?>
\ No newline at end of file