Completed
Branch BUG/session-save-state (bfa6db)
by
unknown
10:29 queued 28s
created

EE_Session::setSaveState()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
use EventEspresso\core\domain\services\session\SessionIdentifierInterface;
4
use EventEspresso\core\domain\values\session\SessionLifespan;
5
use EventEspresso\core\exceptions\InvalidDataTypeException;
6
use EventEspresso\core\exceptions\InvalidInterfaceException;
7
use EventEspresso\core\exceptions\InvalidSessionDataException;
8
use EventEspresso\core\services\cache\CacheStorageInterface;
9
use EventEspresso\core\services\request\RequestInterface;
10
use EventEspresso\core\services\session\SessionStartHandler;
11
12
/**
13
 * EE_Session class
14
 *
15
 * Please note that the session doesn't save by default, except when it has a cart set on it.
16
 * In order for it to save on other pages, you must execute
17
 * `add_action('FHEE__EE_Session___save_session_to_db__abort_session_save', '__return_false');`
18
 * somewhere during the request
19
 *
20
 * @package    Event Espresso
21
 * @subpackage includes/classes
22
 * @author     Brent Christensen
23
 */
24
class EE_Session implements SessionIdentifierInterface
25
{
26
27
    const session_id_prefix = 'ee_ssn_';
28
29
    const hash_check_prefix = 'ee_shc_';
30
31
    const OPTION_NAME_SETTINGS = 'ee_session_settings';
32
33
    const STATUS_CLOSED = 0;
34
35
    const STATUS_OPEN = 1;
36
37
    const SAVE_STATE_CLEAN = 'clean';
38
    const SAVE_STATE_DIRTY = 'dirty';
39
40
41
    /**
42
     * instance of the EE_Session object
43
     *
44
     * @var EE_Session
45
     */
46
    private static $_instance;
47
48
    /**
49
     * @var CacheStorageInterface $cache_storage
50
     */
51
    protected $cache_storage;
52
53
    /**
54
     * @var EE_Encryption $encryption
55
     */
56
    protected $encryption;
57
58
    /**
59
     * @var SessionStartHandler $session_start_handler
60
     */
61
    protected $session_start_handler;
62
63
    /**
64
     * the session id
65
     *
66
     * @var string
67
     */
68
    private $_sid;
69
70
    /**
71
     * session id salt
72
     *
73
     * @var string
74
     */
75
    private $_sid_salt;
76
77
    /**
78
     * session data
79
     *
80
     * @var array
81
     */
82
    private $_session_data = array();
83
84
    /**
85
     * how long an EE session lasts
86
     * default session lifespan of 1 hour (for not so instant IPNs)
87
     *
88
     * @var SessionLifespan $session_lifespan
89
     */
90
    private $session_lifespan;
91
92
    /**
93
     * session expiration time as Unix timestamp in GMT
94
     *
95
     * @var int
96
     */
97
    private $_expiration;
98
99
    /**
100
     * whether or not session has expired at some point
101
     *
102
     * @var boolean
103
     */
104
    private $_expired = false;
105
106
    /**
107
     * current time as Unix timestamp in GMT
108
     *
109
     * @var int
110
     */
111
    private $_time;
112
113
    /**
114
     * whether to encrypt session data
115
     *
116
     * @var bool
117
     */
118
    private $_use_encryption;
119
120
    /**
121
     * well... according to the server...
122
     *
123
     * @var null
124
     */
125
    private $_user_agent;
126
127
    /**
128
     * do you really trust the server ?
129
     *
130
     * @var null
131
     */
132
    private $_ip_address;
133
134
    /**
135
     * current WP user_id
136
     *
137
     * @var null
138
     */
139
    private $_wp_user_id;
140
141
    /**
142
     * array for defining default session vars
143
     *
144
     * @var array
145
     */
146
    private $_default_session_vars = array(
147
        'id'            => null,
148
        'user_id'       => null,
149
        'ip_address'    => null,
150
        'user_agent'    => null,
151
        'init_access'   => null,
152
        'last_access'   => null,
153
        'expiration'    => null,
154
        'pages_visited' => array(),
155
    );
156
157
    /**
158
     * timestamp for when last garbage collection cycle was performed
159
     *
160
     * @var int $_last_gc
161
     */
162
    private $_last_gc;
163
164
    /**
165
     * @var RequestInterface $request
166
     */
167
    protected $request;
168
169
    /**
170
     * whether session is active or not
171
     *
172
     * @var int $status
173
     */
174
    private $status = EE_Session::STATUS_CLOSED;
175
176
    /**
177
     * whether session data has changed therefore requiring a session save
178
     *
179
     * @var string $save_state
180
     */
181
    private $save_state = EE_Session::SAVE_STATE_CLEAN;
182
183
184
    /**
185
     * @singleton method used to instantiate class object
186
     * @param CacheStorageInterface $cache_storage
187
     * @param SessionLifespan|null  $lifespan
188
     * @param RequestInterface      $request
189
     * @param SessionStartHandler   $session_start_handler
190
     * @param EE_Encryption         $encryption
191
     * @return EE_Session
192
     * @throws InvalidArgumentException
193
     * @throws InvalidDataTypeException
194
     * @throws InvalidInterfaceException
195
     */
196
    public static function instance(
197
        CacheStorageInterface $cache_storage = null,
198
        SessionLifespan $lifespan = null,
199
        RequestInterface $request = null,
200
        SessionStartHandler $session_start_handler = null,
201
        EE_Encryption $encryption = null
202
    ) {
203
        // check if class object is instantiated
204
        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
205
        // add_filter( 'FHEE_load_EE_Session', '__return_false' );
206
        if (! self::$_instance instanceof EE_Session
207
            && $cache_storage instanceof CacheStorageInterface
208
            && $lifespan instanceof SessionLifespan
209
            && $request instanceof RequestInterface
210
            && $session_start_handler instanceof SessionStartHandler
211
            && apply_filters('FHEE_load_EE_Session', true)
212
        ) {
213
            self::$_instance = new self(
214
                $cache_storage,
215
                $lifespan,
216
                $request,
217
                $session_start_handler,
218
                $encryption
219
            );
220
        }
221
        return self::$_instance;
222
    }
223
224
225
    /**
226
     * protected constructor to prevent direct creation
227
     *
228
     * @param CacheStorageInterface $cache_storage
229
     * @param SessionLifespan       $lifespan
230
     * @param RequestInterface      $request
231
     * @param SessionStartHandler   $session_start_handler
232
     * @param EE_Encryption         $encryption
233
     * @throws InvalidArgumentException
234
     * @throws InvalidDataTypeException
235
     * @throws InvalidInterfaceException
236
     */
237
    protected function __construct(
238
        CacheStorageInterface $cache_storage,
239
        SessionLifespan $lifespan,
240
        RequestInterface $request,
241
        SessionStartHandler $session_start_handler,
242
        EE_Encryption $encryption = null
243
    ) {
244
        // session loading is turned ON by default,
245
        // but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
246
        // (which currently fires on the init hook at priority 9),
247
        // can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
248
        if (! apply_filters('FHEE_load_EE_Session', true)) {
249
            return;
250
        }
251
        $this->session_start_handler = $session_start_handler;
252
        $this->session_lifespan = $lifespan;
253
        $this->request = $request;
254
        if (! defined('ESPRESSO_SESSION')) {
255
            define('ESPRESSO_SESSION', true);
256
        }
257
        // retrieve session options from db
258
        $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
259
        if (! empty($session_settings)) {
260
            // cycle though existing session options
261
            foreach ($session_settings as $var_name => $session_setting) {
262
                // set values for class properties
263
                $var_name = '_' . $var_name;
264
                $this->{$var_name} = $session_setting;
265
            }
266
        }
267
        $this->cache_storage = $cache_storage;
268
        // are we using encryption?
269
        $this->_use_encryption = $encryption instanceof EE_Encryption
270
                                 && EE_Registry::instance()->CFG->admin->encode_session_data();
271
        // encrypt data via: $this->encryption->encrypt();
272
        $this->encryption = $encryption;
273
        // filter hook allows outside functions/classes/plugins to change default empty cart
274
        $extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
275
        array_merge($this->_default_session_vars, $extra_default_session_vars);
276
        // apply default session vars
277
        $this->_set_defaults();
278
        add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
279
        // check request for 'clear_session' param
280
        add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
281
        // once everything is all said and done,
282
        add_action('shutdown', array($this, 'update'), 100);
283
        add_action('shutdown', array($this, 'garbageCollection'), 1000);
284
        $this->configure_garbage_collection_filters();
285
    }
286
287
288
    /**
289
     * @return bool
290
     * @throws InvalidArgumentException
291
     * @throws InvalidDataTypeException
292
     * @throws InvalidInterfaceException
293
     */
294
    public static function isLoadedAndActive()
295
    {
296
        return did_action('AHEE__EE_System__core_loaded_and_ready')
297
               && EE_Session::instance() instanceof EE_Session
298
               && EE_Session::instance()->isActive();
299
    }
300
301
302
    /**
303
     * @return bool
304
     */
305
    public function isActive()
306
    {
307
        return $this->status === EE_Session::STATUS_OPEN;
308
    }
309
310
311
    /**
312
     * @return void
313
     * @throws EE_Error
314
     * @throws InvalidArgumentException
315
     * @throws InvalidDataTypeException
316
     * @throws InvalidInterfaceException
317
     * @throws InvalidSessionDataException
318
     * @throws RuntimeException
319
     * @throws ReflectionException
320
     */
321
    public function open_session()
322
    {
323
        // check for existing session and retrieve it from db
324
        if (! $this->_espresso_session()) {
325
            // or just start a new one
326
            $this->_create_espresso_session();
327
        }
328
    }
329
330
331
    /**
332
     * @return bool
333
     */
334
    public function expired()
335
    {
336
        return $this->_expired;
337
    }
338
339
340
    /**
341
     * @return void
342
     */
343
    public function reset_expired()
344
    {
345
        $this->_expired = false;
346
    }
347
348
349
    /**
350
     * @return int
351
     */
352
    public function expiration()
353
    {
354
        return $this->_expiration;
355
    }
356
357
358
    /**
359
     * @return int
360
     */
361
    public function extension()
362
    {
363
        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
364
    }
365
366
367
    /**
368
     * @param int $time number of seconds to add to session expiration
369
     */
370
    public function extend_expiration($time = 0)
371
    {
372
        $time = $time ? $time : $this->extension();
373
        $this->_expiration += absint($time);
374
    }
375
376
377
    /**
378
     * @return int
379
     */
380
    public function lifespan()
381
    {
382
        return $this->session_lifespan->inSeconds();
383
    }
384
385
386
    /**
387
     * @param string $save_state
388
     */
389
    public function setSaveState($save_state = EE_Session::SAVE_STATE_DIRTY)
390
    {
391
        $valid_save_states = [
392
            EE_Session::SAVE_STATE_CLEAN,
393
            EE_Session::SAVE_STATE_DIRTY,
394
        ];
395
        if(! in_array($save_state, $valid_save_states, true)) {
396
            $save_state = EE_Session::SAVE_STATE_DIRTY;
397
        }
398
        $this->save_state = $save_state;
399
    }
400
401
402
403
    /**
404
     * This just sets some defaults for the _session data property
405
     *
406
     * @access private
407
     * @return void
408
     */
409
    private function _set_defaults()
410
    {
411
        // set some defaults
412
        foreach ($this->_default_session_vars as $key => $default_var) {
413
            if (is_array($default_var)) {
414
                $this->_session_data[ $key ] = array();
415
            } else {
416
                $this->_session_data[ $key ] = '';
417
            }
418
        }
419
    }
420
421
422
    /**
423
     * @retrieve  session data
424
     * @access    public
425
     * @return    string
426
     */
427
    public function id()
428
    {
429
        return $this->_sid;
430
    }
431
432
433
    /**
434
     * @param \EE_Cart $cart
435
     * @return bool
436
     */
437
    public function set_cart(EE_Cart $cart)
438
    {
439
        $this->_session_data['cart'] = $cart;
440
        $this->setSaveState();
441
        return true;
442
    }
443
444
445
    /**
446
     * reset_cart
447
     */
448
    public function reset_cart()
449
    {
450
        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
451
        $this->_session_data['cart'] = null;
452
        $this->setSaveState();
453
    }
454
455
456
    /**
457
     * @return \EE_Cart
458
     */
459
    public function cart()
460
    {
461
        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
462
            ? $this->_session_data['cart']
463
            : null;
464
    }
465
466
467
    /**
468
     * @param \EE_Checkout $checkout
469
     * @return bool
470
     */
471
    public function set_checkout(EE_Checkout $checkout)
472
    {
473
        $this->_session_data['checkout'] = $checkout;
474
        $this->setSaveState();
475
        return true;
476
    }
477
478
479
    /**
480
     * reset_checkout
481
     */
482
    public function reset_checkout()
483
    {
484
        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
485
        $this->_session_data['checkout'] = null;
486
        $this->setSaveState();
487
    }
488
489
490
    /**
491
     * @return \EE_Checkout
492
     */
493
    public function checkout()
494
    {
495
        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
496
            ? $this->_session_data['checkout']
497
            : null;
498
    }
499
500
501
    /**
502
     * @param \EE_Transaction $transaction
503
     * @return bool
504
     * @throws EE_Error
505
     */
506
    public function set_transaction(EE_Transaction $transaction)
507
    {
508
        // first remove the session from the transaction before we save the transaction in the session
509
        $transaction->set_txn_session_data(null);
510
        $this->_session_data['transaction'] = $transaction;
511
        $this->setSaveState();
512
        return true;
513
    }
514
515
516
    /**
517
     * reset_transaction
518
     */
519
    public function reset_transaction()
520
    {
521
        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
522
        $this->_session_data['transaction'] = null;
523
        $this->setSaveState();
524
    }
525
526
527
    /**
528
     * @return \EE_Transaction
529
     */
530
    public function transaction()
531
    {
532
        return isset($this->_session_data['transaction'])
533
               && $this->_session_data['transaction'] instanceof EE_Transaction
534
            ? $this->_session_data['transaction']
535
            : null;
536
    }
537
538
539
    /**
540
     * retrieve session data
541
     *
542
     * @param null $key
543
     * @param bool $reset_cache
544
     * @return array
545
     */
546
    public function get_session_data($key = null, $reset_cache = false)
547
    {
548
        if ($reset_cache) {
549
            $this->reset_cart();
550
            $this->reset_checkout();
551
            $this->reset_transaction();
552
        }
553
        if (! empty($key)) {
554
            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
555
        }
556
        return $this->_session_data;
557
    }
558
559
560
    /**
561
     * Returns TRUE on success, FALSE on fail
562
     *
563
     * @param array $data
564
     * @return bool
565
     */
566
    public function set_session_data($data)
567
    {
568
        // nothing ??? bad data ??? go home!
569
        if (empty($data) || ! is_array($data)) {
570
            EE_Error::add_error(
571
                esc_html__(
572
                    'No session data or invalid session data was provided.',
573
                    'event_espresso'
574
                ),
575
                __FILE__,
576
                __FUNCTION__,
577
                __LINE__
578
            );
579
            return false;
580
        }
581
        foreach ($data as $key => $value) {
582 View Code Duplication
            if (isset($this->_default_session_vars[ $key ])) {
583
                EE_Error::add_error(
584
                    sprintf(
585
                        esc_html__(
586
                            'Sorry! %s is a default session datum and can not be reset.',
587
                            'event_espresso'
588
                        ),
589
                        $key
590
                    ),
591
                    __FILE__,
592
                    __FUNCTION__,
593
                    __LINE__
594
                );
595
                return false;
596
            }
597
            $this->_session_data[ $key ] = $value;
598
            $this->setSaveState();
599
        }
600
        return true;
601
    }
602
603
604
    /**
605
     * @initiate session
606
     * @access   private
607
     * @return TRUE on success, FALSE on fail
608
     * @throws EE_Error
609
     * @throws InvalidArgumentException
610
     * @throws InvalidDataTypeException
611
     * @throws InvalidInterfaceException
612
     * @throws InvalidSessionDataException
613
     * @throws RuntimeException
614
     * @throws ReflectionException
615
     */
616
    private function _espresso_session()
617
    {
618
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
619
        $this->session_start_handler->startSession();
620
        $this->status = EE_Session::STATUS_OPEN;
621
        // get our modified session ID
622
        $this->_sid = $this->_generate_session_id();
623
        // and the visitors IP
624
        $this->_ip_address = $this->request->ipAddress();
625
        // set the "user agent"
626
        $this->_user_agent = $this->request->userAgent();
627
        // now let's retrieve what's in the db
628
        $session_data = $this->_retrieve_session_data();
629
        if (! empty($session_data)) {
630
            // get the current time in UTC
631
            $this->_time = $this->_time !== null ? $this->_time : time();
632
            // and reset the session expiration
633
            $this->_expiration = isset($session_data['expiration'])
634
                ? $session_data['expiration']
635
                : $this->_time + $this->session_lifespan->inSeconds();
636
        } else {
637
            // set initial site access time and the session expiration
638
            $this->_set_init_access_and_expiration();
639
            // set referer
640
            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
641
                ? esc_attr($_SERVER['HTTP_REFERER'])
642
                : '';
643
            // no previous session = go back and create one (on top of the data above)
644
            return false;
645
        }
646
        // now the user agent
647
        if ($session_data['user_agent'] !== $this->_user_agent) {
648
            return false;
649
        }
650
        // wait a minute... how old are you?
651
        if ($this->_time > $this->_expiration) {
652
            // yer too old fer me!
653
            $this->_expired = true;
654
            // wipe out everything that isn't a default session datum
655
            $this->clear_session(__CLASS__, __FUNCTION__);
656
        }
657
        // make event espresso session data available to plugin
658
        $this->_session_data = array_merge($this->_session_data, $session_data);
659
        return true;
660
    }
661
662
663
    /**
664
     * _get_session_data
665
     * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
666
     * databases
667
     *
668
     * @return array
669
     * @throws EE_Error
670
     * @throws InvalidArgumentException
671
     * @throws InvalidSessionDataException
672
     * @throws InvalidDataTypeException
673
     * @throws InvalidInterfaceException
674
     * @throws RuntimeException
675
     */
676
    protected function _retrieve_session_data()
677
    {
678
        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
679
        try {
680
            // we're using WP's Transient API to store session data using the PHP session ID as the option name
681
            $session_data = $this->cache_storage->get($ssn_key, false);
682
            if (empty($session_data)) {
683
                return array();
684
            }
685
            if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
686
                $hash_check = $this->cache_storage->get(
687
                    EE_Session::hash_check_prefix . $this->_sid,
688
                    false
689
                );
690
                if ($hash_check && $hash_check !== md5($session_data)) {
691
                    EE_Error::add_error(
692
                        sprintf(
693
                            __(
694
                                'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
695
                                'event_espresso'
696
                            ),
697
                            EE_Session::session_id_prefix . $this->_sid
698
                        ),
699
                        __FILE__,
700
                        __FUNCTION__,
701
                        __LINE__
702
                    );
703
                }
704
            }
705
        } catch (Exception $e) {
706
            // let's just eat that error for now and attempt to correct any corrupted data
707
            global $wpdb;
708
            $row = $wpdb->get_row(
709
                $wpdb->prepare(
710
                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
711
                    '_transient_' . $ssn_key
712
                )
713
            );
714
            $session_data = is_object($row) ? $row->option_value : null;
715
            if ($session_data) {
716
                $session_data = preg_replace_callback(
717
                    '!s:(d+):"(.*?)";!',
718 View Code Duplication
                    function ($match) {
719
                        return $match[1] === strlen($match[2])
720
                            ? $match[0]
721
                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
722
                    },
723
                    $session_data
724
                );
725
            }
726
            $session_data = maybe_unserialize($session_data);
727
        }
728
        // in case the data is encoded... try to decode it
729
        $session_data = $this->encryption instanceof EE_Encryption
730
            ? $this->encryption->base64_string_decode($session_data)
731
            : $session_data;
732
        if (! is_array($session_data)) {
733
            try {
734
                $session_data = maybe_unserialize($session_data);
735
            } catch (Exception $e) {
736
                $msg = esc_html__(
737
                    'An error occurred while attempting to unserialize the session data.',
738
                    'event_espresso'
739
                );
740
                $msg .= WP_DEBUG
741
                    ? '<br><pre>'
742
                      . print_r($session_data, true)
743
                      . '</pre><br>'
744
                      . $this->find_serialize_error($session_data)
745
                    : '';
746
                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
747
                throw new InvalidSessionDataException($msg, 0, $e);
748
            }
749
        }
750
        // just a check to make sure the session array is indeed an array
751
        if (! is_array($session_data)) {
752
            // no?!?! then something is wrong
753
            $msg = esc_html__(
754
                'The session data is missing, invalid, or corrupted.',
755
                'event_espresso'
756
            );
757
            $msg .= WP_DEBUG
758
                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
759
                : '';
760
            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
761
            throw new InvalidSessionDataException($msg);
762
        }
763 View Code Duplication
        if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
764
            $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
765
                $session_data['transaction']
766
            );
