HttpResponse.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. /**
  3. * HTTP Response from HttpSocket.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, 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)
  18. */
  19. /**
  20. * HTTP Response
  21. *
  22. * @package Cake.Network.Http
  23. */
  24. class HttpResponse implements ArrayAccess {
  25. /**
  26. * Body content
  27. *
  28. * @var string
  29. */
  30. public $body = '';
  31. /**
  32. * Headers
  33. *
  34. * @var array
  35. */
  36. public $headers = array();
  37. /**
  38. * Cookies
  39. *
  40. * @var array
  41. */
  42. public $cookies = array();
  43. /**
  44. * HTTP version
  45. *
  46. * @var string
  47. */
  48. public $httpVersion = 'HTTP/1.1';
  49. /**
  50. * Response code
  51. *
  52. * @var integer
  53. */
  54. public $code = 0;
  55. /**
  56. * Reason phrase
  57. *
  58. * @var string
  59. */
  60. public $reasonPhrase = '';
  61. /**
  62. * Pure raw content
  63. *
  64. * @var string
  65. */
  66. public $raw = '';
  67. /**
  68. * Contructor
  69. *
  70. * @param string $message
  71. */
  72. public function __construct($message = null) {
  73. if ($message !== null) {
  74. $this->parseResponse($message);
  75. }
  76. }
  77. /**
  78. * Body content
  79. *
  80. * @return string
  81. */
  82. public function body() {
  83. return (string)$this->body;
  84. }
  85. /**
  86. * Get header in case insensitive
  87. *
  88. * @param string $name Header name
  89. * @param array $headers
  90. * @return mixed String if header exists or null
  91. */
  92. public function getHeader($name, $headers = null) {
  93. if (!is_array($headers)) {
  94. $headers =& $this->headers;
  95. }
  96. if (isset($headers[$name])) {
  97. return $headers[$name];
  98. }
  99. foreach ($headers as $key => $value) {
  100. if (strcasecmp($key, $name) == 0) {
  101. return $value;
  102. }
  103. }
  104. return null;
  105. }
  106. /**
  107. * If return is 200 (OK)
  108. *
  109. * @return boolean
  110. */
  111. public function isOk() {
  112. return $this->code == 200;
  113. }
  114. /**
  115. * If return is a valid 3xx (Redirection)
  116. *
  117. * @return boolean
  118. */
  119. public function isRedirect() {
  120. return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location'));
  121. }
  122. /**
  123. * Parses the given message and breaks it down in parts.
  124. *
  125. * @param string $message Message to parse
  126. * @return void
  127. * @throws SocketException
  128. */
  129. public function parseResponse($message) {
  130. if (!is_string($message)) {
  131. throw new SocketException(__d('cake_dev', 'Invalid response.'));
  132. }
  133. if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
  134. throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
  135. }
  136. list(, $statusLine, $header) = $match;
  137. $this->raw = $message;
  138. $this->body = (string)substr($message, strlen($match[0]));
  139. if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
  140. $this->httpVersion = $match[1];
  141. $this->code = $match[2];
  142. $this->reasonPhrase = $match[3];
  143. }
  144. $this->headers = $this->_parseHeader($header);
  145. $transferEncoding = $this->getHeader('Transfer-Encoding');
  146. $decoded = $this->_decodeBody($this->body, $transferEncoding);
  147. $this->body = $decoded['body'];
  148. if (!empty($decoded['header'])) {
  149. $this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
  150. }
  151. if (!empty($this->headers)) {
  152. $this->cookies = $this->parseCookies($this->headers);
  153. }
  154. }
  155. /**
  156. * Generic function to decode a $body with a given $encoding. Returns either an array with the keys
  157. * 'body' and 'header' or false on failure.
  158. *
  159. * @param string $body A string continaing the body to decode.
  160. * @param mixed $encoding Can be false in case no encoding is being used, or a string representing the encoding.
  161. * @return mixed Array of response headers and body or false.
  162. */
  163. protected function _decodeBody($body, $encoding = 'chunked') {
  164. if (!is_string($body)) {
  165. return false;
  166. }
  167. if (empty($encoding)) {
  168. return array('body' => $body, 'header' => false);
  169. }
  170. $decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
  171. if (!is_callable(array(&$this, $decodeMethod))) {
  172. return array('body' => $body, 'header' => false);
  173. }
  174. return $this->{$decodeMethod}($body);
  175. }
  176. /**
  177. * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
  178. * a result.
  179. *
  180. * @param string $body A string continaing the chunked body to decode.
  181. * @return mixed Array of response headers and body or false.
  182. * @throws SocketException
  183. */
  184. protected function _decodeChunkedBody($body) {
  185. if (!is_string($body)) {
  186. return false;
  187. }
  188. $decodedBody = null;
  189. $chunkLength = null;
  190. while ($chunkLength !== 0) {
  191. if (!preg_match("/^([0-9a-f]+) *(?:;(.+)=(.+))?\r\n/iU", $body, $match)) {
  192. throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
  193. }
  194. $chunkSize = 0;
  195. $hexLength = 0;
  196. $chunkExtensionName = '';
  197. $chunkExtensionValue = '';
  198. if (isset($match[0])) {
  199. $chunkSize = $match[0];
  200. }
  201. if (isset($match[1])) {
  202. $hexLength = $match[1];
  203. }
  204. if (isset($match[2])) {
  205. $chunkExtensionName = $match[2];
  206. }
  207. if (isset($match[3])) {
  208. $chunkExtensionValue = $match[3];
  209. }
  210. $body = substr($body, strlen($chunkSize));
  211. $chunkLength = hexdec($hexLength);
  212. $chunk = substr($body, 0, $chunkLength);
  213. if (!empty($chunkExtensionName)) {
  214. /**
  215. * @todo See if there are popular chunk extensions we should implement
  216. */
  217. }
  218. $decodedBody .= $chunk;
  219. if ($chunkLength !== 0) {
  220. $body = substr($body, $chunkLength + strlen("\r\n"));
  221. }
  222. }
  223. $entityHeader = false;
  224. if (!empty($body)) {
  225. $entityHeader = $this->_parseHeader($body);
  226. }
  227. return array('body' => $decodedBody, 'header' => $entityHeader);
  228. }
  229. /**
  230. * Parses an array based header.
  231. *
  232. * @param array $header Header as an indexed array (field => value)
  233. * @return array Parsed header
  234. */
  235. protected function _parseHeader($header) {
  236. if (is_array($header)) {
  237. return $header;
  238. } elseif (!is_string($header)) {
  239. return false;
  240. }
  241. preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
  242. $header = array();
  243. foreach ($matches as $match) {
  244. list(, $field, $value) = $match;
  245. $value = trim($value);
  246. $value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
  247. $field = $this->_unescapeToken($field);
  248. if (!isset($header[$field])) {
  249. $header[$field] = $value;
  250. } else {
  251. $header[$field] = array_merge((array)$header[$field], (array)$value);
  252. }
  253. }
  254. return $header;
  255. }
  256. /**
  257. * Parses cookies in response headers.
  258. *
  259. * @param array $header Header array containing one ore more 'Set-Cookie' headers.
  260. * @return mixed Either false on no cookies, or an array of cookies recieved.
  261. * @todo Make this 100% RFC 2965 confirm
  262. */
  263. public function parseCookies($header) {
  264. $cookieHeader = $this->getHeader('Set-Cookie', $header);
  265. if (!$cookieHeader) {
  266. return false;
  267. }
  268. $cookies = array();
  269. foreach ((array)$cookieHeader as $cookie) {
  270. if (strpos($cookie, '";"') !== false) {
  271. $cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
  272. $parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
  273. } else {
  274. $parts = preg_split('/\;[ \t]*/', $cookie);
  275. }
  276. list($name, $value) = explode('=', array_shift($parts), 2);
  277. $cookies[$name] = compact('value');
  278. foreach ($parts as $part) {
  279. if (strpos($part, '=') !== false) {
  280. list($key, $value) = explode('=', $part);
  281. } else {
  282. $key = $part;
  283. $value = true;
  284. }
  285. $key = strtolower($key);
  286. if (!isset($cookies[$name][$key])) {
  287. $cookies[$name][$key] = $value;
  288. }
  289. }
  290. }
  291. return $cookies;
  292. }
  293. /**
  294. * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  295. *
  296. * @param string $token Token to unescape
  297. * @param array $chars
  298. * @return string Unescaped token
  299. * @todo Test $chars parameter
  300. */
  301. protected function _unescapeToken($token, $chars = null) {
  302. $regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
  303. $token = preg_replace($regex, '\\1', $token);
  304. return $token;
  305. }
  306. /**
  307. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  308. *
  309. * @param boolean $hex true to get them as HEX values, false otherwise
  310. * @param array $chars
  311. * @return array Escape chars
  312. * @todo Test $chars parameter
  313. */
  314. protected function _tokenEscapeChars($hex = true, $chars = null) {
  315. if (!empty($chars)) {
  316. $escape = $chars;
  317. } else {
  318. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  319. for ($i = 0; $i <= 31; $i++) {
  320. $escape[] = chr($i);
  321. }
  322. $escape[] = chr(127);
  323. }
  324. if ($hex == false) {
  325. return $escape;
  326. }
  327. foreach ($escape as $key => $char) {
  328. $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  329. }
  330. return $escape;
  331. }
  332. /**
  333. * ArrayAccess - Offset Exists
  334. *
  335. * @param mixed $offset
  336. * @return boolean
  337. */
  338. public function offsetExists($offset) {
  339. return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
  340. }
  341. /**
  342. * ArrayAccess - Offset Get
  343. *
  344. * @param mixed $offset
  345. * @return mixed
  346. */
  347. public function offsetGet($offset) {
  348. switch ($offset) {
  349. case 'raw':
  350. $firstLineLength = strpos($this->raw, "\r\n") + 2;
  351. if ($this->raw[$firstLineLength] === "\r") {
  352. $header = null;
  353. } else {
  354. $header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
  355. }
  356. return array(
  357. 'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
  358. 'header' => $header,
  359. 'body' => $this->body,
  360. 'response' => $this->raw
  361. );
  362. case 'status':
  363. return array(
  364. 'http-version' => $this->httpVersion,
  365. 'code' => $this->code,
  366. 'reason-phrase' => $this->reasonPhrase
  367. );
  368. case 'header':
  369. return $this->headers;
  370. case 'body':
  371. return $this->body;
  372. case 'cookies':
  373. return $this->cookies;
  374. }
  375. return null;
  376. }
  377. /**
  378. * ArrayAccess - 0ffset Set
  379. *
  380. * @param mixed $offset
  381. * @param mixed $value
  382. * @return void
  383. */
  384. public function offsetSet($offset, $value) {
  385. return;
  386. }
  387. /**
  388. * ArrayAccess - Offset Unset
  389. *
  390. * @param mixed $offset
  391. * @return void
  392. */
  393. public function offsetUnset($offset) {
  394. return;
  395. }
  396. /**
  397. * Instance as string
  398. *
  399. * @return string
  400. */
  401. public function __toString() {
  402. return $this->body();
  403. }
  404. }