Passed
Push — bizley-patch-2 ( f0e2a9...482e2c )
by Paweł
15:18 queued 07:04
created

Session   F

Complexity

Total Complexity 130

Size/Duplication

Total Lines 998
Duplicated Lines 0 %

Test Coverage

Coverage 60.06%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 272
dl 0
loc 998
ccs 197
cts 328
cp 0.6006
rs 2
c 1
b 0
f 0
wmc 130

59 Methods

Rating   Name   Duplication   Size   Complexity  
A removeAll() 0 5 2
A removeFlash() 0 8 2
A set() 0 4 1
A addFlash() 0 11 4
A has() 0 4 1
A getFlash() 0 17 4
A setFlash() 0 6 2
A remove() 0 11 2
A removeAllFlashes() 0 7 2
A updateFlashCounters() 0 15 5
A get() 0 4 2
A hasFlash() 0 3 1
A getAllFlashes() 0 21 5
A offsetSet() 0 5 1
A offsetExists() 0 6 1
A count() 0 4 1
A setSavePath() 0 7 2
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 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 getUseTransparentSessionID() 0 3 1
A setTimeout() 0 5 1
A setUseStrictMode() 0 12 5
A getUseCustomStorage() 0 3 1
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 destroy() 0 10 2
A destroySession() 0 3 1
A getCount() 0 4 1
A setId() 0 3 1
A getIsActive() 0 3 1
A unfreeze() 0 16 5
B open() 0 24 7
A getId() 0 3 1
A setCookieParamsInternal() 0 15 4
A writeSession() 0 3 1
A setUseTransparentSessionID() 0 5 2
A close() 0 7 3
A getIterator() 0 5 1
A init() 0 7 2
A setName() 0 5 1
B registerSessionHandler() 0 41 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
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidArgumentException;
13
use yii\base\InvalidConfigException;
14
15
/**
16
 * Session provides session data management and the related configurations.
17
 *
18
 * Session is a Web application component that can be accessed via `Yii::$app->session`.
19
 *
20
 * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
21
 * To destroy the session, call [[destroy()]].
22
 *
23
 * Session can be used like an array to set and get session data. For example,
24
 *
25
 * ```php
26
 * $session = new Session;
27
 * $session->open();
28
 * $value1 = $session['name1'];  // get session variable 'name1'
29
 * $value2 = $session['name2'];  // get session variable 'name2'
30
 * foreach ($session as $name => $value) // traverse all session variables
31
 * $session['name3'] = $value3;  // set session variable 'name3'
32
 * ```
33
 *
34
 * Session can be extended to support customized session storage.
35
 * To do so, override [[useCustomStorage]] so that it returns true, and
36
 * override these methods with the actual logic about using custom storage:
37
 * [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
38
 * [[destroySession()]] and [[gcSession()]].
39
 *
40
 * Session also supports a special type of session data, called *flash messages*.
41
 * A flash message is available only in the current request and the next request.
42
 * After that, it will be deleted automatically. Flash messages are particularly
43
 * useful for displaying confirmation messages. To use flash messages, simply
44
 * call methods such as [[setFlash()]], [[getFlash()]].
45
 *
46
 * For more details and usage information on Session, see the [guide article on sessions](guide:runtime-sessions-cookies).
47
 *
48
 * @property-read array $allFlashes Flash messages (key => message or key => [message1, message2]).
49
 * @property-read string $cacheLimiter Current cache limiter.
50
 * @property-read array $cookieParams The session cookie parameters.
51
 * @property-read int $count The number of session variables.
52
 * @property-write string $flash The key identifying the flash message. Note that flash messages and normal
53
 * session variables share the same name space. If you have a normal session variable using the same name, its
54
 * value will be overwritten by this method.
55
 * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
56
 * started on every session initialization.
57
 * @property bool $hasSessionId Whether the current request has sent the session ID.
58
 * @property string $id The current session ID.
59
 * @property-read bool $isActive Whether the session has started.
60
 * @property-read SessionIterator $iterator An iterator for traversing the session variables.
61
 * @property string $name The current session name.
62
 * @property string $savePath The current session save path, defaults to '/tmp'.
63
 * @property int $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. The
64
 * default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
65
 * @property bool|null $useCookies The value indicating whether cookies should be used to store session IDs.
66
 * @property-read bool $useCustomStorage Whether to use custom storage.
67
 * @property bool $useStrictMode Whether strict mode is enabled or not.
68
 * @property bool $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to
69
 * false.
70
 *
71
 * @author Qiang Xue <[email protected]>
72
 * @since 2.0
73
 */