767
        }
768
        return $session_data;
769
    }
770
771
772
    /**
773
     * _generate_session_id
774
     * Retrieves the PHP session id either directly from the PHP session,
775
     * or from the $_REQUEST array if it was passed in from an AJAX request.
776
     * The session id is then salted and hashed (mmm sounds tasty)
777
     * so that it can be safely used as a $_REQUEST param
778
     *
779
     * @return string
780
     */
781
    protected function _generate_session_id()
782
    {
783
        // check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
784
        if (isset($_REQUEST['EESID'])) {
785
            $session_id = sanitize_text_field($_REQUEST['EESID']);
786
        } else {
787
            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
788
        }
789
        return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
790
    }
791
792
793
    /**
794
     * _get_sid_salt
795
     *
796
     * @return string
797
     */
798
    protected function _get_sid_salt()
799
    {
800
        // was session id salt already saved to db ?
801
        if (empty($this->_sid_salt)) {
802
            // no?  then maybe use WP defined constant
803
            if (defined('AUTH_SALT')) {
804
                $this->_sid_salt = AUTH_SALT;
805
            }
806
            // if salt doesn't exist or is too short
807
            if (strlen($this->_sid_salt) < 32) {
808
                // create a new one
809
                $this->_sid_salt = wp_generate_password(64);
810
            }
811
            // and save it as a permanent session setting
812
            $this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
813
        }
814
        return $this->_sid_salt;
815
    }
