Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

Session   F

Complexity

Total Complexity 131

Size/Duplication

Total Lines 986
Duplicated Lines 0 %

Test Coverage

Coverage 58.9%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 260
c 1
b 0
f 0
dl 0
loc 986
ccs 172
cts 292
cp 0.589
rs 2
wmc 131

59 Methods

Rating   Name   Duplication   Size   Complexity  
A setUseTransparentSessionID() 0 5 2
A getUseCustomStorage() 0 3 1
A init() 0 7 2
A removeAll() 0 5 2
A removeFlash() 0 8 2
A setSavePath() 0 7 2
A set() 0 4 1
A getGCProbability() 0 3 1
A offsetUnset() 0 5 1
A getCacheLimiter() 0 3 1
A getCookieParams() 0 3 1
A openSession() 0 3 1
A getUseCookies() 0 9 3
A addFlash() 0 11 4
A setCacheLimiter() 0 5 1
A freeze() 0 8 3
A offsetGet() 0 6 2
A getHasSessionId() 0 15 6
A closeSession() 0 3 1
A readSession() 0 3 1
A offsetSet() 0 5 1
A has() 0 4 1
A getUseTransparentSessionID() 0 3 1
A setTimeout() 0 5 1
A setUseStrictMode() 0 12 5
A gcSession() 0 3 1
A setUseCookies() 0 14 3
A getTimeout() 0 3 1
A getUseStrictMode() 0 7 2
A setGCProbability() 0 11 3
A getName() 0 3 1
A setCookieParams() 0 3 1
A setHasSessionId() 0 3 1
A regenerateID() 0 9 4
A getSavePath() 0 3 1
A getFlash() 0 17 4
A destroy() 0 10 2
A setFlash() 0 6 2
A destroySession() 0 3 1
A getCount() 0 4 1
A remove() 0 11 2
A setId() 0 3 1
A removeAllFlashes() 0 7 2
A getIsActive() 0 3 1
A unfreeze() 0 15 5
A updateFlashCounters() 0 15 5
B open() 0 26 8
A getId() 0 3 1
A offsetExists() 0 6 1
A setCookieParamsInternal() 0 14 4
A writeSession() 0 3 1
A count() 0 4 1
A get() 0 4 2
A hasFlash() 0 3 1
A close() 0 7 3
A getIterator() 0 5 1
A getAllFlashes() 0 21 5
A setName() 0 5 1
B registerSessionHandler() 0 30 11

How to fix   Complexity   

Complex Class

Complex classes like Session often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Session, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\web;
10
11
use Yii;
12
use yii\base\Component;
13
use yii\base\InvalidArgumentException;
14
use yii\base\InvalidConfigException;
15
16
/**
17
 * Session provides session data management and the related configurations.
18
 *
19
 * Session is a Web application component that can be accessed via `Yii::$app->session`.
20
 *
21
 * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
22
 * To destroy the session, call [[destroy()]].
23
 *
24
 * Session can be used like an array to set and get session data. For example,
25
 *
26
 * ```php
27
 * $session = new Session;
28
 * $session->open();
29
 * $value1 = $session['name1'];  // get session variable 'name1'
30
 * $value2 = $session['name2'];  // get session variable 'name2'
31
 * foreach ($session as $name => $value) // traverse all session variables
32
 * $session['name3'] = $value3;  // set session variable 'name3'
33
 * ```
34
 *
35
 * Session can be extended to support customized session storage.
36
 * To do so, override [[useCustomStorage]] so that it returns true, and
37
 * override these methods with the actual logic about using custom storage:
38
 * [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
39
 * [[destroySession()]] and [[gcSession()]].
40
 *
41
 * Session also supports a special type of session data, called *flash messages*.
42
 * A flash message is available only in the current request and the next request.
43
 * After that, it will be deleted automatically. Flash messages are particularly
44
 * useful for displaying confirmation messages. To use flash messages, simply
45
 * call methods such as [[setFlash()]], [[getFlash()]].
46
 *
47
 * For more details and usage information on Session, see the [guide article on sessions](guide:runtime-sessions-cookies).
48
 *
49
 * @property-read array $allFlashes Flash messages (key => message or key => [message1, message2]).
50
 * @property-read string $cacheLimiter Current cache limiter.
51
 * @property-read array $cookieParams The session cookie parameters.
52
 * @property-read int $count The number of session variables.
53
 * @property-write string $flash The key identifying the flash message. Note that flash messages and normal
54
 * session variables share the same name space. If you have a normal session variable using the same name, its
55
 * value will be overwritten by this method.
56
 * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
57
 * started on every session initialization.
58
 * @property bool $hasSessionId Whether the current request has sent the session ID.
59
 * @property string $id The current session ID.
60
 * @property-read bool $isActive Whether the session has started.
61
 * @property-read SessionIterator $iterator An iterator for traversing the session variables.
62
 * @property string $name The current session name.
63
 * @property string $savePath The current session save path, defaults to '/tmp'.
64
 * @property int $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. The
65
 * default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
66
 * @property bool|null $useCookies The value indicating whether cookies should be used to store session IDs.
67
 * @property-read bool $useCustomStorage Whether to use custom storage.
68
 * @property bool $useStrictMode Whether strict mode is enabled or not.
69
 * @property bool $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to
70
 * false.
71
 *
72
 * @author Qiang Xue <[email protected]>
73
 * @since 2.0
74
 */