74
class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
75
{
76
    /**
77
     * @var string|null Holds the original session module (before a custom handler is registered) so that it can be
78
     * restored when a Session component without custom handler is used after one that has.
79
     */
80
    static protected $_originalSessionModule = null;
81
    /**
82
     * Polyfill for ini directive session.use-strict-mode for PHP < 5.5.2.
83
     */
84
    static private $_useStrictModePolyfill = false;
85
    /**
86
     * @var string the name of the session variable that stores the flash message data.
87
     */
88
    public $flashParam = '__flash';
89
    /**
90
     * @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.
91
     */
92
    public $handler;
93
94
    /**
95
     * @var string|null Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated
96
     */
97
    protected $_forceRegenerateId = null;
98
99
    /**
100
     * @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
101
     * Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
102
     * @see https://www.php.net/manual/en/function.session-set-cookie-params.php
103
     */
104
    private $_cookieParams = ['httponly' => true];
105
    /**
106
     * @var array|null is used for saving session between recreations due to session parameters update.
107
     */
108
    private $frozenSessionData;
109
110
111
    /**
112
     * Initializes the application component.
113
     * This method is required by IApplicationComponent and is invoked by application.
114
     */
115 124
    public function init()
116
    {
117 124
        parent::init();
118 124
        register_shutdown_function([$this, 'close']);
119 124
        if ($this->getIsActive()) {
120 5
            Yii::warning('Session is already started', __METHOD__);
121 5
            $this->updateFlashCounters();
122
        }
123 124
    }
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 68
    public function getUseCustomStorage()
133
    {
134 68
        return false;
135
    }
136
137
    /**
138
     * Starts the session.
139
     */
140 77
    public function open()
141
    {
142 77
        if ($this->getIsActive()) {
143 77
            return;
144
        }
145
146 76
        $this->registerSessionHandler();
147
148 76
        $this->setCookieParamsInternal();
149
150 76
        YII_DEBUG ? session_start() : @session_start();
151
152 76
        if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
153 7
            $this->regenerateID();
154 7
            $this->_forceRegenerateId = null;
155
        }
156
157 76
        if ($this->getIsActive()) {
158 76
            Yii::info('Session started', __METHOD__);
159 76
            $this->updateFlashCounters();
160
        } else {
161
            $error = error_get_last();
162
            $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
163
            Yii::error($message, __METHOD__);
164
        }
165 76
    }
166
167
    /**
168
     * Registers session handler.
169
     * @throws \yii\base\InvalidConfigException
170
     */
171 76
    protected function registerSessionHandler()