816
817
818
    /**
819
     * _set_init_access_and_expiration
820
     *
821
     * @return void
822
     */
823
    protected function _set_init_access_and_expiration()
824
    {
825
        $this->_time = time();
826
        $this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
827
        // set initial site access time
828
        $this->_session_data['init_access'] = $this->_time;
829
        // and the session expiration
830
        $this->_session_data['expiration'] = $this->_expiration;
831
    }
832
833
834
    /**
835
     * @update session data  prior to saving to the db
836
     * @access public
837
     * @param bool $new_session
838
     * @return TRUE on success, FALSE on fail
839
     * @throws EE_Error
840
     * @throws InvalidArgumentException
841
     * @throws InvalidDataTypeException
842
     * @throws InvalidInterfaceException
843
     * @throws ReflectionException
844
     */
845
    public function update($new_session = false)
846
    {
847
        $this->_session_data = $this->_session_data !== null
848
                               && is_array($this->_session_data)
849
                               && isset($this->_session_data['id'])
850
            ? $this->_session_data
851
            : array();
852
        if (empty($this->_session_data)) {
853
            $this->_set_defaults();
854
        }
855
        $session_data = array();
856
        foreach ($this->_session_data as $key => $value) {
857
            switch ($key) {
858
                case 'id':
859
                    // session ID
860
                    $session_data['id'] = $this->_sid;
861
                    break;
862
                case 'ip_address':
863
                    // visitor ip address
864
                    $session_data['ip_address'] = $this->request->ipAddress();
865
                    break;
866
                case 'user_agent':
867
                    // visitor user_agent
868
                    $session_data['user_agent'] = $this->_user_agent;
869
                    break;
870
                case 'init_access':
871
                    $session_data['init_access'] = absint($value);
872
                    break;
873
                case 'last_access':
874
                    // current access time
875
                    $session_data['last_access'] = $this->_time;
876
                    break;
877
                case 'expiration':
878
                    // when the session expires
879
                    $session_data['expiration'] = ! empty($this->_expiration)
880
                        ? $this->_expiration
881
                        : $session_data['init_access'] + $this->session_lifespan->inSeconds();
882
                    break;
883
                case 'user_id':
884
                    // current user if logged in
885
                    $session_data['user_id'] = $this->_wp_user_id();
886
                    break;
887
                case 'pages_visited':
888
                    $page_visit = $this->_get_page_visit();
889
                    if ($page_visit) {
890
                        // set pages visited where the first will be the http referrer
891
                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
892
                        // we'll only save the last 10 page visits.
893
                        $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
894
                    }
895
                    break;
896
                default:
897
                    // carry any other data over
898
                    $session_data[ $key ] = $this->_session_data[ $key ];
899
            }
900
        }
901
        $this->_session_data = $session_data;
902
        // creating a new session does not require saving to the db just yet
903
        if (! $new_session) {
904
            // ready? let's save
905
            if ($this->_save_session_to_db()) {
906
                return true;
907
            }
908
            return false;
909
        }
910
        // meh, why not?
911
        return true;
912
    }
