PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/udeshika/fake_twitter
PHP | 500 lines | 195 code | 42 blank | 263 comment | 36 complexity | d5b5ed4d8d333643c2e50acb04c2629a 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 2005-2011, 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-2011, 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. /**
  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 only one method is available
  122. * Defaults to Security::cipher();
  123. *
  124. * @var string
  125. * @todo add additional encryption methods
  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. * Constructor
  144. *
  145. * @param ComponentCollection $collection A ComponentCollection for this component
  146. * @param array $settings Array of settings.
  147. */
  148. public function __construct(ComponentCollection $collection, $settings = array()) {
  149. $this->key = Configure::read('Security.salt');
  150. parent::__construct($collection, $settings);
  151. if (isset($this->time)) {
  152. $this->_expire($this->time);
  153. }
  154. }
  155. /**
  156. * Start CookieComponent for use in the controller
  157. *
  158. * @param Controller $controller
  159. * @return void
  160. */
  161. public function startup($controller) {
  162. $this->_expire($this->time);
  163. if (isset($_COOKIE[$this->name])) {
  164. $this->_values = $this->_decrypt($_COOKIE[$this->name]);
  165. }
  166. }
  167. /**
  168. * Write a value to the $_COOKIE[$key];
  169. *
  170. * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires
  171. * $this->Cookie->write('[Name.]key, $value);
  172. *
  173. * By default all values are encrypted.
  174. * You must pass $encrypt false to store values in clear test
  175. *
  176. * You must use this method before any output is sent to the browser.
  177. * Failure to do so will result in header already sent errors.
  178. *
  179. * @param mixed $key Key for the value
  180. * @param mixed $value Value
  181. * @param boolean $encrypt Set to true to encrypt value, false otherwise
  182. * @param string $expires Can be either Unix timestamp, or date string
  183. * @return void
  184. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write
  185. */
  186. public function write($key, $value = null, $encrypt = true, $expires = null) {
  187. if (is_null($encrypt)) {
  188. $encrypt = true;
  189. }
  190. $this->_encrypted = $encrypt;
  191. $this->_expire($expires);
  192. if (!is_array($key)) {
  193. $key = array($key => $value);
  194. }
  195. foreach ($key as $name => $value) {
  196. if (strpos($name, '.') === false) {
  197. $this->_values[$name] = $value;
  198. $this->_write("[$name]", $value);
  199. } else {
  200. $names = explode('.', $name, 2);
  201. if (!isset($this->_values[$names[0]])) {
  202. $this->_values[$names[0]] = array();
  203. }
  204. $this->_values[$names[0]] = Set::insert($this->_values[$names[0]], $names[1], $value);
  205. $this->_write('[' . implode('][', $names) . ']', $value);
  206. }
  207. }
  208. $this->_encrypted = true;
  209. }
  210. /**
  211. * Read the value of the $_COOKIE[$key];
  212. *
  213. * Optional [Name.], required key
  214. * $this->Cookie->read(Name.key);
  215. *
  216. * @param mixed $key Key of the value to be obtained. If none specified, obtain map key => values
  217. * @return string or null, value for specified key
  218. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::read
  219. */
  220. public function read($key = null) {
  221. if (empty($this->_values) && isset($_COOKIE[$this->name])) {
  222. $this->_values = $this->_decrypt($_COOKIE[$this->name]);
  223. }
  224. if (is_null($key)) {
  225. return $this->_values;
  226. }
  227. if (strpos($key, '.') !== false) {
  228. $names = explode('.', $key, 2);
  229. $key = $names[0];
  230. }
  231. if (!isset($this->_values[$key])) {
  232. return null;
  233. }
  234. if (!empty($names[1])) {
  235. return Set::extract($this->_values[$key], $names[1]);
  236. }
  237. return $this->_values[$key];
  238. }
  239. /**
  240. * Delete a cookie value
  241. *
  242. * Optional [Name.], required key
  243. * $this->Cookie->read('Name.key);
  244. *
  245. * You must use this method before any output is sent to the browser.
  246. * Failure to do so will result in header already sent errors.
  247. *
  248. * @param string $key Key of the value to be deleted
  249. * @return void
  250. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::delete
  251. */
  252. public function delete($key) {
  253. if (empty($this->_values)) {
  254. $this->read();
  255. }
  256. if (strpos($key, '.') === false) {
  257. if (isset($this->_values[$key]) && is_array($this->_values[$key])) {
  258. foreach ($this->_values[$key] as $idx => $val) {
  259. $this->_delete("[$key][$idx]");
  260. }
  261. }
  262. $this->_delete("[$key]");
  263. unset($this->_values[$key]);
  264. return;
  265. }
  266. $names = explode('.', $key, 2);
  267. if (isset($this->_values[$names[0]])) {
  268. $this->_values[$names[0]] = Set::remove($this->_values[$names[0]], $names[1]);
  269. }
  270. $this->_delete('[' . implode('][', $names) . ']');
  271. }
  272. /**
  273. * Destroy current cookie
  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. * @return void
  279. * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::destroy
  280. */
  281. public function destroy() {
  282. if (isset($_COOKIE[$this->name])) {
  283. $this->_values = $this->_decrypt($_COOKIE[$this->name]);
  284. }
  285. foreach ($this->_values as $name => $value) {
  286. if (is_array($value)) {
  287. foreach ($value as $key => $val) {
  288. unset($this->_values[$name][$key]);
  289. $this->_delete("[$name][$key]");
  290. }
  291. }
  292. unset($this->_values[$name]);
  293. $this->_delete("[$name]");
  294. }
  295. }
  296. /**
  297. * Will allow overriding default encryption method.
  298. *
  299. * @param string $type Encryption method
  300. * @return void
  301. * @todo NOT IMPLEMENTED
  302. */
  303. public function type($type = 'cipher') {
  304. $this->_type = 'cipher';
  305. }
  306. /**
  307. * Set the expire time for a session variable.
  308. *
  309. * Creates a new expire time for a session variable.
  310. * $expire can be either integer Unix timestamp or a date string.
  311. *
  312. * Used by write()
  313. * CookieComponent::write(string, string, boolean, 8400);
  314. * CookieComponent::write(string, string, boolean, '5 Days');
  315. *
  316. * @param mixed $expires Can be either Unix timestamp, or date string
  317. * @return integer Unix timestamp
  318. */
  319. protected function _expire($expires = null) {
  320. $now = time();
  321. if (is_null($expires)) {
  322. return $this->_expires;
  323. }
  324. $this->_reset = $this->_expires;
  325. if ($expires == 0) {
  326. return $this->_expires = 0;
  327. }
  328. if (is_integer($expires) || is_numeric($expires)) {
  329. return $this->_expires = $now + intval($expires);
  330. }
  331. return $this->_expires = strtotime($expires, $now);
  332. }
  333. /**
  334. * Set cookie
  335. *
  336. * @param string $name Name for cookie
  337. * @param string $value Value for cookie
  338. * @return void
  339. */
  340. protected function _write($name, $value) {
  341. $this->_setcookie(
  342. $this->name . $name, $this->_encrypt($value),
  343. $this->_expires, $this->path, $this->domain, $this->secure, $this->httpOnly
  344. );
  345. if (!is_null($this->_reset)) {
  346. $this->_expires = $this->_reset;
  347. $this->_reset = null;
  348. }
  349. }
  350. /**
  351. * Sets a cookie expire time to remove cookie value
  352. *
  353. * @param string $name Name of cookie
  354. * @return void
  355. */
  356. protected function _delete($name) {
  357. $this->_setcookie(
  358. $this->name . $name, '',
  359. time() - 42000, $this->path, $this->domain, $this->secure, $this->httpOnly
  360. );
  361. }
  362. /**
  363. * Object wrapper for setcookie() so it can be mocked in unit tests.
  364. *
  365. * @todo Re-factor setting cookies into CakeResponse. Cookies are part
  366. * of the HTTP response, and should be handled there.
  367. *
  368. * @param string $name Name of the cookie
  369. * @param string $value Value of the cookie
  370. * @param integer $expire Time the cookie expires in
  371. * @param string $path Path the cookie applies to
  372. * @param string $domain Domain the cookie is for.
  373. * @param boolean $secure Is the cookie https?
  374. * @param boolean $httpOnly Is the cookie available in the client?
  375. * @return void
  376. */
  377. protected function _setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly = false) {
  378. setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
  379. }
  380. /**
  381. * Encrypts $value using public $type method in Security class
  382. *
  383. * @param string $value Value to encrypt
  384. * @return string encrypted string
  385. * @return string Encoded values
  386. */
  387. protected function _encrypt($value) {
  388. if (is_array($value)) {
  389. $value = $this->_implode($value);
  390. }
  391. if ($this->_encrypted === true) {
  392. $type = $this->_type;
  393. $value = "Q2FrZQ==." .base64_encode(Security::$type($value, $this->key));
  394. }
  395. return $value;
  396. }
  397. /**
  398. * Decrypts $value using public $type method in Security class
  399. *
  400. * @param array $values Values to decrypt
  401. * @return string decrypted string
  402. */
  403. protected function _decrypt($values) {
  404. $decrypted = array();
  405. $type = $this->_type;
  406. foreach ((array)$values as $name => $value) {
  407. if (is_array($value)) {
  408. foreach ($value as $key => $val) {
  409. $pos = strpos($val, 'Q2FrZQ==.');
  410. $decrypted[$name][$key] = $this->_explode($val);
  411. if ($pos !== false) {
  412. $val = substr($val, 8);
  413. $decrypted[$name][$key] = $this->_explode(Security::$type(base64_decode($val), $this->key));
  414. }
  415. }
  416. } else {
  417. $pos = strpos($value, 'Q2FrZQ==.');
  418. $decrypted[$name] = $this->_explode($value);
  419. if ($pos !== false) {
  420. $value = substr($value, 8);
  421. $decrypted[$name] = $this->_explode(Security::$type(base64_decode($value), $this->key));
  422. }
  423. }
  424. }
  425. return $decrypted;
  426. }
  427. /**
  428. * Implode method to keep keys are multidimensional arrays
  429. *
  430. * @param array $array Map of key and values
  431. * @return string A json encoded string.
  432. */
  433. protected function _implode(array $array) {
  434. return json_encode($array);
  435. }
  436. /**
  437. * Explode method to return array from string set in CookieComponent::_implode()
  438. * Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
  439. *
  440. * @param string $string A string containing JSON encoded data, or a bare string.
  441. * @return array Map of key and values
  442. */
  443. protected function _explode($string) {
  444. if ($string[0] === '{' || $string[0] === '[') {
  445. $ret = json_decode($string, true);
  446. return ($ret != null) ? $ret : $string;
  447. }
  448. $array = array();
  449. foreach (explode(',', $string) as $pair) {
  450. $key = explode('|', $pair);
  451. if (!isset($key[1])) {
  452. return $key[0];
  453. }
  454. $array[$key[0]] = $key[1];
  455. }
  456. return $array;
  457. }
  458. }