Session.php 23.2 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;
11
use yii\base\Arrayable;
Qiang Xue committed
12
use yii\base\Component;
Qiang Xue committed
13
use yii\base\InvalidConfigException;
Qiang Xue committed
14 15
use yii\base\InvalidParamException;

Qiang Xue committed
16
/**
Qiang Xue committed
17
 * Session provides session data management and the related configurations.
Qiang Xue committed
18
 *
Qiang Xue committed
19
 * Session is a Web application component that can be accessed via `Yii::$app->session`.
20
 *
Qiang Xue committed
21 22
 * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
 * To destroy the session, call [[destroy()]].
Qiang Xue committed
23
 *
Qiang Xue committed
24 25
 * 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
26
 *
Qiang Xue committed
27
 * Session can be used like an array to set and get session data. For example,
Qiang Xue committed
28
 *
Qiang Xue committed
29 30 31 32 33 34 35 36
 * ~~~
 * $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
37
 *
Qiang Xue committed
38
 * Session can be extended to support customized session storage.
Qiang Xue committed
39 40 41 42
 * 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
43
 *
Qiang Xue committed
44 45 46 47 48
 * 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
49
 *
50
 * @property array $allFlashes Flash messages (key => message). This property is read-only.
Qiang Xue committed
51
 * @property array $cookieParams The session cookie parameters. This property is read-only.
52 53 54 55 56 57
 * @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.
58
 * @property string $id The current session ID.
59 60 61
 * @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.
62
 * @property string $name The current session name.
63 64 65
 * @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).
66 67 68 69 70
 * @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.
71
 *
Qiang Xue committed
72
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
73
 * @since 2.0
Qiang Xue committed
74
 */
