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