913
914
915
    /**
916
     * @create session data array
917
     * @access public
918
     * @return bool
919
     * @throws EE_Error
920
     * @throws InvalidArgumentException
921
     * @throws InvalidDataTypeException
922
     * @throws InvalidInterfaceException
923
     * @throws ReflectionException
924
     */
925
    private function _create_espresso_session()
926
    {
927
        do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
928
        // use the update function for now with $new_session arg set to TRUE
929
        return $this->update(true) ? true : false;
930
    }
931
932
    /**
933
     * Detects if there is anything worth saving in the session (eg the cart is a good one, notices are pretty good
934
     * too). This is used when determining if we want to save the session or not.
935
     * @since 4.9.67.p
936
     * @return bool
937
     */
938
    private function sessionHasStuffWorthSaving()
939
    {
940
        return $this->save_state === EE_Session::SAVE_STATE_DIRTY
941
            || $this->cart() instanceof EE_Cart
942
            || (
943
                isset($this->_session_data['ee_notices'])
944
                && (
945
                    ! empty($this->_session_data['ee_notices']['attention'])
946
                    || !empty($this->_session_data['ee_notices']['errors'])
947
                    || !empty($this->_session_data['ee_notices']['success'])
948
                )
949
            );
950
    }
951
952
953
    /**
954
     * _save_session_to_db
955
     *
956
     * @param bool $clear_session
957
     * @return string
958
     * @throws EE_Error
959
     * @throws InvalidArgumentException
960
     * @throws InvalidDataTypeException
961
     * @throws InvalidInterfaceException
962
     * @throws ReflectionException
963
     */