75
class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable, Arrayable
Qiang Xue committed
76
{
Qiang Xue committed
77 78 79
	/**
	 * @var string the name of the session variable that stores the flash message data.
	 */
80
	public $flashParam = '__flash';
81 82 83 84
	/**
	 * @var \SessionHandlerInterface|array an object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.
	 */
	public $handler;
85
	/**
86
	 * @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
87
	 * Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httpOnly'
88
	 * @see http://www.php.net/manual/en/function.session-set-cookie-params.php
89
	 */
90
	private $_cookieParams = ['httpOnly' => true];
91

Qiang Xue committed
92 93 94 95 96 97 98
	/**
	 * Initializes the application component.
	 * This method is required by IApplicationComponent and is invoked by application.
	 */
	public function init()
	{
		parent::init();
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 114
	 * @return boolean whether to use custom storage.
	 */
	public function getUseCustomStorage()
	{
		return false;
	}

	/**
Qiang Xue committed
115
	 * Starts the session.
Qiang Xue committed
116 117 118
	 */
	public function open()
	{
119
		if ($this->getIsActive()) {
120
			return;
Qiang Xue committed
121 122
		}

123 124 125 126 127 128 129
		$this->registerSessionHandler();

		$this->setCookieParamsInternal();

		@session_start();

		if ($this->getIsActive()) {
Qiang Xue committed
130
			Yii::info('Session started', __METHOD__);
131 132 133 134 135 136 137 138 139 140 141 142 143 144
			$this->updateFlashCounters();
		} else {
			$error = error_get_last();
			$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
			Yii::error($message, __METHOD__);
		}
	}

	/**
	 * Registers session handler.
	 * @throws \yii\base\InvalidConfigException
	 */
	protected function registerSessionHandler()
	{
145 146 147 148 149 150 151 152
		if ($this->handler !== null) {
			if (!is_object($this->handler)) {
				$this->handler = Yii::createObject($this->handler);
			}
			if (!$this->handler instanceof \SessionHandlerInterface) {
				throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
			}
			@session_set_save_handler($this->handler, false);
153
		} elseif ($this->getUseCustomStorage()) {
154 155 156 157 158 159 160 161 162
			@session_set_save_handler(
				[$this, 'openSession'],
				[$this, 'closeSession'],
				[$this, 'readSession'],
				[$this, 'writeSession'],
				[$this, 'destroySession'],
				[$this, 'gcSession']
			);
		}
Qiang Xue committed
163 164 165 166 167 168 169
	}

	/**
	 * Ends the current session and store session data.
	 */
	public function close()
	{
170
		if ($this->getIsActive()) {
Qiang Xue committed
171
			@session_write_close();
Qiang Xue committed
172
		}
Qiang Xue committed
173 174 175 176 177 178 179
	}

	/**
	 * Frees all session variables and destroys all data registered to a session.
	 */
	public function destroy()
	{
180
		if ($this->getIsActive()) {
Qiang Xue committed
181 182 183 184 185 186 187 188
			@session_unset();
			@session_destroy();
		}
	}

	/**
	 * @return boolean whether the session has started
	 */
Qiang Xue committed
189
	public function getIsActive()
Qiang Xue committed
190
	{
191
		return session_status() == PHP_SESSION_ACTIVE;
Qiang Xue committed
192 193
	}

194 195 196 197 198 199 200 201 202 203 204 205 206 207
	private $_hasSessionId;

	/**
	 * Returns a value indicating whether the current request has sent the session ID.
	 * The default implementation will check cookie and $_GET using the session name.
	 * If you send session ID via other ways, you may need to override this method
	 * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
	 * @return boolean whether the current request has sent the session ID.
	 */
	public function getHasSessionId()
	{
		if ($this->_hasSessionId === null) {
			$name = $this->getName();
			$request = Yii::$app->getRequest();
Qiang Xue committed
208
			if (ini_get('session.use_cookies') && !empty($_COOKIE[$name])) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
				$this->_hasSessionId = true;
			} elseif (!ini_get('use_only_cookies') && ini_get('use_trans_sid')) {
				$this->_hasSessionId = $request->get($name) !== null;
			} else {
				$this->_hasSessionId = false;
			}
		}
		return $this->_hasSessionId;
	}

	/**
	 * Sets the value indicating whether the current request has sent the session ID.
	 * This method is provided so that you can override the default way of determining
	 * whether the session ID is sent.
	 * @param boolean $value whether the current request has sent the session ID.
	 */
	public function setHasSessionId($value)
	{
		$this->_hasSessionId = $value;
	}

Qiang Xue committed
230 231 232
	/**
	 * @return string the current session ID
	 */
Qiang Xue committed
233
	public function getId()
Qiang Xue committed
234 235 236 237 238 239 240
	{
		return session_id();
	}

	/**
	 * @param string $value the session ID for the current session
	 */
Qiang Xue committed
241
	public function setId($value)
Qiang Xue committed
242 243 244 245 246
	{
		session_id($value);
	}

	/**
Qiang Xue committed
247
	 * Updates the current session ID with a newly generated one .
Carsten Brandt committed
248
	 * Please refer to <http://php.net/session_regenerate_id> for more details.
Qiang Xue committed
249 250
	 * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
	 */
Qiang Xue committed
251
	public function regenerateID($deleteOldSession = false)
Qiang Xue committed
252
	{
253 254 255
		// add @ to inhibit possible warning due to race condition
		// https://github.com/yiisoft/yii2/pull/1812
		@session_regenerate_id($deleteOldSession);
Qiang Xue committed
256 257 258 259 260
	}

	/**
	 * @return string the current session name
	 */
Qiang Xue committed
261
	public function getName()
Qiang Xue committed
262 263 264 265 266
	{
		return session_name();
	}

	/**
Qiang Xue committed
267 268
	 * @param string $value the session name for the current session, must be an alphanumeric string.
	 * It defaults to "PHPSESSID".
Qiang Xue committed
269
	 */
Qiang Xue committed
270
	public function setName($value)
Qiang Xue committed
271 272 273 274 275 276 277 278 279 280 281 282 283
	{
		session_name($value);
	}

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

	/**
Qiang Xue committed
284 285
	 * @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
286 287 288
	 */
	public function setSavePath($value)
	{
Qiang Xue committed
289
		$path = Yii::getAlias($value);
Qiang Xue committed
290
		if (is_dir($path)) {
Qiang Xue committed
291
			session_save_path($path);
Qiang Xue committed
292
		} else {
Qiang Xue committed
293
			throw new InvalidParamException("Session save path is not a valid directory: $value");
Qiang Xue committed
294
		}
Qiang Xue committed
295 296 297 298 299 300 301 302
	}

	/**
	 * @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
303 304 305 306 307
		$params = session_get_cookie_params();
		if (isset($params['httponly'])) {
			$params['httpOnly'] = $params['httponly'];
			unset($params['httponly']);
		}
308
		return array_merge($params, $this->_cookieParams);
Qiang Xue committed
309 310 311 312
	}

	/**
	 * Sets the session cookie parameters.
313 314
	 * The cookie parameters passed to this method will be merged with the result
	 * of `session_get_cookie_params()`.
Qiang Xue committed
315
	 * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httpOnly`.
Qiang Xue committed
316
	 * @throws InvalidParamException if the parameters are incomplete.
Qiang Xue committed
317 318
	 * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
	 */
319 320 321 322 323 324 325 326 327 328 329 330
	public function setCookieParams(array $value)
	{
		$this->_cookieParams = $value;
	}

	/**
	 * Sets the session cookie parameters.
	 * This method is called by [[open()]] when it is about to open the session.
	 * @throws InvalidParamException if the parameters are incomplete.
	 * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
	 */
	private function setCookieParamsInternal()
Qiang Xue committed
331
	{
Qiang Xue committed
332
		$data = $this->getCookieParams();
Qiang Xue committed
333
		extract($data);
Qiang Xue committed
334 335
		if (isset($lifetime, $path, $domain, $secure, $httpOnly)) {
			session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly);
Qiang Xue committed
336
		} else {
337
			throw new InvalidParamException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httpOnly.');
Qiang Xue committed
338
		}
Qiang Xue committed
339 340 341
	}

	/**
Qiang Xue committed
342 343 344
	 * 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
345
	 */