172
    {
173 76
        $sessionModuleName = session_module_name();
174 76
        if (static::$_originalSessionModule === null) {
175 1
            static::$_originalSessionModule = $sessionModuleName;
176
        }
177
178 76
        if ($this->handler !== null) {
179
            if (!is_object($this->handler)) {
180
                $this->handler = Yii::createObject($this->handler);
181
            }
182
            if (!$this->handler instanceof \SessionHandlerInterface) {
183
                throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
184
            }
185
            YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
186 76
        } elseif ($this->getUseCustomStorage()) {
187 8
            if (YII_DEBUG) {
188 8
                session_set_save_handler(
189 8
                    [$this, 'openSession'],
190 8
                    [$this, 'closeSession'],
191 8
                    [$this, 'readSession'],
192 8
                    [$this, 'writeSession'],
193 8
                    [$this, 'destroySession'],
194 8
                    [$this, 'gcSession']
195
                );
196
            } else {
197
                @session_set_save_handler(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for session_set_save_handler(). 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

197
                /** @scrutinizer ignore-unhandled */ @session_set_save_handler(

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...
198
                    [$this, 'openSession'],
199
                    [$this, 'closeSession'],
200
                    [$this, 'readSession'],
201
                    [$this, 'writeSession'],
202
                    [$this, 'destroySession'],
203 8
                    [$this, 'gcSession']
204
                );
205
            }
206
        } elseif (
207 68
            $sessionModuleName !== static::$_originalSessionModule
208 68
            && static::$_originalSessionModule !== null
209 68
            && static::$_originalSessionModule !== 'user'
210
        ) {
211 1
            session_module_name(static::$_originalSessionModule);
212
        }
213 76
    }
214
215
    /**
216
     * Ends the current session and store session data.
217
     */
218 93
    public function close()
219
    {
220 93
        if ($this->getIsActive()) {
221 70
            YII_DEBUG ? session_write_close() : @session_write_close();
222
        }
223
224 93
        $this->_forceRegenerateId = null;
225 93
    }
226
227
    /**
228
     * Frees all session variables and destroys all data registered to a session.
229
     *
230
     * This method has no effect when session is not [[getIsActive()|active]].
231
     * Make sure to call [[open()]] before calling it.
232
     * @see open()
233
     * @see isActive
234
     */
235 7
    public function destroy()
236
    {
237 7
        if ($this->getIsActive()) {
238 7
            $sessionId = session_id();
239 7
            $this->close();
240 7
            $this->setId($sessionId);
241 7
            $this->open();
242 7
            session_unset();
243 7
            session_destroy();
244 7
            $this->setId($sessionId);
245
        }
246 7
    }
247
248
    /**
249
     * @return bool whether the session has started
250
     */
251 124
    public function getIsActive()
252
    {
253 124
        return session_status() === PHP_SESSION_ACTIVE;
254
    }
255
256
    private $_hasSessionId;
257
258
    /**
259
     * Returns a value indicating whether the current request has sent the session ID.
260
     * The default implementation will check cookie and $_GET using the session name.
261
     * If you send session ID via other ways, you may need to override this method
262
     * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
263
     * @return bool whether the current request has sent the session ID.
264
     */
265 37
    public function getHasSessionId()
266
    {
267 37
        if ($this->_hasSessionId === null) {
268 37
            $name = $this->getName();
269 37
            $request = Yii::$app->getRequest();
270 37
            if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
271
                $this->_hasSessionId = true;
272 37
            } elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
273
                $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

273
                $this->_hasSessionId = $request->/** @scrutinizer ignore-call */ get($name) != '';
Loading history...
274
            } else {
275 37
                $this->_hasSessionId = false;
276
            }
277
        }
278
279 37
        return $this->_hasSessionId;
280
    }
281
282
    /**
283
     * Sets the value indicating whether the current request has sent the session ID.
284
     * This method is provided so that you can override the default way of determining
285
     * whether the session ID is sent.
286
     * @param bool $value whether the current request has sent the session ID.
287
     */
288
    public function setHasSessionId($value)
289
    {
290
        $this->_hasSessionId = $value;
291
    }
292
293
    /**
294
     * Gets the session ID.
295
     * This is a wrapper for [PHP session_id()](https://www.php.net/manual/en/function.session-id.php).
296
     * @return string the current session ID
297
     */
298 21
    public function getId()
299
    {
300 21
        return session_id();
301
    }
302
303
    /**
304
     * Sets the session ID.
305
     * This is a wrapper for [PHP session_id()](https://www.php.net/manual/en/function.session-id.php).
306
     * @param string $value the session ID for the current session
307
     */
308 12
    public function setId($value)
309
    {
310 12
        session_id($value);
311 12
    }