964
    private function _save_session_to_db($clear_session = false)
965
    {
966
        // don't save sessions for crawlers
967
        // and unless we're deleting the session data, don't save anything if there isn't a cart
968
        if ($this->request->isBot()
969
            || (
970
                ! $clear_session
971
                && ! $this->sessionHasStuffWorthSaving()
972
                && apply_filters('FHEE__EE_Session___save_session_to_db__abort_session_save', true)
973
            )
974
        ) {
975
            return false;
976
        }
977
        $transaction = $this->transaction();
978
        if ($transaction instanceof EE_Transaction) {
979
            if (! $transaction->ID()) {
980
                $transaction->save();
981
            }
982
            $this->_session_data['transaction'] = $transaction->ID();
983
        }
984
        // then serialize all of our session data
985
        $session_data = serialize($this->_session_data);
986
        // do we need to also encode it to avoid corrupted data when saved to the db?
987
        $session_data = $this->_use_encryption
988
            ? $this->encryption->base64_string_encode($session_data)
989
            : $session_data;
990
        // maybe save hash check
991
        if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
992
            $this->cache_storage->add(
993
                EE_Session::hash_check_prefix . $this->_sid,
994
                md5($session_data),
995
                $this->session_lifespan->inSeconds()
996
            );
997
        }
