CookieComponent.php 14 KB

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