PageRenderTime 44ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Network/Http/HttpResponse.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 443 lines | 232 code | 47 blank | 164 comment | 41 complexity | 78caa5f8453f923c09801f0de126601b MD5 | raw file
  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 from HttpSocket.
  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. * Constructor
  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. * Parses the given message and breaks it down in parts.
  116. *
  117. * @param string $message Message to parse
  118. * @return void
  119. * @throws SocketException
  120. */
  121. public function parseResponse($message) {
  122. if (!is_string($message)) {
  123. throw new SocketException(__d('cake_dev', 'Invalid response.'));
  124. }
  125. if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
  126. throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
  127. }
  128. list(, $statusLine, $header) = $match;
  129. $this->raw = $message;
  130. $this->body = (string)substr($message, strlen($match[0]));
  131. if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
  132. $this->httpVersion = $match[1];
  133. $this->code = $match[2];
  134. $this->reasonPhrase = $match[3];
  135. }
  136. $this->headers = $this->_parseHeader($header);
  137. $transferEncoding = $this->getHeader('Transfer-Encoding');
  138. $decoded = $this->_decodeBody($this->body, $transferEncoding);
  139. $this->body = $decoded['body'];
  140. if (!empty($decoded['header'])) {
  141. $this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
  142. }
  143. if (!empty($this->headers)) {
  144. $this->cookies = $this->parseCookies($this->headers);
  145. }
  146. }
  147. /**
  148. * Generic function to decode a $body with a given $encoding. Returns either an array with the keys
  149. * 'body' and 'header' or false on failure.
  150. *
  151. * @param string $body A string containing the body to decode.
  152. * @param mixed $encoding Can be false in case no encoding is being used, or a string representing the encoding.
  153. * @return mixed Array of response headers and body or false.
  154. */
  155. protected function _decodeBody($body, $encoding = 'chunked') {
  156. if (!is_string($body)) {
  157. return false;
  158. }
  159. if (empty($encoding)) {
  160. return array('body' => $body, 'header' => false);
  161. }
  162. $decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
  163. if (!is_callable(array(&$this, $decodeMethod))) {
  164. return array('body' => $body, 'header' => false);
  165. }
  166. return $this->{$decodeMethod}($body);
  167. }
  168. /**
  169. * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
  170. * a result.
  171. *
  172. * @param string $body A string containing the chunked body to decode.
  173. * @return mixed Array of response headers and body or false.
  174. * @throws SocketException
  175. */
  176. protected function _decodeChunkedBody($body) {
  177. if (!is_string($body)) {
  178. return false;
  179. }
  180. $decodedBody = null;
  181. $chunkLength = null;
  182. while ($chunkLength !== 0) {
  183. if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
  184. throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
  185. }
  186. $chunkSize = 0;
  187. $hexLength = 0;
  188. $chunkExtensionName = '';
  189. $chunkExtensionValue = '';
  190. if (isset($match[0])) {
  191. $chunkSize = $match[0];
  192. }
  193. if (isset($match[1])) {
  194. $hexLength = $match[1];
  195. }
  196. if (isset($match[2])) {
  197. $chunkExtensionName = $match[2];
  198. }
  199. if (isset($match[3])) {
  200. $chunkExtensionValue = $match[3];
  201. }
  202. $body = substr($body, strlen($chunkSize));
  203. $chunkLength = hexdec($hexLength);
  204. $chunk = substr($body, 0, $chunkLength);
  205. if (!empty($chunkExtensionName)) {
  206. /**
  207. * @todo See if there are popular chunk extensions we should implement
  208. */
  209. }
  210. $decodedBody .= $chunk;
  211. if ($chunkLength !== 0) {
  212. $body = substr($body, $chunkLength + strlen("\r\n"));
  213. }
  214. }
  215. $entityHeader = false;
  216. if (!empty($body)) {
  217. $entityHeader = $this->_parseHeader($body);
  218. }
  219. return array('body' => $decodedBody, 'header' => $entityHeader);
  220. }
  221. /**
  222. * Parses an array based header.
  223. *
  224. * @param array $header Header as an indexed array (field => value)
  225. * @return array Parsed header
  226. */
  227. protected function _parseHeader($header) {
  228. if (is_array($header)) {
  229. return $header;
  230. } elseif (!is_string($header)) {
  231. return false;
  232. }
  233. preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
  234. $header = array();
  235. foreach ($matches as $match) {
  236. list(, $field, $value) = $match;
  237. $value = trim($value);
  238. $value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
  239. $field = $this->_unescapeToken($field);
  240. if (!isset($header[$field])) {
  241. $header[$field] = $value;
  242. } else {
  243. $header[$field] = array_merge((array)$header[$field], (array)$value);
  244. }
  245. }
  246. return $header;
  247. }
  248. /**
  249. * Parses cookies in response headers.
  250. *
  251. * @param array $header Header array containing one ore more 'Set-Cookie' headers.
  252. * @return mixed Either false on no cookies, or an array of cookies received.
  253. * @todo Make this 100% RFC 2965 confirm
  254. */
  255. public function parseCookies($header) {
  256. $cookieHeader = $this->getHeader('Set-Cookie', $header);
  257. if (!$cookieHeader) {
  258. return false;
  259. }
  260. $cookies = array();
  261. foreach ((array)$cookieHeader as $cookie) {
  262. if (strpos($cookie, '";"') !== false) {
  263. $cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
  264. $parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
  265. } else {
  266. $parts = preg_split('/\;[ \t]*/', $cookie);
  267. }
  268. list($name, $value) = explode('=', array_shift($parts), 2);
  269. $cookies[$name] = compact('value');
  270. foreach ($parts as $part) {
  271. if (strpos($part, '=') !== false) {
  272. list($key, $value) = explode('=', $part);
  273. } else {
  274. $key = $part;
  275. $value = true;
  276. }
  277. $key = strtolower($key);
  278. if (!isset($cookies[$name][$key])) {
  279. $cookies[$name][$key] = $value;
  280. }
  281. }
  282. }
  283. return $cookies;
  284. }
  285. /**
  286. * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  287. *
  288. * @param string $token Token to unescape
  289. * @param array $chars
  290. * @return string Unescaped token
  291. * @todo Test $chars parameter
  292. */
  293. protected function _unescapeToken($token, $chars = null) {
  294. $regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
  295. $token = preg_replace($regex, '\\1', $token);
  296. return $token;
  297. }
  298. /**
  299. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  300. *
  301. * @param boolean $hex true to get them as HEX values, false otherwise
  302. * @param array $chars
  303. * @return array Escape chars
  304. * @todo Test $chars parameter
  305. */
  306. protected function _tokenEscapeChars($hex = true, $chars = null) {
  307. if (!empty($chars)) {
  308. $escape = $chars;
  309. } else {
  310. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  311. for ($i = 0; $i <= 31; $i++) {
  312. $escape[] = chr($i);
  313. }
  314. $escape[] = chr(127);
  315. }
  316. if ($hex == false) {
  317. return $escape;
  318. }
  319. foreach ($escape as $key => $char) {
  320. $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  321. }
  322. return $escape;
  323. }
  324. /**
  325. * ArrayAccess - Offset Exists
  326. *
  327. * @param mixed $offset
  328. * @return boolean
  329. */
  330. public function offsetExists($offset) {
  331. return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
  332. }
  333. /**
  334. * ArrayAccess - Offset Get
  335. *
  336. * @param mixed $offset
  337. * @return mixed
  338. */
  339. public function offsetGet($offset) {
  340. switch ($offset) {
  341. case 'raw':
  342. $firstLineLength = strpos($this->raw, "\r\n") + 2;
  343. if ($this->raw[$firstLineLength] === "\r") {
  344. $header = null;
  345. } else {
  346. $header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
  347. }
  348. return array(
  349. 'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
  350. 'header' => $header,
  351. 'body' => $this->body,
  352. 'response' => $this->raw
  353. );
  354. case 'status':
  355. return array(
  356. 'http-version' => $this->httpVersion,
  357. 'code' => $this->code,
  358. 'reason-phrase' => $this->reasonPhrase
  359. );
  360. case 'header':
  361. return $this->headers;
  362. case 'body':
  363. return $this->body;
  364. case 'cookies':
  365. return $this->cookies;
  366. }
  367. return null;
  368. }
  369. /**
  370. * ArrayAccess - Offset Set
  371. *
  372. * @param mixed $offset
  373. * @param mixed $value
  374. * @return void
  375. */
  376. public function offsetSet($offset, $value) {
  377. return;
  378. }
  379. /**
  380. * ArrayAccess - Offset Unset
  381. *
  382. * @param mixed $offset
  383. * @return void
  384. */
  385. public function offsetUnset($offset) {
  386. return;
  387. }
  388. /**
  389. * Instance as string
  390. *
  391. * @return string
  392. */
  393. public function __toString() {
  394. return $this->body();
  395. }
  396. }