998
        // we're using the Transient API for storing session data,
999
        $saved = $this->cache_storage->add(
1000
            EE_Session::session_id_prefix . $this->_sid,
1001
            $session_data,
1002
            $this->session_lifespan->inSeconds()
1003
        );
1004
        $this->setSaveState(EE_Session::SAVE_STATE_CLEAN);
1005
        return $saved;
1006
    }
1007
1008
1009
    /**
1010
     * @get    the full page request the visitor is accessing
1011
     * @access public
1012
     * @return string
1013
     */
1014
    public function _get_page_visit()
1015
    {
1016
        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
1017
        // check for request url
1018
        if (isset($_SERVER['REQUEST_URI'])) {
1019
            $http_host = '';
1020
            $page_id = '?';
1021
            $e_reg = '';
1022
            $request_uri = esc_url($_SERVER['REQUEST_URI']);
1023
            $ru_bits = explode('?', $request_uri);
1024
            $request_uri = $ru_bits[0];
1025
            // check for and grab host as well
1026
            if (isset($_SERVER['HTTP_HOST'])) {
1027
                $http_host = esc_url($_SERVER['HTTP_HOST']);
1028
            }
1029
            // check for page_id in SERVER REQUEST
1030
            if (isset($_REQUEST['page_id'])) {
1031
                // rebuild $e_reg without any of the extra parameters
1032
                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
1033
            }
1034
            // check for $e_reg in SERVER REQUEST
1035
            if (isset($_REQUEST['ee'])) {
1036
                // rebuild $e_reg without any of the extra parameters
1037
                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
1038
            }
1039
            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
1040
        }
1041
        return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
1042
    }
1043
1044
1045
    /**
1046
     * @the    current wp user id
1047
     * @access public
1048
     * @return int
1049
     */
1050
    public function _wp_user_id()
