PageRenderTime 22ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/LeThanhDat/firstdummyapp
PHP | 533 lines | 229 code | 44 blank | 260 comment | 40 complexity | ba0530d89d348faaf89adc6abbbd8b22 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 (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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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 (is_null($encrypt)) {
  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 (is_null($key)) {
  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. $now = time();
  360. if (is_null($expires)) {
  361. return $this->_expires;
  362. }
  363. $this->_reset = $this->_expires;
  364. if (!$expires) {
  365. return $this->_expires = 0;
  366. }
  367. if (is_int($expires) || is_numeric($expires)) {
  368. return $this->_expires = $now + intval($expires);
  369. }
  370. return $this->_expires = strtotime($expires, $now);
  371. }
  372. /**
  373. * Set cookie
  374. *
  375. * @param string $name Name for cookie
  376. * @param string $value Value for cookie
  377. * @return void
  378. */
  379. protected function _write($name, $value) {
  380. $this->_response->cookie(array(
  381. 'name' => $this->name . $name,
  382. 'value' => $this->_encrypt($value),
  383. 'expire' => $this->_expires,
  384. 'path' => $this->path,
  385. 'domain' => $this->domain,
  386. 'secure' => $this->secure,
  387. 'httpOnly' => $this->httpOnly
  388. ));
  389. if (!is_null($this->_reset)) {
  390. $this->_expires = $this->_reset;
  391. $this->_reset = null;
  392. }
  393. }
  394. /**
  395. * Sets a cookie expire time to remove cookie value
  396. *
  397. * @param string $name Name of cookie
  398. * @return void
  399. */
  400. protected function _delete($name) {
  401. $this->_response->cookie(array(
  402. 'name' => $this->name . $name,
  403. 'value' => '',
  404. 'expire' => time() - 42000,
  405. 'path' => $this->path,
  406. 'domain' => $this->domain,
  407. 'secure' => $this->secure,
  408. 'httpOnly' => $this->httpOnly
  409. ));
  410. }
  411. /**
  412. * Encrypts $value using public $type method in Security class
  413. *
  414. * @param string $value Value to encrypt
  415. * @return string Encoded values
  416. */
  417. protected function _encrypt($value) {
  418. if (is_array($value)) {
  419. $value = $this->_implode($value);
  420. }
  421. if ($this->_encrypted === true) {
  422. $type = $this->_type;
  423. $value = "Q2FrZQ==." . base64_encode(Security::$type($value, $this->key, 'encrypt'));
  424. }
  425. return $value;
  426. }
  427. /**
  428. * Decrypts $value using public $type method in Security class
  429. *
  430. * @param array $values Values to decrypt
  431. * @return string decrypted string
  432. */
  433. protected function _decrypt($values) {
  434. $decrypted = array();
  435. $type = $this->_type;
  436. foreach ((array)$values as $name => $value) {
  437. if (is_array($value)) {
  438. foreach ($value as $key => $val) {
  439. $pos = strpos($val, 'Q2FrZQ==.');
  440. $decrypted[$name][$key] = $this->_explode($val);
  441. if ($pos !== false) {
  442. $val = substr($val, 8);
  443. $decrypted[$name][$key] = $this->_explode(Security::$type(base64_decode($val), $this->key, 'decrypt'));
  444. }
  445. }
  446. } else {
  447. $pos = strpos($value, 'Q2FrZQ==.');
  448. $decrypted[$name] = $this->_explode($value);
  449. if ($pos !== false) {
  450. $value = substr($value, 8);
  451. $decrypted[$name] = $this->_explode(Security::$type(base64_decode($value), $this->key, 'decrypt'));
  452. }
  453. }
  454. }
  455. return $decrypted;
  456. }
  457. /**
  458. * Implode method to keep keys are multidimensional arrays
  459. *
  460. * @param array $array Map of key and values
  461. * @return string A json encoded string.
  462. */
  463. protected function _implode(array $array) {
  464. return json_encode($array);
  465. }
  466. /**
  467. * Explode method to return array from string set in CookieComponent::_implode()
  468. * Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
  469. *
  470. * @param string $string A string containing JSON encoded data, or a bare string.
  471. * @return array Map of key and values
  472. */
  473. protected function _explode($string) {
  474. $first = substr($string, 0, 1);
  475. if ($first === '{' || $first === '[') {
  476. $ret = json_decode($string, true);
  477. return ($ret) ? $ret : $string;
  478. }
  479. $array = array();
  480. foreach (explode(',', $string) as $pair) {
  481. $key = explode('|', $pair);
  482. if (!isset($key[1])) {
  483. return $key[0];
  484. }
  485. $array[$key[0]] = $key[1];
  486. }
  487. return $array;
  488. }
  489. }