Passed
Pull Request — master (#19131)
by Sam
37:18
created

DbSession::writeSession()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.392

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 7
eloc 16
nc 20
nop 2
dl 0
loc 28
ccs 12
cts 15
cp 0.8
crap 7.392
rs 8.8333
c 1
b 1
f 0
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
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\db\Connection;
13
use yii\db\PdoValue;
14
use yii\db\Query;
15
use yii\di\Instance;
16
17
/**
18
 * DbSession extends [[Session]] by using database as session data storage.
19
 *
20
 * By default, DbSession stores session data in a DB table named 'session'. This table
21
 * must be pre-created. The table name can be changed by setting [[sessionTable]].
22
 *
23
 * The following example shows how you can configure the application to use DbSession:
24
 * Add the following to your application config under `components`:
25
 *
26
 * ```php
27
 * 'session' => [
28
 *     'class' => 'yii\web\DbSession',
29
 *     // 'db' => 'mydb',
30
 *     // 'sessionTable' => 'my_session',
31
 * ]
32
 * ```
33
 *
34
 * DbSession extends [[MultiFieldSession]], thus it allows saving extra fields into the [[sessionTable]].
35
 * Refer to [[MultiFieldSession]] for more details.
36
 *
37
 * @author Qiang Xue <[email protected]>
38
 * @since 2.0
39
 */
40
class DbSession extends MultiFieldSession
41
{
42
    /**
43
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
44
     * After the DbSession object is created, if you want to change this property, you should only assign it
45
     * with a DB connection object.
46
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
47
     */
48
    public $db = 'db';
49
    /**
50
     * @var string the name of the DB table that stores the session data.
51
     * The table should be pre-created as follows:
52
     *
53
     * ```sql
54
     * CREATE TABLE session
55
     * (
56
     *     id CHAR(40) NOT NULL PRIMARY KEY,
57
     *     expire INTEGER,
58
     *     data BLOB
59
     * )
60
     * ```
61
     *
62
     * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
63
     * that can be used for some popular DBMS:
64
     *
65
     * - MySQL: LONGBLOB
66
     * - PostgreSQL: BYTEA
67
     * - MSSQL: BLOB
68
     *
69
     * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
70
     * column in the session table to improve the performance.
71
     *
72
     * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
73
     * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
74
     * length 64 instead of 40.
75
     */
76
    public $sessionTable = '{{%session}}';
77
78
    /**
79
     * @var array Session fields to be written into session table columns
80
     * @since 2.0.17
81
     */
82
    protected $fields = [];
83
84
85
    /**
86
     * Initializes the DbSession component.
87
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
88
     * @throws InvalidConfigException if [[db]] is invalid.
89
     */
90 45
    public function init()
91
    {
92 45
        parent::init();
93 45
        $this->db = Instance::ensure($this->db, Connection::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

93
        $this->db = Instance::ensure($this->db, /** @scrutinizer ignore-deprecated */ Connection::className());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
94 45
    }
95
96
    /**
97
     * Session open handler.
98
     * @internal Do not call this method directly.
99
     * @param string $savePath session save path
100
     * @param string $sessionName session name
101
     * @return bool whether session is opened successfully
102
     */
103 10
    public function openSession($savePath, $sessionName)
104
    {
105 10
        if ($this->getUseStrictMode()) {
106 8
            $id = $this->getId();
107 8
            if (!$this->getReadQuery($id)->exists($this->db)) {
108
                //This session id does not exist, mark it for forced regeneration
109 8
                $this->_forceRegenerateId = $id;
110
            }
111
        }
112
113 10
        return parent::openSession($savePath, $sessionName);
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119 8
    public function regenerateID($deleteOldSession = false)
120
    {
121 8
        $oldID = session_id();
122
123
        // if no session is started, there is nothing to regenerate
124 8
        if (empty($oldID)) {
125
            return;
126
        }
127
128 8
        parent::regenerateID(false);
129 8
        $newID = session_id();
130
        // if session id regeneration failed, no need to create/update it.
131 8
        if (empty($newID)) {
132
            Yii::warning('Failed to generate new session ID', __METHOD__);
133
            return;
134
        }
135
136 8
        $row = $this->db->useMaster(function() use ($oldID) {
137 8
            return (new Query())->from($this->sessionTable)
138 8
               ->where(['id' => $oldID])
139 8
               ->createCommand($this->db)
140 8
               ->queryOne();
141 8
        });
142
143 8
        if ($row !== false) {
144
            if ($deleteOldSession) {
145
                $this->db->createCommand()
146
                    ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
147
                    ->execute();
148
            } else {
149
                $row['id'] = $newID;
150
                $this->db->createCommand()
151
                    ->insert($this->sessionTable, $row)
152
                    ->execute();
153
            }
154
        } else {
155
            // shouldn't reach here normally
156 8
            $this->db->createCommand()
157 8
                ->insert($this->sessionTable, $this->composeFields($newID, ''))
158 8
                ->execute();
159
        }
160 8
    }
161
162
    /**
163
     * Ends the current session and store session data.
164
     * @since 2.0.17
165
     */
166 15
    public function close()
167
    {
168 15
        if ($this->getIsActive()) {
169
            // prepare writeCallback fields before session closes
170 10
            $this->fields = $this->composeFields();
171 10
            YII_DEBUG ? session_write_close() : @session_write_close();
172
        }
173 15
    }
174
175
    /**
176
     * Session read handler.
177
     * @internal Do not call this method directly.
178
     * @param string $id session ID
179
     * @return string the session data
180
     */
181 35
    public function readSession($id)
182
    {
183 35
        $query = $this->getReadQuery($id);
184
185 35
        if ($this->readCallback !== null) {
186
            $fields = $query->one($this->db);
187
            return $fields === false ? '' : $this->extractData($fields);
188
        }
189
190 35
        $data = $query->select(['data'])->scalar($this->db);
191 35
        return $data === false ? '' : $data;
192
    }
193
194
    protected function composeFields($id = null, $data = null)
195
    {
196
        $fields = parent::composeFields($id, $data);
197
        $fields['expire'] = time() + $this->getTimeout();
198
        return $fields;
199
    }
200
201 35
    /**
202
     * Session write handler.
203 35
     * @internal Do not call this method directly.
204
     * @param string $id session ID
205 8
     * @param string $data session data
206
     * @return bool whether session write is successful
207
     */
208
    public function writeSession($id, $data)
209
    {
210
        if ($this->getUseStrictMode() && $id === $this->_forceRegenerateId) {
211
            //Ignore write when forceRegenerate is active for this id
212 35
            return true;
213 5
        }
214
215
        // exception must be caught in session write handler
216 35
        // https://www.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
217 30
        try {
218
            // ensure backwards compatability (fixed #9438)
219 5
            if ($this->writeCallback && !$this->fields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->fields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
220
                $this->fields = $this->composeFields();
221
            }
222 35
            // ensure data consistency
223 35
            if (!isset($this->fields['data'])) {
224 35
                $this->fields['data'] = $data;
225
            } else {
226 35
                $_SESSION = $this->fields['data'];
227 35
            }
228 35
            $this->fields = $this->typecastFields($this->fields);
229
            $this->db->createCommand()->upsert($this->sessionTable, $this->fields)->execute();
230
            $this->fields = [];
231
        } catch (\Exception $e) {
232
            Yii::$app->errorHandler->handleException($e);
233 35
            return false;
234
        }
235
        return true;
236
    }
237
238
    /**
239
     * Session destroy handler.
240
     * @internal Do not call this method directly.
241
     * @param string $id session ID
242 15
     * @return bool whether session is destroyed successfully
243
     */
244 15
    public function destroySession($id)
245 15
    {
246 15
        $this->db->createCommand()
247
            ->delete($this->sessionTable, ['id' => $id])
248 15
            ->execute();
249
250
        return true;
251
    }
252
253
    /**
254
     * Session GC (garbage collection) handler.
255
     * @internal Do not call this method directly.
256
     * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
257 5
     * @return bool whether session is GCed successfully
258
     */
259 5
    public function gcSession($maxLifetime)
260 5
    {
261 5
        $this->db->createCommand()
262
            ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
263 5
            ->execute();
264
265
        return true;
266
    }
267
268
    /**
269
     * Generates a query to get the session from db
270
     * @param string $id The id of the session
271 35
     * @return Query
272
     */
273 35
    protected function getReadQuery($id)
274 35
    {
275 35
        return (new Query())
276
            ->from($this->sessionTable)
277
            ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
278
    }
279
280
    /**
281
     * Method typecasts $fields before passing them to PDO.
282
     * Default implementation casts field `data` to `\PDO::PARAM_LOB`.
283
     * You can override this method in case you need special type casting.
284
     *
285
     * @param array $fields Fields, that will be passed to PDO. Key - name, Value - value
286
     * @return array
287 35
     * @since 2.0.13
288
     */
289 35
    protected function typecastFields($fields)
290 35
    {
291
        if (isset($fields['data']) && !is_array($fields['data']) && !is_object($fields['data'])) {
292
            $fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
293 35
        }
294
295
        return $fields;
296
    }
297
}
298