Passed
Pull Request — 4.2 (#8269)
by Ingo
07:01
created

Session::requestContainsSessionId()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 4
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
222
        if (!$this->isStarted() && $this->requestContainsSessionId($request)) {
223
            $this->start($request);
224
        }
225
226
        // Funny business detected!
227
        if (isset($this->data['HTTP_USER_AGENT'])) {
228
            if ($this->data['HTTP_USER_AGENT'] !== $this->userAgent($request)) {
229
                $this->clearAll();
230
                $this->destroy();
231
                $this->started = false;
232
                $this->start($request);
233
            }
234
        }
235
    }
236
237
    /**
238
     * Destroy existing session and restart
239
     *
240
     * @param HTTPRequest $request
241
     */
242
    public function restart(HTTPRequest $request)
243
    {
244
        $this->destroy();
245
        $this->init($request);
246
    }
247
248
    /**
249
     * Determine if this session has started
250
     *
251
     * @return bool
252
     */
253
    public function isStarted()
254
    {
255
        return $this->started;
256
    }
257
258
    /**
259
     * @param HTTPRequest $request
260
     * @return bool
261
     */
262
    public function requestContainsSessionId(HTTPRequest $request)
263
    {
264
        $secure = Director::is_https($request) && $this->config()->get('cookie_secure');
265
        $name = $secure ? $this->config()->get('cookie_name_secure') : session_name();
266
        return (bool)Cookie::get($name);
267
    }
268
269
    /**
270
     * Begin session, regardless if a session identifier is present in the request,
271
     * or whether any session data needs to be written.
272
     * See {@link init()} if you want to "lazy start" a session.
273
     *
274
     * @param HTTPRequest $request The request for which to start a session
275
     */
276
    public function start(HTTPRequest $request)
