CookieComponent.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. <?php
  2. /**
  3. * Cookie Component
  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. * @package Cake.Controller.Component
  15. * @since CakePHP(tm) v 1.2.0.4213
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('Component', 'Controller');
  19. App::uses('Security', 'Utility');
  20. App::uses('Hash', '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 two methods are available: cipher and rijndael
  122. * Defaults to Security::cipher();
  123. *
  124. * @var string
  125. */
  126. protected $_type = 'cipher';
  127. /**
  128. * Used to reset cookie time if $expire is passed to CookieComponent::write()
  129. *
  130. * @var string
  131. */
  132. protected $_reset = null;
  133. /**
  134. * Expire time of the cookie
  135. *
  136. * This is controlled by CookieComponent::time;
  137. *
  138. * @var string
  139. */
  140. protected $_expires = 0;
  141. /**
  142. * A reference to the Controller's CakeResponse object
  143. *
  144. * @var CakeResponse
  145. */
  146. protected $_response = null;
  147. /**
  148. * Constructor
  149. *
  150. * @param ComponentCollection $collection A ComponentCollection for this component
  151. * @param array $settings Array of settings.
  152. */
  153. public function __construct(ComponentCollection $collection, $settings = array()) {
  154. $this->key = Configure::read('Security.salt');
  155. parent::__construct($collection, $settings);
  156. if (isset($this->time)) {
  157. $this->_expire($this->time);
  158. }
  159. $controller = $collection->getController();
  160. if ($controller && isset($controller->response)) {
  161. $this->_response = $controller->response;
  162. } else {
  163. $this->_response = new CakeResponse();
  164. }
  165. }
  166. /**
  167. * Start CookieComponent for use in the controller
  168. *
  169. * @param Controller $controller
  170. * @return void
  171. */
  172. public function startup(Controller $controller) {
  173. $this->_expire($this->time);
  174. $this->_values[$this->name] = array();
  175. }
  176. /**
  177. * Write a value to the $_COOKIE[$key];
  178. *
  179. * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires
  180. * $this->Cookie->write('[Name.]key, $value);
  181. *
  182. * By default all values are encrypted.
  183. * You must pass $encrypt false to store values in clear test
  184. *
  185. * You must use this method before any output is sent to the browser.
  186. * Failure to do so will result in header already sent errors.
  187. *
  188. * @param string|array $key Key for the value
  189. * @param mixed $value Value
  190. * @param boolean $encrypt Set to true to encrypt value, false otherwise
  191. * @param integer|string $expires Can be either the number of seconds until a cookie
  192. * expires, or a strtotime compatible time offset.
  193. * @return void
  194. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write
  195. */
  196. public function write($key, $value = null, $encrypt = true, $expires = null) {
  197. if (empty($this->_values[$this->name])) {
  198. $this->read();
  199. }
  200. if ($encrypt === null) {
  201. $encrypt = true;
  202. }
  203. $this->_encrypted = $encrypt;
  204. $this->_expire($expires);
  205. if (!is_array($key)) {
  206. $key = array($key => $value);
  207. }
  208. foreach ($key as $name => $value) {
  209. $names = array($name);
  210. if (strpos($name, '.') !== false) {
  211. $names = explode('.', $name, 2);
  212. }
  213. $firstName = $names[0];
  214. $isMultiValue = (is_array($value) || count($names) > 1);
  215. if (!isset($this->_values[$this->name][$firstName]) && $isMultiValue) {
  216. $this->_values[$this->name][$firstName] = array();
  217. }
  218. if (count($names) > 1) {
  219. $this->_values[$this->name][$firstName] = Hash::insert(
  220. $this->_values[$this->name][$firstName],
  221. $names[1],
  222. $value
  223. );
  224. } else {
  225. $this->_values[$this->name][$firstName] = $value;
  226. }
  227. $this->_write('[' . $firstName . ']', $this->_values[$this->name][$firstName]);
  228. }
  229. $this->_encrypted = true;
  230. }
  231. /**
  232. * Read the value of the $_COOKIE[$key];
  233. *
  234. * Optional [Name.], required key
  235. * $this->Cookie->read(Name.key);
  236. *
  237. * @param string $key Key of the value to be obtained. If none specified, obtain map key => values
  238. * @return string or null, value for specified key
  239. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::read
  240. */
  241. public function read($key = null) {
  242. if (empty($this->_values[$this->name]) && isset($_COOKIE[$this->name])) {
  243. $this->_values[$this->name] = $this->_decrypt($_COOKIE[$this->name]);
  244. }
  245. if (empty($this->_values[$this->name])) {
  246. $this->_values[$this->name] = array();
  247. }
  248. if ($key === null) {
  249. return $this->_values[$this->name];
  250. }
  251. if (strpos($key, '.') !== false) {
  252. $names = explode('.', $key, 2);
  253. $key = $names[0];
  254. }
  255. if (!isset($this->_values[$this->name][$key])) {
  256. return null;
  257. }
  258. if (!empty($names[1])) {
  259. return Hash::get($this->_values[$this->name][$key], $names[1]);
  260. }
  261. return $this->_values[$this->name][$key];
  262. }
  263. /**
  264. * Returns true if given variable is set in cookie.
  265. *
  266. * @param string $var Variable name to check for
  267. * @return boolean True if variable is there
  268. */
  269. public function check($key = null) {
  270. if (empty($key)) {
  271. return false;
  272. }
  273. return $this->read($key) !== null;
  274. }
  275. /**
  276. * Delete a cookie value
  277. *
  278. * Optional [Name.], required key
  279. * $this->Cookie->delete('Name.key);
  280. *
  281. * You must use this method before any output is sent to the browser.
  282. * Failure to do so will result in header already sent errors.
  283. *
  284. * This method will delete both the top level and 2nd level cookies set.
  285. * For example assuming that $name = App, deleting `User` will delete
  286. * both `App[User]` and any other cookie values like `App[User][email]`
  287. * This is done to clean up cookie storage from before 2.4.3, where cookies
  288. * were stored inconsistently.
  289. *
  290. * @param string $key Key of the value to be deleted
  291. * @return void
  292. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::delete
  293. */
  294. public function delete($key) {
  295. if (empty($this->_values[$this->name])) {
  296. $this->read();
  297. }
  298. if (strpos($key, '.') === false) {
  299. if (isset($this->_values[$this->name][$key]) && is_array($this->_values[$this->name][$key])) {
  300. foreach ($this->_values[$this->name][$key] as $idx => $val) {
  301. $this->_delete("[$key][$idx]");
  302. }
  303. }
  304. $this->_delete("[$key]");
  305. unset($this->_values[$this->name][$key]);
  306. return;
  307. }
  308. $names = explode('.', $key, 2);
  309. if (isset($this->_values[$this->name][$names[0]])) {
  310. $this->_values[$this->name][$names[0]] = Hash::remove($this->_values[$this->name][$names[0]], $names[1]);
  311. }
  312. $this->_delete('[' . implode('][', $names) . ']');
  313. }
  314. /**
  315. * Destroy current cookie
  316. *
  317. * You must use this method before any output is sent to the browser.
  318. * Failure to do so will result in header already sent errors.
  319. *
  320. * @return void
  321. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::destroy
  322. */
  323. public function destroy() {
  324. if (isset($_COOKIE[$this->name])) {
  325. $this->_values[$this->name] = $this->_decrypt($_COOKIE[$this->name]);
  326. }
  327. foreach ($this->_values[$this->name] as $name => $value) {
  328. if (is_array($value)) {
  329. foreach ($value as $key => $val) {
  330. unset($this->_values[$this->name][$name][$key]);
  331. $this->_delete("[$name][$key]");
  332. }
  333. }
  334. unset($this->_values[$this->name][$name]);
  335. $this->_delete("[$name]");
  336. }
  337. }
  338. /**
  339. * Will allow overriding default encryption method. Use this method
  340. * in ex: AppController::beforeFilter() before you have read or
  341. * written any cookies.
  342. *
  343. * @param string $type Encryption method
  344. * @return void
  345. */
  346. public function type($type = 'cipher') {
  347. $availableTypes = array(
  348. 'cipher',
  349. 'rijndael'
  350. );
  351. if (!in_array($type, $availableTypes)) {
  352. trigger_error(__d('cake_dev', 'You must use cipher or rijndael for cookie encryption type'), E_USER_WARNING);
  353. $type = 'cipher';
  354. }
  355. $this->_type = $type;
  356. }
  357. /**
  358. * Set the expire time for a session variable.
  359. *
  360. * Creates a new expire time for a session variable.
  361. * $expire can be either integer Unix timestamp or a date string.
  362. *
  363. * Used by write()
  364. * CookieComponent::write(string, string, boolean, 8400);
  365. * CookieComponent::write(string, string, boolean, '5 Days');
  366. *
  367. * @param integer|string $expires Can be either Unix timestamp, or date string
  368. * @return integer Unix timestamp
  369. */
  370. protected function _expire($expires = null) {
  371. if ($expires === null) {
  372. return $this->_expires;
  373. }
  374. $this->_reset = $this->_expires;
  375. if (!$expires) {
  376. return $this->_expires = 0;
  377. }
  378. $now = new DateTime();
  379. if (is_int($expires) || is_numeric($expires)) {
  380. return $this->_expires = $now->format('U') + intval($expires);
  381. }
  382. $now->modify($expires);
  383. return $this->_expires = $now->format('U');
  384. }
  385. /**
  386. * Set cookie
  387. *
  388. * @param string $name Name for cookie
  389. * @param string $value Value for cookie
  390. * @return void
  391. */
  392. protected function _write($name, $value) {
  393. $this->_response->cookie(array(
  394. 'name' => $this->name . $name,
  395. 'value' => $this->_encrypt($value),
  396. 'expire' => $this->_expires,
  397. 'path' => $this->path,
  398. 'domain' => $this->domain,
  399. 'secure' => $this->secure,
  400. 'httpOnly' => $this->httpOnly
  401. ));
  402. if (!empty($this->_reset)) {
  403. $this->_expires = $this->_reset;
  404. $this->_reset = null;
  405. }
  406. }
  407. /**
  408. * Sets a cookie expire time to remove cookie value
  409. *
  410. * @param string $name Name of cookie
  411. * @return void
  412. */
  413. protected function _delete($name) {
  414. $this->_response->cookie(array(
  415. 'name' => $this->name . $name,
  416. 'value' => '',
  417. 'expire' => time() - 42000,
  418. 'path' => $this->path,
  419. 'domain' => $this->domain,
  420. 'secure' => $this->secure,
  421. 'httpOnly' => $this->httpOnly
  422. ));
  423. }
  424. /**
  425. * Encrypts $value using public $type method in Security class
  426. *
  427. * @param string $value Value to encrypt
  428. * @return string Encoded values
  429. */
  430. protected function _encrypt($value) {
  431. if (is_array($value)) {
  432. $value = $this->_implode($value);
  433. }
  434. if ($this->_encrypted === true) {
  435. $type = $this->_type;
  436. $value = "Q2FrZQ==." . base64_encode(Security::$type($value, $this->key, 'encrypt'));
  437. }
  438. return $value;
  439. }
  440. /**
  441. * Decrypts $value using public $type method in Security class
  442. *
  443. * @param array $values Values to decrypt
  444. * @return string decrypted string
  445. */
  446. protected function _decrypt($values) {
  447. $decrypted = array();
  448. $type = $this->_type;
  449. foreach ((array)$values as $name => $value) {
  450. if (is_array($value)) {
  451. foreach ($value as $key => $val) {
  452. $pos = strpos($val, 'Q2FrZQ==.');
  453. $decrypted[$name][$key] = $this->_explode($val);
  454. if ($pos !== false) {
  455. $val = substr($val, 8);
  456. $decrypted[$name][$key] = $this->_explode(Security::$type(base64_decode($val), $this->key, 'decrypt'));
  457. }
  458. }
  459. } else {
  460. $pos = strpos($value, 'Q2FrZQ==.');
  461. $decrypted[$name] = $this->_explode($value);
  462. if ($pos !== false) {
  463. $value = substr($value, 8);
  464. $decrypted[$name] = $this->_explode(Security::$type(base64_decode($value), $this->key, 'decrypt'));
  465. }
  466. }
  467. }
  468. return $decrypted;
  469. }
  470. /**
  471. * Implode method to keep keys are multidimensional arrays
  472. *
  473. * @param array $array Map of key and values
  474. * @return string A json encoded string.
  475. */
  476. protected function _implode(array $array) {
  477. return json_encode($array);
  478. }
  479. /**
  480. * Explode method to return array from string set in CookieComponent::_implode()
  481. * Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
  482. *
  483. * @param string $string A string containing JSON encoded data, or a bare string.
  484. * @return array Map of key and values
  485. */
  486. protected function _explode($string) {
  487. $first = substr($string, 0, 1);
  488. if ($first === '{' || $first === '[') {
  489. $ret = json_decode($string, true);
  490. return ($ret !== null) ? $ret : $string;
  491. }
  492. $array = array();
  493. foreach (explode(',', $string) as $pair) {
  494. $key = explode('|', $pair);
  495. if (!isset($key[1])) {
  496. return $key[0];
  497. }
  498. $array[$key[0]] = $key[1];
  499. }
  500. return $array;
  501. }
  502. }