DbSession.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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\InvalidConfigException;
  10. use yii\db\Connection;
  11. use yii\db\PdoValue;
  12. use yii\db\Query;
  13. use yii\di\Instance;
  14. /**
  15. * DbSession extends [[Session]] by using database as session data storage.
  16. *
  17. * By default, DbSession stores session data in a DB table named 'session'. This table
  18. * must be pre-created. The table name can be changed by setting [[sessionTable]].
  19. *
  20. * The following example shows how you can configure the application to use DbSession:
  21. * Add the following to your application config under `components`:
  22. *
  23. * ```php
  24. * 'session' => [
  25. * 'class' => 'yii\web\DbSession',
  26. * // 'db' => 'mydb',
  27. * // 'sessionTable' => 'my_session',
  28. * ]
  29. * ```
  30. *
  31. * DbSession extends [[MultiFieldSession]], thus it allows saving extra fields into the [[sessionTable]].
  32. * Refer to [[MultiFieldSession]] for more details.
  33. *
  34. * @author Qiang Xue <qiang.xue@gmail.com>
  35. * @since 2.0
  36. */
  37. class DbSession extends MultiFieldSession
  38. {
  39. /**
  40. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  41. * After the DbSession object is created, if you want to change this property, you should only assign it
  42. * with a DB connection object.
  43. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  44. */
  45. public $db = 'db';
  46. /**
  47. * @var string the name of the DB table that stores the session data.
  48. * The table should be pre-created as follows:
  49. *
  50. * ```sql
  51. * CREATE TABLE session
  52. * (
  53. * id CHAR(40) NOT NULL PRIMARY KEY,
  54. * expire INTEGER,
  55. * data BLOB
  56. * )
  57. * ```
  58. *
  59. * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
  60. * that can be used for some popular DBMS:
  61. *
  62. * - MySQL: LONGBLOB
  63. * - PostgreSQL: BYTEA
  64. * - MSSQL: BLOB
  65. *
  66. * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
  67. * column in the session table to improve the performance.
  68. *
  69. * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
  70. * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
  71. * length 64 instead of 40.
  72. */
  73. public $sessionTable = '{{%session}}';
  74. /**
  75. * @var array Session fields to be written into session table columns
  76. * @since 2.0.17
  77. */
  78. protected $fields = [];
  79. /**
  80. * Initializes the DbSession component.
  81. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  82. * @throws InvalidConfigException if [[db]] is invalid.
  83. */
  84. public function init()
  85. {
  86. parent::init();
  87. $this->db = Instance::ensure($this->db, Connection::className());
  88. }
  89. /**
  90. * Session open handler.
  91. * @internal Do not call this method directly.
  92. * @param string $savePath session save path
  93. * @param string $sessionName session name
  94. * @return bool whether session is opened successfully
  95. */
  96. public function openSession($savePath, $sessionName)
  97. {
  98. if ($this->getUseStrictMode()) {
  99. $id = $this->getId();
  100. if (!$this->getReadQuery($id)->exists()) {
  101. //This session id does not exist, mark it for forced regeneration
  102. $this->_forceRegenerateId = $id;
  103. }
  104. }
  105. return parent::openSession($savePath, $sessionName);
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function regenerateID($deleteOldSession = false)
  111. {
  112. $oldID = session_id();
  113. // if no session is started, there is nothing to regenerate
  114. if (empty($oldID)) {
  115. return;
  116. }
  117. parent::regenerateID(false);
  118. $newID = session_id();
  119. // if session id regeneration failed, no need to create/update it.
  120. if (empty($newID)) {
  121. Yii::warning('Failed to generate new session ID', __METHOD__);
  122. return;
  123. }
  124. $row = $this->db->useMaster(function() use ($oldID) {
  125. return (new Query())->from($this->sessionTable)
  126. ->where(['id' => $oldID])
  127. ->createCommand($this->db)
  128. ->queryOne();
  129. });
  130. if ($row !== false) {
  131. if ($deleteOldSession) {
  132. $this->db->createCommand()
  133. ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
  134. ->execute();
  135. } else {
  136. $row['id'] = $newID;
  137. $this->db->createCommand()
  138. ->insert($this->sessionTable, $row)
  139. ->execute();
  140. }
  141. } else {
  142. // shouldn't reach here normally
  143. $this->db->createCommand()
  144. ->insert($this->sessionTable, $this->composeFields($newID, ''))
  145. ->execute();
  146. }
  147. }
  148. /**
  149. * Ends the current session and store session data.
  150. * @since 2.0.17
  151. */
  152. public function close()
  153. {
  154. if ($this->getIsActive()) {
  155. // prepare writeCallback fields before session closes
  156. $this->fields = $this->composeFields();
  157. YII_DEBUG ? session_write_close() : @session_write_close();
  158. }
  159. }
  160. /**
  161. * Session read handler.
  162. * @internal Do not call this method directly.
  163. * @param string $id session ID
  164. * @return string the session data
  165. */
  166. public function readSession($id)
  167. {
  168. $query = $this->getReadQuery($id);
  169. if ($this->readCallback !== null) {
  170. $fields = $query->one($this->db);
  171. return $fields === false ? '' : $this->extractData($fields);
  172. }
  173. $data = $query->select(['data'])->scalar($this->db);
  174. return $data === false ? '' : $data;
  175. }
  176. /**
  177. * Session write handler.
  178. * @internal Do not call this method directly.
  179. * @param string $id session ID
  180. * @param string $data session data
  181. * @return bool whether session write is successful
  182. */
  183. public function writeSession($id, $data)
  184. {
  185. if ($this->getUseStrictMode() && $id === $this->_forceRegenerateId) {
  186. //Ignore write when forceRegenerate is active for this id
  187. return true;
  188. }
  189. // exception must be caught in session write handler
  190. // https://secure.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
  191. try {
  192. // ensure backwards compatability (fixed #9438)
  193. if ($this->writeCallback && !$this->fields) {
  194. $this->fields = $this->composeFields();
  195. }
  196. // ensure data consistency
  197. if (!isset($this->fields['data'])) {
  198. $this->fields['data'] = $data;
  199. } else {
  200. $_SESSION = $this->fields['data'];
  201. }
  202. // ensure 'id' and 'expire' are never affected by [[writeCallback]]
  203. $this->fields = array_merge($this->fields, [
  204. 'id' => $id,
  205. 'expire' => time() + $this->getTimeout(),
  206. ]);
  207. $this->fields = $this->typecastFields($this->fields);
  208. $this->db->createCommand()->upsert($this->sessionTable, $this->fields)->execute();
  209. $this->fields = [];
  210. } catch (\Exception $e) {
  211. Yii::$app->errorHandler->handleException($e);
  212. return false;
  213. }
  214. return true;
  215. }
  216. /**
  217. * Session destroy handler.
  218. * @internal Do not call this method directly.
  219. * @param string $id session ID
  220. * @return bool whether session is destroyed successfully
  221. */
  222. public function destroySession($id)
  223. {
  224. $this->db->createCommand()
  225. ->delete($this->sessionTable, ['id' => $id])
  226. ->execute();
  227. return true;
  228. }
  229. /**
  230. * Session GC (garbage collection) handler.
  231. * @internal Do not call this method directly.
  232. * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
  233. * @return bool whether session is GCed successfully
  234. */
  235. public function gcSession($maxLifetime)
  236. {
  237. $this->db->createCommand()
  238. ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
  239. ->execute();
  240. return true;
  241. }
  242. /**
  243. * Generates a query to get the session from db
  244. * @param string $id The id of the session
  245. * @return Query
  246. */
  247. protected function getReadQuery($id)
  248. {
  249. return (new Query())
  250. ->from($this->sessionTable)
  251. ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
  252. }
  253. /**
  254. * Method typecasts $fields before passing them to PDO.
  255. * Default implementation casts field `data` to `\PDO::PARAM_LOB`.
  256. * You can override this method in case you need special type casting.
  257. *
  258. * @param array $fields Fields, that will be passed to PDO. Key - name, Value - value
  259. * @return array
  260. * @since 2.0.13
  261. */
  262. protected function typecastFields($fields)
  263. {
  264. if (isset($fields['data']) && !is_array($fields['data']) && !is_object($fields['data'])) {
  265. $fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
  266. }
  267. return $fields;
  268. }
  269. }