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