Session.php 20.8 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8 9
namespace yii\web;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11 12 13
use yii\base\Component;
use yii\base\InvalidParamException;

Qiang Xue committed
14
/**
Qiang Xue committed
15
 * Session provides session data management and the related configurations.
Qiang Xue committed
16
 *
Qiang Xue committed
17 18
 * Session is a Web application component that can be accessed via `Yii::$app->session`.

Qiang Xue committed
19 20
 * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
 * To destroy the session, call [[destroy()]].
Qiang Xue committed
21
 *
Qiang Xue committed
22 23
 * By default, [[autoStart]] is true which means the session will be started automatically
 * when the session component is accessed the first time.
Qiang Xue committed
24
 *
Qiang Xue committed
25
 * Session can be used like an array to set and get session data. For example,
Qiang Xue committed
26
 *
Qiang Xue committed
27 28 29 30 31 32 33 34
 * ~~~
 * $session = new Session;
 * $session->open();
 * $value1 = $session['name1'];  // get session variable 'name1'
 * $value2 = $session['name2'];  // get session variable 'name2'
 * foreach ($session as $name => $value) // traverse all session variables
 * $session['name3'] = $value3;  // set session variable 'name3'
 * ~~~
Qiang Xue committed
35
 *
Qiang Xue committed
36
 * Session can be extended to support customized session storage.
Qiang Xue committed
37 38 39 40
 * To do so, override [[useCustomStorage()]] so that it returns true, and
 * override these methods with the actual logic about using custom storage:
 * [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
 * [[destroySession()]] and [[gcSession()]].
Qiang Xue committed
41
 *
Qiang Xue committed
42 43 44 45 46
 * Session also supports a special type of session data, called *flash messages*.
 * A flash message is available only in the current request and the next request.
 * After that, it will be deleted automatically. Flash messages are particularly
 * useful for displaying confirmation messages. To use flash messages, simply
 * call methods such as [[setFlash()]], [[getFlash()]].
Qiang Xue committed
47
 *
48
 * @property array $allFlashes Flash messages (key => message). This property is read-only.
49
 * @property array $cookieParams The session cookie parameters.
50 51 52 53 54 55
 * @property integer $count The number of session variables. This property is read-only.
 * @property string $flash The key identifying the flash message. Note that flash messages and normal session
 * variables share the same name space. If you have a normal session variable using the same name, its value will
 * be overwritten by this method. This property is write-only.
 * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
 * started on every session initialization, defaults to 1 meaning 1% chance.
56
 * @property string $id The current session ID.
57 58 59
 * @property boolean $isActive Whether the session has started. This property is read-only.
 * @property SessionIterator $iterator An iterator for traversing the session variables. This property is
 * read-only.
60
 * @property string $name The current session name.
61 62 63
 * @property string $savePath The current session save path, defaults to '/tmp'.
 * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up.
 * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
64 65 66 67 68
 * @property boolean|null $useCookies The value indicating whether cookies should be used to store session
 * IDs.
 * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only.
 * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to
 * false.
69
 *
Qiang Xue committed
70
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
71
 * @since 2.0
Qiang Xue committed
72
 */
