Passed
Push — 4.3 ( aa7c05...8ee5e6 )
by
unknown
08:14
created

Session::regenerateSessionId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace SilverStripe\Control;
4
5
use BadMethodCallException;
6
use SilverStripe\Core\Config\Configurable;
7
use SilverStripe\Dev\Deprecation;
8
9
/**
10
 * Handles all manipulation of the session.
11
 *
12
 * The static methods are used to manipulate the currently active controller's session.
13
 * The instance methods are used to manipulate a particular session.  There can be more than one of these created.
14
 *
15
 * In order to support things like testing, the session is associated with a particular Controller.  In normal usage,
16
 * this is loaded from and saved to the regular PHP session, but for things like static-page-generation and
17
 * unit-testing, you can create multiple Controllers, each with their own session.
18
 *
19
 * The instance object is basically just a way of manipulating a set of nested maps, and isn't specific to session
20
 * data.
21
 *
22
 * <b>Saving Data</b>
23
 *
24
 * You can write a value to a users session from your PHP code using the static function {@link Session::set()}. You
25
 * can add this line in any function or file you wish to save the value.
26
 *
27
 * <code>
28
 *  Session::set('MyValue', 6);
29
 * </code>
30
 *
31
 * Saves the value of "6" to the MyValue session data. You can also save arrays or serialized objects in session (but
32
 * note there may be size restrictions as to how much you can save)
33
 *
34
 * <code>
35
 *  // save a variable
36
 *  $var = 1;
37
 *  Session::set('MyVar', $var);
38
 *
39
 *  // saves an array
40
 *  Session::set('MyArrayOfValues', array('1', '2', '3'));
41
 *
42
 *  // saves an object (you'll have to unserialize it back)
43
 *  $object = new Object();
44
 *
45
 *  Session::set('MyObject', serialize($object));
46
 * </code>
47
 *
48
 * <b>Accessing Data</b>
49
 *
50
 * Once you have saved a value to the Session you can access it by using the {@link Session::get()} function.
51
 * Like the {@link Session::set()} function you can use this anywhere in your PHP files.
52
 * Note that session data isn't persisted in PHP's own session store (via $_SESSION)
53
 * until {@link Session::save()} is called, which happens automatically at the end of a standard request
54
 * through {@link SilverStripe\Control\Middleware\SessionMiddleware}.
55
 *
56
 * The values in the comments are the values stored from the previous example.
57
 *
58
 * <code>
59
 * public function bar() {
60
 *  $value = Session::get('MyValue'); // $value = 6
61
 *  $var   = Session::get('MyVar'); // $var = 1
62
 *  $array = Session::get('MyArrayOfValues'); // $array = array(1,2,3)
63
 *  $object = Session::get('MyObject', unserialize($object)); // $object = Object()
64
 * }
65
 * </code>
66
 *
67
 * You can also get all the values in the session at once. This is useful for debugging.
68
 *
69
 * <code>
70
 * Session::get_all(); // returns an array of all the session values.
71
 * </code>
72
 *
73
 * <b>Clearing Data</b>
74
 *
75
 * Once you have accessed a value from the Session it doesn't automatically wipe the value from the Session, you have
76
 * to specifically remove it. To clear a value you can either delete 1 session value by the name that you saved it
77
 *
78
 * <code>
79
 * Session::clear('MyValue'); // MyValue is no longer 6.
80
 * </code>
81
 *
82
 * Or you can clear every single value in the session at once. Note SilverStripe stores some of its own session data
83
 * including form and page comment information. None of this is vital but clear_all will clear everything.
84
 *
85
 * <code>
86
 *  Session::clear_all();
87
 * </code>
88
 *
89
 * @see Cookie
90
 */
