Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: session.php 8004 2009-01-16 20:15:21Z gwoo $ */
3
/**
4
 * Session class for Cake.
5
 *
6
 * Cake abstracts the handling of sessions.
7
 * There are several convenient methods to access session information.
8
 * This class is the implementation of those methods.
9
 * They are mostly used by the Session Component.
10
 *
11
 * PHP versions 4 and 5
12
 *
13
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
14
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
15
 *
16
 * Licensed under The MIT License
17
 * Redistributions of files must retain the above copyright notice.
18
 *
19
 * @filesource
20
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
21
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
22
 * @package       cake
23
 * @subpackage    cake.cake.libs
24
 * @since         CakePHP(tm) v .0.10.0.1222
25
 * @version       $Revision: 8004 $
26
 * @modifiedby    $LastChangedBy: gwoo $
27
 * @lastmodified  $Date: 2009-01-16 12:15:21 -0800 (Fri, 16 Jan 2009) $
28
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
29
 */
30
/**
31
 * Database name for cake sessions.
32
 *
33
 */
34
if (!class_exists('Set')) {
35
	require LIBS . 'set.php';
36
}
37
if (!class_exists('Security')) {
38
	require LIBS . 'security.php';
39
}
40
/**
41
 * Session class for Cake.
42
 *
43
 * Cake abstracts the handling of sessions. There are several convenient methods to access session information.
44
 * This class is the implementation of those methods. They are mostly used by the Session Component.
45
 *
46
 * @package       cake
47
 * @subpackage    cake.cake.libs
48
 */