Qiang Xue committed
346
	public function getUseCookies()
Qiang Xue committed
347
	{
Qiang Xue committed
348
		if (ini_get('session.use_cookies') === '0') {
Qiang Xue committed
349 350 351
			return false;
		} elseif (ini_get('session.use_only_cookies') === '1') {
			return true;
Qiang Xue committed
352
		} else {
Qiang Xue committed
353
			return null;
Qiang Xue committed
354
		}
Qiang Xue committed
355 356 357
	}

	/**
Qiang Xue committed
358 359 360 361 362 363 364 365
	 * 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
366
	 */
Qiang Xue committed
367
	public function setUseCookies($value)
Qiang Xue committed
368
	{
Qiang Xue committed
369
		if ($value === false) {
Qiang Xue committed
370 371
			ini_set('session.use_cookies', '0');
			ini_set('session.use_only_cookies', '0');
Qiang Xue committed
372 373 374
		} elseif ($value === true) {
			ini_set('session.use_cookies', '1');
			ini_set('session.use_only_cookies', '1');
Qiang Xue committed
375
		} else {
Qiang Xue committed
376 377
			ini_set('session.use_cookies', '1');
			ini_set('session.use_only_cookies', '0');
Qiang Xue committed
378 379 380 381
		}
	}

	/**
Qiang Xue committed
382
	 * @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
383 384 385
	 */
	public function getGCProbability()
	{
Qiang Xue committed
386
		return (float)(ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
Qiang Xue committed
387 388 389
	}

	/**
Qiang Xue committed
390 391
	 * @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
392 393 394
	 */
	public function setGCProbability($value)
	{
Qiang Xue committed
395
		if ($value >= 0 && $value <= 100) {
Qiang Xue committed
396 397 398
			// percent * 21474837 / 2147483647 ≈ percent * 0.01
			ini_set('session.gc_probability', floor($value * 21474836.47));
			ini_set('session.gc_divisor', 2147483647);
Qiang Xue committed
399
		} else {
Qiang Xue committed
400
			throw new InvalidParamException('GCProbability must be a value between 0 and 100.');
Qiang Xue committed
401
		}
Qiang Xue committed
402 403 404 405 406 407 408
	}

	/**
	 * @return boolean whether transparent sid support is enabled or not, defaults to false.
	 */
	public function getUseTransparentSessionID()
	{
Qiang Xue committed
409
		return ini_get('session.use_trans_sid') == 1;
Qiang Xue committed
410 411 412 413 414 415 416
	}

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

	/**
Qiang Xue committed
421 422
	 * @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
423 424 425 426 427 428 429 430 431 432 433
	 */
	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
434
		ini_set('session.gc_maxlifetime', $value);
Qiang Xue committed
435 436 437 438
	}

	/**
	 * Session open handler.
Qiang Xue committed
439
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
440 441 442 443 444
	 * 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
445
	public function openSession($savePath, $sessionName)
Qiang Xue committed
446 447 448 449 450 451
	{
		return true;
	}

	/**
	 * Session close handler.
Qiang Xue committed
452
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
453 454 455 456 457 458 459 460 461 462
	 * Do not call this method directly.
	 * @return boolean whether session is closed successfully
	 */
	public function closeSession()
	{
		return true;
	}

	/**
	 * Session read handler.
Qiang Xue committed
463
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
464 465 466 467 468 469 470 471 472 473 474
	 * 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
475
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
476 477 478 479 480
	 * 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
481
	public function writeSession($id, $data)
Qiang Xue committed
482 483 484 485 486 487
	{
		return true;
	}

	/**
	 * Session destroy handler.
Qiang Xue committed
488
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
489 490 491 492 493 494 495 496 497 498 499
	 * 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
500
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
501 502 503 504 505 506 507 508 509 510 511 512
	 * 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
513
	 * @return SessionIterator an iterator for traversing the session variables.
Qiang Xue committed
514 515 516
	 */
	public function getIterator()
	{
Qiang Xue committed
517
		return new SessionIterator;
Qiang Xue committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
	}

	/**
	 * 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
541 542
	 * If the session variable does not exist, the `$defaultValue` will be returned.
	 * @param string $key the session variable name
Qiang Xue committed
543 544 545
	 * @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
546
	public function get($key, $defaultValue = null)
Qiang Xue committed
547
	{
548
		$this->open();
Qiang Xue committed
549 550 551 552 553
		return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
	}

	/**
	 * Adds a session variable.
Qiang Xue committed
554 555
	 * If the specified name already exists, the old value will be overwritten.
	 * @param string $key session variable name
Qiang Xue committed
556 557
	 * @param mixed $value session variable value
	 */