Qiang Xue committed
73
class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
Qiang Xue committed
74 75
{
	/**
Qiang Xue committed
76
	 * @var boolean whether the session should be automatically started when the session component is initialized.
Qiang Xue committed
77
	 */
Qiang Xue committed
78
	public $autoStart = true;
Qiang Xue committed
79 80 81 82
	/**
	 * @var string the name of the session variable that stores the flash message data.
	 */
	public $flashVar = '__flash';
Qiang Xue committed
83

84 85 86
	/**
	 * @var array parameter-value pairs to override default session cookie parameters
	 */
Alexander Makarov committed
87
	public $cookieParams = ['httpOnly' => true];
88

Qiang Xue committed
89 90 91 92 93 94 95
	/**
	 * Initializes the application component.
	 * This method is required by IApplicationComponent and is invoked by application.
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
96
		if ($this->autoStart) {
Qiang Xue committed
97
			$this->open();
Qiang Xue committed
98
		}
Alexander Makarov committed
99
		register_shutdown_function([$this, 'close']);
Qiang Xue committed
100 101 102 103
	}

	/**
	 * Returns a value indicating whether to use custom session storage.
Qiang Xue committed
104 105 106
	 * This method should be overridden to return true by child classes that implement custom session storage.
	 * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
	 * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
Qiang Xue committed
107 108 109 110 111 112 113
	 * @return boolean whether to use custom storage.
	 */
	public function getUseCustomStorage()
	{
		return false;
	}

Qiang Xue committed
114 115
	private $_opened = false;

Qiang Xue committed
116
	/**
Qiang Xue committed
117
	 * Starts the session.
Qiang Xue committed
118 119 120
	 */
	public function open()
	{
Qiang Xue committed
121 122 123
		// this is available in PHP 5.4.0+
		if (function_exists('session_status')) {
			if (session_status() == PHP_SESSION_ACTIVE) {
Qiang Xue committed
124
				$this->_opened = true;
Qiang Xue committed
125 126 127 128
				return;
			}
		}

Qiang Xue committed
129 130 131
		if (!$this->_opened) {
			if ($this->getUseCustomStorage()) {
				@session_set_save_handler(
Alexander Makarov committed
132 133 134 135 136 137
					[$this, 'openSession'],
					[$this, 'closeSession'],
					[$this, 'readSession'],
					[$this, 'writeSession'],
					[$this, 'destroySession'],
					[$this, 'gcSession']
Qiang Xue committed
138 139
				);
			}
Qiang Xue committed
140

141 142
			$this->setCookieParams($this->cookieParams);

Qiang Xue committed
143
			@session_start();
Qiang Xue committed
144

Qiang Xue committed
145 146 147 148
			if (session_id() == '') {
				$this->_opened = false;
				$error = error_get_last();
				$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
149
				Yii::error($message, __METHOD__);
Qiang Xue committed
150 151 152 153
			} else {
				$this->_opened = true;
				$this->updateFlashCounters();
			}
Qiang Xue committed
154 155 156 157 158 159 160 161
		}
	}

	/**
	 * Ends the current session and store session data.
	 */
	public function close()
	{
Qiang Xue committed
162
		$this->_opened = false;
Qiang Xue committed
163
		if (session_id() !== '') {
Qiang Xue committed
164
			@session_write_close();
Qiang Xue committed
165
		}
Qiang Xue committed
166 167 168 169 170 171 172
	}

	/**
	 * Frees all session variables and destroys all data registered to a session.
	 */
	public function destroy()
	{
Qiang Xue committed
173
		if (session_id() !== '') {
Qiang Xue committed
174 175 176 177 178 179 180 181
			@session_unset();
			@session_destroy();
		}
	}

	/**
	 * @return boolean whether the session has started
	 */
Qiang Xue committed
182
	public function getIsActive()
Qiang Xue committed
183
	{
Qiang Xue committed
184 185 186 187 188
		if (function_exists('session_status')) {
			// available in PHP 5.4.0+
			return session_status() == PHP_SESSION_ACTIVE;
		} else {
			// this is not very reliable
Qiang Xue committed
189
			return $this->_opened && session_id() !== '';
Qiang Xue committed
190
		}
Qiang Xue committed
191 192 193 194 195
	}

	/**
	 * @return string the current session ID
	 */
Qiang Xue committed
196
	public function getId()
Qiang Xue committed
197 198 199 200 201 202 203
	{
		return session_id();
	}

	/**
	 * @param string $value the session ID for the current session
	 */
Qiang Xue committed
204
	public function setId($value)
Qiang Xue committed
205 206 207 208 209
	{
		session_id($value);
	}

	/**
Qiang Xue committed
210 211
	 * Updates the current session ID with a newly generated one .
	 * Please refer to [[http://php.net/session_regenerate_id]] for more details.
Qiang Xue committed
212 213
	 * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
	 */
Qiang Xue committed
214
	public function regenerateID($deleteOldSession = false)
Qiang Xue committed
215 216 217 218 219 220 221
	{
		session_regenerate_id($deleteOldSession);
	}

	/**
	 * @return string the current session name
	 */
Qiang Xue committed
222
	public function getName()
Qiang Xue committed
223 224 225 226 227
	{
		return session_name();
	}

	/**
Qiang Xue committed
228 229
	 * @param string $value the session name for the current session, must be an alphanumeric string.
	 * It defaults to "PHPSESSID".
Qiang Xue committed
230
	 */
Qiang Xue committed
231
	public function setName($value)
Qiang Xue committed
232 233 234 235 236 237 238 239 240 241 242 243 244
	{
		session_name($value);
	}

	/**
	 * @return string the current session save path, defaults to '/tmp'.
	 */
	public function getSavePath()
	{
		return session_save_path();
	}

	/**
Qiang Xue committed
245 246
	 * @param string $value the current session save path. This can be either a directory name or a path alias.
	 * @throws InvalidParamException if the path is not a valid directory
Qiang Xue committed
247 248 249
	 */
	public function setSavePath($value)
	{
Qiang Xue committed
250
		$path = Yii::getAlias($value);
Qiang Xue committed
251
		if (is_dir($path)) {
Qiang Xue committed
252
			session_save_path($path);
Qiang Xue committed
253
		} else {
Qiang Xue committed
254
			throw new InvalidParamException("Session save path is not a valid directory: $value");
Qiang Xue committed
255
		}
Qiang Xue committed
256 257 258 259 260 261 262 263
	}

	/**
	 * @return array the session cookie parameters.
	 * @see http://us2.php.net/manual/en/function.session-get-cookie-params.php
	 */
	public function getCookieParams()
	{
Qiang Xue committed
264 265 266 267 268 269
		$params = session_get_cookie_params();
		if (isset($params['httponly'])) {
			$params['httpOnly'] = $params['httponly'];
			unset($params['httponly']);
		}
		return $params;
Qiang Xue committed
270 271 272 273 274 275
	}

	/**
	 * Sets the session cookie parameters.
	 * The effect of this method only lasts for the duration of the script.
	 * Call this method before the session starts.
Qiang Xue committed
276
	 * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httpOnly`.
Qiang Xue committed
277
	 * @throws InvalidParamException if the parameters are incomplete.
Qiang Xue committed
278 279 280 281
	 * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
	 */
	public function setCookieParams($value)
	{
Qiang Xue committed
282
		$data = $this->getCookieParams();
Qiang Xue committed
283 284
		extract($data);
		extract($value);
Qiang Xue committed
285 286
		if (isset($lifetime, $path, $domain, $secure, $httpOnly)) {
			session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly);
Qiang Xue committed
287
		} else {
Qiang Xue committed
288
			throw new InvalidParamException('Please make sure these parameters are provided: lifetime, path, domain, secure and httpOnly.');
Qiang Xue committed
289
		}
Qiang Xue committed
290 291 292
	}

	/**
Qiang Xue committed
293 294 295
	 * Returns the value indicating whether cookies should be used to store session IDs.
	 * @return boolean|null the value indicating whether cookies should be used to store session IDs.
	 * @see setUseCookies()
Qiang Xue committed
296
	 */