1051
    {
1052
        // if I need to explain the following lines of code, then you shouldn't be looking at this!
1053
        $this->_wp_user_id = get_current_user_id();
1054
        return $this->_wp_user_id;
1055
    }
1056
1057
1058
    /**
1059
     * Clear EE_Session data
1060
     *
1061
     * @access public
1062
     * @param string $class
1063
     * @param string $function
1064
     * @return void
1065
     * @throws EE_Error
1066
     * @throws InvalidArgumentException
1067
     * @throws InvalidDataTypeException
1068
     * @throws InvalidInterfaceException
1069
     * @throws ReflectionException
1070
     */
1071
    public function clear_session($class = '', $function = '')
1072
    {
1073
//         echo '
1074
// <h3 style="color:#999;line-height:.9em;">
1075
// <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1076
// <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1077
// </h3>';
1078
        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1079
        $this->reset_cart();
1080
        $this->reset_checkout();
1081
        $this->reset_transaction();
1082
        // wipe out everything that isn't a default session datum
1083
        $this->reset_data(array_keys($this->_session_data));
1084
        // reset initial site access time and the session expiration
1085
        $this->_set_init_access_and_expiration();
1086
        $this->setSaveState();
1087
        $this->_save_session_to_db(true);
1088
    }
1089
1090
1091
    /**
1092
     * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1093
     *
1094
     * @param array|mixed $data_to_reset
1095
     * @param bool        $show_all_notices
1096
     * @return bool
1097
     */
1098
    public function reset_data($data_to_reset = array(), $show_all_notices = false)
1099
    {
1100
        // if $data_to_reset is not in an array, then put it in one
1101
        if (! is_array($data_to_reset)) {
1102
            $data_to_reset = array($data_to_reset);
1103
        }
1104
        // nothing ??? go home!
1105
        if (empty($data_to_reset)) {
1106
            EE_Error::add_error(
1107
                __(
1108
                    'No session data could be reset, because no session var name was provided.',
1109
                    'event_espresso'
1110
                ),
1111
                __FILE__,
1112
                __FUNCTION__,
1113
                __LINE__
1114
            );
1115
            return false;
1116
        }
1117
        $return_value = true;
1118
        // since $data_to_reset is an array, cycle through the values
1119
        foreach ($data_to_reset as $reset) {
1120
            // first check to make sure it is a valid session var
1121
            if (isset($this->_session_data[ $reset ])) {
1122
                // then check to make sure it is not a default var
1123
                if (! array_key_exists($reset, $this->_default_session_vars)) {
1124
                    // remove session var
1125
                    unset($this->_session_data[ $reset ]);
1126
                    $this->setSaveState();
1127
                    if ($show_all_notices) {
1128
                        EE_Error::add_success(
1129
                            sprintf(
1130
                                __('The session variable %s was removed.', 'event_espresso'),
1131
                                $reset
1132
                            ),
1133
                            __FILE__,
1134
                            __FUNCTION__,
1135
                            __LINE__
1136
                        );
1137
                    }
1138 View Code Duplication
                } else {
1139
                    // yeeeeeeeeerrrrrrrrrrr OUT !!!!
1140
                    if ($show_all_notices) {
1141
                        EE_Error::add_error(
1142
                            sprintf(
1143
                                __(
1144
                                    'Sorry! %s is a default session datum and can not be reset.',
1145
                                    'event_espresso'
1146
                                ),
1147
                                $reset
1148
                            ),
1149
                            __FILE__,
1150
                            __FUNCTION__,
1151
                            __LINE__
1152
                        );
1153
                    }
1154
                    $return_value = false;
1155
                }
1156 View Code Duplication
            } elseif ($show_all_notices) {
1157
                // oops! that session var does not exist!
1158
                EE_Error::add_error(
1159
                    sprintf(
1160
                        __(
1161
                            'The session item provided, %s, is invalid or does not exist.',
1162
                            'event_espresso'
1163
                        ),
1164
                        $reset
1165
                    ),
1166
                    __FILE__,
1167
                    __FUNCTION__,
1168
                    __LINE__
1169
                );
1170
                $return_value = false;
1171
            }
1172
        } // end of foreach
1173
        return $return_value;
1174
    }
1175
1176
1177
    /**
1178
     *   wp_loaded
1179
     *
1180
     * @access public
1181
     * @throws EE_Error
1182
     * @throws InvalidDataTypeException
1183
     * @throws InvalidInterfaceException
1184
     * @throws InvalidArgumentException
1185
     * @throws ReflectionException
1186
     */
1187
    public function wp_loaded()
1188
    {
1189
        if ($this->request->requestParamIsSet('clear_session')) {
1190
            $this->clear_session(__CLASS__, __FUNCTION__);
1191
        }
1192
    }
1193
1194
1195
    /**
1196
     * Used to reset the entire object (for tests).
1197
     *
1198
     * @since 4.3.0
1199
     * @throws EE_Error
1200
     * @throws InvalidDataTypeException
1201
     * @throws InvalidInterfaceException
1202
     * @throws InvalidArgumentException
1203
     * @throws ReflectionException
1204
     */
1205
    public function reset_instance()
1206
    {
1207
        $this->clear_session();
1208
        self::$_instance = null;
1209
    }