Qiang Xue committed
558
	public function set($key, $value)
Qiang Xue committed
559
	{
560
		$this->open();
Qiang Xue committed
561
		$_SESSION[$key] = $value;
Qiang Xue committed
562 563 564 565
	}

	/**
	 * Removes a session variable.
Qiang Xue committed
566
	 * @param string $key the name of the session variable to be removed
Qiang Xue committed
567 568 569 570
	 * @return mixed the removed value, null if no such session variable.
	 */
	public function remove($key)
	{
571
		$this->open();
Qiang Xue committed
572 573
		if (isset($_SESSION[$key])) {
			$value = $_SESSION[$key];
Qiang Xue committed
574 575
			unset($_SESSION[$key]);
			return $value;
Qiang Xue committed
576
		} else {
Qiang Xue committed
577
			return null;
Qiang Xue committed
578
		}
Qiang Xue committed
579 580 581 582 583
	}

	/**
	 * Removes all session variables
	 */
Qiang Xue committed
584
	public function removeAll()
Qiang Xue committed
585
	{
586
		$this->open();
Qiang Xue committed
587
		foreach (array_keys($_SESSION) as $key) {
Qiang Xue committed
588
			unset($_SESSION[$key]);
Qiang Xue committed
589
		}
Qiang Xue committed
590 591 592 593 594 595
	}

	/**
	 * @param mixed $key session variable name
	 * @return boolean whether there is the named session variable
	 */
