Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
/**
3
 * Session class for CakePHP.
4
 *
5
 * CakePHP abstracts the handling of sessions.
6
 * There are several convenient methods to access session information.
7
 * This class is the implementation of those methods.
8
 * They are mostly used by the Session Component.
9
 *
10
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
11
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
12
 *
13
 * Licensed under The MIT License
14
 * For full copyright and license information, please see the LICENSE.txt
15
 * Redistributions of files must retain the above copyright notice.
16
 *
17
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
18
 * @link          http://cakephp.org CakePHP(tm) Project
19
 * @package       Cake.Model.Datasource
20
 * @since         CakePHP(tm) v .0.10.0.1222
21
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
22
 */
23
 
24
App::uses('Hash', 'Utility');
25
App::uses('Security', 'Utility');
26
 
27
/**
28
 * Session class for CakePHP.
29
 *
30
 * CakePHP abstracts the handling of sessions. There are several convenient methods to access session information.
31
 * This class is the implementation of those methods. They are mostly used by the Session Component.
32
 *
33
 * @package       Cake.Model.Datasource
34
 */
35
class CakeSession {
36
 
37
/**
38
 * True if the Session is still valid
39
 *
40
 * @var boolean
41
 */
42
	public static $valid = false;
43
 
44
/**
45
 * Error messages for this session
46
 *
47
 * @var array
48
 */
49
	public static $error = false;
50
 
51
/**
52
 * User agent string
53
 *
54
 * @var string
55
 */
56
	protected static $_userAgent = '';
57
 
58
/**
59
 * Path to where the session is active.
60
 *
61
 * @var string
62
 */
63
	public static $path = '/';
64
 
65
/**
66
 * Error number of last occurred error
67
 *
68
 * @var integer
69
 */
70
	public static $lastError = null;
71
 
72
/**
73
 * Start time for this session.
74
 *
75
 * @var integer
76
 */
77
	public static $time = false;
78
 
79
/**
80
 * Cookie lifetime
81
 *
82
 * @var integer
83
 */
84
	public static $cookieLifeTime;
85
 
86
/**
87
 * Time when this session becomes invalid.
88
 *
89
 * @var integer
90
 */
91
	public static $sessionTime = false;
92
 
93
/**
94
 * Current Session id
95
 *
96
 * @var string
97
 */
98
	public static $id = null;
99
 
100
/**
101
 * Hostname
102
 *
103
 * @var string
104
 */
105
	public static $host = null;
106
 
107
/**
108
 * Session timeout multiplier factor
109
 *
110
 * @var integer
111
 */
112
	public static $timeout = null;
113
 
114
/**
115
 * Number of requests that can occur during a session time without the session being renewed.
116
 * This feature is only used when config value `Session.autoRegenerate` is set to true.
117
 *
118
 * @var integer
119
 * @see CakeSession::_checkValid()
120
 */
121
	public static $requestCountdown = 10;
122
 
123
/**
124
 * Whether or not the init function in this class was already called
125
 *
126
 * @var boolean
127
 */
128
	protected static $_initialized = false;
129
 
130
/**
131
 * Pseudo constructor.
132
 *
133
 * @param string $base The base path for the Session
134
 * @return void
135
 */
136
	public static function init($base = null) {
137
		self::$time = time();
138
		$checkAgent = Configure::read('Session.checkAgent');
139
 
140
		if (env('HTTP_USER_AGENT')) {
141
			self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
142
		}
143
 
144
		self::_setPath($base);
145
		self::_setHost(env('HTTP_HOST'));
146
 
147
		if (!self::$_initialized) {
148
			register_shutdown_function('session_write_close');
149
		}
150
 
151
		self::$_initialized = true;
152
	}
153
 
154
/**
155
 * Setup the Path variable
156
 *
157
 * @param string $base base path
158
 * @return void
159
 */
160
	protected static function _setPath($base = null) {
161
		if (empty($base)) {
162
			self::$path = '/';
163
			return;
164
		}
165
		if (strpos($base, 'index.php') !== false) {
166
			$base = str_replace('index.php', '', $base);
167
		}
168
		if (strpos($base, '?') !== false) {
169
			$base = str_replace('?', '', $base);
170
		}
171
		self::$path = $base;
172
	}
173
 
174
/**
175
 * Set the host name
176
 *
177
 * @param string $host Hostname
178
 * @return void
179
 */
180
	protected static function _setHost($host) {
181
		self::$host = $host;
182
		if (strpos(self::$host, ':') !== false) {
183
			self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
184
		}
185
	}
186
 
187
/**
188
 * Starts the Session.
189
 *
190
 * @return boolean True if session was started
191
 */
192
	public static function start() {
193
		if (self::started()) {
194
			return true;
195
		}
196
 
197
		$id = self::id();
198
		self::_startSession();
199
 
200
		if (!$id && self::started()) {
201
			self::_checkValid();
202
		}
203
 
204
		self::$error = false;
205
		self::$valid = true;
206
		return self::started();
207
	}
208
 
209
/**
210
 * Determine if Session has been started.
211
 *
212
 * @return boolean True if session has been started.
213
 */
214
	public static function started() {
215
		return isset($_SESSION) && session_id();
216
	}
217
 
218
/**
219
 * Returns true if given variable is set in session.
220
 *
221
 * @param string $name Variable name to check for
222
 * @return boolean True if variable is there
223
 */
224
	public static function check($name = null) {
225
		if (!self::start()) {
226
			return false;
227
		}
228
		if (empty($name)) {
229
			return false;
230
		}
231
		return Hash::get($_SESSION, $name) !== null;
232
	}
233
 
234
/**
235
 * Returns the session id.
236
 * Calling this method will not auto start the session. You might have to manually
237
 * assert a started session.
238
 *
239
 * Passing an id into it, you can also replace the session id if the session
240
 * has not already been started.
241
 * Note that depending on the session handler, not all characters are allowed
242
 * within the session id. For example, the file session handler only allows
243
 * characters in the range a-z A-Z 0-9 , (comma) and - (minus).
244
 *
245
 * @param string $id Id to replace the current session id
246
 * @return string Session id
247
 */
248
	public static function id($id = null) {
249
		if ($id) {
250
			self::$id = $id;
251
			session_id(self::$id);
252
		}
253
		if (self::started()) {
254
			return session_id();
255
		}
256
		return self::$id;
257
	}
258
 
259
/**
260
 * Removes a variable from session.
261
 *
262
 * @param string $name Session variable to remove
263
 * @return boolean Success
264
 */
265
	public static function delete($name) {
266
		if (self::check($name)) {
267
			self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
268
			return !self::check($name);
269
		}
270
		return false;
271
	}
272
 
273
/**
274
 * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
275
 *
276
 * @param array $old Set of old variables => values
277
 * @param array $new New set of variable => value
278
 * @return void
279
 */
280
	protected static function _overwrite(&$old, $new) {
281
		if (!empty($old)) {
282
			foreach ($old as $key => $var) {
283
				if (!isset($new[$key])) {
284
					unset($old[$key]);
285
				}
286
			}
287
		}
288
		foreach ($new as $key => $var) {
289
			$old[$key] = $var;
290
		}
291
	}
292
 
293
/**
294
 * Return error description for given error number.
295
 *
296
 * @param integer $errorNumber Error to set
297
 * @return string Error as string
298
 */
299
	protected static function _error($errorNumber) {
300
		if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
301
			return false;
302
		}
303
		return self::$error[$errorNumber];
304
	}
