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.

223 line
7.1KB

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