3
* HTTP Response from HttpSocket.
7
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
10
* Licensed under The MIT License
11
* Redistributions of files must retain the above copyright notice.
13
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
14
* @link http://cakephp.org CakePHP(tm) Project
15
* @package Cake.Network.Http
16
* @since CakePHP(tm) v 2.0.0
17
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
21
* HTTP Response from HttpSocket.
23
* @package Cake.Network.Http
25
class HttpResponse implements ArrayAccess {
39
public $headers = array();
46
public $cookies = array();
53
public $httpVersion = 'HTTP/1.1';
67
public $reasonPhrase = '';
79
* @param string $message
81
public function __construct($message = null) {
82
if ($message !== null) {
83
$this->parseResponse($message);
92
public function body() {
93
return (string)$this->body;
97
* Get header in case insensitive
99
* @param string $name Header name
100
* @param array $headers
101
* @return mixed String if header exists or null
103
public function getHeader($name, $headers = null) {
104
if (!is_array($headers)) {
105
$headers =& $this->headers;
107
if (isset($headers[$name])) {
108
return $headers[$name];
110
foreach ($headers as $key => $value) {
111
if (strcasecmp($key, $name) == 0) {
119
* If return is 200 (OK)
123
public function isOk() {
124
return $this->code == 200;
128
* If return is a valid 3xx (Redirection)
132
public function isRedirect() {
133
return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location'));
137
* Parses the given message and breaks it down in parts.
139
* @param string $message Message to parse
141
* @throws SocketException
143
public function parseResponse($message) {
144
if (!is_string($message)) {
145
throw new SocketException(__d('cake_dev', 'Invalid response.'));
148
if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
149
throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
152
list(, $statusLine, $header) = $match;
153
$this->raw = $message;
154
$this->body = (string)substr($message, strlen($match[0]));
156
if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
157
$this->httpVersion = $match[1];
158
$this->code = $match[2];
159
$this->reasonPhrase = $match[3];
162
$this->headers = $this->_parseHeader($header);
163
$transferEncoding = $this->getHeader('Transfer-Encoding');
164
$decoded = $this->_decodeBody($this->body, $transferEncoding);
165
$this->body = $decoded['body'];
167
if (!empty($decoded['header'])) {
168
$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
171
if (!empty($this->headers)) {
172
$this->cookies = $this->parseCookies($this->headers);
177
* Generic function to decode a $body with a given $encoding. Returns either an array with the keys
178
* 'body' and 'header' or false on failure.
180
* @param string $body A string containing the body to decode.
181
* @param string|boolean $encoding Can be false in case no encoding is being used, or a string representing the encoding.
182
* @return mixed Array of response headers and body or false.
184
protected function _decodeBody($body, $encoding = 'chunked') {
185
if (!is_string($body)) {
188
if (empty($encoding)) {
189
return array('body' => $body, 'header' => false);
191
$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
193
if (!is_callable(array(&$this, $decodeMethod))) {
194
return array('body' => $body, 'header' => false);
196
return $this->{$decodeMethod}($body);
200
* Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
203
* @param string $body A string containing the chunked body to decode.
204
* @return mixed Array of response headers and body or false.
205
* @throws SocketException
207
protected function _decodeChunkedBody($body) {
208
if (!is_string($body)) {
215
while ($chunkLength !== 0) {
216
if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
217
throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
222
$chunkExtensionName = '';
223
$chunkExtensionValue = '';
224
if (isset($match[0])) {
225
$chunkSize = $match[0];
227
if (isset($match[1])) {
228
$hexLength = $match[1];
230
if (isset($match[2])) {
231
$chunkExtensionName = $match[2];
233
if (isset($match[3])) {
234
$chunkExtensionValue = $match[3];
237
$body = substr($body, strlen($chunkSize));
238
$chunkLength = hexdec($hexLength);
239
$chunk = substr($body, 0, $chunkLength);
240
if (!empty($chunkExtensionName)) {
241
// @todo See if there are popular chunk extensions we should implement
243
$decodedBody .= $chunk;
244
if ($chunkLength !== 0) {
245
$body = substr($body, $chunkLength + strlen("\r\n"));
249
$entityHeader = false;
251
$entityHeader = $this->_parseHeader($body);
253
return array('body' => $decodedBody, 'header' => $entityHeader);
257
* Parses an array based header.
259
* @param array $header Header as an indexed array (field => value)
260
* @return array Parsed header
262
protected function _parseHeader($header) {
263
if (is_array($header)) {
265
} elseif (!is_string($header)) {
269
preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
272
foreach ($matches as $match) {
273
list(, $field, $value) = $match;
275
$value = trim($value);
276
$value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
278
$field = $this->_unescapeToken($field);
280
if (!isset($header[$field])) {
281
$header[$field] = $value;
283
$header[$field] = array_merge((array)$header[$field], (array)$value);
290
* Parses cookies in response headers.
292
* @param array $header Header array containing one ore more 'Set-Cookie' headers.
293
* @return mixed Either false on no cookies, or an array of cookies received.
294
* @todo Make this 100% RFC 2965 confirm
296
public function parseCookies($header) {
297
$cookieHeader = $this->getHeader('Set-Cookie', $header);
298
if (!$cookieHeader) {
303
foreach ((array)$cookieHeader as $cookie) {
304
if (strpos($cookie, '";"') !== false) {
305
$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
306
$parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
308
$parts = preg_split('/\;[ \t]*/', $cookie);
311
list($name, $value) = explode('=', array_shift($parts), 2);
312
$cookies[$name] = compact('value');
314
foreach ($parts as $part) {
315
if (strpos($part, '=') !== false) {
316
list($key, $value) = explode('=', $part);
322
$key = strtolower($key);
323
if (!isset($cookies[$name][$key])) {
324
$cookies[$name][$key] = $value;
332
* Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
334
* @param string $token Token to unescape
335
* @param array $chars
336
* @return string Unescaped token
337
* @todo Test $chars parameter
339
protected function _unescapeToken($token, $chars = null) {
340
$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
341
$token = preg_replace($regex, '\\1', $token);
346
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
348
* @param boolean $hex true to get them as HEX values, false otherwise
349
* @param array $chars
350
* @return array Escape chars
351
* @todo Test $chars parameter
353
protected function _tokenEscapeChars($hex = true, $chars = null) {
354
if (!empty($chars)) {
357
$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
358
for ($i = 0; $i <= 31; $i++) {
361
$escape[] = chr(127);
367
foreach ($escape as $key => $char) {
368
$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
374
* ArrayAccess - Offset Exists
376
* @param string $offset
379
public function offsetExists($offset) {
380
return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
384
* ArrayAccess - Offset Get
386
* @param string $offset
389
public function offsetGet($offset) {
392
$firstLineLength = strpos($this->raw, "\r\n") + 2;
393
if ($this->raw[$firstLineLength] === "\r") {
396
$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
399
'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
401
'body' => $this->body,
402
'response' => $this->raw
406
'http-version' => $this->httpVersion,
407
'code' => $this->code,
408
'reason-phrase' => $this->reasonPhrase
411
return $this->headers;
415
return $this->cookies;
421
* ArrayAccess - Offset Set
423
* @param string $offset
424
* @param mixed $value
427
public function offsetSet($offset, $value) {
431
* ArrayAccess - Offset Unset
433
* @param string $offset
436
public function offsetUnset($offset) {
444
public function __toString() {
445
return $this->body();