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