cake/libs/controller/components/cookie.php

1 <?php
2 /**
3 * Cookie Component
4 *
5 * PHP versions 4 and 5
6 *
7 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8 * Copyright 2005-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14 * @link http://cakephp.org CakePHP(tm) Project
15 * @package cake
16 * @subpackage cake.cake.libs.controller.components
17 * @since CakePHP(tm) v 1.2.0.4213
18 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
19 */
20  
21 /**
22 * Load Security class
23 */
24 App::import('Core', 'Security');
25  
26 /**
27 * Cookie Component.
28 *
29 * Cookie handling for the controller.
30 *
31 * @package cake
32 * @subpackage cake.cake.libs.controller.components
33 * @link http://book.cakephp.org/view/1280/Cookies
34 *
35 */
36 class CookieComponent extends Object {
37  
38 /**
39 * The name of the cookie.
40 *
41 * Overridden with the controller beforeFilter();
42 * $this->Cookie->name = 'CookieName';
43 *
44 * @var string
45 * @access public
46 */
47 var $name = 'CakeCookie';
48  
49 /**
50 * The time a cookie will remain valid.
51 *
52 * Can be either integer Unix timestamp or a date string.
53 *
54 * Overridden with the controller beforeFilter();
55 * $this->Cookie->time = '5 Days';
56 *
57 * @var mixed
58 * @access public
59 */
60 var $time = null;
61  
62 /**
63 * Cookie path.
64 *
65 * Overridden with the controller beforeFilter();
66 * $this->Cookie->path = '/';
67 *
68 * The path on the server in which the cookie will be available on.
69 * If var $cookiePath is set to '/foo/', the cookie will only be available
70 * within the /foo/ directory and all sub-directories such as /foo/bar/ of domain.
71 * The default value is the entire domain.
72 *
73 * @var string
74 * @access public
75 */
76 var $path = '/';
77  
78 /**
79 * Domain path.
80 *
81 * The domain that the cookie is available.
82 *
83 * Overridden with the controller beforeFilter();
84 * $this->Cookie->domain = '.example.com';
85 *
86 * To make the cookie available on all subdomains of example.com.
87 * Set $this->Cookie->domain = '.example.com'; in your controller beforeFilter
88 *
89 * @var string
90 * @access public
91 */
92 var $domain = '';
93  
94 /**
95 * Secure HTTPS only cookie.
96 *
97 * Overridden with the controller beforeFilter();
98 * $this->Cookie->secure = true;
99 *
100 * Indicates that the cookie should only be transmitted over a secure HTTPS connection.
101 * When set to true, the cookie will only be set if a secure connection exists.
102 *
103 * @var boolean
104 * @access public
105 */
106 var $secure = false;
107  
108 /**
109 * Encryption key.
110 *
111 * Overridden with the controller beforeFilter();
112 * $this->Cookie->key = 'SomeRandomString';
113 *
114 * @var string
115 * @access protected
116 */
117 var $key = null;
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 * @access private
127 */
128 var $__values = array();
129  
130 /**
131 * Type of encryption to use.
132 *
133 * Currently only one method is available
134 * Defaults to Security::cipher();
135 *
136 * @var string
137 * @access private
138 * @todo add additional encryption methods
139 */
140 var $__type = 'cipher';
141  
142 /**
143 * Used to reset cookie time if $expire is passed to CookieComponent::write()
144 *
145 * @var string
146 * @access private
147 */
148 var $__reset = null;
149  
150 /**
151 * Expire time of the cookie
152 *
153 * This is controlled by CookieComponent::time;
154 *
155 * @var string
156 * @access private
157 */
158 var $__expires = 0;
159  
160 /**
161 * Main execution method.
162 *
163 * @param object $controller A reference to the instantiating controller object
164 * @access public
165 */
166 function initialize(&$controller, $settings) {
167 $this->key = Configure::read('Security.salt');
168 $this->_set($settings);
169 }
170  
171 /**
172 * Start CookieComponent for use in the controller
173 *
174 * @access public
175 */
176 function startup() {
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 * @access public
201 */
202 function write($key, $value = null, $encrypt = true, $expires = null) {
203 if (is_null($encrypt)) {
204 $encrypt = true;
205 }
206 $this->__encrypted = $encrypt;
207 $this->__expire($expires);
208  
209 if (!is_array($key)) {
210 $key = array($key => $value);
211 }
212  
213 foreach ($key as $name => $value) {
214 if (strpos($name, '.') === false) {
215 $this->__values[$name] = $value;
216 $this->__write("[$name]", $value);
217  
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 * @access public
239 */
240 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 * @access public
275 */
276 function delete($key) {
277 if (empty($this->__values)) {
278 $this->read();
279 }
280 if (strpos($key, '.') === false) {
281 unset($this->__values[$key]);
282 $this->__delete("[$key]");
283 return;
284 }
285 $names = explode('.', $key, 2);
286 $this->__values[$names[0]] = Set::remove($this->__values[$names[0]], $names[1]);
287 $this->__delete('[' . implode('][', $names) . ']');
288 }
289  
290 /**
291 * Destroy current cookie
292 *
293 * You must use this method before any output is sent to the browser.
294 * Failure to do so will result in header already sent errors.
295 *
296 * @return void
297 * @access public
298 */
299 function destroy() {
300 if (isset($_COOKIE[$this->name])) {
301 $this->__values = $this->__decrypt($_COOKIE[$this->name]);
302 }
303  
304 foreach ($this->__values as $name => $value) {
305 if (is_array($value)) {
306 foreach ($value as $key => $val) {
307 unset($this->__values[$name][$key]);
308 $this->__delete("[$name][$key]");
309 }
310 }
311 unset($this->__values[$name]);
312 $this->__delete("[$name]");
313 }
314 }
315  
316 /**
317 * Will allow overriding default encryption method.
318 *
319 * @param string $type Encryption method
320 * @access public
321 * @todo NOT IMPLEMENTED
322 */
323 function type($type = 'cipher') {
324 $this->__type = 'cipher';
325 }
326  
327 /**
328 * Set the expire time for a session variable.
329 *
330 * Creates a new expire time for a session variable.
331 * $expire can be either integer Unix timestamp or a date string.
332 *
333 * Used by write()
334 * CookieComponent::write(string, string, boolean, 8400);
335 * CookieComponent::write(string, string, boolean, '5 Days');
336 *
337 * @param mixed $expires Can be either Unix timestamp, or date string
338 * @return int Unix timestamp
339 * @access private
340 */
341 function __expire($expires = null) {
342 $now = time();
343 if (is_null($expires)) {
344 return $this->__expires;
345 }
346 $this->__reset = $this->__expires;
347  
348 if ($expires == 0) {
349 return $this->__expires = 0;
350 }
351  
352 if (is_integer($expires) || is_numeric($expires)) {
353 return $this->__expires = $now + intval($expires);
354 }
355 return $this->__expires = strtotime($expires, $now);
356 }
357  
358 /**
359 * Set cookie
360 *
361 * @param string $name Name for cookie
362 * @param string $value Value for cookie
363 * @access private
364 */
365 function __write($name, $value) {
366 setcookie($this->name . $name, $this->__encrypt($value), $this->__expires, $this->path, $this->domain, $this->secure);
367  
368 if (!is_null($this->__reset)) {
369 $this->__expires = $this->__reset;
370 $this->__reset = null;
371 }
372 }
373  
374 /**
375 * Sets a cookie expire time to remove cookie value
376 *
377 * @param string $name Name of cookie
378 * @access private
379 */
380 function __delete($name) {
381 setcookie($this->name . $name, '', time() - 42000, $this->path, $this->domain, $this->secure);
382 }
383  
384 /**
385 * Encrypts $value using var $type method in Security class
386 *
387 * @param string $value Value to encrypt
388 * @return string encrypted string
389 * @access private
390 */
391 function __encrypt($value) {
392 if (is_array($value)) {
393 $value = $this->__implode($value);
394 }
395  
396 if ($this->__encrypted === true) {
397 $type = $this->__type;
398 $value = "Q2FrZQ==." .base64_encode(Security::$type($value, $this->key));
399 }
400 return $value;
401 }
402  
403 /**
404 * Decrypts $value using var $type method in Security class
405 *
406 * @param array $values Values to decrypt
407 * @return string decrypted string
408 * @access private
409 */
410 function __decrypt($values) {
411 $decrypted = array();
412 $type = $this->__type;
413  
414 foreach ((array)$values as $name => $value) {
415 if (is_array($value)) {
416 foreach ($value as $key => $val) {
417 $pos = strpos($val, 'Q2FrZQ==.');
418 $decrypted[$name][$key] = $this->__explode($val);
419  
420 if ($pos !== false) {
421 $val = substr($val, 8);
422 $decrypted[$name][$key] = $this->__explode(Security::$type(base64_decode($val), $this->key));
423 }
424 }
425 } else {
426 $pos = strpos($value, 'Q2FrZQ==.');
427 $decrypted[$name] = $this->__explode($value);
428  
429 if ($pos !== false) {
430 $value = substr($value, 8);
431 $decrypted[$name] = $this->__explode(Security::$type(base64_decode($value), $this->key));
432 }
433 }
434 }
435 return $decrypted;
436 }
437  
438 /**
439 * Implode method to keep keys are multidimensional arrays
440 *
441 * @param array $array Map of key and values
442 * @return string String in the form key1|value1,key2|value2
443 * @access private
444 */
445 function __implode($array) {
446 $string = '';
447 foreach ($array as $key => $value) {
448 $string .= ',' . $key . '|' . $value;
449 }
450 return substr($string, 1);
451 }
452  
453 /**
454 * Explode method to return array from string set in CookieComponent::__implode()
455 *
456 * @param string $string String in the form key1|value1,key2|value2
457 * @return array Map of key and values
458 * @access private
459 */
460 function __explode($string) {
461 $array = array();
462 foreach (explode(',', $string) as $pair) {
463 $key = explode('|', $pair);
464 if (!isset($key[1])) {
465 return $key[0];
466 }
467 $array[$key[0]] = $key[1];
468 }
469 return $array;
470 }
471 }
472  
473