Qiang Xue committed
596
	public function has($key)
Qiang Xue committed
597
	{
598
		$this->open();
Qiang Xue committed
599 600 601 602 603 604 605 606
		return isset($_SESSION[$key]);
	}

	/**
	 * @return array the list of all session variables in array
	 */
	public function toArray()
	{
607
		$this->open();
Qiang Xue committed
608 609 610
		return $_SESSION;
	}

Qiang Xue committed
611 612 613 614 615 616
	/**
	 * Updates the counters for flash messages and removes outdated flash messages.
	 * This method should only be called once in [[init()]].
	 */
	protected function updateFlashCounters()
	{
617
		$counters = $this->get($this->flashParam, []);
Qiang Xue committed
618 619 620 621 622 623 624 625
		if (is_array($counters)) {
			foreach ($counters as $key => $count) {
				if ($count) {
					unset($counters[$key], $_SESSION[$key]);
				} else {
					$counters[$key]++;
				}
			}
626
			$_SESSION[$this->flashParam] = $counters;
Qiang Xue committed
627
		} else {
628 629
			// fix the unexpected problem that flashParam doesn't return an array
			unset($_SESSION[$this->flashParam]);
Qiang Xue committed
630 631 632 633 634 635 636 637
		}
	}

	/**
	 * 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.
638 639
	 * @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
640 641
	 * @return mixed the flash message
	 */
642
	public function getFlash($key, $defaultValue = null, $delete = false)
Qiang Xue committed
643
	{
644
		$counters = $this->get($this->flashParam, []);
645 646 647 648 649 650 651 652 653
		if (isset($counters[$key])) {
			$value = $this->get($key, $defaultValue);
			if ($delete) {
				$this->removeFlash($key);
			}
			return $value;
		} else {
			return $defaultValue;
		}
Qiang Xue committed
654 655 656 657 658 659 660 661
	}

	/**
	 * Returns all flash messages.
	 * @return array flash messages (key => message).
	 */
	public function getAllFlashes()
	{
662
		$counters = $this->get($this->flashParam, []);
Alexander Makarov committed
663
		$flashes = [];
Qiang Xue committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
		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
680
	public function setFlash($key, $value = true)
Qiang Xue committed
681
	{
682
		$counters = $this->get($this->flashParam, []);
Qiang Xue committed
683 684
		$counters[$key] = 0;
		$_SESSION[$key] = $value;
685
		$_SESSION[$this->flashParam] = $counters;
Qiang Xue committed
686 687 688 689 690 691 692 693 694 695 696 697
	}

	/**
	 * 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)
	{
698
		$counters = $this->get($this->flashParam, []);
Qiang Xue committed
699 700
		$value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
		unset($counters[$key], $_SESSION[$key]);
701
		$_SESSION[$this->flashParam] = $counters;
Qiang Xue committed
702 703 704 705 706 707 708 709 710 711 712
		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()
	{
713
		$counters = $this->get($this->flashParam, []);
Qiang Xue committed
714 715 716
		foreach (array_keys($counters) as $key) {
			unset($_SESSION[$key]);
		}
717
		unset($_SESSION[$this->flashParam]);
Qiang Xue committed
718 719 720
	}

	/**
Qiang Xue committed
721
	 * Returns a value indicating whether there is a flash message associated with the specified key.
Qiang Xue committed
722 723 724 725 726 727 728 729
	 * @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
730 731 732 733 734 735 736
	/**
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
737
		$this->open();
Qiang Xue committed
738 739 740 741 742 743 744 745 746 747
		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)
	{
748
		$this->open();
Qiang Xue committed
749 750 751 752 753 754 755 756
		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
757
	public function offsetSet($offset, $item)
Qiang Xue committed
758
	{
759
		$this->open();
Qiang Xue committed
760
		$_SESSION[$offset] = $item;
Qiang Xue committed
761 762 763 764 765 766 767 768
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
769
		$this->open();
Qiang Xue committed
770 771 772
		unset($_SESSION[$offset]);
	}
}