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

/lib/Cake/Controller/Component/CookieComponent.php

https://bitbucket.org/luobailiang/cake
PHP | 495 lines | 195 code | 41 blank | 259 comment | 36 complexity | 1fef2822fb4af59925c30f65c082de00 MD5 | raw file
  1. <?php
  2. /**
  3. * Cookie Component
  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.Controller.Component
  16. * @since CakePHP(tm) v 1.2.0.4213
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Component', 'Controller');
  20. App::uses('Security', 'Utility');
  21. /**
  22. * Cookie Component.
  23. *
  24. * Cookie handling for the controller.
  25. *
  26. * @package Cake.Controller.Component
  27. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html
  28. *
  29. */
  30. class CookieComponent extends Component {
  31. /**
  32. * The name of the cookie.
  33. *
  34. * Overridden with the controller beforeFilter();
  35. * $this->Cookie->name = 'CookieName';
  36. *
  37. * @var string
  38. */
  39. public $name = 'CakeCookie';
  40. /**
  41. * The time a cookie will remain valid.
  42. *
  43. * Can be either integer Unix timestamp or a date string.
  44. *
  45. * Overridden with the controller beforeFilter();
  46. * $this->Cookie->time = '5 Days';
  47. *
  48. * @var mixed
  49. */
  50. public $time = null;
  51. /**
  52. * Cookie path.
  53. *
  54. * Overridden with the controller beforeFilter();
  55. * $this->Cookie->path = '/';
  56. *
  57. * The path on the server in which the cookie will be available on.
  58. * If public $cookiePath is set to '/foo/', the cookie will only be available
  59. * within the /foo/ directory and all sub-directories such as /foo/bar/ of domain.
  60. * The default value is the entire domain.
  61. *
  62. * @var string
  63. */
  64. public $path = '/';
  65. /**
  66. * Domain path.
  67. *
  68. * The domain that the cookie is available.
  69. *
  70. * Overridden with the controller beforeFilter();
  71. * $this->Cookie->domain = '.example.com';
  72. *
  73. * To make the cookie available on all subdomains of example.com.
  74. * Set $this->Cookie->domain = '.example.com'; in your controller beforeFilter
  75. *
  76. * @var string
  77. */
  78. public $domain = '';
  79. /**
  80. * Secure HTTPS only cookie.
  81. *
  82. * Overridden with the controller beforeFilter();
  83. * $this->Cookie->secure = true;
  84. *
  85. * Indicates that the cookie should only be transmitted over a secure HTTPS connection.
  86. * When set to true, the cookie will only be set if a secure connection exists.
  87. *
  88. * @var boolean
  89. */
  90. public $secure = false;
  91. /**
  92. * Encryption key.
  93. *
  94. * Overridden with the controller beforeFilter();
  95. * $this->Cookie->key = 'SomeRandomString';
  96. *
  97. * @var string
  98. */
  99. public $key = null;
  100. /**
  101. * HTTP only cookie
  102. *
  103. * Set to true to make HTTP only cookies. Cookies that are HTTP only
  104. * are not accessible in Javascript.
  105. *
  106. * @var boolean
  107. */
  108. public $httpOnly = false;
  109. /**
  110. * Values stored in the cookie.
  111. *
  112. * Accessed in the controller using $this->Cookie->read('Name.key');
  113. *
  114. * @see CookieComponent::read();
  115. * @var string
  116. */
  117. protected $_values = array();
  118. /**
  119. * Type of encryption to use.
  120. *
  121. * Currently only one method is available
  122. * Defaults to Security::cipher();
  123. *
  124. * @var string
  125. * @todo add additional encryption methods
  126. */
  127. protected $_type = 'cipher';
  128. /**
  129. * Used to reset cookie time if $expire is passed to CookieComponent::write()
  130. *
  131. * @var string
  132. */
  133. protected $_reset = null;
  134. /**
  135. * Expire time of the cookie
  136. *
  137. * This is controlled by CookieComponent::time;
  138. *
  139. * @var string
  140. */
  141. protected $_expires = 0;
  142. /**
  143. * Constructor
  144. *
  145. * @param ComponentCollection $collection A ComponentCollection for this component
  146. * @param array $settings Array of settings.
  147. */
  148. public function __construct(ComponentCollection $collection, $settings = array()) {
  149. $this->key = Configure::read('Security.salt');
  150. parent::__construct($collection, $settings);
  151. if (isset($this->time)) {
  152. $this->_expire($this->time);
  153. }
  154. }
  155. /**
  156. * Start CookieComponent for use in the controller
  157. *
  158. * @param Controller $controller
  159. * @return void
  160. */
  161. public function startup($controller) {
  162. $this->_expire($this->time);
  163. if (isset($_COOKIE[$this->name])) {
  164. $this->_values = $this->_decrypt($_COOKIE[$this->name]);
  165. }
  166. }
  167. /**
  168. * Write a value to the $_COOKIE[$key];
  169. *
  170. * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires
  171. * $this->Cookie->write('[Name.]key, $value);
  172. *
  173. * By default all values are encrypted.
  174. * You must pass $encrypt false to store values in clear test
  175. *
  176. * You must use this method before any output is sent to the browser.
  177. * Failure to do so will result in header already sent errors.
  178. *
  179. * @param mixed $key Key for the value
  180. * @param mixed $value Value
  181. * @param boolean $encrypt Set to true to encrypt value, false otherwise
  182. * @param string $expires Can be either Unix timestamp, or date string
  183. * @return void
  184. */
  185. public function write($key, $value = null, $encrypt = true, $expires = null) {
  186. if (is_null($encrypt)) {
  187. $encrypt = true;
  188. }
  189. $this->_encrypted = $encrypt;
  190. $this->_expire($expires);
  191. if (!is_array($key)) {
  192. $key = array($key => $value);
  193. }
  194. foreach ($key as $name => $value) {
  195. if (strpos($name, '.') === false) {
  196. $this->_values[$name] = $value;
  197. $this->_write("[$name]", $value);
  198. } else {
  199. $names = explode('.', $name, 2);
  200. if (!isset($this->_values[$names[0]])) {
  201. $this->_values[$names[0]] = array();
  202. }
  203. $this->_values[$names[0]] = Set::insert($this->_values[$names[0]], $names[1], $value);
  204. $this->_write('[' . implode('][', $names) . ']', $value);
  205. }
  206. }
  207. $this->_encrypted = true;
  208. }
  209. /**
  210. * Read the value of the $_COOKIE[$key];
  211. *
  212. * Optional [Name.], required key
  213. * $this->Cookie->read(Name.key);
  214. *
  215. * @param mixed $key Key of the value to be obtained. If none specified, obtain map key => values
  216. * @return string or null, value for specified key
  217. */
  218. public function read($key = null) {
  219. if (empty($this->_values) && isset($_COOKIE[$this->name])) {
  220. $this->_values = $this->_decrypt($_COOKIE[$this->name]);
  221. }
  222. if (is_null($key)) {
  223. return $this->_values;
  224. }
  225. if (strpos($key, '.') !== false) {
  226. $names = explode('.', $key, 2);
  227. $key = $names[0];
  228. }
  229. if (!isset($this->_values[$key])) {
  230. return null;
  231. }
  232. if (!empty($names[1])) {
  233. return Set::extract($this->_values[$key], $names[1]);
  234. }
  235. return $this->_values[$key];
  236. }
  237. /**
  238. * Delete a cookie value
  239. *
  240. * Optional [Name.], required key
  241. * $this->Cookie->read('Name.key);
  242. *
  243. * You must use this method before any output is sent to the browser.
  244. * Failure to do so will result in header already sent errors.
  245. *
  246. * @param string $key Key of the value to be deleted
  247. * @return void
  248. */
  249. public function delete($key) {
  250. if (empty($this->_values)) {
  251. $this->read();
  252. }
  253. if (strpos($key, '.') === false) {
  254. if (isset($this->_values[$key]) && is_array($this->_values[$key])) {
  255. foreach ($this->_values[$key] as $idx => $val) {
  256. $this->_delete("[$key][$idx]");
  257. }
  258. }
  259. $this->_delete("[$key]");
  260. unset($this->_values[$key]);
  261. return;
  262. }
  263. $names = explode('.', $key, 2);
  264. if (isset($this->_values[$names[0]])) {
  265. $this->_values[$names[0]] = Set::remove($this->_values[$names[0]], $names[1]);
  266. }
  267. $this->_delete('[' . implode('][', $names) . ']');
  268. }
  269. /**
  270. * Destroy current cookie
  271. *
  272. * You must use this method before any output is sent to the browser.
  273. * Failure to do so will result in header already sent errors.
  274. *
  275. * @return void
  276. */
  277. public function destroy() {
  278. if (isset($_COOKIE[$this->name])) {
  279. $this->_values = $this->_decrypt($_COOKIE[$this->name]);
  280. }
  281. foreach ($this->_values as $name => $value) {
  282. if (is_array($value)) {
  283. foreach ($value as $key => $val) {
  284. unset($this->_values[$name][$key]);
  285. $this->_delete("[$name][$key]");
  286. }
  287. }
  288. unset($this->_values[$name]);
  289. $this->_delete("[$name]");
  290. }
  291. }
  292. /**
  293. * Will allow overriding default encryption method.
  294. *
  295. * @param string $type Encryption method
  296. * @return void
  297. * @todo NOT IMPLEMENTED
  298. */
  299. public function type($type = 'cipher') {
  300. $this->_type = 'cipher';
  301. }
  302. /**
  303. * Set the expire time for a session variable.
  304. *
  305. * Creates a new expire time for a session variable.
  306. * $expire can be either integer Unix timestamp or a date string.
  307. *
  308. * Used by write()
  309. * CookieComponent::write(string, string, boolean, 8400);
  310. * CookieComponent::write(string, string, boolean, '5 Days');
  311. *
  312. * @param mixed $expires Can be either Unix timestamp, or date string
  313. * @return integer Unix timestamp
  314. */
  315. protected function _expire($expires = null) {
  316. $now = time();
  317. if (is_null($expires)) {
  318. return $this->_expires;
  319. }
  320. $this->_reset = $this->_expires;
  321. if ($expires == 0) {
  322. return $this->_expires = 0;
  323. }
  324. if (is_integer($expires) || is_numeric($expires)) {
  325. return $this->_expires = $now + intval($expires);
  326. }
  327. return $this->_expires = strtotime($expires, $now);
  328. }
  329. /**
  330. * Set cookie
  331. *
  332. * @param string $name Name for cookie
  333. * @param string $value Value for cookie
  334. * @return void
  335. */
  336. protected function _write($name, $value) {
  337. $this->_setcookie(
  338. $this->name . $name, $this->_encrypt($value),
  339. $this->_expires, $this->path, $this->domain, $this->secure, $this->httpOnly
  340. );
  341. if (!is_null($this->_reset)) {
  342. $this->_expires = $this->_reset;
  343. $this->_reset = null;
  344. }
  345. }
  346. /**
  347. * Sets a cookie expire time to remove cookie value
  348. *
  349. * @param string $name Name of cookie
  350. * @return void
  351. */
  352. protected function _delete($name) {
  353. $this->_setcookie(
  354. $this->name . $name, '',
  355. time() - 42000, $this->path, $this->domain, $this->secure, $this->httpOnly
  356. );
  357. }
  358. /**
  359. * Object wrapper for setcookie() so it can be mocked in unit tests.
  360. *
  361. * @todo Re-factor setting cookies into CakeResponse. Cookies are part
  362. * of the HTTP response, and should be handled there.
  363. *
  364. * @param string $name Name of the cookie
  365. * @param string $value Value of the cookie
  366. * @param integer $expire Time the cookie expires in
  367. * @param string $path Path the cookie applies to
  368. * @param string $domain Domain the cookie is for.
  369. * @param boolean $secure Is the cookie https?
  370. * @param boolean $httpOnly Is the cookie available in the client?
  371. * @return void
  372. */
  373. protected function _setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly = false) {
  374. setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
  375. }
  376. /**
  377. * Encrypts $value using public $type method in Security class
  378. *
  379. * @param string $value Value to encrypt
  380. * @return string encrypted string
  381. * @return string Encoded values
  382. */
  383. protected function _encrypt($value) {
  384. if (is_array($value)) {
  385. $value = $this->_implode($value);
  386. }
  387. if ($this->_encrypted === true) {
  388. $type = $this->_type;
  389. $value = "Q2FrZQ==." .base64_encode(Security::$type($value, $this->key));
  390. }
  391. return $value;
  392. }
  393. /**
  394. * Decrypts $value using public $type method in Security class
  395. *
  396. * @param array $values Values to decrypt
  397. * @return string decrypted string
  398. */
  399. protected function _decrypt($values) {
  400. $decrypted = array();
  401. $type = $this->_type;
  402. foreach ((array)$values as $name => $value) {
  403. if (is_array($value)) {
  404. foreach ($value as $key => $val) {
  405. $pos = strpos($val, 'Q2FrZQ==.');
  406. $decrypted[$name][$key] = $this->_explode($val);
  407. if ($pos !== false) {
  408. $val = substr($val, 8);
  409. $decrypted[$name][$key] = $this->_explode(Security::$type(base64_decode($val), $this->key));
  410. }
  411. }
  412. } else {
  413. $pos = strpos($value, 'Q2FrZQ==.');
  414. $decrypted[$name] = $this->_explode($value);
  415. if ($pos !== false) {
  416. $value = substr($value, 8);
  417. $decrypted[$name] = $this->_explode(Security::$type(base64_decode($value), $this->key));
  418. }
  419. }
  420. }
  421. return $decrypted;
  422. }
  423. /**
  424. * Implode method to keep keys are multidimensional arrays
  425. *
  426. * @param array $array Map of key and values
  427. * @return string A json encoded string.
  428. */
  429. protected function _implode(array $array) {
  430. return json_encode($array);
  431. }
  432. /**
  433. * Explode method to return array from string set in CookieComponent::_implode()
  434. * Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
  435. *
  436. * @param string $string A string containing JSON encoded data, or a bare string.
  437. * @return array Map of key and values
  438. */
  439. protected function _explode($string) {
  440. if ($string[0] === '{' || $string[0] === '[') {
  441. $ret = json_decode($string, true);
  442. return ($ret != null) ? $ret : $string;
  443. }
  444. $array = array();
  445. foreach (explode(',', $string) as $pair) {
  446. $key = explode('|', $pair);
  447. if (!isset($key[1])) {
  448. return $key[0];
  449. }
  450. $array[$key[0]] = $key[1];
  451. }
  452. return $array;
  453. }
  454. }