75
class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
76
{
77
    /**
78
     * @var string|null Holds the original session module (before a custom handler is registered) so that it can be
79
     * restored when a Session component without custom handler is used after one that has.
80
     */
81
    protected static $_originalSessionModule = null;
82
    /**
83
     * Polyfill for ini directive session.use-strict-mode for PHP < 5.5.2.
84
     */
85
    private static $_useStrictModePolyfill = false;
86
    /**
87
     * @var string the name of the session variable that stores the flash message data.
88
     */
89
    public $flashParam = '__flash';
90
    /**
91
     * @var \SessionHandlerInterface|array an object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.
92
     */
93
    public $handler;
94
95
    /**
96
     * @var string|null Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated
97
     */
98
    protected $_forceRegenerateId = null;
99
100
    /**
101
     * @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
102
     * Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
103
     * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
104
     */
105
    private $_cookieParams = ['httponly' => true];
106
    /**
107
     * @var array|null is used for saving session between recreations due to session parameters update.
108
     */
109
    private $_frozenSessionData;
110
111
    /**
112
     * Initializes the application component.
113
     * This method is required by IApplicationComponent and is invoked by application.
114
     */
115 98
    public function init()
116
    {
117 98
        parent::init();
118 98
        register_shutdown_function([$this, 'close']);
119 98
        if ($this->getIsActive()) {
120 5
            Yii::warning('Session is already started', __METHOD__);
121 5
            $this->updateFlashCounters();
122
        }
123
    }
124
125
    /**
126
     * Returns a value indicating whether to use custom session storage.
127
     * This method should be overridden to return true by child classes that implement custom session storage.
128
     * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
129
     * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
130
     * @return bool whether to use custom storage.
131
     */
132 69
    public function getUseCustomStorage()
133
    {
134 69
        return false;
135
    }
136
137
    /**
138
     * Starts the session.
139
     */
140 72
    public function open()
141
    {
142 72
        if ($this->getIsActive()) {
143 72
            return;
144
        }
145
146 71
        $this->registerSessionHandler();
147
148 71
        if ($this->getUseCookies() !== false) {
149 71
            $this->setCookieParamsInternal();
150
        }
151
152 71
        YII_DEBUG ? session_start() : @session_start();
153
154 71
        if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
155 1
            $this->regenerateID();
156 1
            $this->_forceRegenerateId = null;
157
        }
158
159 71
        if ($this->getIsActive()) {
160 71
            Yii::info('Session started', __METHOD__);
161 71
            $this->updateFlashCounters();
162
        } else {
163
            $error = error_get_last();
164
            $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
165
            Yii::error($message, __METHOD__);
166
        }
167
    }
168
169
    /**
170
     * Registers session handler.
171
     * @throws \yii\base\InvalidConfigException
172
     */
173 71
    protected function registerSessionHandler()
174
    {
175 71
        $sessionModuleName = session_module_name();
176 71
        if (static::$_originalSessionModule === null) {
177 1
            static::$_originalSessionModule = $sessionModuleName;
178
        }
179
180 71
        if ($this->handler === null && $this->getUseCustomStorage()) {
181 2
            $this->handler = Yii::createObject(
182 2
                [
183 2
                    '__class' => SessionHandler::class,
184 2
                    '__construct()' => [$this],
185 2
                ]
186 2
            );
187
        }
188
189 71
        if ($this->handler !== null) {
190 2
            if (is_array($this->handler)) {
191
                $this->handler = Yii::createObject($this->handler);
192
            }
193 2
            if (!$this->handler instanceof \SessionHandlerInterface) {
194
                throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
195
            }
196 2
            YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
197
        } elseif (
198 69
            $sessionModuleName !== static::$_originalSessionModule
199 69
            && static::$_originalSessionModule !== null
200 69
            && static::$_originalSessionModule !== 'user'
201
        ) {
202 1
            session_module_name(static::$_originalSessionModule);
203
        }
204
    }
205
206
    /**
207
     * Ends the current session and store session data.
208
     */
209 94
    public function close()
210
    {
211 94
        if ($this->getIsActive()) {
212 71
            YII_DEBUG ? session_write_close() : @session_write_close();
213
        }
214
215 94
        $this->_forceRegenerateId = null;
216
    }
