Completed
Push — StalkAlex-fix-session-php72 ( 547f3e )
by Alexander
13:17 queued 01:33
created

DbSession::gcSession()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
eloc 5
nc 1
nop 1
crap 1
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
use yii\helpers\ArrayHelper;
17
18
/**
19
 * DbSession extends [[Session]] by using database as session data storage.
20
 *
21
 * By default, DbSession stores session data in a DB table named 'session'. This table
22
 * must be pre-created. The table name can be changed by setting [[sessionTable]].
23
 *
24
 * The following example shows how you can configure the application to use DbSession:
25
 * Add the following to your application config under `components`:
26
 *
27
 * ```php
28
 * 'session' => [
29
 *     'class' => 'yii\web\DbSession',
30
 *     // 'db' => 'mydb',
31
 *     // 'sessionTable' => 'my_session',
32
 * ]
33
 * ```
34
 *
35
 * DbSession extends [[MultiFieldSession]], thus it allows saving extra fields into the [[sessionTable]].
36
 * Refer to [[MultiFieldSession]] for more details.
37
 *
38
 * @author Qiang Xue <[email protected]>
39
 * @since 2.0
40
 */
41
class DbSession extends MultiFieldSession
42
{
43
    /**
44
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
45
     * After the DbSession object is created, if you want to change this property, you should only assign it
46
     * with a DB connection object.
47
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
48
     */
49
    public $db = 'db';
50
    /**
51
     * @var string the name of the DB table that stores the session data.
52
     * The table should be pre-created as follows:
53
     *
54
     * ```sql
55
     * CREATE TABLE session
56
     * (
57
     *     id CHAR(40) NOT NULL PRIMARY KEY,
58
     *     expire INTEGER,
59
     *     data BLOB
60
     * )
61
     * ```
62
     *
63
     * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
64
     * that can be used for some popular DBMS:
65
     *
66
     * - MySQL: LONGBLOB
67
     * - PostgreSQL: BYTEA
68
     * - MSSQL: BLOB
69
     *
70
     * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
71
     * column in the session table to improve the performance.
72
     *
73
     * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
74
     * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
75
     * length 64 instead of 40.
76
     */
77
    public $sessionTable = '{{%session}}';
78
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 15
    public function __construct(array $config = [])
85
    {
86
        // db component should be initialized before configuring DbSession component
87
        // @see https://github.com/yiisoft/yii2/pull/15523#discussion_r166701079
88 15
        $this->db = Instance::ensure(ArrayHelper::remove($config, 'db', $this->db), Connection::className());
89 15
        parent::__construct($config);
90 12
    }
91
92
    /**
93
     * Updates the current session ID with a newly generated one .
94
     * Please refer to <http://php.net/session_regenerate_id> for more details.
95
     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
96
     */
97
    public function regenerateID($deleteOldSession = false)
98
    {
99
        $oldID = session_id();
100
101
        // if no session is started, there is nothing to regenerate
102
        if (empty($oldID)) {
103
            return;
104
        }
105
106
        parent::regenerateID(false);
107
        $newID = session_id();
108
        // if session id regeneration failed, no need to create/update it.
109
        if (empty($newID)) {
110
            Yii::warning('Failed to generate new session ID', __METHOD__);
111
            return;
112
        }
113
114
        $query = new Query();
115
        $row = $query->from($this->sessionTable)
116
            ->where(['id' => $oldID])
117
            ->createCommand($this->db)
118
            ->queryOne();
119
        if ($row !== false) {
120
            if ($deleteOldSession) {
121
                $this->db->createCommand()
122
                    ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
123
                    ->execute();
124
            } else {
125
                $row['id'] = $newID;
126
                $this->db->createCommand()
127
                    ->insert($this->sessionTable, $row)
128
                    ->execute();
129
            }
130
        } else {
131
            // shouldn't reach here normally
132
            $this->db->createCommand()
133
                ->insert($this->sessionTable, $this->composeFields($newID, ''))
134
                ->execute();
135
        }
136
    }
137
138
    /**
139
     * Session read handler.
140
     * @internal Do not call this method directly.
141
     * @param string $id session ID
142
     * @return string the session data
143
     */
144 12
    public function readSession($id)
145
    {
146 12
        $query = new Query();
147 12
        $query->from($this->sessionTable)
148 12
            ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
149
150 12
        if ($this->readCallback !== null) {
151
            $fields = $query->one($this->db);
152
            return $fields === false ? '' : $this->extractData($fields);
153
        }
154
155 12
        $data = $query->select(['data'])->scalar($this->db);
156 12
        return $data === false ? '' : $data;
157
    }
158
159
    /**
160
     * Session write handler.
161
     * @internal Do not call this method directly.
162
     * @param string $id session ID
163
     * @param string $data session data
164
     * @return bool whether session write is successful
165
     */
166 12
    public function writeSession($id, $data)
167
    {
168
        // exception must be caught in session write handler
169
        // http://us.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
170
        try {
171 12
            $query = new Query();
172 12
            $exists = $query->select(['id'])
173 12
                ->from($this->sessionTable)
174 12
                ->where(['id' => $id])
175 12
                ->createCommand($this->db)
176 12
                ->queryScalar();
177 12
            $fields = $this->composeFields($id, $data);
178 12
            $fields = $this->typecastFields($fields);
179 12
            if ($exists === false) {
180 12
                $this->db->createCommand()
181 12
                    ->insert($this->sessionTable, $fields)
182 12
                    ->execute();
183
            } else {
184
                unset($fields['id']);
185
                $this->db->createCommand()
186
                    ->update($this->sessionTable, $fields, ['id' => $id])
187 12
                    ->execute();
188
            }
189
        } catch (\Exception $e) {
190
            Yii::$app->errorHandler->handleException($e);
191
            return false;
192
        }
193
194 12
        return true;
195
    }
196
197
    /**
198
     * Session destroy handler.
199
     * @internal Do not call this method directly.
200
     * @param string $id session ID
201
     * @return bool whether session is destroyed successfully
202
     */
203 3
    public function destroySession($id)
204
    {
205 3
        $this->db->createCommand()
206 3
            ->delete($this->sessionTable, ['id' => $id])
207 3
            ->execute();
208
209 3
        return true;
210
    }
211
212
    /**
213
     * Session GC (garbage collection) handler.
214
     * @internal Do not call this method directly.
215
     * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
216
     * @return bool whether session is GCed successfully
217
     */
218 3
    public function gcSession($maxLifetime)
219
    {
220 3
        $this->db->createCommand()
221 3
            ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
222 3
            ->execute();
223
224 3
        return true;
225
    }
226
227
    /**
228
     * Method typecasts $fields before passing them to PDO.
229
     * Default implementation casts field `data` to `\PDO::PARAM_LOB`.
230
     * You can override this method in case you need special type casting.
231
     *
232
     * @param array $fields Fields, that will be passed to PDO. Key - name, Value - value
233
     * @return array
234
     * @since 2.0.13
235
     */
236 12
    protected function typecastFields($fields)
237
    {
238 12
        if (isset($fields['data']) && is_array($fields['data'] && is_object($fields['data']))) {
239
            $fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
240
        }
241
242 12
        return $fields;
243
    }
244
}
245