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