217
218
    /**
219
     * Frees all session variables and destroys all data registered to a session.
220
     *
221
     * This method has no effect when session is not [[getIsActive()|active]].
222
     * Make sure to call [[open()]] before calling it.
223
     * @see open()
224
     * @see isActive
225
     */
226 7
    public function destroy()
227
    {
228 7
        if ($this->getIsActive()) {
229 7
            $sessionId = session_id();
230 7
            $this->close();
231 7
            $this->setId($sessionId);
232 7
            $this->open();
233 7
            session_unset();
234 7
            session_destroy();
235 7
            $this->setId($sessionId);
236
        }
237
    }
238
239
    /**
240
     * @return bool whether the session has started
241
     */
242 98
    public function getIsActive()
243
    {
244 98
        return session_status() === PHP_SESSION_ACTIVE;
245
    }
246
247
    private $_hasSessionId;
248
249
    /**
250
     * Returns a value indicating whether the current request has sent the session ID.
251
     * The default implementation will check cookie and $_GET using the session name.
252
     * If you send session ID via other ways, you may need to override this method
253
     * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
254
     * @return bool whether the current request has sent the session ID.
255
     */
256 37
    public function getHasSessionId()
257
    {
258 37
        if ($this->_hasSessionId === null) {
259 37
            $name = $this->getName();
260 37
            $request = Yii::$app->getRequest();
261 37
            if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
262
                $this->_hasSessionId = true;
263 37
            } elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
264
                $this->_hasSessionId = $request->get($name) != '';
0 ignored issues
show
Bug introduced by
The method get() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

264
                $this->_hasSessionId = $request->/** @scrutinizer ignore-call */ get($name) != '';
Loading history...
265
            } else {
266 37
                $this->_hasSessionId = false;
267
            }
268
        }
269
270 37
        return $this->_hasSessionId;
271
    }
272
273
    /**
274
     * Sets the value indicating whether the current request has sent the session ID.
275
     * This method is provided so that you can override the default way of determining
276
     * whether the session ID is sent.
277
     * @param bool $value whether the current request has sent the session ID.
278
     */
279
    public function setHasSessionId($value)
280
    {
281
        $this->_hasSessionId = $value;
282
    }
283
284
    /**
285
     * Gets the session ID.
286
     * This is a wrapper for [PHP session_id()](https://www.php.net/manual/en/function.session-id.php).
287
     * @return string the current session ID
288
     */
289 15
    public function getId()
290
    {
291 15
        return session_id();
292
    }
293
294
    /**
295
     * Sets the session ID.
296
     * This is a wrapper for [PHP session_id()](https://www.php.net/manual/en/function.session-id.php).
297
     * @param string $value the session ID for the current session
298
     */
299 9
    public function setId($value)
300
    {
301 9
        session_id($value);
302
    }
303
304
    /**
305
     * Updates the current session ID with a newly generated one.
306
     *
307
     * Please refer to <https://www.php.net/session_regenerate_id> for more details.
308
     *
309
     * This method has no effect when session is not [[getIsActive()|active]].
310
     * Make sure to call [[open()]] before calling it.
311
     *
312
     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
313
     * @see open()
314
     * @see isActive
315
     */
316 46
    public function regenerateID($deleteOldSession = false)