305
 
306
/**
307
 * Returns last occurred error as a string, if any.
308
 *
309
 * @return mixed Error description as a string, or false.
310
 */
311
	public static function error() {
312
		if (self::$lastError) {
313
			return self::_error(self::$lastError);
314
		}
315
		return false;
316
	}
317
 
318
/**
319
 * Returns true if session is valid.
320
 *
321
 * @return boolean Success
322
 */
323
	public static function valid() {
324
		if (self::read('Config')) {
325
			if (self::_validAgentAndTime() && self::$error === false) {
326
				self::$valid = true;
327
			} else {
328
				self::$valid = false;
329
				self::_setError(1, 'Session Highjacking Attempted !!!');
330
			}
331
		}
332
		return self::$valid;
333
	}
334
 
335
/**
336
 * Tests that the user agent is valid and that the session hasn't 'timed out'.
337
 * Since timeouts are implemented in CakeSession it checks the current self::$time
338
 * against the time the session is set to expire. The User agent is only checked
339
 * if Session.checkAgent == true.
340
 *
341
 * @return boolean
342
 */
343
	protected static function _validAgentAndTime() {
344
		$config = self::read('Config');
345
		$validAgent = (
346
			Configure::read('Session.checkAgent') === false ||
347
			self::$_userAgent == $config['userAgent']
348
		);
349
		return ($validAgent && self::$time <= $config['time']);
350
	}
351
 
352
/**
353
 * Get / Set the user agent
354
 *
355
 * @param string $userAgent Set the user agent
356
 * @return string Current user agent
357
 */
358
	public static function userAgent($userAgent = null) {
359
		if ($userAgent) {
360
			self::$_userAgent = $userAgent;
361
		}
362
		if (empty(self::$_userAgent)) {
363
			CakeSession::init(self::$path);
364
		}
365
		return self::$_userAgent;
366
	}
367
 
368
/**
369
 * Returns given session variable, or all of them, if no parameters given.
370
 *
371
 * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
372
 * @return mixed The value of the session variable
373
 */