Qiang Xue committed
297
	public function getUseCookies()
Qiang Xue committed
298
	{
Qiang Xue committed
299
		if (ini_get('session.use_cookies') === '0') {
Qiang Xue committed
300 301 302
			return false;
		} elseif (ini_get('session.use_only_cookies') === '1') {
			return true;
Qiang Xue committed
303
		} else {
Qiang Xue committed
304
			return null;
Qiang Xue committed
305
		}
Qiang Xue committed
306 307 308
	}

	/**
Qiang Xue committed
309 310 311 312 313 314 315 316
	 * Sets the value indicating whether cookies should be used to store session IDs.
	 * Three states are possible:
	 *
	 * - true: cookies and only cookies will be used to store session IDs.
	 * - false: cookies will not be used to store session IDs.
	 * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
	 *
	 * @param boolean|null $value the value indicating whether cookies should be used to store session IDs.
Qiang Xue committed
317
	 */
Qiang Xue committed
318
	public function setUseCookies($value)
Qiang Xue committed
319
	{
Qiang Xue committed
320
		if ($value === false) {
Qiang Xue committed
321 322
			ini_set('session.use_cookies', '0');
			ini_set('session.use_only_cookies', '0');
Qiang Xue committed
323 324 325
		} elseif ($value === true) {
			ini_set('session.use_cookies', '1');
			ini_set('session.use_only_cookies', '1');
Qiang Xue committed
326
		} else {
Qiang Xue committed
327 328
			ini_set('session.use_cookies', '1');
			ini_set('session.use_only_cookies', '0');
Qiang Xue committed
329 330 331 332
		}
	}

	/**
Qiang Xue committed
333
	 * @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
Qiang Xue committed
334 335 336
	 */
	public function getGCProbability()
	{
Qiang Xue committed
337
		return (float)(ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
Qiang Xue committed
338 339 340
	}

	/**
Qiang Xue committed
341 342
	 * @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
	 * @throws InvalidParamException if the value is not between 0 and 100.
Qiang Xue committed
343 344 345
	 */
	public function setGCProbability($value)
	{
Qiang Xue committed
346
		if ($value >= 0 && $value <= 100) {
Qiang Xue committed
347 348 349
			// percent * 21474837 / 2147483647 ≈ percent * 0.01
			ini_set('session.gc_probability', floor($value * 21474836.47));
			ini_set('session.gc_divisor', 2147483647);
Qiang Xue committed
350
		} else {
Qiang Xue committed
351
			throw new InvalidParamException('GCProbability must be a value between 0 and 100.');
Qiang Xue committed
352
		}
Qiang Xue committed
353 354 355 356 357 358 359
	}

	/**
	 * @return boolean whether transparent sid support is enabled or not, defaults to false.
	 */
	public function getUseTransparentSessionID()
	{
Qiang Xue committed
360
		return ini_get('session.use_trans_sid') == 1;
Qiang Xue committed
361 362 363 364 365 366 367
	}

	/**
	 * @param boolean $value whether transparent sid support is enabled or not.
	 */
	public function setUseTransparentSessionID($value)
	{
Qiang Xue committed
368
		ini_set('session.use_trans_sid', $value ? '1' : '0');
Qiang Xue committed
369 370 371
	}

	/**
Qiang Xue committed
372 373
	 * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up.
	 * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
Qiang Xue committed
374 375 376 377 378 379 380 381 382 383 384
	 */
	public function getTimeout()
	{
		return (int)ini_get('session.gc_maxlifetime');
	}

	/**
	 * @param integer $value the number of seconds after which data will be seen as 'garbage' and cleaned up
	 */
	public function setTimeout($value)
	{
Qiang Xue committed
385
		ini_set('session.gc_maxlifetime', $value);
Qiang Xue committed
386 387 388 389
	}

	/**
	 * Session open handler.
Qiang Xue committed
390
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
391 392 393 394 395
	 * Do not call this method directly.
	 * @param string $savePath session save path
	 * @param string $sessionName session name
	 * @return boolean whether session is opened successfully
	 */
Qiang Xue committed
396
	public function openSession($savePath, $sessionName)
Qiang Xue committed
397 398 399 400 401 402
	{
		return true;
	}

	/**
	 * Session close handler.
Qiang Xue committed
403
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
404 405 406 407 408 409 410 411 412 413
	 * Do not call this method directly.
	 * @return boolean whether session is closed successfully
	 */
	public function closeSession()
	{
		return true;
	}

	/**
	 * Session read handler.
Qiang Xue committed
414
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
415 416 417 418 419 420 421 422 423 424 425
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @return string the session data
	 */
	public function readSession($id)
	{
		return '';
	}

	/**
	 * Session write handler.
Qiang Xue committed
426
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
427 428 429 430 431
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @param string $data session data
	 * @return boolean whether session write is successful
	 */
Qiang Xue committed
432
	public function writeSession($id, $data)
Qiang Xue committed
433 434 435 436 437 438
	{
		return true;
	}

	/**
	 * Session destroy handler.
Qiang Xue committed
439
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
440 441 442 443 444 445 446 447 448 449 450
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @return boolean whether session is destroyed successfully
	 */
	public function destroySession($id)
	{
		return true;
	}

	/**
	 * Session GC (garbage collection) handler.
Qiang Xue committed
451
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
452 453 454 455 456 457 458 459 460 461 462 463
	 * Do not call this method directly.
	 * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
	 * @return boolean whether session is GCed successfully
	 */
	public function gcSession($maxLifetime)
	{
		return true;
	}

	/**
	 * Returns an iterator for traversing the session variables.
	 * This method is required by the interface IteratorAggregate.
Qiang Xue committed
464
	 * @return SessionIterator an iterator for traversing the session variables.
Qiang Xue committed
465 466 467
	 */
	public function getIterator()
	{
Qiang Xue committed
468
		return new SessionIterator;
Qiang Xue committed
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
	}

	/**
	 * Returns the number of items in the session.
	 * @return integer the number of session variables
	 */
	public function getCount()
	{
		return count($_SESSION);
	}

	/**
	 * Returns the number of items in the session.
	 * This method is required by Countable interface.
	 * @return integer number of items in the session.
	 */
	public function count()
	{
		return $this->getCount();
	}

	/**
	 * Returns the session variable value with the session variable name.
Qiang Xue committed
492 493
	 * If the session variable does not exist, the `$defaultValue` will be returned.
	 * @param string $key the session variable name
Qiang Xue committed
494 495 496
	 * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
	 * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
	 */
Qiang Xue committed
497
	public function get($key, $defaultValue = null)
Qiang Xue committed
498 499 500 501 502 503
	{
		return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
	}

	/**
	 * Adds a session variable.
Qiang Xue committed
504 505
	 * If the specified name already exists, the old value will be overwritten.
	 * @param string $key session variable name
Qiang Xue committed
506 507
	 * @param mixed $value session variable value
	 */
Qiang Xue committed
508
	public function set($key, $value)
Qiang Xue committed
509
	{
Qiang Xue committed
510
		$_SESSION[$key] = $value;
Qiang Xue committed
511 512 513 514
	}

	/**
	 * Removes a session variable.
Qiang Xue committed
515
	 * @param string $key the name of the session variable to be removed
Qiang Xue committed
516 517 518 519
	 * @return mixed the removed value, null if no such session variable.
	 */
	public function remove($key)
	{
Qiang Xue committed
520 521
		if (isset($_SESSION[$key])) {
			$value = $_SESSION[$key];
Qiang Xue committed
522 523
			unset($_SESSION[$key]);
			return $value;
Qiang Xue committed
524
		} else {
Qiang Xue committed
525
			return null;
Qiang Xue committed
526
		}
Qiang Xue committed
527 528 529 530 531
	}

	/**
	 * Removes all session variables
	 */
Qiang Xue committed
532
	public function removeAll()
Qiang Xue committed
533
	{
Qiang Xue committed
534
		foreach (array_keys($_SESSION) as $key) {
Qiang Xue committed
535
			unset($_SESSION[$key]);
Qiang Xue committed
536
		}
Qiang Xue committed
537 538 539 540 541 542
	}

	/**
	 * @param mixed $key session variable name
	 * @return boolean whether there is the named session variable
	 */
Qiang Xue committed
543
	public function has($key)
Qiang Xue committed
544 545 546 547 548 549 550 551 552 553 554 555
	{
		return isset($_SESSION[$key]);
	}

	/**
	 * @return array the list of all session variables in array
	 */
	public function toArray()
	{
		return $_SESSION;
	}

Qiang Xue committed
556 557 558 559 560 561
	/**
	 * Updates the counters for flash messages and removes outdated flash messages.
	 * This method should only be called once in [[init()]].
	 */
	protected function updateFlashCounters()
	{
Alexander Makarov committed
562
		$counters = $this->get($this->flashVar, []);
Qiang Xue committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
		if (is_array($counters)) {
			foreach ($counters as $key => $count) {
				if ($count) {
					unset($counters[$key], $_SESSION[$key]);
				} else {
					$counters[$key]++;
				}
			}
			$_SESSION[$this->flashVar] = $counters;
		} else {
			// fix the unexpected problem that flashVar doesn't return an array
			unset($_SESSION[$this->flashVar]);
		}
	}

	/**
	 * Returns a flash message.
	 * A flash message is available only in the current request and the next request.
	 * @param string $key the key identifying the flash message
	 * @param mixed $defaultValue value to be returned if the flash message does not exist.
583 584
	 * @param boolean $delete whether to delete this flash message right after this method is called.
	 * If false, the flash message will be automatically deleted after the next request.
Qiang Xue committed
585 586
	 * @return mixed the flash message
	 */
587
	public function getFlash($key, $defaultValue = null, $delete = false)
Qiang Xue committed
588
	{
Alexander Makarov committed
589
		$counters = $this->get($this->flashVar, []);
590 591 592 593 594 595 596 597 598
		if (isset($counters[$key])) {
			$value = $this->get($key, $defaultValue);
			if ($delete) {
				$this->removeFlash($key);
			}
			return $value;
		} else {
			return $defaultValue;
		}
Qiang Xue committed
599 600 601 602 603 604 605 606
	}

	/**
	 * Returns all flash messages.
	 * @return array flash messages (key => message).
	 */
	public function getAllFlashes()
	{
Alexander Makarov committed
607 608
		$counters = $this->get($this->flashVar, []);
		$flashes = [];
Qiang Xue committed
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
		foreach (array_keys($counters) as $key) {
			if (isset($_SESSION[$key])) {
				$flashes[$key] = $_SESSION[$key];
			}
		}
		return $flashes;
	}

	/**
	 * Stores a flash message.
	 * A flash message is available only in the current request and the next request.
	 * @param string $key the key identifying the flash message. Note that flash messages
	 * and normal session variables share the same name space. If you have a normal
	 * session variable using the same name, its value will be overwritten by this method.
	 * @param mixed $value flash message
	 */
Qiang Xue committed
625
	public function setFlash($key, $value = true)
Qiang Xue committed
626
	{
Alexander Makarov committed
627
		$counters = $this->get($this->flashVar, []);
Qiang Xue committed
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
		$counters[$key] = 0;
		$_SESSION[$key] = $value;
		$_SESSION[$this->flashVar] = $counters;
	}

	/**
	 * Removes a flash message.
	 * Note that flash messages will be automatically removed after the next request.
	 * @param string $key the key identifying the flash message. Note that flash messages
	 * and normal session variables share the same name space.  If you have a normal
	 * session variable using the same name, it will be removed by this method.
	 * @return mixed the removed flash message. Null if the flash message does not exist.
	 */
	public function removeFlash($key)
	{
Alexander Makarov committed
643
		$counters = $this->get($this->flashVar, []);
Qiang Xue committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657
		$value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
		unset($counters[$key], $_SESSION[$key]);
		$_SESSION[$this->flashVar] = $counters;
		return $value;
	}

	/**
	 * Removes all flash messages.
	 * Note that flash messages and normal session variables share the same name space.
	 * If you have a normal session variable using the same name, it will be removed
	 * by this method.
	 */
	public function removeAllFlashes()
	{
Alexander Makarov committed
658
		$counters = $this->get($this->flashVar, []);
Qiang Xue committed
659 660 661 662 663 664 665
		foreach (array_keys($counters) as $key) {
			unset($_SESSION[$key]);
		}
		unset($_SESSION[$this->flashVar]);
	}

	/**
Qiang Xue committed
666
	 * Returns a value indicating whether there is a flash message associated with the specified key.
Qiang Xue committed
667 668 669 670 671 672 673 674
	 * @param string $key key identifying the flash message
	 * @return boolean whether the specified flash message exists
	 */
	public function hasFlash($key)
	{
		return $this->getFlash($key) !== null;
	}

Qiang Xue committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
	/**
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
		return isset($_SESSION[$offset]);
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param integer $offset the offset to retrieve element.
	 * @return mixed the element at the offset, null if no element is found at the offset
	 */
	public function offsetGet($offset)
	{
		return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
Qiang Xue committed
700
	public function offsetSet($offset, $item)
Qiang Xue committed
701
	{
Qiang Xue committed
702
		$_SESSION[$offset] = $item;
Qiang Xue committed
703 704 705 706 707 708 709 710 711 712 713
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($_SESSION[$offset]);
	}
}