49
class CakeSession extends Object {
50
/**
51
 * True if the Session is still valid
52
 *
53
 * @var boolean
54
 * @access public
55
 */
56
	var $valid = false;
57
/**
58
 * Error messages for this session
59
 *
60
 * @var array
61
 * @access public
62
 */
63
	var $error = false;
64
/**
65
 * User agent string
66
 *
67
 * @var string
68
 * @access protected
69
 */
70
	var $_userAgent = '';
71
/**
72
 * Path to where the session is active.
73
 *
74
 * @var string
75
 * @access public
76
 */
77
	var $path = '/';
78
/**
79
 * Error number of last occurred error
80
 *
81
 * @var integer
82
 * @access public
83
 */
84
	var $lastError = null;
85
/**
86
 * 'Security.level' setting, "high", "medium", or "low".
87
 *
88
 * @var string
89
 * @access public
90
 */
91
	var $security = null;
92
/**
93
 * Start time for this session.
94
 *
95
 * @var integer
96
 * @access public
97
 */
98
	var $time = false;
99
/**
100
 * Time when this session becomes invalid.
101
 *
102
 * @var integer
103
 * @access public
104
 */
105
	var $sessionTime = false;
106
/**
107
 * Keeps track of keys to watch for writes on
108
 *
109
 * @var array
110
 * @access public
111
 */
112
	var $watchKeys = array();
113
/**
114
 * Current Session id
115
 *
116
 * @var string
117
 * @access public
118
 */
119
	var $id = null;
120
/**
121
 * Constructor.
122
 *
123
 * @param string $base The base path for the Session
124
 * @param boolean $start Should session be started right now
125
 * @access public
126
 */
127
	function __construct($base = null, $start = true) {
128
		if (Configure::read('Session.save') === 'database' && !class_exists('ConnectionManager')) {
129
			App::import('Core', 'ConnectionManager');
130
		}
131
 
132
		if (Configure::read('Session.checkAgent') === true || Configure::read('Session.checkAgent') === null) {
133
			if (env('HTTP_USER_AGENT') != null) {
134
				$this->_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
135
			}
136
		}
137
		$this->time = time();
138
 
139
		if ($start === true) {
140
			$this->host = env('HTTP_HOST');
141
 
142
			if (empty($base) || strpos($base, '?') === 0 || strpos($base, 'index.php') === 0) {
143
				$this->path = '/';
144
			} else {
145
				$this->path = $base;
146
			}
147
 
148
			if (strpos($this->host, ':') !== false) {
149
				$this->host = substr($this->host, 0, strpos($this->host, ':'));
150
			}
151
 
152
			if (!class_exists('Security')) {
153
				App::import('Core', 'Security');
154
			}
155
 
156
			$this->sessionTime = $this->time + (Security::inactiveMins() * Configure::read('Session.timeout'));
157
			$this->security = Configure::read('Security.level');
158
		}
159
		parent::__construct();
160
	}
161
/**
162
 * Starts the Session.
163
 *
164
 * @param string $name Variable name to check for
165
 * @return boolean True if variable is there
166
 * @access public
167
 */
168
	function start() {
169
		if (function_exists('session_write_close')) {
170
			session_write_close();
171
		}
172
		$this->__initSession();
173
		return $this->__startSession();
174
	}
175
/**
176
 * Determine if Session has been started.
177
 *
178
 * @access public
179
 * @return boolean True if session has been started.
180
 */
181
	function started() {
182
		if (isset($_SESSION)) {
183
			return true;
184
		}
185
		return false;
186
	}
187
/**
188
 * Returns true if given variable is set in session.
189
 *
190
 * @param string $name Variable name to check for
191
 * @return boolean True if variable is there
192
 * @access public
193
 */
194
	function check($name) {
195
		$var = $this->__validateKeys($name);
196
		if (empty($var)) {
197
			return false;
198
		}
199
		$result = Set::extract($_SESSION, $var);
200
		return isset($result);
201
	}
202
/**
203
 * Returns the Session id
204
 *
205
 * @param id $name string
206
 * @return string Session id
207
 * @access public
208
 */
209
	function id($id = null) {
210
		if ($id) {
211
			$this->id = $id;
212
			session_id($this->id);
213
		}
214
		if (isset($_SESSION)) {
215
			return session_id();
216
		} else {
217
			return $this->id;
218
		}
219
	}
220
/**
221
 * Removes a variable from session.
222
 *
223
 * @param string $name Session variable to remove
224
 * @return boolean Success
225
 * @access public
226
 */
227
	function del($name) {
228
		if ($this->check($name)) {
229
			if ($var = $this->__validateKeys($name)) {
230
				if (in_array($var, $this->watchKeys)) {
231
					trigger_error('Deleting session key {' . $var . '}', E_USER_NOTICE);
232
				}
233
				$this->__overwrite($_SESSION, Set::remove($_SESSION, $var));
234
				return ($this->check($var) == false);
235
			}
236
		}
237
		$this->__setError(2, "$name doesn't exist");
238
		return false;
239
	}
240
/**
241
 * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
242
 *
243
 * @param array $old Set of old variables => values
244
 * @param array $new New set of variable => value
245
 * @access private
246
 */
247
	function __overwrite(&$old, $new) {
248
		if (!empty($old)) {
249
			foreach ($old as $key => $var) {
250
				if (!isset($new[$key])) {
251
					unset($old[$key]);
252
				}
253
			}
254
		}
255
		foreach ($new as $key => $var) {
256
			$old[$key] = $var;
257
		}
258
	}
259
/**
260
 * Return error description for given error number.
261
 *
262
 * @param integer $errorNumber Error to set
263
 * @return string Error as string
264
 * @access private
265
 */
266
	function __error($errorNumber) {
267
		if (!is_array($this->error) || !array_key_exists($errorNumber, $this->error)) {
268
			return false;
269
		} else {
270
			return $this->error[$errorNumber];
271
		}
272
	}
273
/**
274
 * Returns last occurred error as a string, if any.
275
 *
276
 * @return mixed Error description as a string, or false.
277
 * @access public
278
 */
279
	function error() {
280
		if ($this->lastError) {
281
			return $this->__error($this->lastError);
282
		} else {
283
			return false;
284
		}
285
	}
286
/**
287
 * Returns true if session is valid.
288
 *
289
 * @return boolean Success
290
 * @access public
291
 */
292
	function valid() {
293
		if ($this->read('Config')) {
294
			if ((Configure::read('Session.checkAgent') === false || $this->_userAgent == $this->read('Config.userAgent')) && $this->time <= $this->read('Config.time')) {
295
				if ($this->error === false) {
296
					$this->valid = true;
297
				}
298
			} else {
299
				$this->valid = false;
300
				$this->__setError(1, 'Session Highjacking Attempted !!!');
301
			}
302
		}
303
		return $this->valid;
304
	}
305
/**
306
 * Returns given session variable, or all of them, if no parameters given.
307
 *
308
 * @param mixed $name The name of the session variable (or a path as sent to Set.extract)
309
 * @return mixed The value of the session variable
310
 * @access public
311
 */
312
	function read($name = null) {
313
		if (is_null($name)) {
314
			return $this->__returnSessionVars();
315
		}
316
		if (empty($name)) {
317
			return false;
318
		}
319
		$result = Set::extract($_SESSION, $name);
320
 
321
		if (!is_null($result)) {
322
			return $result;
323
		}
324
		$this->__setError(2, "$name doesn't exist");
325
		return null;
326
	}
327
/**
328
 * Returns all session variables.
329
 *
330
 * @return mixed Full $_SESSION array, or false on error.
331
 * @access private
332
 */
333
	function __returnSessionVars() {
334
		if (!empty($_SESSION)) {
335
			return $_SESSION;
336
		}
337
		$this->__setError(2, "No Session vars set");
338
		return false;
339
	}
340
/**
341
 * Tells Session to write a notification when a certain session path or subpath is written to
342
 *
343
 * @param mixed $var The variable path to watch
344
 * @return void
345
 * @access public
346
 */
347
	function watch($var) {
348
		$var = $this->__validateKeys($var);
349
		if (empty($var)) {
350
			return false;
351
		}
352
		$this->watchKeys[] = $var;
353
	}
354
/**
355
 * Tells Session to stop watching a given key path
356
 *
357
 * @param mixed $var The variable path to watch
358
 * @return void
359
 * @access public
360
 */
361
	function ignore($var) {
362
		$var = $this->__validateKeys($var);
363
		if (!in_array($var, $this->watchKeys)) {
364
			return;
365
		}
366
		foreach ($this->watchKeys as $i => $key) {
367
			if ($key == $var) {
368
				unset($this->watchKeys[$i]);
369
				$this->watchKeys = array_values($this->watchKeys);
370
				return;
371
			}
372
		}
373
	}
374
/**
375
 * Writes value to given session variable name.
376
 *
377
 * @param mixed $name Name of variable
378
 * @param string $value Value to write
379
 * @return boolean True if the write was successful, false if the write failed
380
 * @access public
381
 */
382
	function write($name, $value) {
383
		$var = $this->__validateKeys($name);
384
 
385
		if (empty($var)) {
386
			return false;
387
		}
388
		if (in_array($var, $this->watchKeys)) {
389
			trigger_error('Writing session key {' . $var . '}: ' . Debugger::exportVar($value), E_USER_NOTICE);
390
		}
391
		$this->__overwrite($_SESSION, Set::insert($_SESSION, $var, $value));
392
		return (Set::extract($_SESSION, $var) === $value);
393
	}
394
/**
395
 * Helper method to destroy invalid sessions.
396
 *
397
 * @return void
398
 * @access public
399
 */
400
	function destroy() {
401
		$_SESSION = array();
402
		$this->__construct($this->path);
403
		$this->start();
404
		$this->renew();
405
		$this->_checkValid();
406
	}
407
/**
408
 * Helper method to initialize a session, based on Cake core settings.
409
 *
410
 * @access private
411
 */
412
	function __initSession() {
413
		$iniSet = function_exists('ini_set');
414
 
415
		if ($iniSet && env('HTTPS')) {
416
			ini_set('session.cookie_secure', 1);
417
		}
418
 
419
		switch ($this->security) {
420
			case 'high':
421
				$this->cookieLifeTime = 0;
422
				if ($iniSet) {
423
					ini_set('session.referer_check', $this->host);
424
				}
425
			break;
426
			case 'medium':
427
				$this->cookieLifeTime = 7 * 86400;
428
				if ($iniSet) {
429
					ini_set('session.referer_check', $this->host);
430
				}
431
			break;
432
			case 'low':
433
			default:
434
				$this->cookieLifeTime = 788940000;
435
			break;
436
		}
437
 
438
		switch (Configure::read('Session.save')) {
439
			case 'cake':
440
				if (empty($_SESSION)) {
441
					if ($iniSet) {
442
						ini_set('session.use_trans_sid', 0);
443
						ini_set('url_rewriter.tags', '');
444
						ini_set('session.serialize_handler', 'php');
445
						ini_set('session.use_cookies', 1);
446
						ini_set('session.name', Configure::read('Session.cookie'));
447
						ini_set('session.cookie_lifetime', $this->cookieLifeTime);
448
						ini_set('session.cookie_path', $this->path);
449
						ini_set('session.auto_start', 0);
450
						ini_set('session.save_path', TMP . 'sessions');
451
					}
452
				}
453
			break;
454
			case 'database':
455
				if (empty($_SESSION)) {
456
					if (Configure::read('Session.table') === null) {
457
						trigger_error(__("You must set the all Configure::write('Session.*') in core.php to use database storage"), E_USER_WARNING);
458
						exit();
459
					} elseif (Configure::read('Session.database') === null) {
460
						Configure::write('Session.database', 'default');
461
					}
462
					if ($iniSet) {
463
						ini_set('session.use_trans_sid', 0);
464
						ini_set('url_rewriter.tags', '');
465
						ini_set('session.save_handler', 'user');
466
						ini_set('session.serialize_handler', 'php');
467
						ini_set('session.use_cookies', 1);
468
						ini_set('session.name', Configure::read('Session.cookie'));
469
						ini_set('session.cookie_lifetime', $this->cookieLifeTime);
470
						ini_set('session.cookie_path', $this->path);
471
						ini_set('session.auto_start', 0);
472
					}
473
				}
474
				session_set_save_handler(array('CakeSession','__open'),
475
													array('CakeSession', '__close'),
476
													array('CakeSession', '__read'),
477
													array('CakeSession', '__write'),
478
													array('CakeSession', '__destroy'),
479
													array('CakeSession', '__gc'));
480
			break;
481
			case 'php':
482
				if (empty($_SESSION)) {
483
					if ($iniSet) {
484
						ini_set('session.use_trans_sid', 0);
485
						ini_set('session.name', Configure::read('Session.cookie'));
486
						ini_set('session.cookie_lifetime', $this->cookieLifeTime);
487
						ini_set('session.cookie_path', $this->path);
488
					}
489
				}
490
			break;
491
			case 'cache':
492
				if (empty($_SESSION)) {
493
					if (!class_exists('Cache')) {
494
						uses('Cache');
495
					}
496
					if ($iniSet) {
497
						ini_set('session.use_trans_sid', 0);
498
						ini_set('url_rewriter.tags', '');
499
						ini_set('session.save_handler', 'user');
500
						ini_set('session.use_cookies', 1);
501
						ini_set('session.name', Configure::read('Session.cookie'));
502
						ini_set('session.cookie_lifetime', $this->cookieLifeTime);
503
						ini_set('session.cookie_path', $this->path);
504
					}
505
				}
506
				session_set_save_handler(array('CakeSession','__open'),
507
													array('CakeSession', '__close'),
508
													array('Cache', 'read'),
509
													array('Cache', 'write'),
510
													array('Cache', 'delete'),
511
													array('CakeSession', '__gc'));
512
			break;
513
			default:
514
				if (empty($_SESSION)) {
515
					$config = CONFIGS . Configure::read('Session.save') . '.php';
516
 
517
					if (is_file($config)) {
518
						require_once ($config);
519
					}
520
				}
521
			break;
522
		}
523
	}
524
/**
525
 * Helper method to start a session
526
 *
527
 * @access private
528
 */
529
	function __startSession() {
530
		if (headers_sent()) {
531
			if (empty($_SESSION)) {
532
				$_SESSION = array();
533
			}
534
			return false;
535
		} elseif (!isset($_SESSION)) {
536
			session_cache_limiter ("must-revalidate");
537
			session_start();
538
			header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
539
			return true;
540
		} else {
541
			session_start();
542
			return true;
543
		}
544
	}
545
/**
546
 * Helper method to create a new session.
547
 *
548
 * @return void
549
 * @access protected
550
 */
551
	function _checkValid() {
552
		if ($this->read('Config')) {
553
			if ((Configure::read('Session.checkAgent') === false || $this->_userAgent == $this->read('Config.userAgent')) && $this->time <= $this->read('Config.time')) {
554
				$time = $this->read('Config.time');
555
				$this->write('Config.time', $this->sessionTime);
556
 
557
				if (Configure::read('Security.level') === 'high') {
558
					$check = $this->read('Config.timeout');
559
					$check = $check - 1;
560
					$this->write('Config.timeout', $check);
561
 
562
					if (time() > ($time - (Security::inactiveMins() * Configure::read('Session.timeout')) + 2) || $check < 1) {
563
						$this->renew();
564
						$this->write('Config.timeout', 10);
565
					}
566
				}
567
				$this->valid = true;
568
			} else {
569
				$this->destroy();
570
				$this->valid = false;
571
				$this->__setError(1, 'Session Highjacking Attempted !!!');
572
			}
573
		} else {
574
			srand ((double)microtime() * 1000000);
575
			$this->write('Config.userAgent', $this->_userAgent);
576
			$this->write('Config.time', $this->sessionTime);
577
			$this->write('Config.rand', mt_rand());
578
			$this->write('Config.timeout', 10);
579
			$this->valid = true;
580
			$this->__setError(1, 'Session is valid');
581
		}
582
	}
583
/**
584
 * Helper method to restart a session.
585
 *
586
 * @return void
587
 * @access private
588
 */
589
	function __regenerateId() {
590
		$oldSessionId = session_id();
591
		if ($oldSessionId) {
592
			$sessionpath = session_save_path();
593
			if (empty($sessionpath)) {
594
				$sessionpath = "/tmp";
595
			}
596
			if (session_id() != "" || isset($_COOKIE[session_name()])) {
597
				setcookie(Configure::read('Session.cookie'), '', time() - 42000, $this->path);
598
			}
599
			session_regenerate_id(true);
600
			if (PHP_VERSION < 5.1) {
601
				$newSessid = session_id();
602
 
603
				if (function_exists('session_write_close')) {
604
					session_write_close();
605
				}
606
				$this->__initSession();
607
				session_id($oldSessionId);
608
				session_start();
609
				session_destroy();
610
				$file = $sessionpath . DS . "sess_$oldSessionId";
611
				@unlink($file);
612
				$this->__initSession();
613
				session_id($newSessid);
614
				session_start();
615
			}
616
		}
617
	}
618
/**
619
 * Restarts this session.
620
 *
621
 * @access public
622
 */
623
	function renew() {
624
		$this->__regenerateId();
625
	}
626
/**
627
 * Validate that the $name is in correct dot notation
628
 * example: $name = 'ControllerName.key';
629
 *
630
 * @param string $name Session key names as string.
631
 * @return mixed false is $name is not correct format, or $name if it is correct
632
 * @access private
633
 */
634
	function __validateKeys($name) {
635
		if (is_string($name) && preg_match("/^[ 0-9a-zA-Z._-]*$/", $name)) {
636
			return $name;
637
		}
638
		$this->__setError(3, "$name is not a string");
639
		return false;
640
	}
641
/**
642
 * Helper method to set an internal error message.
643
 *
644
 * @param integer $errorNumber Number of the error
645
 * @param string $errorMessage Description of the error
646
 * @return void
647
 * @access private
648
 */
649
	function __setError($errorNumber, $errorMessage) {
650
		if ($this->error === false) {
651
			$this->error = array();
652
		}
653
		$this->error[$errorNumber] = $errorMessage;
654
		$this->lastError = $errorNumber;
655
	}
656
/**
657
 * Method called on open of a database session.
658
 *
659
 * @return boolean Success
660
 * @access private
661
 */
662
	function __open() {
663
		return true;
664
	}
665
/**
666
 * Method called on close of a database session.
667
 *
668
 * @return boolean Success
669
 * @access private
670
 */
671
	function __close() {
672
		$probability = mt_rand(1, 150);
673
		if ($probability <= 3) {
674
			switch (Configure::read('Session.save')) {
675
				case 'cache':
676
					Cache::gc();
677
				break;
678
				default:
679
					CakeSession::__gc();
680
				break;
681
			}
682
		}
683
		return true;
684
	}
685
/**
686
 * Method used to read from a database session.
687
 *
688
 * @param mixed $key The key of the value to read
689
 * @return mixed The value of the key or false if it does not exist
690
 * @access private
691
 */
692
	function __read($key) {
693
		$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
694
		$table = $db->fullTableName(Configure::read('Session.table'), false);
695
		$row = $db->query("SELECT " . $db->name($table.'.data') . " FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key), false);
696
 
697
		if ($row && !isset($row[0][$table]) && isset($row[0][0])) {
698
			$table = 0;
699
		}
700
 
701
		if ($row && $row[0][$table]['data']) {
702
			return $row[0][$table]['data'];
703
		} else {
704
			return false;
705
		}
706
	}
707
/**
708
 * Helper function called on write for database sessions.
709
 *
710
 * @param mixed $key The name of the var
711
 * @param mixed $value The value of the var
712
 * @return boolean Success
713
 * @access private
714
 */
715
	function __write($key, $value) {
716
		$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
717
		$table = $db->fullTableName(Configure::read('Session.table'));
718
 
719
		switch (Configure::read('Security.level')) {
720
			case 'high':
721
				$factor = 10;
722
			break;
723
			case 'medium':
724
				$factor = 100;
725
			break;
726
			case 'low':
727
				$factor = 300;
728
			break;
729
			default:
730
				$factor = 10;
731
			break;
732
		}
733
		$expires = time() +  Configure::read('Session.timeout') * $factor;
734
		$row = $db->query("SELECT COUNT(id) AS count FROM " . $db->name($table) . " WHERE "
735
								 . $db->name('id') . " = "
736
								 . $db->value($key), false);
737
 
738
		if ($row[0][0]['count'] > 0) {
739
			$db->execute("UPDATE " . $db->name($table) . " SET " . $db->name('data') . " = "
740
								. $db->value($value) . ", " . $db->name('expires') . " = "
741
								. $db->value($expires) . " WHERE " . $db->name('id') . " = "
742
								. $db->value($key));
743
		} else {
744
			$db->execute("INSERT INTO " . $db->name($table) . " (" . $db->name('data') . ","
745
							  	. $db->name('expires') . "," . $db->name('id')
746
							  	. ") VALUES (" . $db->value($value) . ", " . $db->value($expires) . ", "
747
							  	. $db->value($key) . ")");
748
		}
749
		return true;
750
	}
751
/**
752
 * Method called on the destruction of a database session.
753
 *
754
 * @param integer $key Key that uniquely identifies session in database
755
 * @return boolean Success
756
 * @access private
757
 */
758
	function __destroy($key) {
759
		$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
760
		$table = $db->fullTableName(Configure::read('Session.table'));
761
		$db->execute("DELETE FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key));
762
		return true;
763
	}
764
/**
765
 * Helper function called on gc for database sessions.
766
 *
767
 * @param integer $expires Timestamp (defaults to current time)
768
 * @return boolean Success
769
 * @access private
770
 */
771
	function __gc($expires = null) {
772
		$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
773
		$table = $db->fullTableName(Configure::read('Session.table'));
774
		$db->execute("DELETE FROM " . $db->name($table) . " WHERE " . $db->name($table.'.expires') . " < ". $db->value(time()));
775
		return true;
776
	 }
777
}
778
?>