1210
1211
1212
    public function configure_garbage_collection_filters()
1213
    {
1214
        // run old filter we had for controlling session cleanup
1215
        $expired_session_transient_delete_query_limit = absint(
1216
            apply_filters(
1217
                'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1218
                50
1219
            )
1220
        );
1221
        // is there a value? or one that is different than the default 50 records?
1222
        if ($expired_session_transient_delete_query_limit === 0) {
1223
            // hook into TransientCacheStorage in case Session cleanup was turned off
1224
            add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1225
        } elseif ($expired_session_transient_delete_query_limit !== 50) {
1226
            // or use that for the new transient cleanup query limit
1227
            add_filter(
1228
                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1229
                function () use ($expired_session_transient_delete_query_limit) {
1230
                    return $expired_session_transient_delete_query_limit;
1231
                }
1232
            );
1233
        }
1234
    }
1235
1236
1237
    /**
1238
     * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1239
     * @param $data1
1240
     * @return string
1241
     */
1242
    private function find_serialize_error($data1)
1243
    {
1244
        $error = '<pre>';
1245
        $data2 = preg_replace_callback(
1246
            '!s:(\d+):"(.*?)";!',
1247 View Code Duplication
            function ($match) {
1248
                return ($match[1] === strlen($match[2]))
1249
                    ? $match[0]
1250
                    : 's:'
1251
                      . strlen($match[2])
1252
                      . ':"'
1253
                      . $match[2]
1254
                      . '";';
1255
            },
1256
            $data1
1257
        );
1258
        $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1259
        $error .= $data1 . PHP_EOL;
1260
        $error .= $data2 . PHP_EOL;
1261
        for ($i = 0; $i < $max; $i++) {
1262
            if (@$data1[ $i ] !== @$data2[ $i ]) {
1263
                $error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1264
                $error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1265
                $error .= "\t-> Line Number = $i" . PHP_EOL;
1266
                $start = ($i - 20);
1267
                $start = ($start < 0) ? 0 : $start;
1268
                $length = 40;
1269
                $point = $max - $i;
1270
                if ($point < 20) {
1271
                    $rlength = 1;
1272
                    $rpoint = -$point;
1273
                } else {
1274
                    $rpoint = $length - 20;
1275
                    $rlength = 1;
1276
                }
1277
                $error .= "\t-> Section Data1  = ";
1278
                $error .= substr_replace(
1279
                    substr($data1, $start, $length),
1280
                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1281
                    $rpoint,
1282
                    $rlength
1283
                );
1284
                $error .= PHP_EOL;
1285
                $error .= "\t-> Section Data2  = ";
1286
                $error .= substr_replace(
1287
                    substr($data2, $start, $length),
1288
                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1289
                    $rpoint,
1290
                    $rlength
1291
                );
1292
                $error .= PHP_EOL;
1293
            }
1294
        }
1295
        $error .= '</pre>';
1296
        return $error;
1297
    }
1298
1299
1300
    /**
1301
     * Saves an  array of settings used for configuring aspects of session behaviour
1302
     *
1303
     * @param array $updated_settings
1304
     */
1305
    private function updateSessionSettings(array $updated_settings = array())
1306
    {
1307
        // add existing settings, but only if not included in incoming $updated_settings array
1308
        $updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1309
        update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1310
    }
1311
1312
1313
    /**
1314
     * garbage_collection
1315
     */
1316
    public function garbageCollection()
1317
    {
1318
        // only perform during regular requests if last garbage collection was over an hour ago
1319
        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1320
            $this->_last_gc = time();
1321
            $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1322
            /** @type WPDB $wpdb */
1323
            global $wpdb;
1324
            // filter the query limit. Set to 0 to turn off garbage collection
1325
            $expired_session_transient_delete_query_limit = absint(
1326
                apply_filters(
1327
                    'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1328
                    50
1329
                )
1330
            );
1331
            // non-zero LIMIT means take out the trash
1332
            if ($expired_session_transient_delete_query_limit) {
1333
                $session_key = str_replace('_', '\_', EE_Session::session_id_prefix);
1334
                $hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1335
                // since transient expiration timestamps are set in the future, we can compare against NOW
1336
                // but we only want to pick up any trash that's been around for more than a day
1337
                $expiration = time() - DAY_IN_SECONDS;
1338
                $SQL = "
1339
                    SELECT option_name
1340
                    FROM {$wpdb->options}
1341
                    WHERE
1342
                      ( option_name LIKE '\_transient\_timeout\_{$session_key}%'
1343
                      OR option_name LIKE '\_transient\_timeout\_{$hash_check_key}%' )
1344
                    AND option_value < {$expiration}
1345
                    LIMIT {$expired_session_transient_delete_query_limit}
1346
                ";
1347
                // produces something like:
1348
                // SELECT option_name FROM wp_options
1349
                // WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1350
                // OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1351
                // AND option_value < 1508368198 LIMIT 50
1352
                $expired_sessions = $wpdb->get_col($SQL);
1353
                // valid results?
1354
                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1355
                    $this->cache_storage->deleteMany($expired_sessions, true);
1356
                }
1357
            }
1358
        }
1359
    }
1360
}
1361