312
313
    /**
314
     * Updates the current session ID with a newly generated one.
315
     *
316
     * Please refer to <https://www.php.net/session_regenerate_id> for more details.
317
     *
318
     * This method has no effect when session is not [[getIsActive()|active]].
319
     * Make sure to call [[open()]] before calling it.
320
     *
321
     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
322
     * @see open()
323
     * @see isActive
324
     */
325 52
    public function regenerateID($deleteOldSession = false)
326
    {
327 52
        if ($this->getIsActive()) {
328
            // add @ to inhibit possible warning due to race condition
329
            // https://github.com/yiisoft/yii2/pull/1812
330 39
            if (YII_DEBUG && !headers_sent()) {
331 39
                session_regenerate_id($deleteOldSession);
332
            } else {
333
                @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

333
                /** @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...
334
            }
335
        }
336 52
    }
337
338
    /**
339
     * Gets the name of the current session.
340
     * This is a wrapper for [PHP session_name()](https://www.php.net/manual/en/function.session-name.php).
341
     * @return string the current session name
342
     */
343 38
    public function getName()
344
    {
345 38
        return session_name();
346
    }
347
348
    /**
349
     * Sets the name for the current session.
350
     * This is a wrapper for [PHP session_name()](https://www.php.net/manual/en/function.session-name.php).
351
     * @param string $value the session name for the current session, must be an alphanumeric string.
352
     * It defaults to "PHPSESSID".
353
     */
354 1
    public function setName($value)
355
    {
356 1
        $this->freeze();
357 1
        session_name($value);
358 1
        $this->unfreeze();
359 1
    }
360
361
    /**
362
     * Gets the current session save path.
363
     * This is a wrapper for [PHP session_save_path()](https://www.php.net/manual/en/function.session-save-path.php).
364
     * @return string the current session save path, defaults to '/tmp'.
365
     */
366
    public function getSavePath()
367
    {
368
        return session_save_path();
369
    }
370
371
    /**
372
     * Sets the current session save path.
373
     * This is a wrapper for [PHP session_save_path()](https://www.php.net/manual/en/function.session-save-path.php).
374
     * @param string $value the current session save path. This can be either a directory name or a [path alias](guide:concept-aliases).
375
     * @throws InvalidArgumentException if the path is not a valid directory
376
     */
377
    public function setSavePath($value)
378
    {
379
        $path = Yii::getAlias($value);
380
        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

380
        if (is_dir(/** @scrutinizer ignore-type */ $path)) {
Loading history...
381
            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

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

593
    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...
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

593
    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...
594
    {
595 9
        return true;
596
    }
597
598
    /**
599
     * Session close handler.
600
     * This method should be overridden if [[useCustomStorage]] returns true.
601
     * @internal Do not call this method directly.
602
     * @return bool whether session is closed successfully
603
     */
604 8
    public function closeSession()
605
    {
606 8
        return true;
607
    }
608
609
    /**
610
     * Session read handler.
611
     * This method should be overridden if [[useCustomStorage]] returns true.
612
     * @internal Do not call this method directly.
613
     * @param string $id session ID
614
     * @return string the session data
615
     */
616
    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

616
    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...
617
    {
618
        return '';
619
    }
620
621
    /**
622
     * Session write handler.
623
     * This method should be overridden if [[useCustomStorage]] returns true.
624
     * @internal Do not call this method directly.
625
     * @param string $id session ID
626
     * @param string $data session data
627
     * @return bool whether session write is successful
628
     */
629
    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

629
    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

629
    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...
630
    {
631
        return true;
632
    }
633
634
    /**
635
     * Session destroy handler.
636
     * This method should be overridden if [[useCustomStorage]] returns true.
637
     * @internal Do not call this method directly.
638
     * @param string $id session ID
639
     * @return bool whether session is destroyed successfully
640
     */
641 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

641
    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...
642
    {
643 1
        return true;
644
    }
645
646
    /**
647
     * Session GC (garbage collection) handler.
648
     * This method should be overridden if [[useCustomStorage]] returns true.
649
     * @internal Do not call this method directly.
650
     * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
651
     * @return bool whether session is GCed successfully
652
     */
653
    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

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