PageRenderTime 51ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Network/Http/HttpSocketResponse.php

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