277
    {
278
        if ($this->isStarted()) {
279
            throw new BadMethodCallException("Session has already started");
280
        }
281
282
        $path = $this->config()->get('cookie_path');
283
        if (!$path) {
284
            $path = Director::baseURL();
285
        }
286
        $domain = $this->config()->get('cookie_domain');
287
        $secure = Director::is_https($request) && $this->config()->get('cookie_secure');
288
        $session_path = $this->config()->get('session_store_path');
289
        $timeout = $this->config()->get('timeout');
290
291
        // Director::baseURL can return absolute domain names - this extracts the relevant parts
292
        // for the session otherwise we can get broken session cookies
293
        if (Director::is_absolute_url($path)) {
294
            $urlParts = parse_url($path);
295
            $path = $urlParts['path'];
296
            if (!$domain) {
297
                $domain = $urlParts['host'];
298
            }
299
        }
300
301
        if (!session_id() && !headers_sent()) {
302
            if ($domain) {
303
                session_set_cookie_params($timeout, $path, $domain, $secure, true);
304
            } else {
305
                session_set_cookie_params($timeout, $path, null, $secure, true);
306
            }
307
308
            // Allow storing the session in a non standard location
309
            if ($session_path) {
310
                session_save_path($session_path);
311
            }
312
313
            // If we want a secure cookie for HTTPS, use a seperate session name. This lets us have a
314
            // seperate (less secure) session for non-HTTPS requests
315
            if ($secure) {
316
                session_name($this->config()->get('cookie_name_secure'));
317
            }
318
319
            $limiter = $this->config()->get('sessionCacheLimiter');
320
            if (isset($limiter)) {
321
                session_cache_limiter($limiter);
322
            }
323
324
            session_start();
325
326
            if (isset($_SESSION)) {
327
                // Initialise data from session store if present
328
                $data = $_SESSION;
329
                // Merge in existing in-memory data, taking priority over session store data
330
                $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...5.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

330
                /** @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...
331
            } else {
332
                // Use in-memory data if the session is lazy started
333
                $data = $this->data;
334
            }
335
            $this->data = $data ?: [];
336
        } else {
337
            $this->data = [];
338
        }
339
340
        // Modify the timeout behaviour so it's the *inactive* time before the session expires.
341
        // By default it's the total session lifetime
342
        if ($timeout && !headers_sent()) {
343
            Cookie::set(session_name(), session_id(), $timeout/86400, $path, $domain ? $domain
344
                : null, $secure, true);
345
        }
346
347
        $this->started = true;
348
    }
349
350
    /**
351
     * Destroy this session
352
     *
353
     * @param bool $removeCookie
354
     */
355
    public function destroy($removeCookie = true)
356
    {
357
        if (session_id()) {
358
            if ($removeCookie) {
359
                $path = $this->config()->get('cookie_path') ?: Director::baseURL();
360
                $domain = $this->config()->get('cookie_domain');
361
                $secure = $this->config()->get('cookie_secure');
362
                Cookie::force_expiry(session_name(), $path, $domain, $secure, true);
363
            }
364
            session_destroy();
365
        }
366
        // Clean up the superglobal - session_destroy does not do it.
367
        // http://nz1.php.net/manual/en/function.session-destroy.php
368
        unset($_SESSION);
369
        $this->data = null;
370
    }
371
372
    /**
373
     * Set session value
374
     *
375
     * @param string $name
376
     * @param mixed $val
377
     * @return $this
378
     */
379
    public function set($name, $val)
380
    {
381
        $var = &$this->nestedValueRef($name, $this->data);
382
383
        // Mark changed
384
        if ($var !== $val) {
385
            $var = $val;
386
            $this->markChanged($name);
387
        }
388
        return $this;
389
    }
390
391
    /**
392
     * Mark key as changed
393
     *
394
     * @internal
395
     * @param string $name
396
     */
397
    protected function markChanged($name)
398
    {
399
        $diffVar = &$this->changedData;
400
        foreach (explode('.', $name) as $namePart) {
401
            if (!isset($diffVar[$namePart])) {
402
                $diffVar[$namePart] = [];
403
            }
404
            $diffVar = &$diffVar[$namePart];
405
406
            // Already diffed
407
            if ($diffVar === true) {
408
                return;
409
            }
410
        }
411
        // Mark changed
412
        $diffVar = true;
413
    }
414
415
    /**
416
     * Merge value with array
417
     *
418
     * @param string $name
419
     * @param mixed $val
420
     */
421
    public function addToArray($name, $val)
422
    {
423
        $names = explode('.', $name);
424
425
        // We still want to do this even if we have strict path checking for legacy code
426
        $var = &$this->data;
427
        $diffVar = &$this->changedData;
428
429
        foreach ($names as $n) {
430
            $var = &$var[$n];
431
            $diffVar = &$diffVar[$n];
432
        }
433
434
        $var[] = $val;
435
        $diffVar[sizeof($var)-1] = $val;
436
    }
437
438
    /**
439
     * Get session value
440
     *
441
     * @param string $name
442
     * @return mixed
443
     */
444
    public function get($name)
445
    {
446
        return $this->nestedValue($name, $this->data);
447
    }
448
449
    /**
450
     * Clear session value
451
     *
452
     * @param string $name
453
     * @return $this
454
     */
455
    public function clear($name)
456
    {
457
        // Get var by path
458
        $var = $this->nestedValue($name, $this->data);
459
460
        // Unset var
461
        if ($var !== null) {
462
            // Unset parent key
463
            $parentParts = explode('.', $name);
464
            $basePart = array_pop($parentParts);
465
            if ($parentParts) {
466
                $parent = &$this->nestedValueRef(implode('.', $parentParts), $this->data);
467
                unset($parent[$basePart]);
468
            } else {
469
                unset($this->data[$name]);
470
            }
471
            $this->markChanged($name);
472
        }
473
        return $this;
474
    }
475
476
    /**
477
     * Clear all values
478
     */
479
    public function clearAll()
480
    {
481
        if ($this->data && is_array($this->data)) {
482
            foreach (array_keys($this->data) as $key) {
483
                $this->clear($key);
484
            }
485
        }
486
    }
487
488
    /**
489
     * Get all values
490
     *
491
     * @return array|null
492
     */
493
    public function getAll()
494
    {
495
        return $this->data;
496
    }
497
498
    /**
499
     * Set user agent key
500
     *
501
     * @param HTTPRequest $request
502
     */
503
    public function finalize(HTTPRequest $request)
504
    {
505
        $this->set('HTTP_USER_AGENT', $this->userAgent($request));
506
    }
507
508
    /**
509
     * Save data to session
510
     * Only save the changes, so that anyone manipulating $_SESSION directly doesn't get burned.
511
     *
512
     * @param HTTPRequest $request
513
     */
514
    public function save(HTTPRequest $request)
515
    {
516
        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...
517
            $this->finalize($request);
518
519
            if (!$this->isStarted()) {
520
                $this->start($request);
521
            }
522
523
            // Apply all changes recursively, implicitly writing them to the actual PHP session store.
524
            $this->recursivelyApplyChanges($this->changedData, $this->data, $_SESSION);
525
        }
526
    }
527
528
    /**
529
     * Recursively apply the changes represented in $data to $dest.
530
     * Used to update $_SESSION
531
     *
532
     * @deprecated 4.1...5.0 Use recursivelyApplyChanges() instead
533
     * @param array $data
534
     * @param array $dest
535
     */
536
    protected function recursivelyApply($data, &$dest)
537
    {
538
        Deprecation::notice('5.0', 'Use recursivelyApplyChanges() instead');
539
        foreach ($data as $k => $v) {
540
            if (is_array($v)) {
541
                if (!isset($dest[$k]) || !is_array($dest[$k])) {
542
                    $dest[$k] = array();
543
                }
544
                $this->recursivelyApply($v, $dest[$k]);
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Control\Session::recursivelyApply() has been deprecated: 4.1...5.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

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