PageRenderTime 61ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

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

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