CookieComponent.php 15 KB

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