374
	public static function read($name = null) {
375
		if (!self::start()) {
376
			return false;
377
		}
378
		if ($name === null) {
379
			return self::_returnSessionVars();
380
		}
381
		if (empty($name)) {
382
			return false;
383
		}
384
		$result = Hash::get($_SESSION, $name);
385
 
386
		if (isset($result)) {
387
			return $result;
388
		}
389
		return null;
390
	}
391
 
392
/**
393
 * Returns all session variables.
394
 *
395
 * @return mixed Full $_SESSION array, or false on error.
396
 */
397
	protected static function _returnSessionVars() {
398
		if (!empty($_SESSION)) {
399
			return $_SESSION;
400
		}
401
		self::_setError(2, 'No Session vars set');
402
		return false;
403
	}
404
 
405
/**
406
 * Writes value to given session variable name.
407
 *
408
 * @param string|array $name Name of variable
409
 * @param string $value Value to write
410
 * @return boolean True if the write was successful, false if the write failed
411
 */
412
	public static function write($name, $value = null) {
413
		if (!self::start()) {
414
			return false;
415
		}
416
		if (empty($name)) {
417
			return false;
418
		}
419
		$write = $name;
420
		if (!is_array($name)) {
421
			$write = array($name => $value);
422
		}
423
		foreach ($write as $key => $val) {
424
			self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
425
			if (Hash::get($_SESSION, $key) !== $val) {
426
				return false;
427
			}
428
		}
429
		return true;
430
	}
431
 
432
/**
433
 * Helper method to destroy invalid sessions.
434
 *
435
 * @return void
436
 */
437
	public static function destroy() {
438
		if (!self::started()) {
439
			self::_startSession();
440
		}
441
 
442
		session_destroy();
443
 
444
		$_SESSION = null;
445
		self::$id = null;
446
	}
447
 
448
/**
449
 * Clears the session, the session id, and renews the session.
450
 *
451
 * @return void
452
 */
453
	public static function clear() {
454
		$_SESSION = null;
455
		self::$id = null;
456
		self::renew();
457
	}
458
 
459
/**
460
 * Helper method to initialize a session, based on CakePHP core settings.
461
 *
462
 * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
463
 *
464
 * @return void
465
 * @throws CakeSessionException Throws exceptions when ini_set() fails.
466
 */
467
	protected static function _configureSession() {
468
		$sessionConfig = Configure::read('Session');
469
 
470
		if (isset($sessionConfig['defaults'])) {
471
			$defaults = self::_defaultConfig($sessionConfig['defaults']);
472
			if ($defaults) {
473
				$sessionConfig = Hash::merge($defaults, $sessionConfig);
474
			}
475
		}
476
		if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
477
			$sessionConfig['ini']['session.cookie_secure'] = 1;
478
		}
479
		if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
480
			$sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
481
		}
482
		if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
483
			$sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
484
		}
485
		if (!isset($sessionConfig['ini']['session.name'])) {
486
			$sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
487
		}
488
		if (!empty($sessionConfig['handler'])) {
489
			$sessionConfig['ini']['session.save_handler'] = 'user';
490
		}
491
		if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
492
			$sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
493
		}
494
		if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
495
			$sessionConfig['ini']['session.cookie_httponly'] = 1;
496
		}
497
 
498
		if (empty($_SESSION)) {
499
			if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
500
				foreach ($sessionConfig['ini'] as $setting => $value) {
501
					if (ini_set($setting, $value) === false) {
502
						throw new CakeSessionException(__d('cake_dev', 'Unable to configure the session, setting %s failed.', $setting));
503
					}
504
				}
505
			}
506
		}
507
		if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
508
			call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
509
		}
510
		if (!empty($sessionConfig['handler']['engine'])) {
511
			$handler = self::_getHandler($sessionConfig['handler']['engine']);
512
			session_set_save_handler(
513
				array($handler, 'open'),
514
				array($handler, 'close'),
515
				array($handler, 'read'),
516
				array($handler, 'write'),
517
				array($handler, 'destroy'),
518
				array($handler, 'gc')
519
			);
520
		}
521
		Configure::write('Session', $sessionConfig);
522
		self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
523
	}
524
 
525
/**
526
 * Find the handler class and make sure it implements the correct interface.
527
 *
528
 * @param string $handler
529
 * @return void
530
 * @throws CakeSessionException
531
 */
532
	protected static function _getHandler($handler) {
533
		list($plugin, $class) = pluginSplit($handler, true);
534
		App::uses($class, $plugin . 'Model/Datasource/Session');
535
		if (!class_exists($class)) {
536
			throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
537
		}
538
		$handler = new $class();
539
		if ($handler instanceof CakeSessionHandlerInterface) {
540
			return $handler;
541
		}
542
		throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
543
	}
