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