317
    {
318 46
        if ($this->getIsActive()) {
319
            // add @ to inhibit possible warning due to race condition
320
            // https://github.com/yiisoft/yii2/pull/1812
321 33
            if (YII_DEBUG && !headers_sent()) {
322 33
                session_regenerate_id($deleteOldSession);
323
            } else {
324
                @session_regenerate_id($deleteOldSession);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for session_regenerate_id(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

324
                /** @scrutinizer ignore-unhandled */ @session_regenerate_id($deleteOldSession);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
325
            }
326
        }
327
    }
328
329
    /**
330
     * Gets the name of the current session.
331
     * This is a wrapper for [PHP session_name()](https://www.php.net/manual/en/function.session-name.php).
332
     * @return string the current session name
333
     */
334 38
    public function getName()
335
    {
336 38
        return session_name();
337
    }
338
339
    /**
340
     * Sets the name for the current session.
341
     * This is a wrapper for [PHP session_name()](https://www.php.net/manual/en/function.session-name.php).
342
     * @param string $value the session name for the current session, must be an alphanumeric string.
343
     * It defaults to "PHPSESSID".
344
     */
345 1
    public function setName($value)
346
    {
347 1
        $this->freeze();
348 1
        session_name($value);
349 1
        $this->unfreeze();
350
    }
351
352
    /**
353
     * Gets the current session save path.
354
     * This is a wrapper for [PHP session_save_path()](https://www.php.net/manual/en/function.session-save-path.php).
355
     * @return string the current session save path, defaults to '/tmp'.
356
     */
357
    public function getSavePath()
358
    {
359
        return session_save_path();
360
    }
361
362
    /**
363
     * Sets the current session save path.
364
     * This is a wrapper for [PHP session_save_path()](https://www.php.net/manual/en/function.session-save-path.php).
365
     * @param string $value the current session save path. This can be either a directory name or a [path alias](guide:concept-aliases).
366
     * @throws InvalidArgumentException if the path is not a valid directory
367
     */
368
    public function setSavePath($value)
369
    {
370
        $path = Yii::getAlias($value);
371
        if (is_dir($path)) {
0 ignored issues
show
Bug introduced by
It seems like $path can also be of type false; however, parameter $filename of is_dir() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

371
        if (is_dir(/** @scrutinizer ignore-type */ $path)) {
Loading history...
372
            session_save_path($path);
0 ignored issues
show
Bug introduced by
It seems like $path can also be of type false; however, parameter $path of session_save_path() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

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

372
            session_save_path(/** @scrutinizer ignore-type */ $path);
Loading history...
373
        } else {
374
            throw new InvalidArgumentException("Session save path is not a valid directory: $value");
375
        }
376
    }
377
378
    /**
379
     * @return array the session cookie parameters.
380
     * @see https://www.php.net/manual/en/function.session-get-cookie-params.php
381
     */
382 71
    public function getCookieParams()
383
    {
384 71
        return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
385
    }
386
387
    /**
388
     * Sets the session cookie parameters.
389
     * The cookie parameters passed to this method will be merged with the result
390
     * of `session_get_cookie_params()`.
391
     * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httponly`.
392
     * Starting with Yii 2.0.21 `sameSite` is also supported. It requires PHP version 7.3.0 or higher.
393
     * For security, an exception will be thrown if `sameSite` is set while using an unsupported version of PHP.
394
     * To use this feature across different PHP versions check the version first. E.g.
395
     * ```php
396
     * [
397
     *     'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,
398
     * ]
399
     * ```
400
     * See https://owasp.org/www-community/SameSite for more information about `sameSite`.
401
     *
402
     * @throws InvalidArgumentException if the parameters are incomplete.
403
     * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
404
     */
405
    public function setCookieParams(array $value)
406
    {
407
        $this->_cookieParams = $value;
408
    }
409
410
    /**
411
     * Sets the session cookie parameters.
412
     * This method is called by [[open()]] when it is about to open the session.
413
     * @throws InvalidArgumentException if the parameters are incomplete.
414
     * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
415
     */
416 71
    private function setCookieParamsInternal()
417
    {
418 71
        $data = $this->getCookieParams();
419 71
        if (isset($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly'])) {
420 71
            if (PHP_VERSION_ID >= 70300) {
421 71
                session_set_cookie_params($data);
422
            } else {
423
                if (!empty($data['samesite'])) {
424
                    $data['path'] .= '; samesite=' . $data['samesite'];
425
                }
426 71
                session_set_cookie_params($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly']);
427
            }
428
        } else {
429
            throw new InvalidArgumentException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.');
430
        }
431
    }
432
433
    /**
434
     * Returns the value indicating whether cookies should be used to store session IDs.
435
     * @return bool|null the value indicating whether cookies should be used to store session IDs.
436
     * @see setUseCookies()
437
     */
438 71
    public function getUseCookies()
439
    {
440 71
        if (ini_get('session.use_cookies') === '0') {
441 1
            return false;
442 71
        } elseif (ini_get('session.use_only_cookies') === '1') {
443 71
            return true;
444
        }
445
446
        return null;
447
    }
448
449
    /**
450
     * Sets the value indicating whether cookies should be used to store session IDs.
451
     *
452
     * Three states are possible:
453
     *
454
     * - true: cookies and only cookies will be used to store session IDs.
455
     * - false: cookies will not be used to store session IDs.
456
     * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
457
     *
458
     * @param bool|null $value the value indicating whether cookies should be used to store session IDs.
459
     */
460 1
    public function setUseCookies($value)
461
    {
462 1
        $this->freeze();
463 1
        if ($value === false) {
464 1
            ini_set('session.use_cookies', '0');
465 1
            ini_set('session.use_only_cookies', '0');
466 1
        } elseif ($value === true) {
0 ignored issues
show
introduced by
The condition $value === true is always true.
Loading history...
467 1
            ini_set('session.use_cookies', '1');
468 1
            ini_set('session.use_only_cookies', '1');
469
        } else {
470
            ini_set('session.use_cookies', '1');
471
            ini_set('session.use_only_cookies', '0');
472
        }
473 1
        $this->unfreeze();
474
    }
475
476
    /**
477
     * @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
478
     */
479 1
    public function getGCProbability()
480
    {
481 1
        return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
482
    }
483
484
    /**
485
     * @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
486
     * @throws InvalidArgumentException if the value is not between 0 and 100.
487
     */
488 1
    public function setGCProbability($value)
489
    {
490 1
        $this->freeze();
491 1
        if ($value >= 0 && $value <= 100) {
492
            // percent * 21474837 / 2147483647 ≈ percent * 0.01
493 1
            ini_set('session.gc_probability', floor($value * 21474836.47));
494 1
            ini_set('session.gc_divisor', 2147483647);
495
        } else {
496
            throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
497
        }
498 1
        $this->unfreeze();
499
    }
500
501
    /**
502
     * @return bool whether transparent sid support is enabled or not, defaults to false.
503
     */
504 1
    public function getUseTransparentSessionID()
505
    {
506 1
        return ini_get('session.use_trans_sid') == 1;
507
    }
508
509
    /**
510
     * @param bool $value whether transparent sid support is enabled or not.
511
     */
512 1
    public function setUseTransparentSessionID($value)
513
    {
514 1
        $this->freeze();
515 1
        ini_set('session.use_trans_sid', $value ? '1' : '0');
516 1
        $this->unfreeze();
517
    }
518
519
    /**
520
     * @return int the number of seconds after which data will be seen as 'garbage' and cleaned up.
521
     * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
522
     */
523 4
    public function getTimeout()
524
    {
525 4
        return (int) ini_get('session.gc_maxlifetime');
526
    }
527
528
    /**
529
     * @param int $value the number of seconds after which data will be seen as 'garbage' and cleaned up
530
     */
531 1
    public function setTimeout($value)
532
    {
533 1
        $this->freeze();
534 1
        ini_set('session.gc_maxlifetime', $value);
535 1
        $this->unfreeze();
536
    }
537
538
    /**
539
     * @param bool $value Whether strict mode is enabled or not.
540
     * When `true` this setting prevents the session component to use an uninitialized session ID.
541
     * Note: Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.
542
     * Warning! Although enabling strict mode is mandatory for secure sessions, the default value of 'session.use-strict-mode' is `0`.
543
     * @see https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode
544
     * @since 2.0.38
545
     */
546 4
    public function setUseStrictMode($value)
547
    {
548 4
        if (PHP_VERSION_ID < 50502) {
549
            if ($this->getUseCustomStorage() || !$value) {
550
                self::$_useStrictModePolyfill = $value;
551
            } else {
552
                throw new InvalidConfigException('Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.');
553
            }
554
        } else {
555 4
            $this->freeze();
556 4
            ini_set('session.use_strict_mode', $value ? '1' : '0');
557 4
            $this->unfreeze();
558
        }
559
    }
560
561
    /**
562
     * @return bool Whether strict mode is enabled or not.
563
     * @see setUseStrictMode()
564
     * @since 2.0.38
565
     */
566 74
    public function getUseStrictMode()
567
    {
568 74
        if (PHP_VERSION_ID < 50502) {
569
            return self::$_useStrictModePolyfill;
570
        }
571
572 74
        return (bool)ini_get('session.use_strict_mode');
573
    }
574
575
    /**
576
     * Session open handler.
577
     * This method should be overridden if [[useCustomStorage]] returns true.
578
     * @internal Do not call this method directly.
579
     * @param string $savePath session save path
580
     * @param string $sessionName session name
581
     * @return bool whether session is opened successfully
582
     */
583 3
    public function openSession($savePath, $sessionName)
0 ignored issues
show
Unused Code introduced by
The parameter $sessionName is not used and could be removed. ( Ignorable by Annotation )

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

583
    public function openSession($savePath, /** @scrutinizer ignore-unused */ $sessionName)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $savePath is not used and could be removed. ( Ignorable by Annotation )

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

583
    public function openSession(/** @scrutinizer ignore-unused */ $savePath, $sessionName)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
584
    {
585 3
        return true;
586
    }
587
588
    /**
589
     * Session close handler.
590
     * This method should be overridden if [[useCustomStorage]] returns true.
591
     * @internal Do not call this method directly.
592
     * @return bool whether session is closed successfully
593
     */
594 2
    public function closeSession()
595
    {
596 2
        return true;
597
    }
598
599
    /**
600
     * Session read handler.
601
     * This method should be overridden if [[useCustomStorage]] returns true.
602
     * @internal Do not call this method directly.
603
     * @param string $id session ID
604
     * @return string|false the session data, or false on failure
605
     */
606
    public function readSession($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

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

606
    public function readSession(/** @scrutinizer ignore-unused */ $id)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
607
    {
608
        return '';
609
    }
610
611
    /**
612
     * Session write handler.
613
     * This method should be overridden if [[useCustomStorage]] returns true.
614
     * @internal Do not call this method directly.
615
     * @param string $id session ID
616
     * @param string $data session data
617
     * @return bool whether session write is successful
618
     */
619
    public function writeSession($id, $data)
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed. ( Ignorable by Annotation )

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

619
    public function writeSession($id, /** @scrutinizer ignore-unused */ $data)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

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

619
    public function writeSession(/** @scrutinizer ignore-unused */ $id, $data)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
620
    {
621
        return true;
622
    }
623
624
    /**
625
     * Session destroy handler.
626
     * This method should be overridden if [[useCustomStorage]] returns true.
627
     * @internal Do not call this method directly.
628
     * @param string $id session ID
629
     * @return bool whether session is destroyed successfully
630
     */
631 1
    public function destroySession($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

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

631
    public function destroySession(/** @scrutinizer ignore-unused */ $id)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
632
    {
633 1
        return true;
634
    }
635
636
    /**
637
     * Session GC (garbage collection) handler.
638
     * This method should be overridden if [[useCustomStorage]] returns true.
639
     * @internal Do not call this method directly.
640
     * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
641
     * @return int|false the number of deleted sessions on success, or false on failure
642
     */
643
    public function gcSession($maxLifetime)
0 ignored issues
show
Unused Code introduced by
The parameter $maxLifetime is not used and could be removed. ( Ignorable by Annotation )

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

643
    public function gcSession(/** @scrutinizer ignore-unused */ $maxLifetime)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
644
    {
645
        return 0;
646
    }
647
648
    /**
649
     * Returns an iterator for traversing the session variables.
650
     * This method is required by the interface [[\IteratorAggregate]].
651
     * @return SessionIterator an iterator for traversing the session variables.
652
     */
653
    #[\ReturnTypeWillChange]
654
    public function getIterator()
655
    {
656
        $this->open();
657
        return new SessionIterator();
658
    }
659
660
    /**
661
     * Returns the number of items in the session.
662
     * @return int the number of session variables
663
     */
664
    public function getCount()
665
    {
666
        $this->open();
667
        return count($_SESSION);
668
    }
669
670
    /**
671
     * Returns the number of items in the session.
672
     * This method is required by [[\Countable]] interface.
673
     * @return int number of items in the session.
674
     */
675
    #[\ReturnTypeWillChange]
676
    public function count()
677
    {
678
        return $this->getCount();
679
    }
680
681
    /**
682
     * Returns the session variable value with the session variable name.
683
     * If the session variable does not exist, the `$defaultValue` will be returned.
684
     * @param string $key the session variable name
685
     * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
686
     * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
687
     */
688 72
    public function get($key, $defaultValue = null)
689
    {
690 72
        $this->open();
691 72
        return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
692
    }
693
694
    /**
695
     * Adds a session variable.
696
     * If the specified name already exists, the old value will be overwritten.
697
     * @param string $key session variable name
698
     * @param mixed $value session variable value
699
     */
700 54
    public function set($key, $value)
701
    {
702 54
        $this->open();
703 54
        $_SESSION[$key] = $value;
704
    }
705
706
    /**
707
     * Removes a session variable.
708
     * @param string $key the name of the session variable to be removed
709
     * @return mixed the removed value, null if no such session variable.
710
     */
711 45
    public function remove($key)
712
    {
713 45
        $this->open();
714 45
        if (isset($_SESSION[$key])) {
715 37
            $value = $_SESSION[$key];
716 37
            unset($_SESSION[$key]);
717
718 37
            return $value;
719
        }
720
721 45
        return null;
722
    }
723
724
    /**
725
     * Removes all session variables.
726
     */
727 22
    public function removeAll()
728
    {
729 22
        $this->open();
730 22
        foreach (array_keys($_SESSION) as $key) {
731 22
            unset($_SESSION[$key]);
732
        }
733
    }
734
735
    /**
736
     * @param mixed $key session variable name
737
     * @return bool whether there is the named session variable
738
     */
739
    public function has($key)
740
    {
741
        $this->open();
742
        return isset($_SESSION[$key]);
743
    }
744
745
    /**
746
     * Updates the counters for flash messages and removes outdated flash messages.
747
     * This method should only be called once in [[init()]].
748
     */
749 72
    protected function updateFlashCounters()
750
    {
751 72
        $counters = $this->get($this->flashParam, []);
752 72
        if (is_array($counters)) {
753 72
            foreach ($counters as $key => $count) {
754
                if ($count > 0) {
755
                    unset($counters[$key], $_SESSION[$key]);
756
                } elseif ($count == 0) {
757
                    $counters[$key]++;
758
                }
759
            }
760 72
            $_SESSION[$this->flashParam] = $counters;
761
        } else {
762
            // fix the unexpected problem that flashParam doesn't return an array
763
            unset($_SESSION[$this->flashParam]);
764
        }
765
    }
766
767
    /**
768
     * Returns a flash message.
769
     * @param string $key the key identifying the flash message
770
     * @param mixed $defaultValue value to be returned if the flash message does not exist.
771
     * @param bool $delete whether to delete this flash message right after this method is called.
772
     * If false, the flash message will be automatically deleted in the next request.
773
     * @return mixed the flash message or an array of messages if addFlash was used
774
     * @see setFlash()
775
     * @see addFlash()
776
     * @see hasFlash()
777
     * @see getAllFlashes()
778
     * @see removeFlash()
779
     */
780
    public function getFlash($key, $defaultValue = null, $delete = false)
781
    {
782
        $counters = $this->get($this->flashParam, []);
783
        if (isset($counters[$key])) {
784
            $value = $this->get($key, $defaultValue);
785
            if ($delete) {
786
                $this->removeFlash($key);
787
            } elseif ($counters[$key] < 0) {
788
                // mark for deletion in the next request
789
                $counters[$key] = 1;
790
                $_SESSION[$this->flashParam] = $counters;
791
            }
792
793
            return $value;
794
        }
795
796
        return $defaultValue;
797
    }
798
799
    /**
800
     * Returns all flash messages.
801
     *
802
     * You may use this method to display all the flash messages in a view file:
803
     *
804
     * ```php
805
     * <?php
806
     * foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
807
     *     echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
808
     * } ?>
809
     * ```
810
     *
811
     * With the above code you can use the [bootstrap alert][] classes such as `success`, `info`, `danger`
812
     * as the flash message key to influence the color of the div.
813
     *
814
     * Note that if you use [[addFlash()]], `$message` will be an array, and you will have to adjust the above code.
815
     *
816
     * [bootstrap alert]: https://getbootstrap.com/docs/3.4/components/#alerts
817
     *
818
     * @param bool $delete whether to delete the flash messages right after this method is called.
819
     * If false, the flash messages will be automatically deleted in the next request.
820
     * @return array flash messages (key => message or key => [message1, message2]).
821
     * @see setFlash()
822
     * @see addFlash()
823
     * @see getFlash()
824
     * @see hasFlash()
825
     * @see removeFlash()
826
     */
827
    public function getAllFlashes($delete = false)
828
    {
829
        $counters = $this->get($this->flashParam, []);
830
        $flashes = [];
831
        foreach (array_keys($counters) as $key) {
832
            if (array_key_exists($key, $_SESSION)) {
833
                $flashes[$key] = $_SESSION[$key];
834
                if ($delete) {
835
                    unset($counters[$key], $_SESSION[$key]);
836
                } elseif ($counters[$key] < 0) {
837
                    // mark for deletion in the next request
838
                    $counters[$key] = 1;
839
                }
840
            } else {
841
                unset($counters[$key]);
842
            }
843
        }
844
845
        $_SESSION[$this->flashParam] = $counters;
846
847
        return $flashes;
848
    }
849
850
    /**
851
     * Sets a flash message.
852
     * A flash message will be automatically deleted after it is accessed in a request and the deletion will happen
853
     * in the next request.
854
     * If there is already an existing flash message with the same key, it will be overwritten by the new one.
855
     * @param string $key the key identifying the flash message. Note that flash messages
856
     * and normal session variables share the same name space. If you have a normal
857
     * session variable using the same name, its value will be overwritten by this method.
858
     * @param mixed $value flash message
859
     * @param bool $removeAfterAccess whether the flash message should be automatically removed only if
860
     * it is accessed. If false, the flash message will be automatically removed after the next request,
861
     * regardless if it is accessed or not. If true (default value), the flash message will remain until after
862
     * it is accessed.
863
     * @see getFlash()
864
     * @see addFlash()
865
     * @see removeFlash()
866
     */
867
    public function setFlash($key, $value = true, $removeAfterAccess = true)
868
    {
869
        $counters = $this->get($this->flashParam, []);
870
        $counters[$key] = $removeAfterAccess ? -1 : 0;
871
        $_SESSION[$key] = $value;
872
        $_SESSION[$this->flashParam] = $counters;
873
    }
874
875
    /**
876
     * Adds a flash message.
877
     * If there are existing flash messages with the same key, the new one will be appended to the existing message array.
878
     * @param string $key the key identifying the flash message.
879
     * @param mixed $value flash message
880
     * @param bool $removeAfterAccess whether the flash message should be automatically removed only if
881
     * it is accessed. If false, the flash message will be automatically removed after the next request,
882
     * regardless if it is accessed or not. If true (default value), the flash message will remain until after
883
     * it is accessed.
884
     * @see getFlash()
885
     * @see setFlash()
886
     * @see removeFlash()
887
     */
888
    public function addFlash($key, $value = true, $removeAfterAccess = true)
889
    {
890
        $counters = $this->get($this->flashParam, []);
891
        $counters[$key] = $removeAfterAccess ? -1 : 0;
892
        $_SESSION[$this->flashParam] = $counters;
893
        if (empty($_SESSION[$key])) {
894
            $_SESSION[$key] = [$value];
895
        } elseif (is_array($_SESSION[$key])) {
896
            $_SESSION[$key][] = $value;
897
        } else {
898
            $_SESSION[$key] = [$_SESSION[$key], $value];
899
        }
900
    }
901
902
    /**
903
     * Removes a flash message.
904
     * @param string $key the key identifying the flash message. Note that flash messages
905
     * and normal session variables share the same name space.  If you have a normal
906
     * session variable using the same name, it will be removed by this method.
907
     * @return mixed the removed flash message. Null if the flash message does not exist.
908
     * @see getFlash()
909
     * @see setFlash()
910
     * @see addFlash()
911
     * @see removeAllFlashes()
912
     */
913
    public function removeFlash($key)
914
    {
915
        $counters = $this->get($this->flashParam, []);
916
        $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
917
        unset($counters[$key], $_SESSION[$key]);
918
        $_SESSION[$this->flashParam] = $counters;
919
920
        return $value;
921
    }
922
923
    /**
924
     * Removes all flash messages.
925
     * Note that flash messages and normal session variables share the same name space.
926
     * If you have a normal session variable using the same name, it will be removed
927
     * by this method.
928
     * @see getFlash()
929
     * @see setFlash()
930
     * @see addFlash()
931
     * @see removeFlash()
932
     */
933
    public function removeAllFlashes()
934
    {
935
        $counters = $this->get($this->flashParam, []);
936
        foreach (array_keys($counters) as $key) {
937
            unset($_SESSION[$key]);
938
        }
939
        unset($_SESSION[$this->flashParam]);
940
    }
941
942
    /**
943
     * Returns a value indicating whether there are flash messages associated with the specified key.
944
     * @param string $key key identifying the flash message type
945
     * @return bool whether any flash messages exist under specified key
946
     */
947
    public function hasFlash($key)
948
    {
949
        return $this->getFlash($key) !== null;
950
    }
951
952
    /**
953
     * This method is required by the interface [[\ArrayAccess]].
954
     * @param int|string $offset the offset to check on
955
     * @return bool
956
     */
957
    #[\ReturnTypeWillChange]
958
    public function offsetExists($offset)
959
    {
960
        $this->open();
961
962
        return isset($_SESSION[$offset]);
963
    }
964
965
    /**
966
     * This method is required by the interface [[\ArrayAccess]].
967
     * @param int|string $offset the offset to retrieve element.
968
     * @return mixed the element at the offset, null if no element is found at the offset
969
     */
970
    #[\ReturnTypeWillChange]
971
    public function offsetGet($offset)
972
    {
973
        $this->open();
974
975
        return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
976
    }
977
978
    /**
979
     * This method is required by the interface [[\ArrayAccess]].
980
     * @param int|string $offset the offset to set element
981
     * @param mixed $item the element value
982
     */
983
    #[\ReturnTypeWillChange]
984
    public function offsetSet($offset, $item)
985
    {
986
        $this->open();
987
        $_SESSION[$offset] = $item;
988
    }
989
990
    /**
991
     * This method is required by the interface [[\ArrayAccess]].
992
     * @param int|string $offset the offset to unset element
993
     */
994
    #[\ReturnTypeWillChange]
995
    public function offsetUnset($offset)
996
    {
997
        $this->open();
998
        unset($_SESSION[$offset]);
999
    }
1000
1001
    /**
1002
     * If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception.
1003
     * This function saves session data to temporary variable and stop session.
1004
     * @since 2.0.14
1005
     */
1006 7
    protected function freeze()
1007
    {
1008 7
        if ($this->getIsActive()) {
1009 4
            if (isset($_SESSION)) {
1010 4
                $this->_frozenSessionData = $_SESSION;
1011
            }
1012 4
            $this->close();
1013 4
            Yii::info('Session frozen', __METHOD__);
1014
        }
1015
    }
1016
1017
    /**
1018
     * Starts session and restores data from temporary variable
1019
     * @since 2.0.14
1020
     */
1021 7
    protected function unfreeze()
1022
    {
1023 7
        if (null !== $this->_frozenSessionData) {
1024 4
            YII_DEBUG ? session_start() : @session_start();
1025
1026 4
            if ($this->getIsActive()) {
1027 4
                Yii::info('Session unfrozen', __METHOD__);
1028
            } else {
1029
                $error = error_get_last();
1030
                $message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
1031
                Yii::error($message, __METHOD__);
1032
            }
1033
1034 4
            $_SESSION = $this->_frozenSessionData;
1035 4
            $this->_frozenSessionData = null;
1036
        }
1037
    }
1038
1039
    /**
1040
     * Set cache limiter
1041
     *
1042
     * @param string $cacheLimiter
1043
     * @since 2.0.14
1044
     */
1045 1
    public function setCacheLimiter($cacheLimiter)
1046
    {
1047 1
        $this->freeze();
1048 1
        session_cache_limiter($cacheLimiter);
1049 1
        $this->unfreeze();
1050
    }
1051
1052
    /**
1053
     * Returns current cache limiter
1054
     *
1055
     * @return string current cache limiter
1056
     * @since 2.0.14
1057
     */
1058
    public function getCacheLimiter()
1059
    {
1060
        return session_cache_limiter();
1061
    }
1062
}
1063