91
class Session
92
{
93
    use Configurable;
94
95
    /**
96
     * Set session timeout in seconds.
97
     *
98
     * @var int
99
     * @config
100
     */
101
    private static $timeout = 0;
0 ignored issues
show
introduced by
The private property $timeout is not used, and could be removed.
Loading history...
102
103
    /**
104
     * @config
105
     * @var array
106
     */
107
    private static $session_ips = array();
0 ignored issues
show
introduced by
The private property $session_ips is not used, and could be removed.
Loading history...
108
109
    /**
110
     * @config
111
     * @var string
112
     */
113
    private static $cookie_domain;
0 ignored issues
show
introduced by
The private property $cookie_domain is not used, and could be removed.
Loading history...
114
115
    /**
116
     * @config
117
     * @var string
118
     */
119
    private static $cookie_path;
0 ignored issues
show
introduced by
The private property $cookie_path is not used, and could be removed.
Loading history...
120
121
    /**
122
     * @config
123
     * @var string
124
     */
125
    private static $session_store_path;
0 ignored issues
show
introduced by
The private property $session_store_path is not used, and could be removed.
Loading history...
126
127
    /**
128
     * @config
129
     * @var boolean
130
     */
131
    private static $cookie_secure = false;
0 ignored issues
show
introduced by
The private property $cookie_secure is not used, and could be removed.
Loading history...
132
133
    /**
134
     * @config
135
     * @var string
136
     */
137
    private static $cookie_name_secure = 'SECSESSID';
0 ignored issues
show
introduced by
The private property $cookie_name_secure is not used, and could be removed.
Loading history...
138
139
    /**
140
     * Name of session cache limiter to use.
141
     * Defaults to '' to disable cache limiter entirely.
142
     *
143
     * @see https://secure.php.net/manual/en/function.session-cache-limiter.php
144
     * @var string|null
145
     */
146
    private static $sessionCacheLimiter = '';
0 ignored issues
show
introduced by
The private property $sessionCacheLimiter is not used, and could be removed.
Loading history...
147
148
    /**
149
     * Session data.
150
     * Will be null if session has not been started
151
     *
152
     * @var array|null
153
     */
154
    protected $data = null;
155
156
    /**
157
     * @var bool
158
     */
159
    protected $started = false;
160
161
    /**
162
     * List of keys changed. This is a nested array which represents the
163
     * keys modified in $this->data. The value of each item is either "true"
164
     * or a nested array.
165
     *
166
     * If a value is in changedData but not in data, it must be removed
167
     * from the destination during save().
168
     *
169
     * Only highest level changes are stored. E.g. changes to `Base.Sub`
170
     * and then `Base` only records `Base` as the change.
171
     *
172
     * E.g.
173
     * [
174
     *   'Base' => true,
175
     *   'Key' => [
176
     *      'Nested' => true,
177
     *   ],
178
     * ]
179
     *
180
     * @var array
181
     */
182
    protected $changedData = array();
183
184
    /**
185
     * Get user agent for this request
186
     *
187
     * @param HTTPRequest $request
188
     * @return string
189
     */
190
    protected function userAgent(HTTPRequest $request)
191
    {
192
        return $request->getHeader('User-Agent');
193
    }
194
195
    /**
196
     * Start PHP session, then create a new Session object with the given start data.
197
     *
198
     * @param array|null|Session $data Can be an array of data (such as $_SESSION) or another Session object to clone.
199
     * If null, this session is treated as unstarted.
200
     */
201
    public function __construct($data)
202
    {
203
        if ($data instanceof Session) {
204
            $data = $data->getAll();
205
        }
206
207
        $this->data = $data;
208
        $this->started = isset($data);
209
    }
210
211
    /**
212
     * Init this session instance before usage,
213
     * if a session identifier is part of the passed in request.
214
     * Otherwise, a session might be started in {@link save()}
215
     * if session data needs to be written with a new session identifier.
216
     *
217
     * @param HTTPRequest $request
218
     */
219
    public function init(HTTPRequest $request)
220
    {
221
        if (!$this->isStarted() && $this->requestContainsSessionId($request)) {
222
            $this->start($request);
223
        }
224
225
        // Funny business detected!
226
        if (isset($this->data['HTTP_USER_AGENT'])) {
227
            if ($this->data['HTTP_USER_AGENT'] !== $this->userAgent($request)) {
228
                $this->clearAll();
229
                $this->destroy();
230
                $this->started = false;
231
                $this->start($request);
232
            }
233
        }
234
    }
235
236
    /**
237
     * Destroy existing session and restart
238
     *
239
     * @param HTTPRequest $request
240
     */
241
    public function restart(HTTPRequest $request)
242
    {
243
        $this->destroy();
244
        $this->init($request);
245
    }
246
247
    /**
248
     * Determine if this session has started
249
     *
250
     * @return bool
251
     */
252
    public function isStarted()
253
    {
254
        return $this->started;
255
    }
256
257
    /**
258
     * @param HTTPRequest $request
259
     * @return bool
260
     */
261
    public function requestContainsSessionId(HTTPRequest $request)
262
    {
263
        $secure = Director::is_https($request) && $this->config()->get('cookie_secure');
264
        $name = $secure ? $this->config()->get('cookie_name_secure') : session_name();
265
        return (bool)Cookie::get($name);
266
    }
267
268
    /**
269
     * Begin session, regardless if a session identifier is present in the request,
270
     * or whether any session data needs to be written.
271
     * See {@link init()} if you want to "lazy start" a session.
272
     *
273
     * @param HTTPRequest $request The request for which to start a session
274
     */
275
    public function start(HTTPRequest $request)
276
    {
277
        if ($this->isStarted()) {
278
            throw new BadMethodCallException("Session has already started");
279
        }
280
281
        $path = $this->config()->get('cookie_path');
282
        if (!$path) {
283
            $path = Director::baseURL();
284
        }
285
        $domain = $this->config()->get('cookie_domain');
286
        $secure = Director::is_https($request) && $this->config()->get('cookie_secure');
287
        $session_path = $this->config()->get('session_store_path');
288
        $timeout = $this->config()->get('timeout');
289
290
        // Director::baseURL can return absolute domain names - this extracts the relevant parts
291
        // for the session otherwise we can get broken session cookies
292
        if (Director::is_absolute_url($path)) {
293
            $urlParts = parse_url($path);
294
            $path = $urlParts['path'];
295
            if (!$domain) {
296
                $domain = $urlParts['host'];
297
            }
298
        }
299
300
        // If the session cookie is already set, then the session can be read even if headers_sent() = true
301
        // This helps with edge-case such as debugging.
302
        $data = [];
303
        if (!session_id() && (!headers_sent() || $this->requestContainsSessionId($request))) {
304
            if (!headers_sent()) {
305
                session_set_cookie_params($timeout ?: 0, $path, $domain ?: null, $secure, true);
306
307
                $limiter = $this->config()->get('sessionCacheLimiter');
308
                if (isset($limiter)) {
309
                    session_cache_limiter($limiter);
310
                }
311
312
                // Allow storing the session in a non standard location
313
                if ($session_path) {
314
                    session_save_path($session_path);
315
                }
316
317
                // If we want a secure cookie for HTTPS, use a separate session name. This lets us have a
318
                // separate (less secure) session for non-HTTPS requests
319
                // if headers_sent() is true then it's best to throw the resulting error rather than risk
320
                // a security hole.
321
                if ($secure) {
322
                    session_name($this->config()->get('cookie_name_secure'));
323
                }
324
325
                session_start();
326
327
                // Session start emits a cookie, but only if there's no existing session. If there is a session timeout
328
                // tied to this request, make sure the session is held for the entire timeout by refreshing the cookie age.
329
                if ($timeout && $this->requestContainsSessionId($request)) {
330
                    Cookie::set(session_name(), session_id(), $timeout / 86400, $path, $domain ?: null, $secure, true);
331
                }
332
            } else {
333
                // If headers are sent then we can't have a session_cache_limiter otherwise we'll get a warning
334
                session_cache_limiter(null);
335
            }
336
337
            if (isset($_SESSION)) {
338
                // Initialise data from session store if present
339
                $data = $_SESSION;
340
341
                // Merge in existing in-memory data, taking priority over session store data
342
                $this->recursivelyApply((array)$this->data, $data);
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Control\Session::recursivelyApply() has been deprecated: 4.1.0:5.0.0 Use recursivelyApplyChanges() instead ( Ignorable by Annotation )

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

342
                /** @scrutinizer ignore-deprecated */ $this->recursivelyApply((array)$this->data, $data);

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

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

Loading history...
343
            }
344
        }
345
346
        // Save any modified session data back to the session store if present, otherwise initialise it to an array.
347
        $this->data = $data;
348
349
        $this->started = true;
350
    }
351
352
    /**
353
     * Destroy this session
354
     *
355
     * @param bool $removeCookie
356
     */
357
    public function destroy($removeCookie = true)
358
    {
359
        if (session_id()) {
360
            if ($removeCookie) {
361
                $path = $this->config()->get('cookie_path') ?: Director::baseURL();
362
                $domain = $this->config()->get('cookie_domain');
363
                $secure = $this->config()->get('cookie_secure');
364
                Cookie::force_expiry(session_name(), $path, $domain, $secure, true);
365
            }
366
            session_destroy();
367
        }
368
        // Clean up the superglobal - session_destroy does not do it.
369
        // http://nz1.php.net/manual/en/function.session-destroy.php
370
        unset($_SESSION);
371
        $this->data = null;
372
    }
373
374
    /**
375
     * Set session value
376
     *
377
     * @param string $name
378
     * @param mixed $val
379
     * @return $this
380
     */
381
    public function set($name, $val)
382
    {
383
        $var = &$this->nestedValueRef($name, $this->data);
384
385
        // Mark changed
386
        if ($var !== $val) {
387
            $var = $val;
388
            $this->markChanged($name);
389
        }
390
        return $this;
391
    }
392
393
    /**
394
     * Mark key as changed
395
     *
396
     * @internal
397
     * @param string $name
398
     */
399
    protected function markChanged($name)
400
    {
401
        $diffVar = &$this->changedData;
402
        foreach (explode('.', $name) as $namePart) {
403
            if (!isset($diffVar[$namePart])) {
404
                $diffVar[$namePart] = [];
405
            }
406
            $diffVar = &$diffVar[$namePart];
407
408
            // Already diffed
409
            if ($diffVar === true) {
410
                return;
411
            }
412
        }
413
        // Mark changed
414
        $diffVar = true;
415
    }
416
417
    /**
418
     * Merge value with array
419
     *
420
     * @param string $name
421
     * @param mixed $val
422
     */
423
    public function addToArray($name, $val)
424
    {
425
        $names = explode('.', $name);
426
427
        // We still want to do this even if we have strict path checking for legacy code
428
        $var = &$this->data;
429
        $diffVar = &$this->changedData;
430
431
        foreach ($names as $n) {
432
            $var = &$var[$n];
433
            $diffVar = &$diffVar[$n];
434
        }
435
436
        $var[] = $val;
437
        $diffVar[sizeof($var) - 1] = $val;
438
    }
439
440
    /**
441
     * Get session value
442
     *
443
     * @param string $name
444
     * @return mixed
445
     */
446
    public function get($name)
447
    {
448
        return $this->nestedValue($name, $this->data);
449
    }
450
451
    /**
452
     * Clear session value
453
     *
454
     * @param string $name
455
     * @return $this
456
     */
457
    public function clear($name)
458
    {
459
        // Get var by path
460
        $var = $this->nestedValue($name, $this->data);
461
462
        // Unset var
463
        if ($var !== null) {
464
            // Unset parent key
465
            $parentParts = explode('.', $name);
466
            $basePart = array_pop($parentParts);
467
            if ($parentParts) {
468
                $parent = &$this->nestedValueRef(implode('.', $parentParts), $this->data);
469
                unset($parent[$basePart]);
470
            } else {
471
                unset($this->data[$name]);
472
            }
473
            $this->markChanged($name);
474
        }
475
        return $this;
476
    }
477
478
    /**
479
     * Clear all values
480
     */
481
    public function clearAll()
482
    {
483
        if ($this->data && is_array($this->data)) {
484
            foreach (array_keys($this->data) as $key) {
485
                $this->clear($key);
486
            }
487
        }
488
    }
489
490
    /**
491
     * Get all values
492
     *
493
     * @return array|null
494
     */
495
    public function getAll()
496
    {
497
        return $this->data;
498
    }
499
500
    /**
501
     * Set user agent key
502
     *
503
     * @param HTTPRequest $request
504
     */
505
    public function finalize(HTTPRequest $request)
506
    {
507
        $this->set('HTTP_USER_AGENT', $this->userAgent($request));
508
    }
509
510
    /**
511
     * Save data to session
512
     * Only save the changes, so that anyone manipulating $_SESSION directly doesn't get burned.
513
     *
514
     * @param HTTPRequest $request
515
     */
516
    public function save(HTTPRequest $request)
517
    {
518
        if ($this->changedData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->changedData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
519
            $this->finalize($request);
520
521
            if (!$this->isStarted()) {
522
                $this->start($request);
523
            }
524
525
            // Apply all changes recursively, implicitly writing them to the actual PHP session store.
526
            $this->recursivelyApplyChanges($this->changedData, $this->data, $_SESSION);
527
        }
528
    }
529
530
    /**
531
     * Recursively apply the changes represented in $data to $dest.
532
     * Used to update $_SESSION
533
     *
534
     * @deprecated 4.1.0:5.0.0 Use recursivelyApplyChanges() instead
535
     * @param array $data
536
     * @param array $dest
537
     */
538
    protected function recursivelyApply($data, &$dest)
539
    {
540
        Deprecation::notice('5.0', 'Use recursivelyApplyChanges() instead');
541
        foreach ($data as $k => $v) {
542
            if (is_array($v)) {
543
                if (!isset($dest[$k]) || !is_array($dest[$k])) {
544
                    $dest[$k] = array();
545
                }
546
                $this->recursivelyApply($v, $dest[$k]);
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Control\Session::recursivelyApply() has been deprecated: 4.1.0:5.0.0 Use recursivelyApplyChanges() instead ( Ignorable by Annotation )

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

546
                /** @scrutinizer ignore-deprecated */ $this->recursivelyApply($v, $dest[$k]);

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

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

Loading history...
547
            } else {
548
                $dest[$k] = $v;
549
            }
550
        }
551
    }
552
553
    /**
554
     * Returns the list of changed keys
555
     *
556
     * @return array
557
     */
558
    public function changedData()
559
    {
560
        return $this->changedData;
561
    }
562
563
    /**
564
     * Navigate to nested value in source array by name,
565
     * creating a null placeholder if it doesn't exist.
566
     *
567
     * @internal
568
     * @param string $name
569
     * @param array $source
570
     * @return mixed Reference to value in $source
571
     */
572
    protected function &nestedValueRef($name, &$source)
573
    {
574
        // Find var to change
575
        $var = &$source;
576
        foreach (explode('.', $name) as $namePart) {
577
            if (!isset($var)) {
578
                $var = [];
579
            }
580
            if (!isset($var[$namePart])) {
581
                $var[$namePart] = null;
582
            }
583
            $var = &$var[$namePart];
584
        }
585
        return $var;
586
    }
587
588
    /**
589
     * Navigate to nested value in source array by name,
590
     * returning null if it doesn't exist.
591
     *
592
     * @internal
593
     * @param string $name
594
     * @param array $source
595
     * @return mixed Value in array in $source
596
     */
597
    protected function nestedValue($name, $source)
598
    {
599
        // Find var to change
600
        $var = $source;
601
        foreach (explode('.', $name) as $namePart) {
602
            if (!isset($var[$namePart])) {
603
                return null;
604
            }
605
            $var = $var[$namePart];
606
        }
607
        return $var;
608
    }
609
610
    /**
611
     * Apply all changes using separate keys and data sources and a destination
612
     *
613
     * @internal
614
     * @param array $changes
615
     * @param array $source
616
     * @param array $destination
617
     */
618
    protected function recursivelyApplyChanges($changes, $source, &$destination)
619
    {
620
        $source = $source ?: [];
621
        foreach ($changes as $key => $changed) {
622
            if ($changed === true) {
623
                // Determine if replacement or removal
624
                if (array_key_exists($key, $source)) {
625
                    $destination[$key] = $source[$key];
626
                } else {
627
                    unset($destination[$key]);
628
                }
629
            } else {
630
                // Recursively apply
631
                $destVal = &$this->nestedValueRef($key, $destination);
632
                $sourceVal = $this->nestedValue($key, $source);
633
                $this->recursivelyApplyChanges($changed, $sourceVal, $destVal);
634
            }
635
        }
636
    }
637
638
    /**
639
     * Regenerate session id
640
     *
641
     * @internal This is for internal use only. Isn't a part of public API.
642
     */
643
    public function regenerateSessionId()
644
    {
645
        if (!headers_sent()) {
646
            session_regenerate_id(true);
647
        }
648
    }
649
}
650