You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

892 lines
31KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\InvalidParamException;
  12. /**
  13. * Session provides session data management and the related configurations.
  14. *
  15. * Session is a Web application component that can be accessed via `Yii::$app->session`.
  16. *
  17. * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
  18. * To destroy the session, call [[destroy()]].
  19. *
  20. * Session can be used like an array to set and get session data. For example,
  21. *
  22. * ```php
  23. * $session = new Session;
  24. * $session->open();
  25. * $value1 = $session['name1']; // get session variable 'name1'
  26. * $value2 = $session['name2']; // get session variable 'name2'
  27. * foreach ($session as $name => $value) // traverse all session variables
  28. * $session['name3'] = $value3; // set session variable 'name3'
  29. * ```
  30. *
  31. * Session can be extended to support customized session storage.
  32. * To do so, override [[useCustomStorage]] so that it returns true, and
  33. * override these methods with the actual logic about using custom storage:
  34. * [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
  35. * [[destroySession()]] and [[gcSession()]].
  36. *
  37. * Session also supports a special type of session data, called *flash messages*.
  38. * A flash message is available only in the current request and the next request.
  39. * After that, it will be deleted automatically. Flash messages are particularly
  40. * useful for displaying confirmation messages. To use flash messages, simply
  41. * call methods such as [[setFlash()]], [[getFlash()]].
  42. *
  43. * @property array $allFlashes Flash messages (key => message or key => [message1, message2]). This property
  44. * is read-only.
  45. * @property array $cookieParams The session cookie parameters. This property is read-only.
  46. * @property integer $count The number of session variables. This property is read-only.
  47. * @property string $flash The key identifying the flash message. Note that flash messages and normal session
  48. * variables share the same name space. If you have a normal session variable using the same name, its value will
  49. * be overwritten by this method. This property is write-only.
  50. * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
  51. * started on every session initialization, defaults to 1 meaning 1% chance.
  52. * @property boolean $hasSessionId Whether the current request has sent the session ID.
  53. * @property string $id The current session ID.
  54. * @property boolean $isActive Whether the session has started. This property is read-only.
  55. * @property SessionIterator $iterator An iterator for traversing the session variables. This property is
  56. * read-only.
  57. * @property string $name The current session name.
  58. * @property string $savePath The current session save path, defaults to '/tmp'.
  59. * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up.
  60. * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
  61. * @property boolean|null $useCookies The value indicating whether cookies should be used to store session
  62. * IDs.
  63. * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only.
  64. * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to
  65. * false.
  66. *
  67. * @author Qiang Xue <qiang.xue@gmail.com>
  68. * @since 2.0
  69. */
  70. class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
  71. {
  72. /**
  73. * @var string the name of the session variable that stores the flash message data.
  74. */
  75. public $flashParam = '__flash';
  76. /**
  77. * @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.
  78. */
  79. public $handler;
  80. /**
  81. * @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
  82. * Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
  83. * @see http://www.php.net/manual/en/function.session-set-cookie-params.php
  84. */
  85. private $_cookieParams = ['httponly' => true];
  86. /**
  87. * Initializes the application component.
  88. * This method is required by IApplicationComponent and is invoked by application.
  89. */
  90. public function init()
  91. {
  92. parent::init();
  93. register_shutdown_function([$this, 'close']);
  94. if ($this->getIsActive()) {
  95. Yii::warning('Session is already started', __METHOD__);
  96. $this->updateFlashCounters();
  97. }
  98. }
  99. /**
  100. * Returns a value indicating whether to use custom session storage.
  101. * This method should be overridden to return true by child classes that implement custom session storage.
  102. * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
  103. * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
  104. * @return boolean whether to use custom storage.
  105. */
  106. public function getUseCustomStorage()
  107. {
  108. return false;
  109. }
  110. /**
  111. * Starts the session.
  112. */
  113. public function open()
  114. {
  115. if ($this->getIsActive()) {
  116. return;
  117. }
  118. $this->registerSessionHandler();
  119. $this->setCookieParamsInternal();
  120. @session_start();
  121. if ($this->getIsActive()) {
  122. Yii::info('Session started', __METHOD__);
  123. $this->updateFlashCounters();
  124. } else {
  125. $error = error_get_last();
  126. $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
  127. Yii::error($message, __METHOD__);
  128. }
  129. }
  130. /**
  131. * Registers session handler.
  132. * @throws \yii\base\InvalidConfigException
  133. */
  134. protected function registerSessionHandler()
  135. {
  136. if ($this->handler !== null) {
  137. if (!is_object($this->handler)) {
  138. $this->handler = Yii::createObject($this->handler);
  139. }
  140. if (!$this->handler instanceof \SessionHandlerInterface) {
  141. throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
  142. }
  143. YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
  144. } elseif ($this->getUseCustomStorage()) {
  145. if (YII_DEBUG) {
  146. session_set_save_handler(
  147. [$this, 'openSession'],
  148. [$this, 'closeSession'],
  149. [$this, 'readSession'],
  150. [$this, 'writeSession'],
  151. [$this, 'destroySession'],
  152. [$this, 'gcSession']
  153. );
  154. } else {
  155. @session_set_save_handler(
  156. [$this, 'openSession'],
  157. [$this, 'closeSession'],
  158. [$this, 'readSession'],
  159. [$this, 'writeSession'],
  160. [$this, 'destroySession'],
  161. [$this, 'gcSession']
  162. );
  163. }
  164. }
  165. }
  166. /**
  167. * Ends the current session and store session data.
  168. */
  169. public function close()
  170. {
  171. if ($this->getIsActive()) {
  172. YII_DEBUG ? session_write_close() : @session_write_close();
  173. }
  174. }
  175. /**
  176. * Frees all session variables and destroys all data registered to a session.
  177. */
  178. public function destroy()
  179. {
  180. if ($this->getIsActive()) {
  181. $sessionId = session_id();
  182. $this->close();
  183. $this->setId($sessionId);
  184. $this->open();
  185. session_unset();
  186. session_destroy();
  187. $this->setId($sessionId);
  188. }
  189. }
  190. /**
  191. * @return boolean whether the session has started
  192. */
  193. public function getIsActive()
  194. {
  195. return session_status() === PHP_SESSION_ACTIVE;
  196. }
  197. private $_hasSessionId;
  198. /**
  199. * Returns a value indicating whether the current request has sent the session ID.
  200. * The default implementation will check cookie and $_GET using the session name.
  201. * If you send session ID via other ways, you may need to override this method
  202. * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
  203. * @return boolean whether the current request has sent the session ID.
  204. */
  205. public function getHasSessionId()
  206. {
  207. if ($this->_hasSessionId === null) {
  208. $name = $this->getName();
  209. $request = Yii::$app->getRequest();
  210. if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
  211. $this->_hasSessionId = true;
  212. } elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
  213. $this->_hasSessionId = $request->get($name) != '';
  214. } else {
  215. $this->_hasSessionId = false;
  216. }
  217. }
  218. return $this->_hasSessionId;
  219. }
  220. /**
  221. * Sets the value indicating whether the current request has sent the session ID.
  222. * This method is provided so that you can override the default way of determining
  223. * whether the session ID is sent.
  224. * @param boolean $value whether the current request has sent the session ID.
  225. */
  226. public function setHasSessionId($value)
  227. {
  228. $this->_hasSessionId = $value;
  229. }
  230. /**
  231. * Gets the session ID.
  232. * This is a wrapper for [PHP session_id()](http://php.net/manual/en/function.session-id.php).
  233. * @return string the current session ID
  234. */
  235. public function getId()
  236. {
  237. return session_id();
  238. }
  239. /**
  240. * Sets the session ID.
  241. * This is a wrapper for [PHP session_id()](http://php.net/manual/en/function.session-id.php).
  242. * @param string $value the session ID for the current session
  243. */
  244. public function setId($value)
  245. {
  246. session_id($value);
  247. }
  248. /**
  249. * Updates the current session ID with a newly generated one .
  250. * Please refer to <http://php.net/session_regenerate_id> for more details.
  251. * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
  252. */
  253. public function regenerateID($deleteOldSession = false)
  254. {
  255. if ($this->getIsActive()) {
  256. // add @ to inhibit possible warning due to race condition
  257. // https://github.com/yiisoft/yii2/pull/1812
  258. if (YII_DEBUG && !headers_sent()) {
  259. session_regenerate_id($deleteOldSession);
  260. } else {
  261. @session_regenerate_id($deleteOldSession);
  262. }
  263. }
  264. }
  265. /**
  266. * Gets the name of the current session.
  267. * This is a wrapper for [PHP session_name()](http://php.net/manual/en/function.session-name.php).
  268. * @return string the current session name
  269. */
  270. public function getName()
  271. {
  272. return session_name();
  273. }
  274. /**
  275. * Sets the name for the current session.
  276. * This is a wrapper for [PHP session_name()](http://php.net/manual/en/function.session-name.php).
  277. * @param string $value the session name for the current session, must be an alphanumeric string.
  278. * It defaults to "PHPSESSID".
  279. */
  280. public function setName($value)
  281. {
  282. session_name($value);
  283. }
  284. /**
  285. * Gets the current session save path.
  286. * This is a wrapper for [PHP session_save_path()](http://php.net/manual/en/function.session-save-path.php).
  287. * @return string the current session save path, defaults to '/tmp'.
  288. */
  289. public function getSavePath()
  290. {
  291. return session_save_path();
  292. }
  293. /**
  294. * Sets the current session save path.
  295. * This is a wrapper for [PHP session_save_path()](http://php.net/manual/en/function.session-save-path.php).
  296. * @param string $value the current session save path. This can be either a directory name or a path alias.
  297. * @throws InvalidParamException if the path is not a valid directory
  298. */
  299. public function setSavePath($value)
  300. {
  301. $path = Yii::getAlias($value);
  302. if (is_dir($path)) {
  303. session_save_path($path);
  304. } else {
  305. throw new InvalidParamException("Session save path is not a valid directory: $value");
  306. }
  307. }
  308. /**
  309. * @return array the session cookie parameters.
  310. * @see http://php.net/manual/en/function.session-get-cookie-params.php
  311. */
  312. public function getCookieParams()
  313. {
  314. return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
  315. }
  316. /**
  317. * Sets the session cookie parameters.
  318. * The cookie parameters passed to this method will be merged with the result
  319. * of `session_get_cookie_params()`.
  320. * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httponly`.
  321. * @throws InvalidParamException if the parameters are incomplete.
  322. * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
  323. */
  324. public function setCookieParams(array $value)
  325. {
  326. $this->_cookieParams = $value;
  327. }
  328. /**
  329. * Sets the session cookie parameters.
  330. * This method is called by [[open()]] when it is about to open the session.
  331. * @throws InvalidParamException if the parameters are incomplete.
  332. * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
  333. */
  334. private function setCookieParamsInternal()
  335. {
  336. $data = $this->getCookieParams();
  337. if (isset($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly'])) {
  338. session_set_cookie_params($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly']);
  339. } else {
  340. throw new InvalidParamException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.');
  341. }
  342. }
  343. /**
  344. * Returns the value indicating whether cookies should be used to store session IDs.
  345. * @return boolean|null the value indicating whether cookies should be used to store session IDs.
  346. * @see setUseCookies()
  347. */
  348. public function getUseCookies()
  349. {
  350. if (ini_get('session.use_cookies') === '0') {
  351. return false;
  352. } elseif (ini_get('session.use_only_cookies') === '1') {
  353. return true;
  354. } else {
  355. return null;
  356. }
  357. }
  358. /**
  359. * Sets the value indicating whether cookies should be used to store session IDs.
  360. * Three states are possible:
  361. *
  362. * - true: cookies and only cookies will be used to store session IDs.
  363. * - false: cookies will not be used to store session IDs.
  364. * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
  365. *
  366. * @param boolean|null $value the value indicating whether cookies should be used to store session IDs.
  367. */
  368. public function setUseCookies($value)
  369. {
  370. if ($value === false) {
  371. ini_set('session.use_cookies', '0');
  372. ini_set('session.use_only_cookies', '0');
  373. } elseif ($value === true) {
  374. ini_set('session.use_cookies', '1');
  375. ini_set('session.use_only_cookies', '1');
  376. } else {
  377. ini_set('session.use_cookies', '1');
  378. ini_set('session.use_only_cookies', '0');
  379. }
  380. }
  381. /**
  382. * @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
  383. */
  384. public function getGCProbability()
  385. {
  386. return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
  387. }
  388. /**
  389. * @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
  390. * @throws InvalidParamException if the value is not between 0 and 100.
  391. */
  392. public function setGCProbability($value)
  393. {
  394. if ($value >= 0 && $value <= 100) {
  395. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  396. ini_set('session.gc_probability', floor($value * 21474836.47));
  397. ini_set('session.gc_divisor', 2147483647);
  398. } else {
  399. throw new InvalidParamException('GCProbability must be a value between 0 and 100.');
  400. }
  401. }
  402. /**
  403. * @return boolean whether transparent sid support is enabled or not, defaults to false.
  404. */
  405. public function getUseTransparentSessionID()
  406. {
  407. return ini_get('session.use_trans_sid') == 1;
  408. }
  409. /**
  410. * @param boolean $value whether transparent sid support is enabled or not.
  411. */
  412. public function setUseTransparentSessionID($value)
  413. {
  414. ini_set('session.use_trans_sid', $value ? '1' : '0');
  415. }
  416. /**
  417. * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up.
  418. * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
  419. */
  420. public function getTimeout()
  421. {
  422. return (int) ini_get('session.gc_maxlifetime');
  423. }
  424. /**
  425. * @param integer $value the number of seconds after which data will be seen as 'garbage' and cleaned up
  426. */
  427. public function setTimeout($value)
  428. {
  429. ini_set('session.gc_maxlifetime', $value);
  430. }
  431. /**
  432. * Session open handler.
  433. * This method should be overridden if [[useCustomStorage]] returns true.
  434. * Do not call this method directly.
  435. * @param string $savePath session save path
  436. * @param string $sessionName session name
  437. * @return boolean whether session is opened successfully
  438. */
  439. public function openSession($savePath, $sessionName)
  440. {
  441. return true;
  442. }
  443. /**
  444. * Session close handler.
  445. * This method should be overridden if [[useCustomStorage]] returns true.
  446. * Do not call this method directly.
  447. * @return boolean whether session is closed successfully
  448. */
  449. public function closeSession()
  450. {
  451. return true;
  452. }
  453. /**
  454. * Session read handler.
  455. * This method should be overridden if [[useCustomStorage]] returns true.
  456. * Do not call this method directly.
  457. * @param string $id session ID
  458. * @return string the session data
  459. */
  460. public function readSession($id)
  461. {
  462. return '';
  463. }
  464. /**
  465. * Session write handler.
  466. * This method should be overridden if [[useCustomStorage]] returns true.
  467. * Do not call this method directly.
  468. * @param string $id session ID
  469. * @param string $data session data
  470. * @return boolean whether session write is successful
  471. */
  472. public function writeSession($id, $data)
  473. {
  474. return true;
  475. }
  476. /**
  477. * Session destroy handler.
  478. * This method should be overridden if [[useCustomStorage]] returns true.
  479. * Do not call this method directly.
  480. * @param string $id session ID
  481. * @return boolean whether session is destroyed successfully
  482. */
  483. public function destroySession($id)
  484. {
  485. return true;
  486. }
  487. /**
  488. * Session GC (garbage collection) handler.
  489. * This method should be overridden if [[useCustomStorage]] returns true.
  490. * Do not call this method directly.
  491. * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  492. * @return boolean whether session is GCed successfully
  493. */
  494. public function gcSession($maxLifetime)
  495. {
  496. return true;
  497. }
  498. /**
  499. * Returns an iterator for traversing the session variables.
  500. * This method is required by the interface [[\IteratorAggregate]].
  501. * @return SessionIterator an iterator for traversing the session variables.
  502. */
  503. public function getIterator()
  504. {
  505. $this->open();
  506. return new SessionIterator;
  507. }
  508. /**
  509. * Returns the number of items in the session.
  510. * @return integer the number of session variables
  511. */
  512. public function getCount()
  513. {
  514. $this->open();
  515. return count($_SESSION);
  516. }
  517. /**
  518. * Returns the number of items in the session.
  519. * This method is required by [[\Countable]] interface.
  520. * @return integer number of items in the session.
  521. */
  522. public function count()
  523. {
  524. return $this->getCount();
  525. }
  526. /**
  527. * Returns the session variable value with the session variable name.
  528. * If the session variable does not exist, the `$defaultValue` will be returned.
  529. * @param string $key the session variable name
  530. * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
  531. * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
  532. */
  533. public function get($key, $defaultValue = null)
  534. {
  535. $this->open();
  536. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  537. }
  538. /**
  539. * Adds a session variable.
  540. * If the specified name already exists, the old value will be overwritten.
  541. * @param string $key session variable name
  542. * @param mixed $value session variable value
  543. */
  544. public function set($key, $value)
  545. {
  546. $this->open();
  547. $_SESSION[$key] = $value;
  548. }
  549. /**
  550. * Removes a session variable.
  551. * @param string $key the name of the session variable to be removed
  552. * @return mixed the removed value, null if no such session variable.
  553. */
  554. public function remove($key)
  555. {
  556. $this->open();
  557. if (isset($_SESSION[$key])) {
  558. $value = $_SESSION[$key];
  559. unset($_SESSION[$key]);
  560. return $value;
  561. } else {
  562. return null;
  563. }
  564. }
  565. /**
  566. * Removes all session variables
  567. */
  568. public function removeAll()
  569. {
  570. $this->open();
  571. foreach (array_keys($_SESSION) as $key) {
  572. unset($_SESSION[$key]);
  573. }
  574. }
  575. /**
  576. * @param mixed $key session variable name
  577. * @return boolean whether there is the named session variable
  578. */
  579. public function has($key)
  580. {
  581. $this->open();
  582. return isset($_SESSION[$key]);
  583. }
  584. /**
  585. * Updates the counters for flash messages and removes outdated flash messages.
  586. * This method should only be called once in [[init()]].
  587. */
  588. protected function updateFlashCounters()
  589. {
  590. $counters = $this->get($this->flashParam, []);
  591. if (is_array($counters)) {
  592. foreach ($counters as $key => $count) {
  593. if ($count > 0) {
  594. unset($counters[$key], $_SESSION[$key]);
  595. } elseif ($count == 0) {
  596. $counters[$key]++;
  597. }
  598. }
  599. $_SESSION[$this->flashParam] = $counters;
  600. } else {
  601. // fix the unexpected problem that flashParam doesn't return an array
  602. unset($_SESSION[$this->flashParam]);
  603. }
  604. }
  605. /**
  606. * Returns a flash message.
  607. * @param string $key the key identifying the flash message
  608. * @param mixed $defaultValue value to be returned if the flash message does not exist.
  609. * @param boolean $delete whether to delete this flash message right after this method is called.
  610. * If false, the flash message will be automatically deleted in the next request.
  611. * @return mixed the flash message or an array of messages if addFlash was used
  612. * @see setFlash()
  613. * @see addFlash()
  614. * @see hasFlash()
  615. * @see getAllFlashes()
  616. * @see removeFlash()
  617. */
  618. public function getFlash($key, $defaultValue = null, $delete = false)
  619. {
  620. $counters = $this->get($this->flashParam, []);
  621. if (isset($counters[$key])) {
  622. $value = $this->get($key, $defaultValue);
  623. if ($delete) {
  624. $this->removeFlash($key);
  625. } elseif ($counters[$key] < 0) {
  626. // mark for deletion in the next request
  627. $counters[$key] = 1;
  628. $_SESSION[$this->flashParam] = $counters;
  629. }
  630. return $value;
  631. } else {
  632. return $defaultValue;
  633. }
  634. }
  635. /**
  636. * Returns all flash messages.
  637. *
  638. * You may use this method to display all the flash messages in a view file:
  639. *
  640. * ```php
  641. * <?php
  642. * foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
  643. * echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
  644. * } ?>
  645. * ```
  646. *
  647. * With the above code you can use the [bootstrap alert][] classes such as `success`, `info`, `danger`
  648. * as the flash message key to influence the color of the div.
  649. *
  650. * Note that if you use [[addFlash()]], `$message` will be an array, and you will have to adjust the above code.
  651. *
  652. * [bootstrap alert]: http://getbootstrap.com/components/#alerts
  653. *
  654. * @param boolean $delete whether to delete the flash messages right after this method is called.
  655. * If false, the flash messages will be automatically deleted in the next request.
  656. * @return array flash messages (key => message or key => [message1, message2]).
  657. * @see setFlash()
  658. * @see addFlash()
  659. * @see getFlash()
  660. * @see hasFlash()
  661. * @see removeFlash()
  662. */
  663. public function getAllFlashes($delete = false)
  664. {
  665. $counters = $this->get($this->flashParam, []);
  666. $flashes = [];
  667. foreach (array_keys($counters) as $key) {
  668. if (array_key_exists($key, $_SESSION)) {
  669. $flashes[$key] = $_SESSION[$key];
  670. if ($delete) {
  671. unset($counters[$key], $_SESSION[$key]);
  672. } elseif ($counters[$key] < 0) {
  673. // mark for deletion in the next request
  674. $counters[$key] = 1;
  675. }
  676. } else {
  677. unset($counters[$key]);
  678. }
  679. }
  680. $_SESSION[$this->flashParam] = $counters;
  681. return $flashes;
  682. }
  683. /**
  684. * Sets a flash message.
  685. * A flash message will be automatically deleted after it is accessed in a request and the deletion will happen
  686. * in the next request.
  687. * If there is already an existing flash message with the same key, it will be overwritten by the new one.
  688. * @param string $key the key identifying the flash message. Note that flash messages
  689. * and normal session variables share the same name space. If you have a normal
  690. * session variable using the same name, its value will be overwritten by this method.
  691. * @param mixed $value flash message
  692. * @param boolean $removeAfterAccess whether the flash message should be automatically removed only if
  693. * it is accessed. If false, the flash message will be automatically removed after the next request,
  694. * regardless if it is accessed or not. If true (default value), the flash message will remain until after
  695. * it is accessed.
  696. * @see getFlash()
  697. * @see addFlash()
  698. * @see removeFlash()
  699. */
  700. public function setFlash($key, $value = true, $removeAfterAccess = true)
  701. {
  702. $counters = $this->get($this->flashParam, []);
  703. $counters[$key] = $removeAfterAccess ? -1 : 0;
  704. $_SESSION[$key] = $value;
  705. $_SESSION[$this->flashParam] = $counters;
  706. }
  707. /**
  708. * Adds a flash message.
  709. * If there are existing flash messages with the same key, the new one will be appended to the existing message array.
  710. * @param string $key the key identifying the flash message.
  711. * @param mixed $value flash message
  712. * @param boolean $removeAfterAccess whether the flash message should be automatically removed only if
  713. * it is accessed. If false, the flash message will be automatically removed after the next request,
  714. * regardless if it is accessed or not. If true (default value), the flash message will remain until after
  715. * it is accessed.
  716. * @see getFlash()
  717. * @see setFlash()
  718. * @see removeFlash()
  719. */
  720. public function addFlash($key, $value = true, $removeAfterAccess = true)
  721. {
  722. $counters = $this->get($this->flashParam, []);
  723. $counters[$key] = $removeAfterAccess ? -1 : 0;
  724. $_SESSION[$this->flashParam] = $counters;
  725. if (empty($_SESSION[$key])) {
  726. $_SESSION[$key] = [$value];
  727. } else {
  728. if (is_array($_SESSION[$key])) {
  729. $_SESSION[$key][] = $value;
  730. } else {
  731. $_SESSION[$key] = [$_SESSION[$key], $value];
  732. }
  733. }
  734. }
  735. /**
  736. * Removes a flash message.
  737. * @param string $key the key identifying the flash message. Note that flash messages
  738. * and normal session variables share the same name space. If you have a normal
  739. * session variable using the same name, it will be removed by this method.
  740. * @return mixed the removed flash message. Null if the flash message does not exist.
  741. * @see getFlash()
  742. * @see setFlash()
  743. * @see addFlash()
  744. * @see removeAllFlashes()
  745. */
  746. public function removeFlash($key)
  747. {
  748. $counters = $this->get($this->flashParam, []);
  749. $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
  750. unset($counters[$key], $_SESSION[$key]);
  751. $_SESSION[$this->flashParam] = $counters;
  752. return $value;
  753. }
  754. /**
  755. * Removes all flash messages.
  756. * Note that flash messages and normal session variables share the same name space.
  757. * If you have a normal session variable using the same name, it will be removed
  758. * by this method.
  759. * @see getFlash()
  760. * @see setFlash()
  761. * @see addFlash()
  762. * @see removeFlash()
  763. */
  764. public function removeAllFlashes()
  765. {
  766. $counters = $this->get($this->flashParam, []);
  767. foreach (array_keys($counters) as $key) {
  768. unset($_SESSION[$key]);
  769. }
  770. unset($_SESSION[$this->flashParam]);
  771. }
  772. /**
  773. * Returns a value indicating whether there are flash messages associated with the specified key.
  774. * @param string $key key identifying the flash message type
  775. * @return boolean whether any flash messages exist under specified key
  776. */
  777. public function hasFlash($key)
  778. {
  779. return $this->getFlash($key) !== null;
  780. }
  781. /**
  782. * This method is required by the interface [[\ArrayAccess]].
  783. * @param mixed $offset the offset to check on
  784. * @return boolean
  785. */
  786. public function offsetExists($offset)
  787. {
  788. $this->open();
  789. return isset($_SESSION[$offset]);
  790. }
  791. /**
  792. * This method is required by the interface [[\ArrayAccess]].
  793. * @param integer $offset the offset to retrieve element.
  794. * @return mixed the element at the offset, null if no element is found at the offset
  795. */
  796. public function offsetGet($offset)
  797. {
  798. $this->open();
  799. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  800. }
  801. /**
  802. * This method is required by the interface [[\ArrayAccess]].
  803. * @param integer $offset the offset to set element
  804. * @param mixed $item the element value
  805. */
  806. public function offsetSet($offset, $item)
  807. {
  808. $this->open();
  809. $_SESSION[$offset] = $item;
  810. }
  811. /**
  812. * This method is required by the interface [[\ArrayAccess]].
  813. * @param mixed $offset the offset to unset element
  814. */
  815. public function offsetUnset($offset)
  816. {
  817. $this->open();
  818. unset($_SESSION[$offset]);
  819. }
  820. }