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.

232 lines
7.3KB

  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\db\Connection;
  10. use yii\db\Query;
  11. use yii\base\InvalidConfigException;
  12. use yii\di\Instance;
  13. /**
  14. * DbSession extends [[Session]] by using database as session data storage.
  15. *
  16. * By default, DbSession stores session data in a DB table named 'session'. This table
  17. * must be pre-created. The table name can be changed by setting [[sessionTable]].
  18. *
  19. * The following example shows how you can configure the application to use DbSession:
  20. * Add the following to your application config under `components`:
  21. *
  22. * ~~~
  23. * 'session' => [
  24. * 'class' => 'yii\web\DbSession',
  25. * // 'db' => 'mydb',
  26. * // 'sessionTable' => 'my_session',
  27. * ]
  28. * ~~~
  29. *
  30. * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only.
  31. *
  32. * @author Qiang Xue <qiang.xue@gmail.com>
  33. * @since 2.0
  34. */
  35. class DbSession extends Session
  36. {
  37. /**
  38. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  39. * After the DbSession object is created, if you want to change this property, you should only assign it
  40. * with a DB connection object.
  41. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  42. */
  43. public $db = 'db';
  44. /**
  45. * @var string the name of the DB table that stores the session data.
  46. * The table should be pre-created as follows:
  47. *
  48. * ~~~
  49. * CREATE TABLE session
  50. * (
  51. * id CHAR(40) NOT NULL PRIMARY KEY,
  52. * expire INTEGER,
  53. * data BLOB
  54. * )
  55. * ~~~
  56. *
  57. * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
  58. * that can be used for some popular DBMS:
  59. *
  60. * - MySQL: LONGBLOB
  61. * - PostgreSQL: BYTEA
  62. * - MSSQL: BLOB
  63. *
  64. * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
  65. * column in the session table to improve the performance.
  66. *
  67. * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
  68. * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
  69. * length 64 instead of 40.
  70. */
  71. public $sessionTable = '{{%session}}';
  72. /**
  73. * Initializes the DbSession component.
  74. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  75. * @throws InvalidConfigException if [[db]] is invalid.
  76. */
  77. public function init()
  78. {
  79. parent::init();
  80. $this->db = Instance::ensure($this->db, Connection::className());
  81. }
  82. /**
  83. * Returns a value indicating whether to use custom session storage.
  84. * This method overrides the parent implementation and always returns true.
  85. * @return boolean whether to use custom storage.
  86. */
  87. public function getUseCustomStorage()
  88. {
  89. return true;
  90. }
  91. /**
  92. * Updates the current session ID with a newly generated one .
  93. * Please refer to <http://php.net/session_regenerate_id> for more details.
  94. * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
  95. */
  96. public function regenerateID($deleteOldSession = false)
  97. {
  98. $oldID = session_id();
  99. // if no session is started, there is nothing to regenerate
  100. if (empty($oldID)) {
  101. return;
  102. }
  103. parent::regenerateID(false);
  104. $newID = session_id();
  105. $query = new Query;
  106. $row = $query->from($this->sessionTable)
  107. ->where(['id' => $oldID])
  108. ->createCommand($this->db)
  109. ->queryOne();
  110. if ($row !== false) {
  111. if ($deleteOldSession) {
  112. $this->db->createCommand()
  113. ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
  114. ->execute();
  115. } else {
  116. $row['id'] = $newID;
  117. $this->db->createCommand()
  118. ->insert($this->sessionTable, $row)
  119. ->execute();
  120. }
  121. } else {
  122. // shouldn't reach here normally
  123. $this->db->createCommand()
  124. ->insert($this->sessionTable, [
  125. 'id' => $newID,
  126. 'expire' => time() + $this->getTimeout(),
  127. ])->execute();
  128. }
  129. }
  130. /**
  131. * Session read handler.
  132. * Do not call this method directly.
  133. * @param string $id session ID
  134. * @return string the session data
  135. */
  136. public function readSession($id)
  137. {
  138. $query = new Query;
  139. $data = $query->select(['data'])
  140. ->from($this->sessionTable)
  141. ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id])
  142. ->createCommand($this->db)
  143. ->queryScalar();
  144. return $data === false ? '' : $data;
  145. }
  146. /**
  147. * Session write handler.
  148. * Do not call this method directly.
  149. * @param string $id session ID
  150. * @param string $data session data
  151. * @return boolean whether session write is successful
  152. */
  153. public function writeSession($id, $data)
  154. {
  155. // exception must be caught in session write handler
  156. // http://us.php.net/manual/en/function.session-set-save-handler.php
  157. try {
  158. $expire = time() + $this->getTimeout();
  159. $query = new Query;
  160. $exists = $query->select(['id'])
  161. ->from($this->sessionTable)
  162. ->where(['id' => $id])
  163. ->createCommand($this->db)
  164. ->queryScalar();
  165. if ($exists === false) {
  166. $this->db->createCommand()
  167. ->insert($this->sessionTable, [
  168. 'id' => $id,
  169. 'data' => $data,
  170. 'expire' => $expire,
  171. ])->execute();
  172. } else {
  173. $this->db->createCommand()
  174. ->update($this->sessionTable, ['data' => $data, 'expire' => $expire], ['id' => $id])
  175. ->execute();
  176. }
  177. } catch (\Exception $e) {
  178. $exception = ErrorHandler::convertExceptionToString($e);
  179. // its too late to use Yii logging here
  180. error_log($exception);
  181. echo $exception;
  182. return false;
  183. }
  184. return true;
  185. }
  186. /**
  187. * Session destroy handler.
  188. * Do not call this method directly.
  189. * @param string $id session ID
  190. * @return boolean whether session is destroyed successfully
  191. */
  192. public function destroySession($id)
  193. {
  194. $this->db->createCommand()
  195. ->delete($this->sessionTable, ['id' => $id])
  196. ->execute();
  197. return true;
  198. }
  199. /**
  200. * Session GC (garbage collection) handler.
  201. * Do not call this method directly.
  202. * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  203. * @return boolean whether session is GCed successfully
  204. */
  205. public function gcSession($maxLifetime)
  206. {
  207. $this->db->createCommand()
  208. ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
  209. ->execute();
  210. return true;
  211. }
  212. }