544
 
545
/**
546
 * Get one of the prebaked default session configurations.
547
 *
548
 * @param string $name
549
 * @return boolean|array
550
 */
551
	protected static function _defaultConfig($name) {
552
		$defaults = array(
553
			'php' => array(
554
				'cookie' => 'CAKEPHP',
555
				'timeout' => 240,
556
				'ini' => array(
557
					'session.use_trans_sid' => 0,
558
					'session.cookie_path' => self::$path
559
				)
560
			),
561
			'cake' => array(
562
				'cookie' => 'CAKEPHP',
563
				'timeout' => 240,
564
				'ini' => array(
565
					'session.use_trans_sid' => 0,
566
					'url_rewriter.tags' => '',
567
					'session.serialize_handler' => 'php',
568
					'session.use_cookies' => 1,
569
					'session.cookie_path' => self::$path,
570
					'session.save_path' => TMP . 'sessions',
571
					'session.save_handler' => 'files'
572
				)
573
			),
574
			'cache' => array(
575
				'cookie' => 'CAKEPHP',
576
				'timeout' => 240,
577
				'ini' => array(
578
					'session.use_trans_sid' => 0,
579
					'url_rewriter.tags' => '',
580
					'session.use_cookies' => 1,
581
					'session.cookie_path' => self::$path,
582
					'session.save_handler' => 'user',
583
				),
584
				'handler' => array(
585
					'engine' => 'CacheSession',
586
					'config' => 'default'
587
				)
588
			),
589
			'database' => array(
590
				'cookie' => 'CAKEPHP',
591
				'timeout' => 240,
592
				'ini' => array(
593
					'session.use_trans_sid' => 0,
594
					'url_rewriter.tags' => '',
595
					'session.use_cookies' => 1,
596
					'session.cookie_path' => self::$path,
597
					'session.save_handler' => 'user',
598
					'session.serialize_handler' => 'php',
599
				),
600
				'handler' => array(
601
					'engine' => 'DatabaseSession',
602
					'model' => 'Session'
603
				)
604
			)
605
		);
606
		if (isset($defaults[$name])) {
607
			return $defaults[$name];
608
		}
609
		return false;
610
	}
611
 
612
/**
613
 * Helper method to start a session
614
 *
615
 * @return boolean Success
616
 */
617
	protected static function _startSession() {
618
		self::init();
619
		session_write_close();
620
		self::_configureSession();
621
 
622
		if (headers_sent()) {
623
			if (empty($_SESSION)) {
624
				$_SESSION = array();
625
			}
626
		} else {
627
			// For IE<=8
628
			session_cache_limiter("must-revalidate");
629
			session_start();
630
		}
631
		return true;
632
	}
633
 
634
/**
635
 * Helper method to create a new session.
636
 *
637
 * @return void
638
 */
639
	protected static function _checkValid() {
640
		$config = self::read('Config');
641
		if ($config) {
642
			$sessionConfig = Configure::read('Session');
643
 
644
			if (self::valid()) {
645
				self::write('Config.time', self::$sessionTime);
646
				if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
647
					$check = $config['countdown'];
648
					$check -= 1;
649
					self::write('Config.countdown', $check);
650
 
651
					if ($check < 1) {
652
						self::renew();
653
						self::write('Config.countdown', self::$requestCountdown);
654
					}
655
				}
656
			} else {
657
				$_SESSION = array();
658
				self::destroy();
659
				self::_setError(1, 'Session Highjacking Attempted !!!');
660
				self::_startSession();
661
				self::_writeConfig();
662
			}
663
		} else {
664
			self::_writeConfig();
665
		}
666
	}
667
 
668
/**
669
 * Writes configuration variables to the session
670
 *
671
 * @return void
672
 */
673
	protected static function _writeConfig() {
674
		self::write('Config.userAgent', self::$_userAgent);
675
		self::write('Config.time', self::$sessionTime);
676
		self::write('Config.countdown', self::$requestCountdown);
677
	}
678
 
679
/**
680
 * Restarts this session.
681
 *
682
 * @return void
683
 */
684
	public static function renew() {
685
		if (session_id()) {
686
			if (session_id() || isset($_COOKIE[session_name()])) {
687
				setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
688
			}
689
			session_regenerate_id(true);
690
		}
691
	}
692
 
693
/**
694
 * Helper method to set an internal error message.
695
 *
696
 * @param integer $errorNumber Number of the error
697
 * @param string $errorMessage Description of the error
698
 * @return void
699
 */
700
	protected static function _setError($errorNumber, $errorMessage) {
701
		if (self::$error === false) {
702
			self::$error = array();
703
		}
704
		self::$error[$errorNumber] = $errorMessage;
705
		self::$lastError = $errorNumber;
706
	}
707
 
708
}