CookieComponent.php 14 KB

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