Completed
Branch Gutenberg/master (5ab96a)
by
unknown
46:44 queued 37:22
created
core/EE_Session.core.php 2 patches
Indentation   +1328 added lines, -1328 removed lines patch added patch discarded remove patch
@@ -24,1326 +24,1326 @@  discard block
 block discarded – undo
24 24
 class EE_Session implements SessionIdentifierInterface
25 25
 {
26 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
-     * Marks whether the session data has been updated or not.
388
-     * Valid options are:
389
-     *      EE_Session::SAVE_STATE_CLEAN - session data remains unchanged and updating is not necessary
390
-     *      EE_Session::SAVE_STATE_DIRTY - session data has changed since last save and needs to be updated
391
-     * default value is EE_Session::SAVE_STATE_DIRTY
392
-     *
393
-     * @param string $save_state
394
-     */
395
-    public function setSaveState($save_state = EE_Session::SAVE_STATE_DIRTY)
396
-    {
397
-        $valid_save_states = [
398
-            EE_Session::SAVE_STATE_CLEAN,
399
-            EE_Session::SAVE_STATE_DIRTY,
400
-        ];
401
-        if (! in_array($save_state, $valid_save_states, true)) {
402
-            $save_state = EE_Session::SAVE_STATE_DIRTY;
403
-        }
404
-        $this->save_state = $save_state;
405
-    }
406
-
407
-
408
-
409
-    /**
410
-     * This just sets some defaults for the _session data property
411
-     *
412
-     * @access private
413
-     * @return void
414
-     */
415
-    private function _set_defaults()
416
-    {
417
-        // set some defaults
418
-        foreach ($this->_default_session_vars as $key => $default_var) {
419
-            if (is_array($default_var)) {
420
-                $this->_session_data[ $key ] = array();
421
-            } else {
422
-                $this->_session_data[ $key ] = '';
423
-            }
424
-        }
425
-    }
426
-
427
-
428
-    /**
429
-     * @retrieve  session data
430
-     * @access    public
431
-     * @return    string
432
-     */
433
-    public function id()
434
-    {
435
-        return $this->_sid;
436
-    }
437
-
438
-
439
-    /**
440
-     * @param \EE_Cart $cart
441
-     * @return bool
442
-     */
443
-    public function set_cart(EE_Cart $cart)
444
-    {
445
-        $this->_session_data['cart'] = $cart;
446
-        $this->setSaveState();
447
-        return true;
448
-    }
449
-
450
-
451
-    /**
452
-     * reset_cart
453
-     */
454
-    public function reset_cart()
455
-    {
456
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
457
-        $this->_session_data['cart'] = null;
458
-        $this->setSaveState();
459
-    }
460
-
461
-
462
-    /**
463
-     * @return \EE_Cart
464
-     */
465
-    public function cart()
466
-    {
467
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
468
-            ? $this->_session_data['cart']
469
-            : null;
470
-    }
471
-
472
-
473
-    /**
474
-     * @param \EE_Checkout $checkout
475
-     * @return bool
476
-     */
477
-    public function set_checkout(EE_Checkout $checkout)
478
-    {
479
-        $this->_session_data['checkout'] = $checkout;
480
-        $this->setSaveState();
481
-        return true;
482
-    }
483
-
484
-
485
-    /**
486
-     * reset_checkout
487
-     */
488
-    public function reset_checkout()
489
-    {
490
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
491
-        $this->_session_data['checkout'] = null;
492
-        $this->setSaveState();
493
-    }
494
-
495
-
496
-    /**
497
-     * @return \EE_Checkout
498
-     */
499
-    public function checkout()
500
-    {
501
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
502
-            ? $this->_session_data['checkout']
503
-            : null;
504
-    }
505
-
506
-
507
-    /**
508
-     * @param \EE_Transaction $transaction
509
-     * @return bool
510
-     * @throws EE_Error
511
-     */
512
-    public function set_transaction(EE_Transaction $transaction)
513
-    {
514
-        // first remove the session from the transaction before we save the transaction in the session
515
-        $transaction->set_txn_session_data(null);
516
-        $this->_session_data['transaction'] = $transaction;
517
-        $this->setSaveState();
518
-        return true;
519
-    }
520
-
521
-
522
-    /**
523
-     * reset_transaction
524
-     */
525
-    public function reset_transaction()
526
-    {
527
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
528
-        $this->_session_data['transaction'] = null;
529
-        $this->setSaveState();
530
-    }
531
-
532
-
533
-    /**
534
-     * @return \EE_Transaction
535
-     */
536
-    public function transaction()
537
-    {
538
-        return isset($this->_session_data['transaction'])
539
-               && $this->_session_data['transaction'] instanceof EE_Transaction
540
-            ? $this->_session_data['transaction']
541
-            : null;
542
-    }
543
-
544
-
545
-    /**
546
-     * retrieve session data
547
-     *
548
-     * @param null $key
549
-     * @param bool $reset_cache
550
-     * @return array
551
-     */
552
-    public function get_session_data($key = null, $reset_cache = false)
553
-    {
554
-        if ($reset_cache) {
555
-            $this->reset_cart();
556
-            $this->reset_checkout();
557
-            $this->reset_transaction();
558
-        }
559
-        if (! empty($key)) {
560
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
561
-        }
562
-        return $this->_session_data;
563
-    }
564
-
565
-
566
-    /**
567
-     * Returns TRUE on success, FALSE on fail
568
-     *
569
-     * @param array $data
570
-     * @return bool
571
-     */
572
-    public function set_session_data($data)
573
-    {
574
-        // nothing ??? bad data ??? go home!
575
-        if (empty($data) || ! is_array($data)) {
576
-            EE_Error::add_error(
577
-                esc_html__(
578
-                    'No session data or invalid session data was provided.',
579
-                    'event_espresso'
580
-                ),
581
-                __FILE__,
582
-                __FUNCTION__,
583
-                __LINE__
584
-            );
585
-            return false;
586
-        }
587
-        foreach ($data as $key => $value) {
588
-            if (isset($this->_default_session_vars[ $key ])) {
589
-                EE_Error::add_error(
590
-                    sprintf(
591
-                        esc_html__(
592
-                            'Sorry! %s is a default session datum and can not be reset.',
593
-                            'event_espresso'
594
-                        ),
595
-                        $key
596
-                    ),
597
-                    __FILE__,
598
-                    __FUNCTION__,
599
-                    __LINE__
600
-                );
601
-                return false;
602
-            }
603
-            $this->_session_data[ $key ] = $value;
604
-            $this->setSaveState();
605
-        }
606
-        return true;
607
-    }
608
-
609
-
610
-    /**
611
-     * @initiate session
612
-     * @access   private
613
-     * @return TRUE on success, FALSE on fail
614
-     * @throws EE_Error
615
-     * @throws InvalidArgumentException
616
-     * @throws InvalidDataTypeException
617
-     * @throws InvalidInterfaceException
618
-     * @throws InvalidSessionDataException
619
-     * @throws RuntimeException
620
-     * @throws ReflectionException
621
-     */
622
-    private function _espresso_session()
623
-    {
624
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
625
-        $this->session_start_handler->startSession();
626
-        $this->status = EE_Session::STATUS_OPEN;
627
-        // get our modified session ID
628
-        $this->_sid = $this->_generate_session_id();
629
-        // and the visitors IP
630
-        $this->_ip_address = $this->request->ipAddress();
631
-        // set the "user agent"
632
-        $this->_user_agent = $this->request->userAgent();
633
-        // now let's retrieve what's in the db
634
-        $session_data = $this->_retrieve_session_data();
635
-        if (! empty($session_data)) {
636
-            // get the current time in UTC
637
-            $this->_time = $this->_time !== null ? $this->_time : time();
638
-            // and reset the session expiration
639
-            $this->_expiration = isset($session_data['expiration'])
640
-                ? $session_data['expiration']
641
-                : $this->_time + $this->session_lifespan->inSeconds();
642
-        } else {
643
-            // set initial site access time and the session expiration
644
-            $this->_set_init_access_and_expiration();
645
-            // set referer
646
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
647
-                ? esc_attr($_SERVER['HTTP_REFERER'])
648
-                : '';
649
-            // no previous session = go back and create one (on top of the data above)
650
-            return false;
651
-        }
652
-        // now the user agent
653
-        if ($session_data['user_agent'] !== $this->_user_agent) {
654
-            return false;
655
-        }
656
-        // wait a minute... how old are you?
657
-        if ($this->_time > $this->_expiration) {
658
-            // yer too old fer me!
659
-            $this->_expired = true;
660
-            // wipe out everything that isn't a default session datum
661
-            $this->clear_session(__CLASS__, __FUNCTION__);
662
-        }
663
-        // make event espresso session data available to plugin
664
-        $this->_session_data = array_merge($this->_session_data, $session_data);
665
-        return true;
666
-    }
667
-
668
-
669
-    /**
670
-     * _get_session_data
671
-     * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
672
-     * databases
673
-     *
674
-     * @return array
675
-     * @throws EE_Error
676
-     * @throws InvalidArgumentException
677
-     * @throws InvalidSessionDataException
678
-     * @throws InvalidDataTypeException
679
-     * @throws InvalidInterfaceException
680
-     * @throws RuntimeException
681
-     */
682
-    protected function _retrieve_session_data()
683
-    {
684
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
685
-        try {
686
-            // we're using WP's Transient API to store session data using the PHP session ID as the option name
687
-            $session_data = $this->cache_storage->get($ssn_key, false);
688
-            if (empty($session_data)) {
689
-                return array();
690
-            }
691
-            if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
692
-                $hash_check = $this->cache_storage->get(
693
-                    EE_Session::hash_check_prefix . $this->_sid,
694
-                    false
695
-                );
696
-                if ($hash_check && $hash_check !== md5($session_data)) {
697
-                    EE_Error::add_error(
698
-                        sprintf(
699
-                            __(
700
-                                'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
701
-                                'event_espresso'
702
-                            ),
703
-                            EE_Session::session_id_prefix . $this->_sid
704
-                        ),
705
-                        __FILE__,
706
-                        __FUNCTION__,
707
-                        __LINE__
708
-                    );
709
-                }
710
-            }
711
-        } catch (Exception $e) {
712
-            // let's just eat that error for now and attempt to correct any corrupted data
713
-            global $wpdb;
714
-            $row = $wpdb->get_row(
715
-                $wpdb->prepare(
716
-                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
717
-                    '_transient_' . $ssn_key
718
-                )
719
-            );
720
-            $session_data = is_object($row) ? $row->option_value : null;
721
-            if ($session_data) {
722
-                $session_data = preg_replace_callback(
723
-                    '!s:(d+):"(.*?)";!',
724
-                    function ($match) {
725
-                        return $match[1] === strlen($match[2])
726
-                            ? $match[0]
727
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
728
-                    },
729
-                    $session_data
730
-                );
731
-            }
732
-            $session_data = maybe_unserialize($session_data);
733
-        }
734
-        // in case the data is encoded... try to decode it
735
-        $session_data = $this->encryption instanceof EE_Encryption
736
-            ? $this->encryption->base64_string_decode($session_data)
737
-            : $session_data;
738
-        if (! is_array($session_data)) {
739
-            try {
740
-                $session_data = maybe_unserialize($session_data);
741
-            } catch (Exception $e) {
742
-                $msg = esc_html__(
743
-                    'An error occurred while attempting to unserialize the session data.',
744
-                    'event_espresso'
745
-                );
746
-                $msg .= WP_DEBUG
747
-                    ? '<br><pre>'
748
-                      . print_r($session_data, true)
749
-                      . '</pre><br>'
750
-                      . $this->find_serialize_error($session_data)
751
-                    : '';
752
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
753
-                throw new InvalidSessionDataException($msg, 0, $e);
754
-            }
755
-        }
756
-        // just a check to make sure the session array is indeed an array
757
-        if (! is_array($session_data)) {
758
-            // no?!?! then something is wrong
759
-            $msg = esc_html__(
760
-                'The session data is missing, invalid, or corrupted.',
761
-                'event_espresso'
762
-            );
763
-            $msg .= WP_DEBUG
764
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
765
-                : '';
766
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
767
-            throw new InvalidSessionDataException($msg);
768
-        }
769
-        if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
770
-            $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
771
-                $session_data['transaction']
772
-            );
773
-        }
774
-        return $session_data;
775
-    }
776
-
777
-
778
-    /**
779
-     * _generate_session_id
780
-     * Retrieves the PHP session id either directly from the PHP session,
781
-     * or from the $_REQUEST array if it was passed in from an AJAX request.
782
-     * The session id is then salted and hashed (mmm sounds tasty)
783
-     * so that it can be safely used as a $_REQUEST param
784
-     *
785
-     * @return string
786
-     */
787
-    protected function _generate_session_id()
788
-    {
789
-        // check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
790
-        if (isset($_REQUEST['EESID'])) {
791
-            $session_id = sanitize_text_field($_REQUEST['EESID']);
792
-        } else {
793
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
794
-        }
795
-        return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
796
-    }
797
-
798
-
799
-    /**
800
-     * _get_sid_salt
801
-     *
802
-     * @return string
803
-     */
804
-    protected function _get_sid_salt()
805
-    {
806
-        // was session id salt already saved to db ?
807
-        if (empty($this->_sid_salt)) {
808
-            // no?  then maybe use WP defined constant
809
-            if (defined('AUTH_SALT')) {
810
-                $this->_sid_salt = AUTH_SALT;
811
-            }
812
-            // if salt doesn't exist or is too short
813
-            if (strlen($this->_sid_salt) < 32) {
814
-                // create a new one
815
-                $this->_sid_salt = wp_generate_password(64);
816
-            }
817
-            // and save it as a permanent session setting
818
-            $this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
819
-        }
820
-        return $this->_sid_salt;
821
-    }
822
-
823
-
824
-    /**
825
-     * _set_init_access_and_expiration
826
-     *
827
-     * @return void
828
-     */
829
-    protected function _set_init_access_and_expiration()
830
-    {
831
-        $this->_time = time();
832
-        $this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
833
-        // set initial site access time
834
-        $this->_session_data['init_access'] = $this->_time;
835
-        // and the session expiration
836
-        $this->_session_data['expiration'] = $this->_expiration;
837
-    }
838
-
839
-
840
-    /**
841
-     * @update session data  prior to saving to the db
842
-     * @access public
843
-     * @param bool $new_session
844
-     * @return TRUE on success, FALSE on fail
845
-     * @throws EE_Error
846
-     * @throws InvalidArgumentException
847
-     * @throws InvalidDataTypeException
848
-     * @throws InvalidInterfaceException
849
-     * @throws ReflectionException
850
-     */
851
-    public function update($new_session = false)
852
-    {
853
-        $this->_session_data = $this->_session_data !== null
854
-                               && is_array($this->_session_data)
855
-                               && isset($this->_session_data['id'])
856
-            ? $this->_session_data
857
-            : array();
858
-        if (empty($this->_session_data)) {
859
-            $this->_set_defaults();
860
-        }
861
-        $session_data = array();
862
-        foreach ($this->_session_data as $key => $value) {
863
-            switch ($key) {
864
-                case 'id':
865
-                    // session ID
866
-                    $session_data['id'] = $this->_sid;
867
-                    break;
868
-                case 'ip_address':
869
-                    // visitor ip address
870
-                    $session_data['ip_address'] = $this->request->ipAddress();
871
-                    break;
872
-                case 'user_agent':
873
-                    // visitor user_agent
874
-                    $session_data['user_agent'] = $this->_user_agent;
875
-                    break;
876
-                case 'init_access':
877
-                    $session_data['init_access'] = absint($value);
878
-                    break;
879
-                case 'last_access':
880
-                    // current access time
881
-                    $session_data['last_access'] = $this->_time;
882
-                    break;
883
-                case 'expiration':
884
-                    // when the session expires
885
-                    $session_data['expiration'] = ! empty($this->_expiration)
886
-                        ? $this->_expiration
887
-                        : $session_data['init_access'] + $this->session_lifespan->inSeconds();
888
-                    break;
889
-                case 'user_id':
890
-                    // current user if logged in
891
-                    $session_data['user_id'] = $this->_wp_user_id();
892
-                    break;
893
-                case 'pages_visited':
894
-                    $page_visit = $this->_get_page_visit();
895
-                    if ($page_visit) {
896
-                        // set pages visited where the first will be the http referrer
897
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
898
-                        // we'll only save the last 10 page visits.
899
-                        $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
900
-                    }
901
-                    break;
902
-                default:
903
-                    // carry any other data over
904
-                    $session_data[ $key ] = $this->_session_data[ $key ];
905
-            }
906
-        }
907
-        $this->_session_data = $session_data;
908
-        // creating a new session does not require saving to the db just yet
909
-        if (! $new_session) {
910
-            // ready? let's save
911
-            if ($this->_save_session_to_db()) {
912
-                return true;
913
-            }
914
-            return false;
915
-        }
916
-        // meh, why not?
917
-        return true;
918
-    }
919
-
920
-
921
-    /**
922
-     * @create session data array
923
-     * @access public
924
-     * @return bool
925
-     * @throws EE_Error
926
-     * @throws InvalidArgumentException
927
-     * @throws InvalidDataTypeException
928
-     * @throws InvalidInterfaceException
929
-     * @throws ReflectionException
930
-     */
931
-    private function _create_espresso_session()
932
-    {
933
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
934
-        // use the update function for now with $new_session arg set to TRUE
935
-        return $this->update(true) ? true : false;
936
-    }
937
-
938
-    /**
939
-     * Detects if there is anything worth saving in the session (eg the cart is a good one, notices are pretty good
940
-     * too). This is used when determining if we want to save the session or not.
941
-     * @since 4.9.67.p
942
-     * @return bool
943
-     */
944
-    private function sessionHasStuffWorthSaving()
945
-    {
946
-        return $this->save_state === EE_Session::SAVE_STATE_DIRTY
947
-               // we may want to eventually remove the following
948
-               // on the assumption that the above check is enough
949
-               || $this->cart() instanceof EE_Cart
950
-               || (
951
-                   isset($this->_session_data['ee_notices'])
952
-                   && (
953
-                       ! empty($this->_session_data['ee_notices']['attention'])
954
-                       || ! empty($this->_session_data['ee_notices']['errors'])
955
-                       || ! empty($this->_session_data['ee_notices']['success'])
956
-                   )
957
-               );
958
-    }
959
-
960
-
961
-    /**
962
-     * _save_session_to_db
963
-     *
964
-     * @param bool $clear_session
965
-     * @return string
966
-     * @throws EE_Error
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidDataTypeException
969
-     * @throws InvalidInterfaceException
970
-     * @throws ReflectionException
971
-     */
972
-    private function _save_session_to_db($clear_session = false)
973
-    {
974
-        // don't save sessions for crawlers
975
-        // and unless we're deleting the session data, don't save anything if there isn't a cart
976
-        if ($this->request->isBot()
977
-            || (
978
-                ! $clear_session
979
-                && ! $this->sessionHasStuffWorthSaving()
980
-                && apply_filters('FHEE__EE_Session___save_session_to_db__abort_session_save', true)
981
-            )
982
-        ) {
983
-            return false;
984
-        }
985
-        $transaction = $this->transaction();
986
-        if ($transaction instanceof EE_Transaction) {
987
-            if (! $transaction->ID()) {
988
-                $transaction->save();
989
-            }
990
-            $this->_session_data['transaction'] = $transaction->ID();
991
-        }
992
-        // then serialize all of our session data
993
-        $session_data = serialize($this->_session_data);
994
-        // do we need to also encode it to avoid corrupted data when saved to the db?
995
-        $session_data = $this->_use_encryption
996
-            ? $this->encryption->base64_string_encode($session_data)
997
-            : $session_data;
998
-        // maybe save hash check
999
-        if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
1000
-            $this->cache_storage->add(
1001
-                EE_Session::hash_check_prefix . $this->_sid,
1002
-                md5($session_data),
1003
-                $this->session_lifespan->inSeconds()
1004
-            );
1005
-        }
1006
-        // we're using the Transient API for storing session data,
1007
-        $saved = $this->cache_storage->add(
1008
-            EE_Session::session_id_prefix . $this->_sid,
1009
-            $session_data,
1010
-            $this->session_lifespan->inSeconds()
1011
-        );
1012
-        $this->setSaveState(EE_Session::SAVE_STATE_CLEAN);
1013
-        return $saved;
1014
-    }
1015
-
1016
-
1017
-    /**
1018
-     * @get    the full page request the visitor is accessing
1019
-     * @access public
1020
-     * @return string
1021
-     */
1022
-    public function _get_page_visit()
1023
-    {
1024
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
1025
-        // check for request url
1026
-        if (isset($_SERVER['REQUEST_URI'])) {
1027
-            $http_host = '';
1028
-            $page_id = '?';
1029
-            $e_reg = '';
1030
-            $request_uri = esc_url($_SERVER['REQUEST_URI']);
1031
-            $ru_bits = explode('?', $request_uri);
1032
-            $request_uri = $ru_bits[0];
1033
-            // check for and grab host as well
1034
-            if (isset($_SERVER['HTTP_HOST'])) {
1035
-                $http_host = esc_url($_SERVER['HTTP_HOST']);
1036
-            }
1037
-            // check for page_id in SERVER REQUEST
1038
-            if (isset($_REQUEST['page_id'])) {
1039
-                // rebuild $e_reg without any of the extra parameters
1040
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
1041
-            }
1042
-            // check for $e_reg in SERVER REQUEST
1043
-            if (isset($_REQUEST['ee'])) {
1044
-                // rebuild $e_reg without any of the extra parameters
1045
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
1046
-            }
1047
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
1048
-        }
1049
-        return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
1050
-    }
1051
-
1052
-
1053
-    /**
1054
-     * @the    current wp user id
1055
-     * @access public
1056
-     * @return int
1057
-     */
1058
-    public function _wp_user_id()
1059
-    {
1060
-        // if I need to explain the following lines of code, then you shouldn't be looking at this!
1061
-        $this->_wp_user_id = get_current_user_id();
1062
-        return $this->_wp_user_id;
1063
-    }
1064
-
1065
-
1066
-    /**
1067
-     * Clear EE_Session data
1068
-     *
1069
-     * @access public
1070
-     * @param string $class
1071
-     * @param string $function
1072
-     * @return void
1073
-     * @throws EE_Error
1074
-     * @throws InvalidArgumentException
1075
-     * @throws InvalidDataTypeException
1076
-     * @throws InvalidInterfaceException
1077
-     * @throws ReflectionException
1078
-     */
1079
-    public function clear_session($class = '', $function = '')
1080
-    {
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
+	 * Marks whether the session data has been updated or not.
388
+	 * Valid options are:
389
+	 *      EE_Session::SAVE_STATE_CLEAN - session data remains unchanged and updating is not necessary
390
+	 *      EE_Session::SAVE_STATE_DIRTY - session data has changed since last save and needs to be updated
391
+	 * default value is EE_Session::SAVE_STATE_DIRTY
392
+	 *
393
+	 * @param string $save_state
394
+	 */
395
+	public function setSaveState($save_state = EE_Session::SAVE_STATE_DIRTY)
396
+	{
397
+		$valid_save_states = [
398
+			EE_Session::SAVE_STATE_CLEAN,
399
+			EE_Session::SAVE_STATE_DIRTY,
400
+		];
401
+		if (! in_array($save_state, $valid_save_states, true)) {
402
+			$save_state = EE_Session::SAVE_STATE_DIRTY;
403
+		}
404
+		$this->save_state = $save_state;
405
+	}
406
+
407
+
408
+
409
+	/**
410
+	 * This just sets some defaults for the _session data property
411
+	 *
412
+	 * @access private
413
+	 * @return void
414
+	 */
415
+	private function _set_defaults()
416
+	{
417
+		// set some defaults
418
+		foreach ($this->_default_session_vars as $key => $default_var) {
419
+			if (is_array($default_var)) {
420
+				$this->_session_data[ $key ] = array();
421
+			} else {
422
+				$this->_session_data[ $key ] = '';
423
+			}
424
+		}
425
+	}
426
+
427
+
428
+	/**
429
+	 * @retrieve  session data
430
+	 * @access    public
431
+	 * @return    string
432
+	 */
433
+	public function id()
434
+	{
435
+		return $this->_sid;
436
+	}
437
+
438
+
439
+	/**
440
+	 * @param \EE_Cart $cart
441
+	 * @return bool
442
+	 */
443
+	public function set_cart(EE_Cart $cart)
444
+	{
445
+		$this->_session_data['cart'] = $cart;
446
+		$this->setSaveState();
447
+		return true;
448
+	}
449
+
450
+
451
+	/**
452
+	 * reset_cart
453
+	 */
454
+	public function reset_cart()
455
+	{
456
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
457
+		$this->_session_data['cart'] = null;
458
+		$this->setSaveState();
459
+	}
460
+
461
+
462
+	/**
463
+	 * @return \EE_Cart
464
+	 */
465
+	public function cart()
466
+	{
467
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
468
+			? $this->_session_data['cart']
469
+			: null;
470
+	}
471
+
472
+
473
+	/**
474
+	 * @param \EE_Checkout $checkout
475
+	 * @return bool
476
+	 */
477
+	public function set_checkout(EE_Checkout $checkout)
478
+	{
479
+		$this->_session_data['checkout'] = $checkout;
480
+		$this->setSaveState();
481
+		return true;
482
+	}
483
+
484
+
485
+	/**
486
+	 * reset_checkout
487
+	 */
488
+	public function reset_checkout()
489
+	{
490
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
491
+		$this->_session_data['checkout'] = null;
492
+		$this->setSaveState();
493
+	}
494
+
495
+
496
+	/**
497
+	 * @return \EE_Checkout
498
+	 */
499
+	public function checkout()
500
+	{
501
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
502
+			? $this->_session_data['checkout']
503
+			: null;
504
+	}
505
+
506
+
507
+	/**
508
+	 * @param \EE_Transaction $transaction
509
+	 * @return bool
510
+	 * @throws EE_Error
511
+	 */
512
+	public function set_transaction(EE_Transaction $transaction)
513
+	{
514
+		// first remove the session from the transaction before we save the transaction in the session
515
+		$transaction->set_txn_session_data(null);
516
+		$this->_session_data['transaction'] = $transaction;
517
+		$this->setSaveState();
518
+		return true;
519
+	}
520
+
521
+
522
+	/**
523
+	 * reset_transaction
524
+	 */
525
+	public function reset_transaction()
526
+	{
527
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
528
+		$this->_session_data['transaction'] = null;
529
+		$this->setSaveState();
530
+	}
531
+
532
+
533
+	/**
534
+	 * @return \EE_Transaction
535
+	 */
536
+	public function transaction()
537
+	{
538
+		return isset($this->_session_data['transaction'])
539
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
540
+			? $this->_session_data['transaction']
541
+			: null;
542
+	}
543
+
544
+
545
+	/**
546
+	 * retrieve session data
547
+	 *
548
+	 * @param null $key
549
+	 * @param bool $reset_cache
550
+	 * @return array
551
+	 */
552
+	public function get_session_data($key = null, $reset_cache = false)
553
+	{
554
+		if ($reset_cache) {
555
+			$this->reset_cart();
556
+			$this->reset_checkout();
557
+			$this->reset_transaction();
558
+		}
559
+		if (! empty($key)) {
560
+			return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
561
+		}
562
+		return $this->_session_data;
563
+	}
564
+
565
+
566
+	/**
567
+	 * Returns TRUE on success, FALSE on fail
568
+	 *
569
+	 * @param array $data
570
+	 * @return bool
571
+	 */
572
+	public function set_session_data($data)
573
+	{
574
+		// nothing ??? bad data ??? go home!
575
+		if (empty($data) || ! is_array($data)) {
576
+			EE_Error::add_error(
577
+				esc_html__(
578
+					'No session data or invalid session data was provided.',
579
+					'event_espresso'
580
+				),
581
+				__FILE__,
582
+				__FUNCTION__,
583
+				__LINE__
584
+			);
585
+			return false;
586
+		}
587
+		foreach ($data as $key => $value) {
588
+			if (isset($this->_default_session_vars[ $key ])) {
589
+				EE_Error::add_error(
590
+					sprintf(
591
+						esc_html__(
592
+							'Sorry! %s is a default session datum and can not be reset.',
593
+							'event_espresso'
594
+						),
595
+						$key
596
+					),
597
+					__FILE__,
598
+					__FUNCTION__,
599
+					__LINE__
600
+				);
601
+				return false;
602
+			}
603
+			$this->_session_data[ $key ] = $value;
604
+			$this->setSaveState();
605
+		}
606
+		return true;
607
+	}
608
+
609
+
610
+	/**
611
+	 * @initiate session
612
+	 * @access   private
613
+	 * @return TRUE on success, FALSE on fail
614
+	 * @throws EE_Error
615
+	 * @throws InvalidArgumentException
616
+	 * @throws InvalidDataTypeException
617
+	 * @throws InvalidInterfaceException
618
+	 * @throws InvalidSessionDataException
619
+	 * @throws RuntimeException
620
+	 * @throws ReflectionException
621
+	 */
622
+	private function _espresso_session()
623
+	{
624
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
625
+		$this->session_start_handler->startSession();
626
+		$this->status = EE_Session::STATUS_OPEN;
627
+		// get our modified session ID
628
+		$this->_sid = $this->_generate_session_id();
629
+		// and the visitors IP
630
+		$this->_ip_address = $this->request->ipAddress();
631
+		// set the "user agent"
632
+		$this->_user_agent = $this->request->userAgent();
633
+		// now let's retrieve what's in the db
634
+		$session_data = $this->_retrieve_session_data();
635
+		if (! empty($session_data)) {
636
+			// get the current time in UTC
637
+			$this->_time = $this->_time !== null ? $this->_time : time();
638
+			// and reset the session expiration
639
+			$this->_expiration = isset($session_data['expiration'])
640
+				? $session_data['expiration']
641
+				: $this->_time + $this->session_lifespan->inSeconds();
642
+		} else {
643
+			// set initial site access time and the session expiration
644
+			$this->_set_init_access_and_expiration();
645
+			// set referer
646
+			$this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
647
+				? esc_attr($_SERVER['HTTP_REFERER'])
648
+				: '';
649
+			// no previous session = go back and create one (on top of the data above)
650
+			return false;
651
+		}
652
+		// now the user agent
653
+		if ($session_data['user_agent'] !== $this->_user_agent) {
654
+			return false;
655
+		}
656
+		// wait a minute... how old are you?
657
+		if ($this->_time > $this->_expiration) {
658
+			// yer too old fer me!
659
+			$this->_expired = true;
660
+			// wipe out everything that isn't a default session datum
661
+			$this->clear_session(__CLASS__, __FUNCTION__);
662
+		}
663
+		// make event espresso session data available to plugin
664
+		$this->_session_data = array_merge($this->_session_data, $session_data);
665
+		return true;
666
+	}
667
+
668
+
669
+	/**
670
+	 * _get_session_data
671
+	 * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
672
+	 * databases
673
+	 *
674
+	 * @return array
675
+	 * @throws EE_Error
676
+	 * @throws InvalidArgumentException
677
+	 * @throws InvalidSessionDataException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws InvalidInterfaceException
680
+	 * @throws RuntimeException
681
+	 */
682
+	protected function _retrieve_session_data()
683
+	{
684
+		$ssn_key = EE_Session::session_id_prefix . $this->_sid;
685
+		try {
686
+			// we're using WP's Transient API to store session data using the PHP session ID as the option name
687
+			$session_data = $this->cache_storage->get($ssn_key, false);
688
+			if (empty($session_data)) {
689
+				return array();
690
+			}
691
+			if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
692
+				$hash_check = $this->cache_storage->get(
693
+					EE_Session::hash_check_prefix . $this->_sid,
694
+					false
695
+				);
696
+				if ($hash_check && $hash_check !== md5($session_data)) {
697
+					EE_Error::add_error(
698
+						sprintf(
699
+							__(
700
+								'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
701
+								'event_espresso'
702
+							),
703
+							EE_Session::session_id_prefix . $this->_sid
704
+						),
705
+						__FILE__,
706
+						__FUNCTION__,
707
+						__LINE__
708
+					);
709
+				}
710
+			}
711
+		} catch (Exception $e) {
712
+			// let's just eat that error for now and attempt to correct any corrupted data
713
+			global $wpdb;
714
+			$row = $wpdb->get_row(
715
+				$wpdb->prepare(
716
+					"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
717
+					'_transient_' . $ssn_key
718
+				)
719
+			);
720
+			$session_data = is_object($row) ? $row->option_value : null;
721
+			if ($session_data) {
722
+				$session_data = preg_replace_callback(
723
+					'!s:(d+):"(.*?)";!',
724
+					function ($match) {
725
+						return $match[1] === strlen($match[2])
726
+							? $match[0]
727
+							: 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
728
+					},
729
+					$session_data
730
+				);
731
+			}
732
+			$session_data = maybe_unserialize($session_data);
733
+		}
734
+		// in case the data is encoded... try to decode it
735
+		$session_data = $this->encryption instanceof EE_Encryption
736
+			? $this->encryption->base64_string_decode($session_data)
737
+			: $session_data;
738
+		if (! is_array($session_data)) {
739
+			try {
740
+				$session_data = maybe_unserialize($session_data);
741
+			} catch (Exception $e) {
742
+				$msg = esc_html__(
743
+					'An error occurred while attempting to unserialize the session data.',
744
+					'event_espresso'
745
+				);
746
+				$msg .= WP_DEBUG
747
+					? '<br><pre>'
748
+					  . print_r($session_data, true)
749
+					  . '</pre><br>'
750
+					  . $this->find_serialize_error($session_data)
751
+					: '';
752
+				$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
753
+				throw new InvalidSessionDataException($msg, 0, $e);
754
+			}
755
+		}
756
+		// just a check to make sure the session array is indeed an array
757
+		if (! is_array($session_data)) {
758
+			// no?!?! then something is wrong
759
+			$msg = esc_html__(
760
+				'The session data is missing, invalid, or corrupted.',
761
+				'event_espresso'
762
+			);
763
+			$msg .= WP_DEBUG
764
+				? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
765
+				: '';
766
+			$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
767
+			throw new InvalidSessionDataException($msg);
768
+		}
769
+		if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
770
+			$session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
771
+				$session_data['transaction']
772
+			);
773
+		}
774
+		return $session_data;
775
+	}
776
+
777
+
778
+	/**
779
+	 * _generate_session_id
780
+	 * Retrieves the PHP session id either directly from the PHP session,
781
+	 * or from the $_REQUEST array if it was passed in from an AJAX request.
782
+	 * The session id is then salted and hashed (mmm sounds tasty)
783
+	 * so that it can be safely used as a $_REQUEST param
784
+	 *
785
+	 * @return string
786
+	 */
787
+	protected function _generate_session_id()
788
+	{
789
+		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
790
+		if (isset($_REQUEST['EESID'])) {
791
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
792
+		} else {
793
+			$session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
794
+		}
795
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
796
+	}
797
+
798
+
799
+	/**
800
+	 * _get_sid_salt
801
+	 *
802
+	 * @return string
803
+	 */
804
+	protected function _get_sid_salt()
805
+	{
806
+		// was session id salt already saved to db ?
807
+		if (empty($this->_sid_salt)) {
808
+			// no?  then maybe use WP defined constant
809
+			if (defined('AUTH_SALT')) {
810
+				$this->_sid_salt = AUTH_SALT;
811
+			}
812
+			// if salt doesn't exist or is too short
813
+			if (strlen($this->_sid_salt) < 32) {
814
+				// create a new one
815
+				$this->_sid_salt = wp_generate_password(64);
816
+			}
817
+			// and save it as a permanent session setting
818
+			$this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
819
+		}
820
+		return $this->_sid_salt;
821
+	}
822
+
823
+
824
+	/**
825
+	 * _set_init_access_and_expiration
826
+	 *
827
+	 * @return void
828
+	 */
829
+	protected function _set_init_access_and_expiration()
830
+	{
831
+		$this->_time = time();
832
+		$this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
833
+		// set initial site access time
834
+		$this->_session_data['init_access'] = $this->_time;
835
+		// and the session expiration
836
+		$this->_session_data['expiration'] = $this->_expiration;
837
+	}
838
+
839
+
840
+	/**
841
+	 * @update session data  prior to saving to the db
842
+	 * @access public
843
+	 * @param bool $new_session
844
+	 * @return TRUE on success, FALSE on fail
845
+	 * @throws EE_Error
846
+	 * @throws InvalidArgumentException
847
+	 * @throws InvalidDataTypeException
848
+	 * @throws InvalidInterfaceException
849
+	 * @throws ReflectionException
850
+	 */
851
+	public function update($new_session = false)
852
+	{
853
+		$this->_session_data = $this->_session_data !== null
854
+							   && is_array($this->_session_data)
855
+							   && isset($this->_session_data['id'])
856
+			? $this->_session_data
857
+			: array();
858
+		if (empty($this->_session_data)) {
859
+			$this->_set_defaults();
860
+		}
861
+		$session_data = array();
862
+		foreach ($this->_session_data as $key => $value) {
863
+			switch ($key) {
864
+				case 'id':
865
+					// session ID
866
+					$session_data['id'] = $this->_sid;
867
+					break;
868
+				case 'ip_address':
869
+					// visitor ip address
870
+					$session_data['ip_address'] = $this->request->ipAddress();
871
+					break;
872
+				case 'user_agent':
873
+					// visitor user_agent
874
+					$session_data['user_agent'] = $this->_user_agent;
875
+					break;
876
+				case 'init_access':
877
+					$session_data['init_access'] = absint($value);
878
+					break;
879
+				case 'last_access':
880
+					// current access time
881
+					$session_data['last_access'] = $this->_time;
882
+					break;
883
+				case 'expiration':
884
+					// when the session expires
885
+					$session_data['expiration'] = ! empty($this->_expiration)
886
+						? $this->_expiration
887
+						: $session_data['init_access'] + $this->session_lifespan->inSeconds();
888
+					break;
889
+				case 'user_id':
890
+					// current user if logged in
891
+					$session_data['user_id'] = $this->_wp_user_id();
892
+					break;
893
+				case 'pages_visited':
894
+					$page_visit = $this->_get_page_visit();
895
+					if ($page_visit) {
896
+						// set pages visited where the first will be the http referrer
897
+						$this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
898
+						// we'll only save the last 10 page visits.
899
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
900
+					}
901
+					break;
902
+				default:
903
+					// carry any other data over
904
+					$session_data[ $key ] = $this->_session_data[ $key ];
905
+			}
906
+		}
907
+		$this->_session_data = $session_data;
908
+		// creating a new session does not require saving to the db just yet
909
+		if (! $new_session) {
910
+			// ready? let's save
911
+			if ($this->_save_session_to_db()) {
912
+				return true;
913
+			}
914
+			return false;
915
+		}
916
+		// meh, why not?
917
+		return true;
918
+	}
919
+
920
+
921
+	/**
922
+	 * @create session data array
923
+	 * @access public
924
+	 * @return bool
925
+	 * @throws EE_Error
926
+	 * @throws InvalidArgumentException
927
+	 * @throws InvalidDataTypeException
928
+	 * @throws InvalidInterfaceException
929
+	 * @throws ReflectionException
930
+	 */
931
+	private function _create_espresso_session()
932
+	{
933
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
934
+		// use the update function for now with $new_session arg set to TRUE
935
+		return $this->update(true) ? true : false;
936
+	}
937
+
938
+	/**
939
+	 * Detects if there is anything worth saving in the session (eg the cart is a good one, notices are pretty good
940
+	 * too). This is used when determining if we want to save the session or not.
941
+	 * @since 4.9.67.p
942
+	 * @return bool
943
+	 */
944
+	private function sessionHasStuffWorthSaving()
945
+	{
946
+		return $this->save_state === EE_Session::SAVE_STATE_DIRTY
947
+			   // we may want to eventually remove the following
948
+			   // on the assumption that the above check is enough
949
+			   || $this->cart() instanceof EE_Cart
950
+			   || (
951
+				   isset($this->_session_data['ee_notices'])
952
+				   && (
953
+					   ! empty($this->_session_data['ee_notices']['attention'])
954
+					   || ! empty($this->_session_data['ee_notices']['errors'])
955
+					   || ! empty($this->_session_data['ee_notices']['success'])
956
+				   )
957
+			   );
958
+	}
959
+
960
+
961
+	/**
962
+	 * _save_session_to_db
963
+	 *
964
+	 * @param bool $clear_session
965
+	 * @return string
966
+	 * @throws EE_Error
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidDataTypeException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws ReflectionException
971
+	 */
972
+	private function _save_session_to_db($clear_session = false)
973
+	{
974
+		// don't save sessions for crawlers
975
+		// and unless we're deleting the session data, don't save anything if there isn't a cart
976
+		if ($this->request->isBot()
977
+			|| (
978
+				! $clear_session
979
+				&& ! $this->sessionHasStuffWorthSaving()
980
+				&& apply_filters('FHEE__EE_Session___save_session_to_db__abort_session_save', true)
981
+			)
982
+		) {
983
+			return false;
984
+		}
985
+		$transaction = $this->transaction();
986
+		if ($transaction instanceof EE_Transaction) {
987
+			if (! $transaction->ID()) {
988
+				$transaction->save();
989
+			}
990
+			$this->_session_data['transaction'] = $transaction->ID();
991
+		}
992
+		// then serialize all of our session data
993
+		$session_data = serialize($this->_session_data);
994
+		// do we need to also encode it to avoid corrupted data when saved to the db?
995
+		$session_data = $this->_use_encryption
996
+			? $this->encryption->base64_string_encode($session_data)
997
+			: $session_data;
998
+		// maybe save hash check
999
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
1000
+			$this->cache_storage->add(
1001
+				EE_Session::hash_check_prefix . $this->_sid,
1002
+				md5($session_data),
1003
+				$this->session_lifespan->inSeconds()
1004
+			);
1005
+		}
1006
+		// we're using the Transient API for storing session data,
1007
+		$saved = $this->cache_storage->add(
1008
+			EE_Session::session_id_prefix . $this->_sid,
1009
+			$session_data,
1010
+			$this->session_lifespan->inSeconds()
1011
+		);
1012
+		$this->setSaveState(EE_Session::SAVE_STATE_CLEAN);
1013
+		return $saved;
1014
+	}
1015
+
1016
+
1017
+	/**
1018
+	 * @get    the full page request the visitor is accessing
1019
+	 * @access public
1020
+	 * @return string
1021
+	 */
1022
+	public function _get_page_visit()
1023
+	{
1024
+		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
1025
+		// check for request url
1026
+		if (isset($_SERVER['REQUEST_URI'])) {
1027
+			$http_host = '';
1028
+			$page_id = '?';
1029
+			$e_reg = '';
1030
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
1031
+			$ru_bits = explode('?', $request_uri);
1032
+			$request_uri = $ru_bits[0];
1033
+			// check for and grab host as well
1034
+			if (isset($_SERVER['HTTP_HOST'])) {
1035
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
1036
+			}
1037
+			// check for page_id in SERVER REQUEST
1038
+			if (isset($_REQUEST['page_id'])) {
1039
+				// rebuild $e_reg without any of the extra parameters
1040
+				$page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
1041
+			}
1042
+			// check for $e_reg in SERVER REQUEST
1043
+			if (isset($_REQUEST['ee'])) {
1044
+				// rebuild $e_reg without any of the extra parameters
1045
+				$e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
1046
+			}
1047
+			$page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
1048
+		}
1049
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
1050
+	}
1051
+
1052
+
1053
+	/**
1054
+	 * @the    current wp user id
1055
+	 * @access public
1056
+	 * @return int
1057
+	 */
1058
+	public function _wp_user_id()
1059
+	{
1060
+		// if I need to explain the following lines of code, then you shouldn't be looking at this!
1061
+		$this->_wp_user_id = get_current_user_id();
1062
+		return $this->_wp_user_id;
1063
+	}
1064
+
1065
+
1066
+	/**
1067
+	 * Clear EE_Session data
1068
+	 *
1069
+	 * @access public
1070
+	 * @param string $class
1071
+	 * @param string $function
1072
+	 * @return void
1073
+	 * @throws EE_Error
1074
+	 * @throws InvalidArgumentException
1075
+	 * @throws InvalidDataTypeException
1076
+	 * @throws InvalidInterfaceException
1077
+	 * @throws ReflectionException
1078
+	 */
1079
+	public function clear_session($class = '', $function = '')
1080
+	{
1081 1081
 //         echo '
1082 1082
 // <h3 style="color:#999;line-height:.9em;">
1083 1083
 // <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1084 1084
 // <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1085 1085
 // </h3>';
1086
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1087
-        $this->reset_cart();
1088
-        $this->reset_checkout();
1089
-        $this->reset_transaction();
1090
-        // wipe out everything that isn't a default session datum
1091
-        $this->reset_data(array_keys($this->_session_data));
1092
-        // reset initial site access time and the session expiration
1093
-        $this->_set_init_access_and_expiration();
1094
-        $this->setSaveState();
1095
-        $this->_save_session_to_db(true);
1096
-    }
1097
-
1098
-
1099
-    /**
1100
-     * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1101
-     *
1102
-     * @param array|mixed $data_to_reset
1103
-     * @param bool        $show_all_notices
1104
-     * @return bool
1105
-     */
1106
-    public function reset_data($data_to_reset = array(), $show_all_notices = false)
1107
-    {
1108
-        // if $data_to_reset is not in an array, then put it in one
1109
-        if (! is_array($data_to_reset)) {
1110
-            $data_to_reset = array($data_to_reset);
1111
-        }
1112
-        // nothing ??? go home!
1113
-        if (empty($data_to_reset)) {
1114
-            EE_Error::add_error(
1115
-                __(
1116
-                    'No session data could be reset, because no session var name was provided.',
1117
-                    'event_espresso'
1118
-                ),
1119
-                __FILE__,
1120
-                __FUNCTION__,
1121
-                __LINE__
1122
-            );
1123
-            return false;
1124
-        }
1125
-        $return_value = true;
1126
-        // since $data_to_reset is an array, cycle through the values
1127
-        foreach ($data_to_reset as $reset) {
1128
-            // first check to make sure it is a valid session var
1129
-            if (isset($this->_session_data[ $reset ])) {
1130
-                // then check to make sure it is not a default var
1131
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1132
-                    // remove session var
1133
-                    unset($this->_session_data[ $reset ]);
1134
-                    $this->setSaveState();
1135
-                    if ($show_all_notices) {
1136
-                        EE_Error::add_success(
1137
-                            sprintf(
1138
-                                __('The session variable %s was removed.', 'event_espresso'),
1139
-                                $reset
1140
-                            ),
1141
-                            __FILE__,
1142
-                            __FUNCTION__,
1143
-                            __LINE__
1144
-                        );
1145
-                    }
1146
-                } else {
1147
-                    // yeeeeeeeeerrrrrrrrrrr OUT !!!!
1148
-                    if ($show_all_notices) {
1149
-                        EE_Error::add_error(
1150
-                            sprintf(
1151
-                                __(
1152
-                                    'Sorry! %s is a default session datum and can not be reset.',
1153
-                                    'event_espresso'
1154
-                                ),
1155
-                                $reset
1156
-                            ),
1157
-                            __FILE__,
1158
-                            __FUNCTION__,
1159
-                            __LINE__
1160
-                        );
1161
-                    }
1162
-                    $return_value = false;
1163
-                }
1164
-            } elseif ($show_all_notices) {
1165
-                // oops! that session var does not exist!
1166
-                EE_Error::add_error(
1167
-                    sprintf(
1168
-                        __(
1169
-                            'The session item provided, %s, is invalid or does not exist.',
1170
-                            'event_espresso'
1171
-                        ),
1172
-                        $reset
1173
-                    ),
1174
-                    __FILE__,
1175
-                    __FUNCTION__,
1176
-                    __LINE__
1177
-                );
1178
-                $return_value = false;
1179
-            }
1180
-        } // end of foreach
1181
-        return $return_value;
1182
-    }
1183
-
1184
-
1185
-    /**
1186
-     *   wp_loaded
1187
-     *
1188
-     * @access public
1189
-     * @throws EE_Error
1190
-     * @throws InvalidDataTypeException
1191
-     * @throws InvalidInterfaceException
1192
-     * @throws InvalidArgumentException
1193
-     * @throws ReflectionException
1194
-     */
1195
-    public function wp_loaded()
1196
-    {
1197
-        if ($this->request->requestParamIsSet('clear_session')) {
1198
-            $this->clear_session(__CLASS__, __FUNCTION__);
1199
-        }
1200
-    }
1201
-
1202
-
1203
-    /**
1204
-     * Used to reset the entire object (for tests).
1205
-     *
1206
-     * @since 4.3.0
1207
-     * @throws EE_Error
1208
-     * @throws InvalidDataTypeException
1209
-     * @throws InvalidInterfaceException
1210
-     * @throws InvalidArgumentException
1211
-     * @throws ReflectionException
1212
-     */
1213
-    public function reset_instance()
1214
-    {
1215
-        $this->clear_session();
1216
-        self::$_instance = null;
1217
-    }
1218
-
1219
-
1220
-    public function configure_garbage_collection_filters()
1221
-    {
1222
-        // run old filter we had for controlling session cleanup
1223
-        $expired_session_transient_delete_query_limit = absint(
1224
-            apply_filters(
1225
-                'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1226
-                50
1227
-            )
1228
-        );
1229
-        // is there a value? or one that is different than the default 50 records?
1230
-        if ($expired_session_transient_delete_query_limit === 0) {
1231
-            // hook into TransientCacheStorage in case Session cleanup was turned off
1232
-            add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1233
-        } elseif ($expired_session_transient_delete_query_limit !== 50) {
1234
-            // or use that for the new transient cleanup query limit
1235
-            add_filter(
1236
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1237
-                function () use ($expired_session_transient_delete_query_limit) {
1238
-                    return $expired_session_transient_delete_query_limit;
1239
-                }
1240
-            );
1241
-        }
1242
-    }
1243
-
1244
-
1245
-    /**
1246
-     * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1247
-     * @param $data1
1248
-     * @return string
1249
-     */
1250
-    private function find_serialize_error($data1)
1251
-    {
1252
-        $error = '<pre>';
1253
-        $data2 = preg_replace_callback(
1254
-            '!s:(\d+):"(.*?)";!',
1255
-            function ($match) {
1256
-                return ($match[1] === strlen($match[2]))
1257
-                    ? $match[0]
1258
-                    : 's:'
1259
-                      . strlen($match[2])
1260
-                      . ':"'
1261
-                      . $match[2]
1262
-                      . '";';
1263
-            },
1264
-            $data1
1265
-        );
1266
-        $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1267
-        $error .= $data1 . PHP_EOL;
1268
-        $error .= $data2 . PHP_EOL;
1269
-        for ($i = 0; $i < $max; $i++) {
1270
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1271
-                $error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1272
-                $error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1273
-                $error .= "\t-> Line Number = $i" . PHP_EOL;
1274
-                $start = ($i - 20);
1275
-                $start = ($start < 0) ? 0 : $start;
1276
-                $length = 40;
1277
-                $point = $max - $i;
1278
-                if ($point < 20) {
1279
-                    $rlength = 1;
1280
-                    $rpoint = -$point;
1281
-                } else {
1282
-                    $rpoint = $length - 20;
1283
-                    $rlength = 1;
1284
-                }
1285
-                $error .= "\t-> Section Data1  = ";
1286
-                $error .= substr_replace(
1287
-                    substr($data1, $start, $length),
1288
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1289
-                    $rpoint,
1290
-                    $rlength
1291
-                );
1292
-                $error .= PHP_EOL;
1293
-                $error .= "\t-> Section Data2  = ";
1294
-                $error .= substr_replace(
1295
-                    substr($data2, $start, $length),
1296
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1297
-                    $rpoint,
1298
-                    $rlength
1299
-                );
1300
-                $error .= PHP_EOL;
1301
-            }
1302
-        }
1303
-        $error .= '</pre>';
1304
-        return $error;
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * Saves an  array of settings used for configuring aspects of session behaviour
1310
-     *
1311
-     * @param array $updated_settings
1312
-     */
1313
-    private function updateSessionSettings(array $updated_settings = array())
1314
-    {
1315
-        // add existing settings, but only if not included in incoming $updated_settings array
1316
-        $updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1317
-        update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1318
-    }
1319
-
1320
-
1321
-    /**
1322
-     * garbage_collection
1323
-     */
1324
-    public function garbageCollection()
1325
-    {
1326
-        // only perform during regular requests if last garbage collection was over an hour ago
1327
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1328
-            $this->_last_gc = time();
1329
-            $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1330
-            /** @type WPDB $wpdb */
1331
-            global $wpdb;
1332
-            // filter the query limit. Set to 0 to turn off garbage collection
1333
-            $expired_session_transient_delete_query_limit = absint(
1334
-                apply_filters(
1335
-                    'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1336
-                    50
1337
-                )
1338
-            );
1339
-            // non-zero LIMIT means take out the trash
1340
-            if ($expired_session_transient_delete_query_limit) {
1341
-                $session_key = str_replace('_', '\_', EE_Session::session_id_prefix);
1342
-                $hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1343
-                // since transient expiration timestamps are set in the future, we can compare against NOW
1344
-                // but we only want to pick up any trash that's been around for more than a day
1345
-                $expiration = time() - DAY_IN_SECONDS;
1346
-                $SQL = "
1086
+		do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1087
+		$this->reset_cart();
1088
+		$this->reset_checkout();
1089
+		$this->reset_transaction();
1090
+		// wipe out everything that isn't a default session datum
1091
+		$this->reset_data(array_keys($this->_session_data));
1092
+		// reset initial site access time and the session expiration
1093
+		$this->_set_init_access_and_expiration();
1094
+		$this->setSaveState();
1095
+		$this->_save_session_to_db(true);
1096
+	}
1097
+
1098
+
1099
+	/**
1100
+	 * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1101
+	 *
1102
+	 * @param array|mixed $data_to_reset
1103
+	 * @param bool        $show_all_notices
1104
+	 * @return bool
1105
+	 */
1106
+	public function reset_data($data_to_reset = array(), $show_all_notices = false)
1107
+	{
1108
+		// if $data_to_reset is not in an array, then put it in one
1109
+		if (! is_array($data_to_reset)) {
1110
+			$data_to_reset = array($data_to_reset);
1111
+		}
1112
+		// nothing ??? go home!
1113
+		if (empty($data_to_reset)) {
1114
+			EE_Error::add_error(
1115
+				__(
1116
+					'No session data could be reset, because no session var name was provided.',
1117
+					'event_espresso'
1118
+				),
1119
+				__FILE__,
1120
+				__FUNCTION__,
1121
+				__LINE__
1122
+			);
1123
+			return false;
1124
+		}
1125
+		$return_value = true;
1126
+		// since $data_to_reset is an array, cycle through the values
1127
+		foreach ($data_to_reset as $reset) {
1128
+			// first check to make sure it is a valid session var
1129
+			if (isset($this->_session_data[ $reset ])) {
1130
+				// then check to make sure it is not a default var
1131
+				if (! array_key_exists($reset, $this->_default_session_vars)) {
1132
+					// remove session var
1133
+					unset($this->_session_data[ $reset ]);
1134
+					$this->setSaveState();
1135
+					if ($show_all_notices) {
1136
+						EE_Error::add_success(
1137
+							sprintf(
1138
+								__('The session variable %s was removed.', 'event_espresso'),
1139
+								$reset
1140
+							),
1141
+							__FILE__,
1142
+							__FUNCTION__,
1143
+							__LINE__
1144
+						);
1145
+					}
1146
+				} else {
1147
+					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
1148
+					if ($show_all_notices) {
1149
+						EE_Error::add_error(
1150
+							sprintf(
1151
+								__(
1152
+									'Sorry! %s is a default session datum and can not be reset.',
1153
+									'event_espresso'
1154
+								),
1155
+								$reset
1156
+							),
1157
+							__FILE__,
1158
+							__FUNCTION__,
1159
+							__LINE__
1160
+						);
1161
+					}
1162
+					$return_value = false;
1163
+				}
1164
+			} elseif ($show_all_notices) {
1165
+				// oops! that session var does not exist!
1166
+				EE_Error::add_error(
1167
+					sprintf(
1168
+						__(
1169
+							'The session item provided, %s, is invalid or does not exist.',
1170
+							'event_espresso'
1171
+						),
1172
+						$reset
1173
+					),
1174
+					__FILE__,
1175
+					__FUNCTION__,
1176
+					__LINE__
1177
+				);
1178
+				$return_value = false;
1179
+			}
1180
+		} // end of foreach
1181
+		return $return_value;
1182
+	}
1183
+
1184
+
1185
+	/**
1186
+	 *   wp_loaded
1187
+	 *
1188
+	 * @access public
1189
+	 * @throws EE_Error
1190
+	 * @throws InvalidDataTypeException
1191
+	 * @throws InvalidInterfaceException
1192
+	 * @throws InvalidArgumentException
1193
+	 * @throws ReflectionException
1194
+	 */
1195
+	public function wp_loaded()
1196
+	{
1197
+		if ($this->request->requestParamIsSet('clear_session')) {
1198
+			$this->clear_session(__CLASS__, __FUNCTION__);
1199
+		}
1200
+	}
1201
+
1202
+
1203
+	/**
1204
+	 * Used to reset the entire object (for tests).
1205
+	 *
1206
+	 * @since 4.3.0
1207
+	 * @throws EE_Error
1208
+	 * @throws InvalidDataTypeException
1209
+	 * @throws InvalidInterfaceException
1210
+	 * @throws InvalidArgumentException
1211
+	 * @throws ReflectionException
1212
+	 */
1213
+	public function reset_instance()
1214
+	{
1215
+		$this->clear_session();
1216
+		self::$_instance = null;
1217
+	}
1218
+
1219
+
1220
+	public function configure_garbage_collection_filters()
1221
+	{
1222
+		// run old filter we had for controlling session cleanup
1223
+		$expired_session_transient_delete_query_limit = absint(
1224
+			apply_filters(
1225
+				'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1226
+				50
1227
+			)
1228
+		);
1229
+		// is there a value? or one that is different than the default 50 records?
1230
+		if ($expired_session_transient_delete_query_limit === 0) {
1231
+			// hook into TransientCacheStorage in case Session cleanup was turned off
1232
+			add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1233
+		} elseif ($expired_session_transient_delete_query_limit !== 50) {
1234
+			// or use that for the new transient cleanup query limit
1235
+			add_filter(
1236
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1237
+				function () use ($expired_session_transient_delete_query_limit) {
1238
+					return $expired_session_transient_delete_query_limit;
1239
+				}
1240
+			);
1241
+		}
1242
+	}
1243
+
1244
+
1245
+	/**
1246
+	 * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1247
+	 * @param $data1
1248
+	 * @return string
1249
+	 */
1250
+	private function find_serialize_error($data1)
1251
+	{
1252
+		$error = '<pre>';
1253
+		$data2 = preg_replace_callback(
1254
+			'!s:(\d+):"(.*?)";!',
1255
+			function ($match) {
1256
+				return ($match[1] === strlen($match[2]))
1257
+					? $match[0]
1258
+					: 's:'
1259
+					  . strlen($match[2])
1260
+					  . ':"'
1261
+					  . $match[2]
1262
+					  . '";';
1263
+			},
1264
+			$data1
1265
+		);
1266
+		$max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1267
+		$error .= $data1 . PHP_EOL;
1268
+		$error .= $data2 . PHP_EOL;
1269
+		for ($i = 0; $i < $max; $i++) {
1270
+			if (@$data1[ $i ] !== @$data2[ $i ]) {
1271
+				$error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1272
+				$error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1273
+				$error .= "\t-> Line Number = $i" . PHP_EOL;
1274
+				$start = ($i - 20);
1275
+				$start = ($start < 0) ? 0 : $start;
1276
+				$length = 40;
1277
+				$point = $max - $i;
1278
+				if ($point < 20) {
1279
+					$rlength = 1;
1280
+					$rpoint = -$point;
1281
+				} else {
1282
+					$rpoint = $length - 20;
1283
+					$rlength = 1;
1284
+				}
1285
+				$error .= "\t-> Section Data1  = ";
1286
+				$error .= substr_replace(
1287
+					substr($data1, $start, $length),
1288
+					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1289
+					$rpoint,
1290
+					$rlength
1291
+				);
1292
+				$error .= PHP_EOL;
1293
+				$error .= "\t-> Section Data2  = ";
1294
+				$error .= substr_replace(
1295
+					substr($data2, $start, $length),
1296
+					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1297
+					$rpoint,
1298
+					$rlength
1299
+				);
1300
+				$error .= PHP_EOL;
1301
+			}
1302
+		}
1303
+		$error .= '</pre>';
1304
+		return $error;
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * Saves an  array of settings used for configuring aspects of session behaviour
1310
+	 *
1311
+	 * @param array $updated_settings
1312
+	 */
1313
+	private function updateSessionSettings(array $updated_settings = array())
1314
+	{
1315
+		// add existing settings, but only if not included in incoming $updated_settings array
1316
+		$updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1317
+		update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1318
+	}
1319
+
1320
+
1321
+	/**
1322
+	 * garbage_collection
1323
+	 */
1324
+	public function garbageCollection()
1325
+	{
1326
+		// only perform during regular requests if last garbage collection was over an hour ago
1327
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1328
+			$this->_last_gc = time();
1329
+			$this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1330
+			/** @type WPDB $wpdb */
1331
+			global $wpdb;
1332
+			// filter the query limit. Set to 0 to turn off garbage collection
1333
+			$expired_session_transient_delete_query_limit = absint(
1334
+				apply_filters(
1335
+					'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1336
+					50
1337
+				)
1338
+			);
1339
+			// non-zero LIMIT means take out the trash
1340
+			if ($expired_session_transient_delete_query_limit) {
1341
+				$session_key = str_replace('_', '\_', EE_Session::session_id_prefix);
1342
+				$hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1343
+				// since transient expiration timestamps are set in the future, we can compare against NOW
1344
+				// but we only want to pick up any trash that's been around for more than a day
1345
+				$expiration = time() - DAY_IN_SECONDS;
1346
+				$SQL = "
1347 1347
                     SELECT option_name
1348 1348
                     FROM {$wpdb->options}
1349 1349
                     WHERE
@@ -1352,17 +1352,17 @@  discard block
 block discarded – undo
1352 1352
                     AND option_value < {$expiration}
1353 1353
                     LIMIT {$expired_session_transient_delete_query_limit}
1354 1354
                 ";
1355
-                // produces something like:
1356
-                // SELECT option_name FROM wp_options
1357
-                // WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1358
-                // OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1359
-                // AND option_value < 1508368198 LIMIT 50
1360
-                $expired_sessions = $wpdb->get_col($SQL);
1361
-                // valid results?
1362
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1363
-                    $this->cache_storage->deleteMany($expired_sessions, true);
1364
-                }
1365
-            }
1366
-        }
1367
-    }
1355
+				// produces something like:
1356
+				// SELECT option_name FROM wp_options
1357
+				// WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1358
+				// OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1359
+				// AND option_value < 1508368198 LIMIT 50
1360
+				$expired_sessions = $wpdb->get_col($SQL);
1361
+				// valid results?
1362
+				if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1363
+					$this->cache_storage->deleteMany($expired_sessions, true);
1364
+				}
1365
+			}
1366
+		}
1367
+	}
1368 1368
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
         // check if class object is instantiated
204 204
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
205 205
         // add_filter( 'FHEE_load_EE_Session', '__return_false' );
206
-        if (! self::$_instance instanceof EE_Session
206
+        if ( ! self::$_instance instanceof EE_Session
207 207
             && $cache_storage instanceof CacheStorageInterface
208 208
             && $lifespan instanceof SessionLifespan
209 209
             && $request instanceof RequestInterface
@@ -245,22 +245,22 @@  discard block
 block discarded – undo
245 245
         // but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
246 246
         // (which currently fires on the init hook at priority 9),
247 247
         // can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
248
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
248
+        if ( ! apply_filters('FHEE_load_EE_Session', true)) {
249 249
             return;
250 250
         }
251 251
         $this->session_start_handler = $session_start_handler;
252 252
         $this->session_lifespan = $lifespan;
253 253
         $this->request = $request;
254
-        if (! defined('ESPRESSO_SESSION')) {
254
+        if ( ! defined('ESPRESSO_SESSION')) {
255 255
             define('ESPRESSO_SESSION', true);
256 256
         }
257 257
         // retrieve session options from db
258 258
         $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
259
-        if (! empty($session_settings)) {
259
+        if ( ! empty($session_settings)) {
260 260
             // cycle though existing session options
261 261
             foreach ($session_settings as $var_name => $session_setting) {
262 262
                 // set values for class properties
263
-                $var_name = '_' . $var_name;
263
+                $var_name = '_'.$var_name;
264 264
                 $this->{$var_name} = $session_setting;
265 265
             }
266 266
         }
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
     public function open_session()
322 322
     {
323 323
         // check for existing session and retrieve it from db
324
-        if (! $this->_espresso_session()) {
324
+        if ( ! $this->_espresso_session()) {
325 325
             // or just start a new one
326 326
             $this->_create_espresso_session();
327 327
         }
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
             EE_Session::SAVE_STATE_CLEAN,
399 399
             EE_Session::SAVE_STATE_DIRTY,
400 400
         ];
401
-        if (! in_array($save_state, $valid_save_states, true)) {
401
+        if ( ! in_array($save_state, $valid_save_states, true)) {
402 402
             $save_state = EE_Session::SAVE_STATE_DIRTY;
403 403
         }
404 404
         $this->save_state = $save_state;
@@ -417,9 +417,9 @@  discard block
 block discarded – undo
417 417
         // set some defaults
418 418
         foreach ($this->_default_session_vars as $key => $default_var) {
419 419
             if (is_array($default_var)) {
420
-                $this->_session_data[ $key ] = array();
420
+                $this->_session_data[$key] = array();
421 421
             } else {
422
-                $this->_session_data[ $key ] = '';
422
+                $this->_session_data[$key] = '';
423 423
             }
424 424
         }
425 425
     }
@@ -556,8 +556,8 @@  discard block
 block discarded – undo
556 556
             $this->reset_checkout();
557 557
             $this->reset_transaction();
558 558
         }
559
-        if (! empty($key)) {
560
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
559
+        if ( ! empty($key)) {
560
+            return isset($this->_session_data[$key]) ? $this->_session_data[$key] : null;
561 561
         }
562 562
         return $this->_session_data;
563 563
     }
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
             return false;
586 586
         }
587 587
         foreach ($data as $key => $value) {
588
-            if (isset($this->_default_session_vars[ $key ])) {
588
+            if (isset($this->_default_session_vars[$key])) {
589 589
                 EE_Error::add_error(
590 590
                     sprintf(
591 591
                         esc_html__(
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
                 );
601 601
                 return false;
602 602
             }
603
-            $this->_session_data[ $key ] = $value;
603
+            $this->_session_data[$key] = $value;
604 604
             $this->setSaveState();
605 605
         }
606 606
         return true;
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
         $this->_user_agent = $this->request->userAgent();
633 633
         // now let's retrieve what's in the db
634 634
         $session_data = $this->_retrieve_session_data();
635
-        if (! empty($session_data)) {
635
+        if ( ! empty($session_data)) {
636 636
             // get the current time in UTC
637 637
             $this->_time = $this->_time !== null ? $this->_time : time();
638 638
             // and reset the session expiration
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
             // set initial site access time and the session expiration
644 644
             $this->_set_init_access_and_expiration();
645 645
             // set referer
646
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
646
+            $this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
647 647
                 ? esc_attr($_SERVER['HTTP_REFERER'])
648 648
                 : '';
649 649
             // no previous session = go back and create one (on top of the data above)
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
      */
682 682
     protected function _retrieve_session_data()
683 683
     {
684
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
684
+        $ssn_key = EE_Session::session_id_prefix.$this->_sid;
685 685
         try {
686 686
             // we're using WP's Transient API to store session data using the PHP session ID as the option name
687 687
             $session_data = $this->cache_storage->get($ssn_key, false);
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
             }
691 691
             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
692 692
                 $hash_check = $this->cache_storage->get(
693
-                    EE_Session::hash_check_prefix . $this->_sid,
693
+                    EE_Session::hash_check_prefix.$this->_sid,
694 694
                     false
695 695
                 );
696 696
                 if ($hash_check && $hash_check !== md5($session_data)) {
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
                                 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
701 701
                                 'event_espresso'
702 702
                             ),
703
-                            EE_Session::session_id_prefix . $this->_sid
703
+                            EE_Session::session_id_prefix.$this->_sid
704 704
                         ),
705 705
                         __FILE__,
706 706
                         __FUNCTION__,
@@ -714,17 +714,17 @@  discard block
 block discarded – undo
714 714
             $row = $wpdb->get_row(
715 715
                 $wpdb->prepare(
716 716
                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
717
-                    '_transient_' . $ssn_key
717
+                    '_transient_'.$ssn_key
718 718
                 )
719 719
             );
720 720
             $session_data = is_object($row) ? $row->option_value : null;
721 721
             if ($session_data) {
722 722
                 $session_data = preg_replace_callback(
723 723
                     '!s:(d+):"(.*?)";!',
724
-                    function ($match) {
724
+                    function($match) {
725 725
                         return $match[1] === strlen($match[2])
726 726
                             ? $match[0]
727
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
727
+                            : 's:'.strlen($match[2]).':"'.$match[2].'";';
728 728
                     },
729 729
                     $session_data
730 730
                 );
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
         $session_data = $this->encryption instanceof EE_Encryption
736 736
             ? $this->encryption->base64_string_decode($session_data)
737 737
             : $session_data;
738
-        if (! is_array($session_data)) {
738
+        if ( ! is_array($session_data)) {
739 739
             try {
740 740
                 $session_data = maybe_unserialize($session_data);
741 741
             } catch (Exception $e) {
@@ -749,21 +749,21 @@  discard block
 block discarded – undo
749 749
                       . '</pre><br>'
750 750
                       . $this->find_serialize_error($session_data)
751 751
                     : '';
752
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
752
+                $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
753 753
                 throw new InvalidSessionDataException($msg, 0, $e);
754 754
             }
755 755
         }
756 756
         // just a check to make sure the session array is indeed an array
757
-        if (! is_array($session_data)) {
757
+        if ( ! is_array($session_data)) {
758 758
             // no?!?! then something is wrong
759 759
             $msg = esc_html__(
760 760
                 'The session data is missing, invalid, or corrupted.',
761 761
                 'event_espresso'
762 762
             );
763 763
             $msg .= WP_DEBUG
764
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
764
+                ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
765 765
                 : '';
766
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
766
+            $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
767 767
             throw new InvalidSessionDataException($msg);
768 768
         }
769 769
         if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
         if (isset($_REQUEST['EESID'])) {
791 791
             $session_id = sanitize_text_field($_REQUEST['EESID']);
792 792
         } else {
793
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
793
+            $session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
794 794
         }
795 795
         return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
796 796
     }
@@ -894,19 +894,19 @@  discard block
 block discarded – undo
894 894
                     $page_visit = $this->_get_page_visit();
895 895
                     if ($page_visit) {
896 896
                         // set pages visited where the first will be the http referrer
897
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
897
+                        $this->_session_data['pages_visited'][$this->_time] = $page_visit;
898 898
                         // we'll only save the last 10 page visits.
899 899
                         $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
900 900
                     }
901 901
                     break;
902 902
                 default:
903 903
                     // carry any other data over
904
-                    $session_data[ $key ] = $this->_session_data[ $key ];
904
+                    $session_data[$key] = $this->_session_data[$key];
905 905
             }
906 906
         }
907 907
         $this->_session_data = $session_data;
908 908
         // creating a new session does not require saving to the db just yet
909
-        if (! $new_session) {
909
+        if ( ! $new_session) {
910 910
             // ready? let's save
911 911
             if ($this->_save_session_to_db()) {
912 912
                 return true;
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
         }
985 985
         $transaction = $this->transaction();
986 986
         if ($transaction instanceof EE_Transaction) {
987
-            if (! $transaction->ID()) {
987
+            if ( ! $transaction->ID()) {
988 988
                 $transaction->save();
989 989
             }
990 990
             $this->_session_data['transaction'] = $transaction->ID();
@@ -998,14 +998,14 @@  discard block
 block discarded – undo
998 998
         // maybe save hash check
999 999
         if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
1000 1000
             $this->cache_storage->add(
1001
-                EE_Session::hash_check_prefix . $this->_sid,
1001
+                EE_Session::hash_check_prefix.$this->_sid,
1002 1002
                 md5($session_data),
1003 1003
                 $this->session_lifespan->inSeconds()
1004 1004
             );
1005 1005
         }
1006 1006
         // we're using the Transient API for storing session data,
1007 1007
         $saved = $this->cache_storage->add(
1008
-            EE_Session::session_id_prefix . $this->_sid,
1008
+            EE_Session::session_id_prefix.$this->_sid,
1009 1009
             $session_data,
1010 1010
             $this->session_lifespan->inSeconds()
1011 1011
         );
@@ -1021,7 +1021,7 @@  discard block
 block discarded – undo
1021 1021
      */
1022 1022
     public function _get_page_visit()
1023 1023
     {
1024
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
1024
+        $page_visit = home_url('/').'wp-admin/admin-ajax.php';
1025 1025
         // check for request url
1026 1026
         if (isset($_SERVER['REQUEST_URI'])) {
1027 1027
             $http_host = '';
@@ -1037,14 +1037,14 @@  discard block
 block discarded – undo
1037 1037
             // check for page_id in SERVER REQUEST
1038 1038
             if (isset($_REQUEST['page_id'])) {
1039 1039
                 // rebuild $e_reg without any of the extra parameters
1040
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
1040
+                $page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
1041 1041
             }
1042 1042
             // check for $e_reg in SERVER REQUEST
1043 1043
             if (isset($_REQUEST['ee'])) {
1044 1044
                 // rebuild $e_reg without any of the extra parameters
1045
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
1045
+                $e_reg = 'ee='.esc_attr($_REQUEST['ee']);
1046 1046
             }
1047
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
1047
+            $page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
1048 1048
         }
1049 1049
         return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
1050 1050
     }
@@ -1083,7 +1083,7 @@  discard block
 block discarded – undo
1083 1083
 // <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1084 1084
 // <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1085 1085
 // </h3>';
1086
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1086
+        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
1087 1087
         $this->reset_cart();
1088 1088
         $this->reset_checkout();
1089 1089
         $this->reset_transaction();
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1107 1107
     {
1108 1108
         // if $data_to_reset is not in an array, then put it in one
1109
-        if (! is_array($data_to_reset)) {
1109
+        if ( ! is_array($data_to_reset)) {
1110 1110
             $data_to_reset = array($data_to_reset);
1111 1111
         }
1112 1112
         // nothing ??? go home!
@@ -1126,11 +1126,11 @@  discard block
 block discarded – undo
1126 1126
         // since $data_to_reset is an array, cycle through the values
1127 1127
         foreach ($data_to_reset as $reset) {
1128 1128
             // first check to make sure it is a valid session var
1129
-            if (isset($this->_session_data[ $reset ])) {
1129
+            if (isset($this->_session_data[$reset])) {
1130 1130
                 // then check to make sure it is not a default var
1131
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1131
+                if ( ! array_key_exists($reset, $this->_default_session_vars)) {
1132 1132
                     // remove session var
1133
-                    unset($this->_session_data[ $reset ]);
1133
+                    unset($this->_session_data[$reset]);
1134 1134
                     $this->setSaveState();
1135 1135
                     if ($show_all_notices) {
1136 1136
                         EE_Error::add_success(
@@ -1234,7 +1234,7 @@  discard block
 block discarded – undo
1234 1234
             // or use that for the new transient cleanup query limit
1235 1235
             add_filter(
1236 1236
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1237
-                function () use ($expired_session_transient_delete_query_limit) {
1237
+                function() use ($expired_session_transient_delete_query_limit) {
1238 1238
                     return $expired_session_transient_delete_query_limit;
1239 1239
                 }
1240 1240
             );
@@ -1252,7 +1252,7 @@  discard block
 block discarded – undo
1252 1252
         $error = '<pre>';
1253 1253
         $data2 = preg_replace_callback(
1254 1254
             '!s:(\d+):"(.*?)";!',
1255
-            function ($match) {
1255
+            function($match) {
1256 1256
                 return ($match[1] === strlen($match[2]))
1257 1257
                     ? $match[0]
1258 1258
                     : 's:'
@@ -1264,13 +1264,13 @@  discard block
 block discarded – undo
1264 1264
             $data1
1265 1265
         );
1266 1266
         $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1267
-        $error .= $data1 . PHP_EOL;
1268
-        $error .= $data2 . PHP_EOL;
1267
+        $error .= $data1.PHP_EOL;
1268
+        $error .= $data2.PHP_EOL;
1269 1269
         for ($i = 0; $i < $max; $i++) {
1270
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1271
-                $error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1272
-                $error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1273
-                $error .= "\t-> Line Number = $i" . PHP_EOL;
1270
+            if (@$data1[$i] !== @$data2[$i]) {
1271
+                $error .= 'Difference '.@$data1[$i].' != '.@$data2[$i].PHP_EOL;
1272
+                $error .= "\t-> ORD number ".ord(@$data1[$i]).' != '.ord(@$data2[$i]).PHP_EOL;
1273
+                $error .= "\t-> Line Number = $i".PHP_EOL;
1274 1274
                 $start = ($i - 20);
1275 1275
                 $start = ($start < 0) ? 0 : $start;
1276 1276
                 $length = 40;
@@ -1285,7 +1285,7 @@  discard block
 block discarded – undo
1285 1285
                 $error .= "\t-> Section Data1  = ";
1286 1286
                 $error .= substr_replace(
1287 1287
                     substr($data1, $start, $length),
1288
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1288
+                    "<b style=\"color:green\">{$data1[$i]}</b>",
1289 1289
                     $rpoint,
1290 1290
                     $rlength
1291 1291
                 );
@@ -1293,7 +1293,7 @@  discard block
 block discarded – undo
1293 1293
                 $error .= "\t-> Section Data2  = ";
1294 1294
                 $error .= substr_replace(
1295 1295
                     substr($data2, $start, $length),
1296
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1296
+                    "<b style=\"color:red\">{$data2[$i]}</b>",
1297 1297
                     $rpoint,
1298 1298
                     $rlength
1299 1299
                 );
@@ -1324,7 +1324,7 @@  discard block
 block discarded – undo
1324 1324
     public function garbageCollection()
1325 1325
     {
1326 1326
         // only perform during regular requests if last garbage collection was over an hour ago
1327
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1327
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1328 1328
             $this->_last_gc = time();
1329 1329
             $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1330 1330
             /** @type WPDB $wpdb */
@@ -1359,7 +1359,7 @@  discard block
 block discarded – undo
1359 1359
                 // AND option_value < 1508368198 LIMIT 50
1360 1360
                 $expired_sessions = $wpdb->get_col($SQL);
1361 1361
                 // valid results?
1362
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1362
+                if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1363 1363
                     $this->cache_storage->deleteMany($expired_sessions, true);
1364 1364
                 }
1365 1365
             }
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 1 patch
Indentation   +2499 added lines, -2499 removed lines patch added patch discarded remove patch
@@ -14,2503 +14,2503 @@
 block discarded – undo
14 14
 class Transactions_Admin_Page extends EE_Admin_Page
15 15
 {
16 16
 
17
-    /**
18
-     * @var EE_Transaction
19
-     */
20
-    private $_transaction;
21
-
22
-    /**
23
-     * @var EE_Session
24
-     */
25
-    private $_session;
26
-
27
-    /**
28
-     * @var array $_txn_status
29
-     */
30
-    private static $_txn_status;
31
-
32
-    /**
33
-     * @var array $_pay_status
34
-     */
35
-    private static $_pay_status;
36
-
37
-    /**
38
-     * @var array $_existing_reg_payment_REG_IDs
39
-     */
40
-    protected $_existing_reg_payment_REG_IDs = null;
41
-
42
-
43
-    /**
44
-     * @Constructor
45
-     * @access public
46
-     * @param bool $routing
47
-     * @throws EE_Error
48
-     * @throws InvalidArgumentException
49
-     * @throws ReflectionException
50
-     * @throws InvalidDataTypeException
51
-     * @throws InvalidInterfaceException
52
-     */
53
-    public function __construct($routing = true)
54
-    {
55
-        parent::__construct($routing);
56
-    }
57
-
58
-
59
-    /**
60
-     *    _init_page_props
61
-     *
62
-     * @return void
63
-     */
64
-    protected function _init_page_props()
65
-    {
66
-        $this->page_slug = TXN_PG_SLUG;
67
-        $this->page_label = esc_html__('Transactions', 'event_espresso');
68
-        $this->_admin_base_url = TXN_ADMIN_URL;
69
-        $this->_admin_base_path = TXN_ADMIN;
70
-    }
71
-
72
-
73
-    /**
74
-     *    _ajax_hooks
75
-     *
76
-     * @return void
77
-     */
78
-    protected function _ajax_hooks()
79
-    {
80
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
-    }
84
-
85
-
86
-    /**
87
-     *    _define_page_props
88
-     *
89
-     * @return void
90
-     */
91
-    protected function _define_page_props()
92
-    {
93
-        $this->_admin_page_title = $this->page_label;
94
-        $this->_labels = array(
95
-            'buttons' => array(
96
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
-            ),
100
-        );
101
-    }
102
-
103
-
104
-    /**
105
-     *        grab url requests and route them
106
-     *
107
-     * @access private
108
-     * @return void
109
-     * @throws EE_Error
110
-     * @throws InvalidArgumentException
111
-     * @throws InvalidDataTypeException
112
-     * @throws InvalidInterfaceException
113
-     */
114
-    public function _set_page_routes()
115
-    {
116
-
117
-        $this->_set_transaction_status_array();
118
-
119
-        $txn_id = ! empty($this->_req_data['TXN_ID'])
120
-                  && ! is_array($this->_req_data['TXN_ID'])
121
-            ? $this->_req_data['TXN_ID']
122
-            : 0;
123
-
124
-        $this->_page_routes = array(
125
-
126
-            'default' => array(
127
-                'func'       => '_transactions_overview_list_table',
128
-                'capability' => 'ee_read_transactions',
129
-            ),
130
-
131
-            'view_transaction' => array(
132
-                'func'       => '_transaction_details',
133
-                'capability' => 'ee_read_transaction',
134
-                'obj_id'     => $txn_id,
135
-            ),
136
-
137
-            'send_payment_reminder' => array(
138
-                'func'       => '_send_payment_reminder',
139
-                'noheader'   => true,
140
-                'capability' => 'ee_send_message',
141
-            ),
142
-
143
-            'espresso_apply_payment' => array(
144
-                'func'       => 'apply_payments_or_refunds',
145
-                'noheader'   => true,
146
-                'capability' => 'ee_edit_payments',
147
-            ),
148
-
149
-            'espresso_apply_refund' => array(
150
-                'func'       => 'apply_payments_or_refunds',
151
-                'noheader'   => true,
152
-                'capability' => 'ee_edit_payments',
153
-            ),
154
-
155
-            'espresso_delete_payment' => array(
156
-                'func'       => 'delete_payment',
157
-                'noheader'   => true,
158
-                'capability' => 'ee_delete_payments',
159
-            ),
160
-
161
-        );
162
-    }
163
-
164
-
165
-    protected function _set_page_config()
166
-    {
167
-        $this->_page_config = array(
168
-            'default'          => array(
169
-                'nav'           => array(
170
-                    'label' => esc_html__('Overview', 'event_espresso'),
171
-                    'order' => 10,
172
-                ),
173
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
174
-                'help_tabs'     => array(
175
-                    'transactions_overview_help_tab'                       => array(
176
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
-                        'filename' => 'transactions_overview',
178
-                    ),
179
-                    'transactions_overview_table_column_headings_help_tab' => array(
180
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
-                        'filename' => 'transactions_overview_table_column_headings',
182
-                    ),
183
-                    'transactions_overview_views_filters_help_tab'         => array(
184
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
-                        'filename' => 'transactions_overview_views_filters_search',
186
-                    ),
187
-                ),
188
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
-                /**
190
-                 * commented out because currently we are not displaying tips for transaction list table status but this
191
-                 * may change in a later iteration so want to keep the code for then.
192
-                 */
193
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
-                'require_nonce' => false,
195
-            ),
196
-            'view_transaction' => array(
197
-                'nav'       => array(
198
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
199
-                    'order'      => 5,
200
-                    'url'        => isset($this->_req_data['TXN_ID'])
201
-                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
-                        : $this->_admin_base_url,
203
-                    'persistent' => false,
204
-                ),
205
-                'help_tabs' => array(
206
-                    'transactions_view_transaction_help_tab'                                              => array(
207
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
208
-                        'filename' => 'transactions_view_transaction',
209
-                    ),
210
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
213
-                    ),
214
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
-                        'filename' => 'transactions_view_transaction_attendees_registered',
217
-                    ),
218
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
-                    ),
222
-                ),
223
-                'qtips'     => array('Transaction_Details_Tips'),
224
-                'help_tour' => array('Transaction_Details_Help_Tour'),
225
-                'metaboxes' => array('_transaction_details_metaboxes'),
226
-
227
-                'require_nonce' => false,
228
-            ),
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * The below methods aren't used by this class currently
235
-     */
236
-    protected function _add_screen_options()
237
-    {
238
-        // noop
239
-    }
240
-
241
-    protected function _add_feature_pointers()
242
-    {
243
-        // noop
244
-    }
245
-
246
-    public function admin_init()
247
-    {
248
-        // IF a registration was JUST added via the admin...
249
-        if (isset(
250
-            $this->_req_data['redirect_from'],
251
-            $this->_req_data['EVT_ID'],
252
-            $this->_req_data['event_name']
253
-        )) {
254
-            // then set a cookie so that we can block any attempts to use
255
-            // the back button as a way to enter another registration.
256
-            setcookie(
257
-                'ee_registration_added',
258
-                $this->_req_data['EVT_ID'],
259
-                time() + WEEK_IN_SECONDS,
260
-                '/'
261
-            );
262
-            // and update the global
263
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
-        }
265
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
-            'event_espresso'
268
-        );
269
-        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
-            'An error occurred! Please refresh the page and try again.',
271
-            'event_espresso'
272
-        );
273
-        EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
-        EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
-        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
-        EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
-            'This transaction has been overpaid ! Payments Total',
278
-            'event_espresso'
279
-        );
280
-    }
281
-
282
-    public function admin_notices()
283
-    {
284
-        // noop
285
-    }
286
-
287
-    public function admin_footer_scripts()
288
-    {
289
-        // noop
290
-    }
291
-
292
-
293
-    /**
294
-     * _set_transaction_status_array
295
-     * sets list of transaction statuses
296
-     *
297
-     * @access private
298
-     * @return void
299
-     * @throws EE_Error
300
-     * @throws InvalidArgumentException
301
-     * @throws InvalidDataTypeException
302
-     * @throws InvalidInterfaceException
303
-     */
304
-    private function _set_transaction_status_array()
305
-    {
306
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
-    }
308
-
309
-
310
-    /**
311
-     * get_transaction_status_array
312
-     * return the transaction status array for wp_list_table
313
-     *
314
-     * @access public
315
-     * @return array
316
-     */
317
-    public function get_transaction_status_array()
318
-    {
319
-        return self::$_txn_status;
320
-    }
321
-
322
-
323
-    /**
324
-     *    get list of payment statuses
325
-     *
326
-     * @access private
327
-     * @return void
328
-     * @throws EE_Error
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidDataTypeException
331
-     * @throws InvalidInterfaceException
332
-     */
333
-    private function _get_payment_status_array()
334
-    {
335
-        self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
-        $this->_template_args['payment_status'] = self::$_pay_status;
337
-    }
338
-
339
-
340
-    /**
341
-     *    _add_screen_options_default
342
-     *
343
-     * @access protected
344
-     * @return void
345
-     * @throws InvalidArgumentException
346
-     * @throws InvalidDataTypeException
347
-     * @throws InvalidInterfaceException
348
-     */
349
-    protected function _add_screen_options_default()
350
-    {
351
-        $this->_per_page_screen_option();
352
-    }
353
-
354
-
355
-    /**
356
-     * load_scripts_styles
357
-     *
358
-     * @access public
359
-     * @return void
360
-     */
361
-    public function load_scripts_styles()
362
-    {
363
-        // enqueue style
364
-        wp_register_style(
365
-            'espresso_txn',
366
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
-            array(),
368
-            EVENT_ESPRESSO_VERSION
369
-        );
370
-        wp_enqueue_style('espresso_txn');
371
-        // scripts
372
-        wp_register_script(
373
-            'espresso_txn',
374
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
-            array(
376
-                'ee_admin_js',
377
-                'ee-datepicker',
378
-                'jquery-ui-datepicker',
379
-                'jquery-ui-draggable',
380
-                'ee-dialog',
381
-                'ee-accounting',
382
-                'ee-serialize-full-array',
383
-            ),
384
-            EVENT_ESPRESSO_VERSION,
385
-            true
386
-        );
387
-        wp_enqueue_script('espresso_txn');
388
-    }
389
-
390
-
391
-    /**
392
-     *    load_scripts_styles_view_transaction
393
-     *
394
-     * @access public
395
-     * @return void
396
-     */
397
-    public function load_scripts_styles_view_transaction()
398
-    {
399
-        // styles
400
-        wp_enqueue_style('espresso-ui-theme');
401
-    }
402
-
403
-
404
-    /**
405
-     *    load_scripts_styles_default
406
-     *
407
-     * @access public
408
-     * @return void
409
-     */
410
-    public function load_scripts_styles_default()
411
-    {
412
-        // styles
413
-        wp_enqueue_style('espresso-ui-theme');
414
-    }
415
-
416
-
417
-    /**
418
-     *    _set_list_table_views_default
419
-     *
420
-     * @access protected
421
-     * @return void
422
-     */
423
-    protected function _set_list_table_views_default()
424
-    {
425
-        $this->_views = array(
426
-            'all'       => array(
427
-                'slug'  => 'all',
428
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
429
-                'count' => 0,
430
-            ),
431
-            'abandoned' => array(
432
-                'slug'  => 'abandoned',
433
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
-                'count' => 0,
435
-            ),
436
-            'incomplete' => array(
437
-                'slug'  => 'incomplete',
438
-                'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
439
-                'count' => 0,
440
-            )
441
-        );
442
-        if (/**
443
-             * Filters whether a link to the "Failed Transactions" list table
444
-             * appears on the Transactions Admin Page list table.
445
-             * List display can be turned back on via the following:
446
-             * add_filter(
447
-             *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
448
-             *     '__return_true'
449
-             * );
450
-             *
451
-             * @since 4.9.70.p
452
-             * @param boolean                 $display_failed_txns_list
453
-             * @param Transactions_Admin_Page $this
454
-             */
455
-            apply_filters(
456
-                'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
457
-                false,
458
-                $this
459
-            )
460
-        ) {
461
-            $this->_views['failed'] = array(
462
-                'slug'  => 'failed',
463
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
464
-                'count' => 0,
465
-            );
466
-        }
467
-    }
468
-
469
-
470
-    /**
471
-     * _set_transaction_object
472
-     * This sets the _transaction property for the transaction details screen
473
-     *
474
-     * @access private
475
-     * @return void
476
-     * @throws EE_Error
477
-     * @throws InvalidArgumentException
478
-     * @throws RuntimeException
479
-     * @throws InvalidDataTypeException
480
-     * @throws InvalidInterfaceException
481
-     * @throws ReflectionException
482
-     */
483
-    private function _set_transaction_object()
484
-    {
485
-        if ($this->_transaction instanceof EE_Transaction) {
486
-            return;
487
-        } //get out we've already set the object
488
-
489
-        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
490
-            ? absint($this->_req_data['TXN_ID'])
491
-            : false;
492
-
493
-        // get transaction object
494
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
495
-        $this->_session = $this->_transaction instanceof EE_Transaction
496
-            ? $this->_transaction->get('TXN_session_data')
497
-            : null;
498
-        if ($this->_transaction instanceof EE_Transaction) {
499
-            $this->_transaction->verify_abandoned_transaction_status();
500
-        }
501
-
502
-        if (! $this->_transaction instanceof EE_Transaction) {
503
-            $error_msg = sprintf(
504
-                esc_html__(
505
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
506
-                    'event_espresso'
507
-                ),
508
-                $TXN_ID
509
-            );
510
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
511
-        }
512
-    }
513
-
514
-
515
-    /**
516
-     *    _transaction_legend_items
517
-     *
518
-     * @access protected
519
-     * @return array
520
-     * @throws EE_Error
521
-     * @throws InvalidArgumentException
522
-     * @throws ReflectionException
523
-     * @throws InvalidDataTypeException
524
-     * @throws InvalidInterfaceException
525
-     */
526
-    protected function _transaction_legend_items()
527
-    {
528
-        EE_Registry::instance()->load_helper('MSG_Template');
529
-        $items = array();
530
-
531
-        if (EE_Registry::instance()->CAP->current_user_can(
532
-            'ee_read_global_messages',
533
-            'view_filtered_messages'
534
-        )) {
535
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
536
-            if (is_array($related_for_icon)
537
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
538
-            ) {
539
-                $items['view_related_messages'] = array(
540
-                    'class' => $related_for_icon['css_class'],
541
-                    'desc'  => $related_for_icon['label'],
542
-                );
543
-            }
544
-        }
545
-
546
-        $items = apply_filters(
547
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
548
-            array_merge(
549
-                $items,
550
-                array(
551
-                    'view_details'          => array(
552
-                        'class' => 'dashicons dashicons-cart',
553
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
554
-                    ),
555
-                    'view_invoice'          => array(
556
-                        'class' => 'dashicons dashicons-media-spreadsheet',
557
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
558
-                    ),
559
-                    'view_receipt'          => array(
560
-                        'class' => 'dashicons dashicons-media-default',
561
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
562
-                    ),
563
-                    'view_registration'     => array(
564
-                        'class' => 'dashicons dashicons-clipboard',
565
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
566
-                    ),
567
-                    'payment_overview_link' => array(
568
-                        'class' => 'dashicons dashicons-money',
569
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
570
-                    ),
571
-                )
572
-            )
573
-        );
574
-
575
-        if (EE_Registry::instance()->CAP->current_user_can(
576
-            'ee_send_message',
577
-            'espresso_transactions_send_payment_reminder'
578
-        )) {
579
-            if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
580
-                $items['send_payment_reminder'] = array(
581
-                    'class' => 'dashicons dashicons-email-alt',
582
-                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
583
-                );
584
-            } else {
585
-                $items['blank*'] = array(
586
-                    'class' => '',
587
-                    'desc'  => '',
588
-                );
589
-            }
590
-        } else {
591
-            $items['blank*'] = array(
592
-                'class' => '',
593
-                'desc'  => '',
594
-            );
595
-        }
596
-        $more_items = apply_filters(
597
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
598
-            array(
599
-                'overpaid'   => array(
600
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
601
-                    'desc'  => EEH_Template::pretty_status(
602
-                        EEM_Transaction::overpaid_status_code,
603
-                        false,
604
-                        'sentence'
605
-                    ),
606
-                ),
607
-                'complete'   => array(
608
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
609
-                    'desc'  => EEH_Template::pretty_status(
610
-                        EEM_Transaction::complete_status_code,
611
-                        false,
612
-                        'sentence'
613
-                    ),
614
-                ),
615
-                'incomplete' => array(
616
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
617
-                    'desc'  => EEH_Template::pretty_status(
618
-                        EEM_Transaction::incomplete_status_code,
619
-                        false,
620
-                        'sentence'
621
-                    ),
622
-                ),
623
-                'abandoned'  => array(
624
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
625
-                    'desc'  => EEH_Template::pretty_status(
626
-                        EEM_Transaction::abandoned_status_code,
627
-                        false,
628
-                        'sentence'
629
-                    ),
630
-                ),
631
-                'failed'     => array(
632
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
633
-                    'desc'  => EEH_Template::pretty_status(
634
-                        EEM_Transaction::failed_status_code,
635
-                        false,
636
-                        'sentence'
637
-                    ),
638
-                ),
639
-            )
640
-        );
641
-
642
-        return array_merge($items, $more_items);
643
-    }
644
-
645
-
646
-    /**
647
-     *    _transactions_overview_list_table
648
-     *
649
-     * @access protected
650
-     * @return void
651
-     * @throws DomainException
652
-     * @throws EE_Error
653
-     * @throws InvalidArgumentException
654
-     * @throws InvalidDataTypeException
655
-     * @throws InvalidInterfaceException
656
-     * @throws ReflectionException
657
-     */
658
-    protected function _transactions_overview_list_table()
659
-    {
660
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
661
-        $event = isset($this->_req_data['EVT_ID'])
662
-            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
663
-            : null;
664
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
665
-            ? sprintf(
666
-                esc_html__(
667
-                    '%sViewing Transactions for the Event: %s%s',
668
-                    'event_espresso'
669
-                ),
670
-                '<h3>',
671
-                '<a href="'
672
-                . EE_Admin_Page::add_query_args_and_nonce(
673
-                    array('action' => 'edit', 'post' => $event->ID()),
674
-                    EVENTS_ADMIN_URL
675
-                )
676
-                . '" title="'
677
-                . esc_attr__(
678
-                    'Click to Edit event',
679
-                    'event_espresso'
680
-                )
681
-                . '">' . $event->get('EVT_name') . '</a>',
682
-                '</h3>'
683
-            )
684
-            : '';
685
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
686
-        $this->display_admin_list_table_page_with_no_sidebar();
687
-    }
688
-
689
-
690
-    /**
691
-     *    _transaction_details
692
-     * generates HTML for the View Transaction Details Admin page
693
-     *
694
-     * @access protected
695
-     * @return void
696
-     * @throws DomainException
697
-     * @throws EE_Error
698
-     * @throws InvalidArgumentException
699
-     * @throws InvalidDataTypeException
700
-     * @throws InvalidInterfaceException
701
-     * @throws RuntimeException
702
-     * @throws ReflectionException
703
-     */
704
-    protected function _transaction_details()
705
-    {
706
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
707
-
708
-        $this->_set_transaction_status_array();
709
-
710
-        $this->_template_args = array();
711
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
712
-
713
-        $this->_set_transaction_object();
714
-
715
-        if (! $this->_transaction instanceof EE_Transaction) {
716
-            return;
717
-        }
718
-        $primary_registration = $this->_transaction->primary_registration();
719
-        $attendee = $primary_registration instanceof EE_Registration
720
-            ? $primary_registration->attendee()
721
-            : null;
722
-
723
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
724
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
725
-
726
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
727
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
728
-
729
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
730
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
731
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
732
-
733
-        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
734
-        $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
735
-
736
-        $amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
737
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
738
-            $amount_due,
739
-            true
740
-        );
741
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
742
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
743
-                                                  . $this->_template_args['amount_due'];
744
-        } else {
745
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
746
-        }
747
-        $this->_template_args['amount_due_class'] = '';
748
-
749
-        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
750
-            // paid in full
751
-            $this->_template_args['amount_due'] = false;
752
-        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
753
-            // overpaid
754
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
755
-        } elseif ($this->_transaction->get('TXN_total') > 0
756
-                  && $this->_transaction->get('TXN_paid') > 0
757
-        ) {
758
-            // monies owing
759
-            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
760
-        } elseif ($this->_transaction->get('TXN_total') > 0
761
-                  && $this->_transaction->get('TXN_paid') == 0
762
-        ) {
763
-            // no payments made yet
764
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
765
-        } elseif ($this->_transaction->get('TXN_total') == 0) {
766
-            // free event
767
-            $this->_template_args['amount_due'] = false;
768
-        }
769
-
770
-        $payment_method = $this->_transaction->payment_method();
771
-
772
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
773
-            ? $payment_method->admin_name()
774
-            : esc_html__('Unknown', 'event_espresso');
775
-
776
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
777
-        // link back to overview
778
-        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
779
-            ? $_SERVER['HTTP_REFERER']
780
-            : TXN_ADMIN_URL;
781
-
782
-
783
-        // next link
784
-        $next_txn = $this->_transaction->next(
785
-            null,
786
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
787
-            'TXN_ID'
788
-        );
789
-        $this->_template_args['next_transaction'] = $next_txn
790
-            ? $this->_next_link(
791
-                EE_Admin_Page::add_query_args_and_nonce(
792
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
793
-                    TXN_ADMIN_URL
794
-                ),
795
-                'dashicons dashicons-arrow-right ee-icon-size-22'
796
-            )
797
-            : '';
798
-        // previous link
799
-        $previous_txn = $this->_transaction->previous(
800
-            null,
801
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
802
-            'TXN_ID'
803
-        );
804
-        $this->_template_args['previous_transaction'] = $previous_txn
805
-            ? $this->_previous_link(
806
-                EE_Admin_Page::add_query_args_and_nonce(
807
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
808
-                    TXN_ADMIN_URL
809
-                ),
810
-                'dashicons dashicons-arrow-left ee-icon-size-22'
811
-            )
812
-            : '';
813
-
814
-        // were we just redirected here after adding a new registration ???
815
-        if (isset(
816
-            $this->_req_data['redirect_from'],
817
-            $this->_req_data['EVT_ID'],
818
-            $this->_req_data['event_name']
819
-        )) {
820
-            if (EE_Registry::instance()->CAP->current_user_can(
821
-                'ee_edit_registrations',
822
-                'espresso_registrations_new_registration',
823
-                $this->_req_data['EVT_ID']
824
-            )) {
825
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
826
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
827
-                    array(
828
-                        'page'     => 'espresso_registrations',
829
-                        'action'   => 'new_registration',
830
-                        'return'   => 'default',
831
-                        'TXN_ID'   => $this->_transaction->ID(),
832
-                        'event_id' => $this->_req_data['EVT_ID'],
833
-                    ),
834
-                    REG_ADMIN_URL
835
-                );
836
-                $this->_admin_page_title .= '">';
837
-
838
-                $this->_admin_page_title .= sprintf(
839
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
840
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
841
-                );
842
-                $this->_admin_page_title .= '</a>';
843
-            }
844
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
845
-        }
846
-        // grab messages at the last second
847
-        $this->_template_args['notices'] = EE_Error::get_notices();
848
-        // path to template
849
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
850
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
851
-            $template_path,
852
-            $this->_template_args,
853
-            true
854
-        );
855
-
856
-        // the details template wrapper
857
-        $this->display_admin_page_with_sidebar();
858
-    }
859
-
860
-
861
-    /**
862
-     *        _transaction_details_metaboxes
863
-     *
864
-     * @access protected
865
-     * @return void
866
-     * @throws EE_Error
867
-     * @throws InvalidArgumentException
868
-     * @throws InvalidDataTypeException
869
-     * @throws InvalidInterfaceException
870
-     * @throws RuntimeException
871
-     * @throws ReflectionException
872
-     */
873
-    protected function _transaction_details_metaboxes()
874
-    {
875
-
876
-        $this->_set_transaction_object();
877
-
878
-        if (! $this->_transaction instanceof EE_Transaction) {
879
-            return;
880
-        }
881
-        add_meta_box(
882
-            'edit-txn-details-mbox',
883
-            esc_html__('Transaction Details', 'event_espresso'),
884
-            array($this, 'txn_details_meta_box'),
885
-            $this->_wp_page_slug,
886
-            'normal',
887
-            'high'
888
-        );
889
-        add_meta_box(
890
-            'edit-txn-attendees-mbox',
891
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
892
-            array($this, 'txn_attendees_meta_box'),
893
-            $this->_wp_page_slug,
894
-            'normal',
895
-            'high',
896
-            array('TXN_ID' => $this->_transaction->ID())
897
-        );
898
-        add_meta_box(
899
-            'edit-txn-registrant-mbox',
900
-            esc_html__('Primary Contact', 'event_espresso'),
901
-            array($this, 'txn_registrant_side_meta_box'),
902
-            $this->_wp_page_slug,
903
-            'side',
904
-            'high'
905
-        );
906
-        add_meta_box(
907
-            'edit-txn-billing-info-mbox',
908
-            esc_html__('Billing Information', 'event_espresso'),
909
-            array($this, 'txn_billing_info_side_meta_box'),
910
-            $this->_wp_page_slug,
911
-            'side',
912
-            'high'
913
-        );
914
-    }
915
-
916
-
917
-    /**
918
-     * Callback for transaction actions metabox.
919
-     *
920
-     * @param EE_Transaction|null $transaction
921
-     * @throws DomainException
922
-     * @throws EE_Error
923
-     * @throws InvalidArgumentException
924
-     * @throws InvalidDataTypeException
925
-     * @throws InvalidInterfaceException
926
-     * @throws ReflectionException
927
-     * @throws RuntimeException
928
-     */
929
-    public function getActionButtons(EE_Transaction $transaction = null)
930
-    {
931
-        $content = '';
932
-        $actions = array();
933
-        if (! $transaction instanceof EE_Transaction) {
934
-            return $content;
935
-        }
936
-        /** @var EE_Registration $primary_registration */
937
-        $primary_registration = $transaction->primary_registration();
938
-        $attendee = $primary_registration instanceof EE_Registration
939
-            ? $primary_registration->attendee()
940
-            : null;
941
-
942
-        if ($attendee instanceof EE_Attendee
943
-            && EE_Registry::instance()->CAP->current_user_can(
944
-                'ee_send_message',
945
-                'espresso_transactions_send_payment_reminder'
946
-            )
947
-        ) {
948
-            $actions['payment_reminder'] =
949
-                EEH_MSG_Template::is_mt_active('payment_reminder')
950
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
951
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
952
-                    ? EEH_Template::get_button_or_link(
953
-                        EE_Admin_Page::add_query_args_and_nonce(
954
-                            array(
955
-                                'action'      => 'send_payment_reminder',
956
-                                'TXN_ID'      => $this->_transaction->ID(),
957
-                                'redirect_to' => 'view_transaction',
958
-                            ),
959
-                            TXN_ADMIN_URL
960
-                        ),
961
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
962
-                        'button secondary-button',
963
-                        'dashicons dashicons-email-alt'
964
-                    )
965
-                    : '';
966
-        }
967
-
968
-        if ($primary_registration instanceof EE_Registration
969
-            && EEH_MSG_Template::is_mt_active('receipt')
970
-        ) {
971
-            $actions['receipt'] = EEH_Template::get_button_or_link(
972
-                $primary_registration->receipt_url(),
973
-                esc_html__('View Receipt', 'event_espresso'),
974
-                'button secondary-button',
975
-                'dashicons dashicons-media-default'
976
-            );
977
-        }
978
-
979
-        if ($primary_registration instanceof EE_Registration
980
-            && EEH_MSG_Template::is_mt_active('invoice')
981
-        ) {
982
-            $actions['invoice'] = EEH_Template::get_button_or_link(
983
-                $primary_registration->invoice_url(),
984
-                esc_html__('View Invoice', 'event_espresso'),
985
-                'button secondary-button',
986
-                'dashicons dashicons-media-spreadsheet'
987
-            );
988
-        }
989
-        $actions = array_filter(
990
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
991
-        );
992
-        if ($actions) {
993
-            $content = '<ul>';
994
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
995
-            $content .= '</uL>';
996
-        }
997
-        return $content;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * txn_details_meta_box
1003
-     * generates HTML for the Transaction main meta box
1004
-     *
1005
-     * @return void
1006
-     * @throws DomainException
1007
-     * @throws EE_Error
1008
-     * @throws InvalidArgumentException
1009
-     * @throws InvalidDataTypeException
1010
-     * @throws InvalidInterfaceException
1011
-     * @throws RuntimeException
1012
-     * @throws ReflectionException
1013
-     */
1014
-    public function txn_details_meta_box()
1015
-    {
1016
-        $this->_set_transaction_object();
1017
-        $this->_template_args['TXN_ID'] = $this->_transaction->ID();
1018
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1019
-            ? $this->_transaction->primary_registration()->attendee()
1020
-            : null;
1021
-        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
-            'ee_edit_payments',
1023
-            'apply_payment_or_refund_from_registration_details'
1024
-        );
1025
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1026
-            'ee_delete_payments',
1027
-            'delete_payment_from_registration_details'
1028
-        );
1029
-
1030
-        // get line table
1031
-        EEH_Autoloader::register_line_item_display_autoloaders();
1032
-        $Line_Item_Display = new EE_Line_Item_Display(
1033
-            'admin_table',
1034
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1035
-        );
1036
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1037
-            $this->_transaction->total_line_item()
1038
-        );
1039
-        $this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1040
-                                                               ->get('REG_code');
1041
-
1042
-        // process taxes
1043
-        $taxes = $this->_transaction->get_many_related(
1044
-            'Line_Item',
1045
-            array(array('LIN_type' => EEM_Line_Item::type_tax))
1046
-        );
1047
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1048
-
1049
-        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1050
-            $this->_transaction->get('TXN_total'),
1051
-            false,
1052
-            false
1053
-        );
1054
-        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1055
-        $this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1056
-
1057
-        // process payment details
1058
-        $payments = $this->_transaction->get_many_related('Payment');
1059
-        if (! empty($payments)) {
1060
-            $this->_template_args['payments'] = $payments;
1061
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1062
-        } else {
1063
-            $this->_template_args['payments'] = false;
1064
-            $this->_template_args['existing_reg_payments'] = array();
1065
-        }
1066
-
1067
-        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1068
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1069
-            array('action' => 'espresso_delete_payment'),
1070
-            TXN_ADMIN_URL
1071
-        );
1072
-
1073
-        if (isset($txn_details['invoice_number'])) {
1074
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1075
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1076
-                'Invoice Number',
1077
-                'event_espresso'
1078
-            );
1079
-        }
1080
-
1081
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1082
-            ->get_first_related('Registration')
1083
-            ->get('REG_session');
1084
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1085
-            'Registration Session',
1086
-            'event_espresso'
1087
-        );
1088
-
1089
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1090
-            ? $this->_session['ip_address']
1091
-            : '';
1092
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1093
-            'Transaction placed from IP',
1094
-            'event_espresso'
1095
-        );
1096
-
1097
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1098
-            ? $this->_session['user_agent']
1099
-            : '';
1100
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1101
-            'Registrant User Agent',
1102
-            'event_espresso'
1103
-        );
1104
-
1105
-        $reg_steps = '<ul>';
1106
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1107
-            if ($reg_step_status === true) {
1108
-                $reg_steps .= '<li style="color:#70cc50">'
1109
-                              . sprintf(
1110
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1111
-                                  ucwords(str_replace('_', ' ', $reg_step))
1112
-                              )
1113
-                              . '</li>';
1114
-            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1115
-                $reg_steps .= '<li style="color:#2EA2CC">'
1116
-                              . sprintf(
1117
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1118
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1119
-                                  date(
1120
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1121
-                                      ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1122
-                                  )
1123
-                              )
1124
-                              . '</li>';
1125
-            } else {
1126
-                $reg_steps .= '<li style="color:#E76700">'
1127
-                              . sprintf(
1128
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1129
-                                  ucwords(str_replace('_', ' ', $reg_step))
1130
-                              )
1131
-                              . '</li>';
1132
-            }
1133
-        }
1134
-        $reg_steps .= '</ul>';
1135
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1136
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1137
-            'Registration Step Progress',
1138
-            'event_espresso'
1139
-        );
1140
-
1141
-
1142
-        $this->_get_registrations_to_apply_payment_to();
1143
-        $this->_get_payment_methods($payments);
1144
-        $this->_get_payment_status_array();
1145
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1146
-
1147
-        $this->_template_args['transaction_form_url'] = add_query_arg(
1148
-            array(
1149
-                'action'  => 'edit_transaction',
1150
-                'process' => 'transaction',
1151
-            ),
1152
-            TXN_ADMIN_URL
1153
-        );
1154
-        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1155
-            array(
1156
-                'page'   => 'espresso_transactions',
1157
-                'action' => 'espresso_apply_payment',
1158
-            ),
1159
-            WP_AJAX_URL
1160
-        );
1161
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1162
-            array(
1163
-                'page'   => 'espresso_transactions',
1164
-                'action' => 'espresso_delete_payment',
1165
-            ),
1166
-            WP_AJAX_URL
1167
-        );
1168
-
1169
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1170
-
1171
-        // 'espresso_delete_payment_nonce'
1172
-
1173
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1174
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * _get_registration_payment_IDs
1180
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1181
-     *
1182
-     * @access protected
1183
-     * @param EE_Payment[] $payments
1184
-     * @return array
1185
-     * @throws EE_Error
1186
-     * @throws InvalidArgumentException
1187
-     * @throws InvalidDataTypeException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws ReflectionException
1190
-     */
1191
-    protected function _get_registration_payment_IDs($payments = array())
1192
-    {
1193
-        $existing_reg_payments = array();
1194
-        // get all reg payments for these payments
1195
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1196
-            array(
1197
-                array(
1198
-                    'PAY_ID' => array(
1199
-                        'IN',
1200
-                        array_keys($payments),
1201
-                    ),
1202
-                ),
1203
-            )
1204
-        );
1205
-        if (! empty($reg_payments)) {
1206
-            foreach ($payments as $payment) {
1207
-                if (! $payment instanceof EE_Payment) {
1208
-                    continue;
1209
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1210
-                    $existing_reg_payments[ $payment->ID() ] = array();
1211
-                }
1212
-                foreach ($reg_payments as $reg_payment) {
1213
-                    if ($reg_payment instanceof EE_Registration_Payment
1214
-                        && $reg_payment->payment_ID() === $payment->ID()
1215
-                    ) {
1216
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1217
-                    }
1218
-                }
1219
-            }
1220
-        }
1221
-
1222
-        return $existing_reg_payments;
1223
-    }
1224
-
1225
-
1226
-    /**
1227
-     * _get_registrations_to_apply_payment_to
1228
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1229
-     * which allows the admin to only apply the payment to the specific registrations
1230
-     *
1231
-     * @access protected
1232
-     * @return void
1233
-     * @throws \EE_Error
1234
-     */
1235
-    protected function _get_registrations_to_apply_payment_to()
1236
-    {
1237
-        // we want any registration with an active status (ie: not deleted or cancelled)
1238
-        $query_params = array(
1239
-            array(
1240
-                'STS_ID' => array(
1241
-                    'IN',
1242
-                    array(
1243
-                        EEM_Registration::status_id_approved,
1244
-                        EEM_Registration::status_id_pending_payment,
1245
-                        EEM_Registration::status_id_not_approved,
1246
-                    ),
1247
-                ),
1248
-            ),
1249
-        );
1250
-        $registrations_to_apply_payment_to = EEH_HTML::br()
1251
-                                             . EEH_HTML::div(
1252
-                                                 '',
1253
-                                                 'txn-admin-apply-payment-to-registrations-dv',
1254
-                                                 '',
1255
-                                                 'clear: both; margin: 1.5em 0 0; display: none;'
1256
-                                             );
1257
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1258
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1259
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1260
-            EEH_HTML::tr(
1261
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1262
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1263
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1264
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1265
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1266
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1267
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1268
-            )
1269
-        );
1270
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1271
-        // get registrations for TXN
1272
-        $registrations = $this->_transaction->registrations($query_params);
1273
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1274
-        foreach ($registrations as $registration) {
1275
-            if ($registration instanceof EE_Registration) {
1276
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
1277
-                    ? $registration->attendee()->full_name()
1278
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1279
-                $owing = $registration->final_price() - $registration->paid();
1280
-                $taxable = $registration->ticket()->taxable()
1281
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1282
-                    : '';
1283
-                $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1284
-                    ? ' checked="checked"'
1285
-                    : '';
1286
-                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1287
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
-                    EEH_HTML::td($registration->ID()) .
1289
-                    EEH_HTML::td($attendee_name) .
1290
-                    EEH_HTML::td(
1291
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
-                    ) .
1293
-                    EEH_HTML::td($registration->event_name()) .
1294
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1295
-                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1296
-                    EEH_HTML::td(
1297
-                        '<input type="checkbox" value="' . $registration->ID()
1298
-                        . '" name="txn_admin_payment[registrations]"'
1299
-                        . $checked . $disabled . '>',
1300
-                        '',
1301
-                        'jst-cntr'
1302
-                    ),
1303
-                    'apply-payment-registration-row-' . $registration->ID()
1304
-                );
1305
-            }
1306
-        }
1307
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1308
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1309
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1310
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1311
-            esc_html__(
1312
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1313
-                'event_espresso'
1314
-            ),
1315
-            '',
1316
-            'clear description'
1317
-        );
1318
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1319
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * _get_reg_status_selection
1325
-     *
1326
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1327
-     *         instead of events.
1328
-     * @access protected
1329
-     * @return void
1330
-     * @throws EE_Error
1331
-     */
1332
-    protected function _get_reg_status_selection()
1333
-    {
1334
-        // first get all possible statuses
1335
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1336
-        // let's add a "don't change" option.
1337
-        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1338
-        $status_array = array_merge($status_array, $statuses);
1339
-        $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1340
-            'txn_reg_status_change[reg_status]',
1341
-            $status_array,
1342
-            'NAN',
1343
-            'id="txn-admin-payment-reg-status-inp"',
1344
-            'txn-reg-status-change-reg-status'
1345
-        );
1346
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1347
-            'delete_txn_reg_status_change[reg_status]',
1348
-            $status_array,
1349
-            'NAN',
1350
-            'delete-txn-admin-payment-reg-status-inp',
1351
-            'delete-txn-reg-status-change-reg-status'
1352
-        );
1353
-    }
1354
-
1355
-
1356
-    /**
1357
-     *    _get_payment_methods
1358
-     * Gets all the payment methods available generally, or the ones that are already
1359
-     * selected on these payments (in case their payment methods are no longer active).
1360
-     * Has the side-effect of updating the template args' payment_methods item
1361
-     *
1362
-     * @access private
1363
-     * @param EE_Payment[] to show on this page
1364
-     * @return void
1365
-     * @throws EE_Error
1366
-     * @throws InvalidArgumentException
1367
-     * @throws InvalidDataTypeException
1368
-     * @throws InvalidInterfaceException
1369
-     * @throws ReflectionException
1370
-     */
1371
-    private function _get_payment_methods($payments = array())
1372
-    {
1373
-        $payment_methods_of_payments = array();
1374
-        foreach ($payments as $payment) {
1375
-            if ($payment instanceof EE_Payment) {
1376
-                $payment_methods_of_payments[] = $payment->get('PMD_ID');
1377
-            }
1378
-        }
1379
-        if ($payment_methods_of_payments) {
1380
-            $query_args = array(
1381
-                array(
1382
-                    'OR*payment_method_for_payment' => array(
1383
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1384
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1385
-                    ),
1386
-                ),
1387
-            );
1388
-        } else {
1389
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1390
-        }
1391
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * txn_attendees_meta_box
1397
-     *    generates HTML for the Attendees Transaction main meta box
1398
-     *
1399
-     * @access public
1400
-     * @param WP_Post $post
1401
-     * @param array   $metabox
1402
-     * @return void
1403
-     * @throws DomainException
1404
-     * @throws EE_Error
1405
-     */
1406
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1407
-    {
1408
-
1409
-        /** @noinspection NonSecureExtractUsageInspection */
1410
-        extract($metabox['args']);
1411
-        $this->_template_args['post'] = $post;
1412
-        $this->_template_args['event_attendees'] = array();
1413
-        // process items in cart
1414
-        $line_items = $this->_transaction->get_many_related(
1415
-            'Line_Item',
1416
-            array(array('LIN_type' => 'line-item'))
1417
-        );
1418
-        if (! empty($line_items)) {
1419
-            foreach ($line_items as $item) {
1420
-                if ($item instanceof EE_Line_Item) {
1421
-                    switch ($item->OBJ_type()) {
1422
-                        case 'Event':
1423
-                            break;
1424
-                        case 'Ticket':
1425
-                            $ticket = $item->ticket();
1426
-                            // right now we're only handling tickets here.
1427
-                            // Cause its expected that only tickets will have attendees right?
1428
-                            if (! $ticket instanceof EE_Ticket) {
1429
-                                continue;
1430
-                            }
1431
-                            try {
1432
-                                $event_name = $ticket->get_event_name();
1433
-                            } catch (Exception $e) {
1434
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1435
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1436
-                            }
1437
-                            $event_name .= ' - ' . $item->get('LIN_name');
1438
-                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1439
-                            // now get all of the registrations for this transaction that use this ticket
1440
-                            $registrations = $ticket->get_many_related(
1441
-                                'Registration',
1442
-                                array(array('TXN_ID' => $this->_transaction->ID()))
1443
-                            );
1444
-                            foreach ($registrations as $registration) {
1445
-                                if (! $registration instanceof EE_Registration) {
1446
-                                    continue;
1447
-                                }
1448
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1449
-                                    = $registration->status_ID();
1450
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1451
-                                    = $registration->count();
1452
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1453
-                                    = $event_name;
1454
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1455
-                                    = $ticket_price;
1456
-                                // attendee info
1457
-                                $attendee = $registration->get_first_related('Attendee');
1458
-                                if ($attendee instanceof EE_Attendee) {
1459
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1460
-                                        = $attendee->ID();
1461
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1462
-                                        = $attendee->full_name();
1463
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1464
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1465
-                                          . esc_html__(
1466
-                                              ' Event',
1467
-                                              'event_espresso'
1468
-                                          )
1469
-                                          . '">' . $attendee->email() . '</a>';
1470
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1471
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1472
-                                } else {
1473
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1474
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1475
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1476
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1477
-                                }
1478
-                            }
1479
-                            break;
1480
-                    }
1481
-                }
1482
-            }
1483
-
1484
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1485
-                array(
1486
-                    'action'  => 'edit_transaction',
1487
-                    'process' => 'attendees',
1488
-                ),
1489
-                TXN_ADMIN_URL
1490
-            );
1491
-            echo EEH_Template::display_template(
1492
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1493
-                $this->_template_args,
1494
-                true
1495
-            );
1496
-        } else {
1497
-            echo sprintf(
1498
-                esc_html__(
1499
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1500
-                    'event_espresso'
1501
-                ),
1502
-                '<p class="important-notice">',
1503
-                '</p>'
1504
-            );
1505
-        }
1506
-    }
1507
-
1508
-
1509
-    /**
1510
-     * txn_registrant_side_meta_box
1511
-     * generates HTML for the Edit Transaction side meta box
1512
-     *
1513
-     * @access public
1514
-     * @return void
1515
-     * @throws DomainException
1516
-     * @throws EE_Error
1517
-     * @throws InvalidArgumentException
1518
-     * @throws InvalidDataTypeException
1519
-     * @throws InvalidInterfaceException
1520
-     * @throws ReflectionException
1521
-     */
1522
-    public function txn_registrant_side_meta_box()
1523
-    {
1524
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1525
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1526
-            : null;
1527
-        if (! $primary_att instanceof EE_Attendee) {
1528
-            $this->_template_args['no_attendee_message'] = esc_html__(
1529
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1530
-                'event_espresso'
1531
-            );
1532
-            $primary_att = EEM_Attendee::instance()->create_default_object();
1533
-        }
1534
-        $this->_template_args['ATT_ID'] = $primary_att->ID();
1535
-        $this->_template_args['prime_reg_fname'] = $primary_att->fname();
1536
-        $this->_template_args['prime_reg_lname'] = $primary_att->lname();
1537
-        $this->_template_args['prime_reg_email'] = $primary_att->email();
1538
-        $this->_template_args['prime_reg_phone'] = $primary_att->phone();
1539
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1540
-            array(
1541
-                'action' => 'edit_attendee',
1542
-                'post'   => $primary_att->ID(),
1543
-            ),
1544
-            REG_ADMIN_URL
1545
-        );
1546
-        // get formatted address for registrant
1547
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1548
-        echo EEH_Template::display_template(
1549
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1550
-            $this->_template_args,
1551
-            true
1552
-        );
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     * txn_billing_info_side_meta_box
1558
-     *    generates HTML for the Edit Transaction side meta box
1559
-     *
1560
-     * @access public
1561
-     * @return void
1562
-     * @throws DomainException
1563
-     * @throws EE_Error
1564
-     */
1565
-    public function txn_billing_info_side_meta_box()
1566
-    {
1567
-
1568
-        $this->_template_args['billing_form'] = $this->_transaction->billing_info();
1569
-        $this->_template_args['billing_form_url'] = add_query_arg(
1570
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1571
-            TXN_ADMIN_URL
1572
-        );
1573
-
1574
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1575
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1576
-    }
1577
-
1578
-
1579
-    /**
1580
-     * apply_payments_or_refunds
1581
-     *    registers a payment or refund made towards a transaction
1582
-     *
1583
-     * @access public
1584
-     * @return void
1585
-     * @throws EE_Error
1586
-     * @throws InvalidArgumentException
1587
-     * @throws ReflectionException
1588
-     * @throws RuntimeException
1589
-     * @throws InvalidDataTypeException
1590
-     * @throws InvalidInterfaceException
1591
-     */
1592
-    public function apply_payments_or_refunds()
1593
-    {
1594
-        $json_response_data = array('return_data' => false);
1595
-        $valid_data = $this->_validate_payment_request_data();
1596
-        $has_access = EE_Registry::instance()->CAP->current_user_can(
1597
-            'ee_edit_payments',
1598
-            'apply_payment_or_refund_from_registration_details'
1599
-        );
1600
-        if (! empty($valid_data) && $has_access) {
1601
-            $PAY_ID = $valid_data['PAY_ID'];
1602
-            // save  the new payment
1603
-            $payment = $this->_create_payment_from_request_data($valid_data);
1604
-            // get the TXN for this payment
1605
-            $transaction = $payment->transaction();
1606
-            // verify transaction
1607
-            if ($transaction instanceof EE_Transaction) {
1608
-                // calculate_total_payments_and_update_status
1609
-                $this->_process_transaction_payments($transaction);
1610
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1611
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1612
-                // apply payment to registrations (if applicable)
1613
-                if (! empty($REG_IDs)) {
1614
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1615
-                    $this->_maybe_send_notifications();
1616
-                    // now process status changes for the same registrations
1617
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1618
-                }
1619
-                $this->_maybe_send_notifications($payment);
1620
-                // prepare to render page
1621
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1622
-                do_action(
1623
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1624
-                    $transaction,
1625
-                    $payment
1626
-                );
1627
-            } else {
1628
-                EE_Error::add_error(
1629
-                    esc_html__(
1630
-                        'A valid Transaction for this payment could not be retrieved.',
1631
-                        'event_espresso'
1632
-                    ),
1633
-                    __FILE__,
1634
-                    __FUNCTION__,
1635
-                    __LINE__
1636
-                );
1637
-            }
1638
-        } else {
1639
-            if ($has_access) {
1640
-                EE_Error::add_error(
1641
-                    esc_html__(
1642
-                        'The payment form data could not be processed. Please try again.',
1643
-                        'event_espresso'
1644
-                    ),
1645
-                    __FILE__,
1646
-                    __FUNCTION__,
1647
-                    __LINE__
1648
-                );
1649
-            } else {
1650
-                EE_Error::add_error(
1651
-                    esc_html__(
1652
-                        'You do not have access to apply payments or refunds to a registration.',
1653
-                        'event_espresso'
1654
-                    ),
1655
-                    __FILE__,
1656
-                    __FUNCTION__,
1657
-                    __LINE__
1658
-                );
1659
-            }
1660
-        }
1661
-        $notices = EE_Error::get_notices(
1662
-            false,
1663
-            false,
1664
-            false
1665
-        );
1666
-        $this->_template_args = array(
1667
-            'data'    => $json_response_data,
1668
-            'error'   => $notices['errors'],
1669
-            'success' => $notices['success'],
1670
-        );
1671
-        $this->_return_json();
1672
-    }
1673
-
1674
-
1675
-    /**
1676
-     * _validate_payment_request_data
1677
-     *
1678
-     * @return array
1679
-     * @throws EE_Error
1680
-     */
1681
-    protected function _validate_payment_request_data()
1682
-    {
1683
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1684
-            return false;
1685
-        }
1686
-        $payment_form = $this->_generate_payment_form_section();
1687
-        try {
1688
-            if ($payment_form->was_submitted()) {
1689
-                $payment_form->receive_form_submission();
1690
-                if (! $payment_form->is_valid()) {
1691
-                    $submission_error_messages = array();
1692
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1693
-                        if ($validation_error instanceof EE_Validation_Error) {
1694
-                            $submission_error_messages[] = sprintf(
1695
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1696
-                                $validation_error->get_form_section()->html_label_text(),
1697
-                                $validation_error->getMessage()
1698
-                            );
1699
-                        }
1700
-                    }
1701
-                    EE_Error::add_error(
1702
-                        implode('<br />', $submission_error_messages),
1703
-                        __FILE__,
1704
-                        __FUNCTION__,
1705
-                        __LINE__
1706
-                    );
1707
-
1708
-                    return array();
1709
-                }
1710
-            }
1711
-        } catch (EE_Error $e) {
1712
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1713
-
1714
-            return array();
1715
-        }
1716
-
1717
-        return $payment_form->valid_data();
1718
-    }
1719
-
1720
-
1721
-    /**
1722
-     * _generate_payment_form_section
1723
-     *
1724
-     * @return EE_Form_Section_Proper
1725
-     * @throws EE_Error
1726
-     */
1727
-    protected function _generate_payment_form_section()
1728
-    {
1729
-        return new EE_Form_Section_Proper(
1730
-            array(
1731
-                'name'        => 'txn_admin_payment',
1732
-                'subsections' => array(
1733
-                    'PAY_ID'          => new EE_Text_Input(
1734
-                        array(
1735
-                            'default'               => 0,
1736
-                            'required'              => false,
1737
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1738
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1739
-                        )
1740
-                    ),
1741
-                    'TXN_ID'          => new EE_Text_Input(
1742
-                        array(
1743
-                            'default'               => 0,
1744
-                            'required'              => true,
1745
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1746
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1747
-                        )
1748
-                    ),
1749
-                    'type'            => new EE_Text_Input(
1750
-                        array(
1751
-                            'default'               => 1,
1752
-                            'required'              => true,
1753
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1754
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1755
-                        )
1756
-                    ),
1757
-                    'amount'          => new EE_Text_Input(
1758
-                        array(
1759
-                            'default'               => 0,
1760
-                            'required'              => true,
1761
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1762
-                            'validation_strategies' => array(new EE_Float_Normalization()),
1763
-                        )
1764
-                    ),
1765
-                    'status'          => new EE_Text_Input(
1766
-                        array(
1767
-                            'default'         => EEM_Payment::status_id_approved,
1768
-                            'required'        => true,
1769
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1770
-                        )
1771
-                    ),
1772
-                    'PMD_ID'          => new EE_Text_Input(
1773
-                        array(
1774
-                            'default'               => 2,
1775
-                            'required'              => true,
1776
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1777
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1778
-                        )
1779
-                    ),
1780
-                    'date'            => new EE_Text_Input(
1781
-                        array(
1782
-                            'default'         => time(),
1783
-                            'required'        => true,
1784
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1785
-                        )
1786
-                    ),
1787
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1788
-                        array(
1789
-                            'default'               => '',
1790
-                            'required'              => false,
1791
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1792
-                            'validation_strategies' => array(
1793
-                                new EE_Max_Length_Validation_Strategy(
1794
-                                    esc_html__('Input too long', 'event_espresso'),
1795
-                                    100
1796
-                                ),
1797
-                            ),
1798
-                        )
1799
-                    ),
1800
-                    'po_number'       => new EE_Text_Input(
1801
-                        array(
1802
-                            'default'               => '',
1803
-                            'required'              => false,
1804
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1805
-                            'validation_strategies' => array(
1806
-                                new EE_Max_Length_Validation_Strategy(
1807
-                                    esc_html__('Input too long', 'event_espresso'),
1808
-                                    100
1809
-                                ),
1810
-                            ),
1811
-                        )
1812
-                    ),
1813
-                    'accounting'      => new EE_Text_Input(
1814
-                        array(
1815
-                            'default'               => '',
1816
-                            'required'              => false,
1817
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1818
-                            'validation_strategies' => array(
1819
-                                new EE_Max_Length_Validation_Strategy(
1820
-                                    esc_html__('Input too long', 'event_espresso'),
1821
-                                    100
1822
-                                ),
1823
-                            ),
1824
-                        )
1825
-                    ),
1826
-                ),
1827
-            )
1828
-        );
1829
-    }
1830
-
1831
-
1832
-    /**
1833
-     * _create_payment_from_request_data
1834
-     *
1835
-     * @param array $valid_data
1836
-     * @return EE_Payment
1837
-     * @throws EE_Error
1838
-     */
1839
-    protected function _create_payment_from_request_data($valid_data)
1840
-    {
1841
-        $PAY_ID = $valid_data['PAY_ID'];
1842
-        // get payment amount
1843
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1844
-        // payments have a type value of 1 and refunds have a type value of -1
1845
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1846
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1847
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1848
-        $date = $valid_data['date']
1849
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1850
-            : date('Y-m-d g:i a', current_time('timestamp'));
1851
-        $payment = EE_Payment::new_instance(
1852
-            array(
1853
-                'TXN_ID'              => $valid_data['TXN_ID'],
1854
-                'STS_ID'              => $valid_data['status'],
1855
-                'PAY_timestamp'       => $date,
1856
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1857
-                'PMD_ID'              => $valid_data['PMD_ID'],
1858
-                'PAY_amount'          => $amount,
1859
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1860
-                'PAY_po_number'       => $valid_data['po_number'],
1861
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1862
-                'PAY_details'         => $valid_data,
1863
-                'PAY_ID'              => $PAY_ID,
1864
-            ),
1865
-            '',
1866
-            array('Y-m-d', 'g:i a')
1867
-        );
1868
-
1869
-        if (! $payment->save()) {
1870
-            EE_Error::add_error(
1871
-                sprintf(
1872
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1873
-                    $payment->ID()
1874
-                ),
1875
-                __FILE__,
1876
-                __FUNCTION__,
1877
-                __LINE__
1878
-            );
1879
-        }
1880
-
1881
-        return $payment;
1882
-    }
1883
-
1884
-
1885
-    /**
1886
-     * _process_transaction_payments
1887
-     *
1888
-     * @param \EE_Transaction $transaction
1889
-     * @return void
1890
-     * @throws EE_Error
1891
-     * @throws InvalidArgumentException
1892
-     * @throws ReflectionException
1893
-     * @throws InvalidDataTypeException
1894
-     * @throws InvalidInterfaceException
1895
-     */
1896
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1897
-    {
1898
-        /** @type EE_Transaction_Payments $transaction_payments */
1899
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1900
-        // update the transaction with this payment
1901
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1902
-            EE_Error::add_success(
1903
-                esc_html__(
1904
-                    'The payment has been processed successfully.',
1905
-                    'event_espresso'
1906
-                ),
1907
-                __FILE__,
1908
-                __FUNCTION__,
1909
-                __LINE__
1910
-            );
1911
-        } else {
1912
-            EE_Error::add_error(
1913
-                esc_html__(
1914
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1915
-                    'event_espresso'
1916
-                ),
1917
-                __FILE__,
1918
-                __FUNCTION__,
1919
-                __LINE__
1920
-            );
1921
-        }
1922
-    }
1923
-
1924
-
1925
-    /**
1926
-     * _get_REG_IDs_to_apply_payment_to
1927
-     * returns a list of registration IDs that the payment will apply to
1928
-     *
1929
-     * @param \EE_Payment $payment
1930
-     * @return array
1931
-     * @throws EE_Error
1932
-     */
1933
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1934
-    {
1935
-        $REG_IDs = array();
1936
-        // grab array of IDs for specific registrations to apply changes to
1937
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1938
-            $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1939
-        }
1940
-        // nothing specified ? then get all reg IDs
1941
-        if (empty($REG_IDs)) {
1942
-            $registrations = $payment->transaction()->registrations();
1943
-            $REG_IDs = ! empty($registrations)
1944
-                ? array_keys($registrations)
1945
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1946
-        }
1947
-
1948
-        // ensure that REG_IDs are integers and NOT strings
1949
-        return array_map('intval', $REG_IDs);
1950
-    }
1951
-
1952
-
1953
-    /**
1954
-     * @return array
1955
-     */
1956
-    public function existing_reg_payment_REG_IDs()
1957
-    {
1958
-        return $this->_existing_reg_payment_REG_IDs;
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     * @param array $existing_reg_payment_REG_IDs
1964
-     */
1965
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1966
-    {
1967
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * _get_existing_reg_payment_REG_IDs
1973
-     * returns a list of registration IDs that the payment is currently related to
1974
-     * as recorded in the database
1975
-     *
1976
-     * @param \EE_Payment $payment
1977
-     * @return array
1978
-     * @throws EE_Error
1979
-     */
1980
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1981
-    {
1982
-        if ($this->existing_reg_payment_REG_IDs() === null) {
1983
-            // let's get any existing reg payment records for this payment
1984
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1985
-            // but we only want the REG IDs, so grab the array keys
1986
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1987
-                ? array_keys($existing_reg_payment_REG_IDs)
1988
-                : array();
1989
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1990
-        }
1991
-
1992
-        return $this->existing_reg_payment_REG_IDs();
1993
-    }
1994
-
1995
-
1996
-    /**
1997
-     * _remove_existing_registration_payments
1998
-     * this calculates the difference between existing relations
1999
-     * to the supplied payment and the new list registration IDs,
2000
-     * removes any related registrations that no longer apply,
2001
-     * and then updates the registration paid fields
2002
-     *
2003
-     * @param \EE_Payment $payment
2004
-     * @param int         $PAY_ID
2005
-     * @return bool;
2006
-     * @throws EE_Error
2007
-     * @throws InvalidArgumentException
2008
-     * @throws ReflectionException
2009
-     * @throws InvalidDataTypeException
2010
-     * @throws InvalidInterfaceException
2011
-     */
2012
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2013
-    {
2014
-        // newly created payments will have nothing recorded for $PAY_ID
2015
-        if ($PAY_ID == 0) {
2016
-            return false;
2017
-        }
2018
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2019
-        if (empty($existing_reg_payment_REG_IDs)) {
2020
-            return false;
2021
-        }
2022
-        /** @type EE_Transaction_Payments $transaction_payments */
2023
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2024
-
2025
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2026
-            $payment,
2027
-            array(
2028
-                array(
2029
-                    'PAY_ID' => $payment->ID(),
2030
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2031
-                ),
2032
-            )
2033
-        );
2034
-    }
2035
-
2036
-
2037
-    /**
2038
-     * _update_registration_payments
2039
-     * this applies the payments to the selected registrations
2040
-     * but only if they have not already been paid for
2041
-     *
2042
-     * @param  EE_Transaction $transaction
2043
-     * @param \EE_Payment     $payment
2044
-     * @param array           $REG_IDs
2045
-     * @return void
2046
-     * @throws EE_Error
2047
-     * @throws InvalidArgumentException
2048
-     * @throws ReflectionException
2049
-     * @throws RuntimeException
2050
-     * @throws InvalidDataTypeException
2051
-     * @throws InvalidInterfaceException
2052
-     */
2053
-    protected function _update_registration_payments(
2054
-        EE_Transaction $transaction,
2055
-        EE_Payment $payment,
2056
-        $REG_IDs = array()
2057
-    ) {
2058
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2059
-        // so let's do that using our set of REG_IDs from the form
2060
-        $registration_query_where_params = array(
2061
-            'REG_ID' => array('IN', $REG_IDs),
2062
-        );
2063
-        // but add in some conditions regarding payment,
2064
-        // so that we don't apply payments to registrations that are free or have already been paid for
2065
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2066
-        if (! $payment->is_a_refund()) {
2067
-            $registration_query_where_params['REG_final_price'] = array('!=', 0);
2068
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2069
-        }
2070
-        $registrations = $transaction->registrations(array($registration_query_where_params));
2071
-        if (! empty($registrations)) {
2072
-            /** @type EE_Payment_Processor $payment_processor */
2073
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2074
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2075
-        }
2076
-    }
2077
-
2078
-
2079
-    /**
2080
-     * _process_registration_status_change
2081
-     * This processes requested registration status changes for all the registrations
2082
-     * on a given transaction and (optionally) sends out notifications for the changes.
2083
-     *
2084
-     * @param  EE_Transaction $transaction
2085
-     * @param array           $REG_IDs
2086
-     * @return bool
2087
-     * @throws EE_Error
2088
-     * @throws InvalidArgumentException
2089
-     * @throws ReflectionException
2090
-     * @throws InvalidDataTypeException
2091
-     * @throws InvalidInterfaceException
2092
-     */
2093
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2094
-    {
2095
-        // first if there is no change in status then we get out.
2096
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2097
-            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2098
-        ) {
2099
-            // no error message, no change requested, just nothing to do man.
2100
-            return false;
2101
-        }
2102
-        /** @type EE_Transaction_Processor $transaction_processor */
2103
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2104
-
2105
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2106
-        return $transaction_processor->manually_update_registration_statuses(
2107
-            $transaction,
2108
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2109
-            array(array('REG_ID' => array('IN', $REG_IDs)))
2110
-        );
2111
-    }
2112
-
2113
-
2114
-    /**
2115
-     * _build_payment_json_response
2116
-     *
2117
-     * @access public
2118
-     * @param \EE_Payment $payment
2119
-     * @param array       $REG_IDs
2120
-     * @param bool | null $delete_txn_reg_status_change
2121
-     * @return array
2122
-     * @throws EE_Error
2123
-     * @throws InvalidArgumentException
2124
-     * @throws InvalidDataTypeException
2125
-     * @throws InvalidInterfaceException
2126
-     * @throws ReflectionException
2127
-     */
2128
-    protected function _build_payment_json_response(
2129
-        EE_Payment $payment,
2130
-        $REG_IDs = array(),
2131
-        $delete_txn_reg_status_change = null
2132
-    ) {
2133
-        // was the payment deleted ?
2134
-        if (is_bool($delete_txn_reg_status_change)) {
2135
-            return array(
2136
-                'PAY_ID'                       => $payment->ID(),
2137
-                'amount'                       => $payment->amount(),
2138
-                'total_paid'                   => $payment->transaction()->paid(),
2139
-                'txn_status'                   => $payment->transaction()->status_ID(),
2140
-                'pay_status'                   => $payment->STS_ID(),
2141
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2142
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2143
-            );
2144
-        } else {
2145
-            $this->_get_payment_status_array();
2146
-
2147
-            return array(
2148
-                'amount'           => $payment->amount(),
2149
-                'total_paid'       => $payment->transaction()->paid(),
2150
-                'txn_status'       => $payment->transaction()->status_ID(),
2151
-                'pay_status'       => $payment->STS_ID(),
2152
-                'PAY_ID'           => $payment->ID(),
2153
-                'STS_ID'           => $payment->STS_ID(),
2154
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2155
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2156
-                'method'           => strtoupper($payment->source()),
2157
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2158
-                'gateway'          => $payment->payment_method()
2159
-                    ? $payment->payment_method()->admin_name()
2160
-                    : esc_html__("Unknown", 'event_espresso'),
2161
-                'gateway_response' => $payment->gateway_response(),
2162
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2163
-                'po_number'        => $payment->po_number(),
2164
-                'extra_accntng'    => $payment->extra_accntng(),
2165
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2166
-            );
2167
-        }
2168
-    }
2169
-
2170
-
2171
-    /**
2172
-     * delete_payment
2173
-     *    delete a payment or refund made towards a transaction
2174
-     *
2175
-     * @access public
2176
-     * @return void
2177
-     * @throws EE_Error
2178
-     * @throws InvalidArgumentException
2179
-     * @throws ReflectionException
2180
-     * @throws InvalidDataTypeException
2181
-     * @throws InvalidInterfaceException
2182
-     */
2183
-    public function delete_payment()
2184
-    {
2185
-        $json_response_data = array('return_data' => false);
2186
-        $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2187
-            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2188
-            : 0;
2189
-        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2190
-            'ee_delete_payments',
2191
-            'delete_payment_from_registration_details'
2192
-        );
2193
-        if ($PAY_ID && $can_delete) {
2194
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2195
-                ? $this->_req_data['delete_txn_reg_status_change']
2196
-                : false;
2197
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2198
-            if ($payment instanceof EE_Payment) {
2199
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2200
-                /** @type EE_Transaction_Payments $transaction_payments */
2201
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2202
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2203
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2204
-                        $payment,
2205
-                        $REG_IDs,
2206
-                        $delete_txn_reg_status_change
2207
-                    );
2208
-                    if ($delete_txn_reg_status_change) {
2209
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2210
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2211
-                        // $_REQUEST global because that's how messages will be looking for it.
2212
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2213
-                        $this->_maybe_send_notifications();
2214
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2215
-                    }
2216
-                }
2217
-            } else {
2218
-                EE_Error::add_error(
2219
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2220
-                    __FILE__,
2221
-                    __FUNCTION__,
2222
-                    __LINE__
2223
-                );
2224
-            }
2225
-        } else {
2226
-            if ($can_delete) {
2227
-                EE_Error::add_error(
2228
-                    esc_html__(
2229
-                        'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2230
-                        'event_espresso'
2231
-                    ),
2232
-                    __FILE__,
2233
-                    __FUNCTION__,
2234
-                    __LINE__
2235
-                );
2236
-            } else {
2237
-                EE_Error::add_error(
2238
-                    esc_html__(
2239
-                        'You do not have access to delete a payment.',
2240
-                        'event_espresso'
2241
-                    ),
2242
-                    __FILE__,
2243
-                    __FUNCTION__,
2244
-                    __LINE__
2245
-                );
2246
-            }
2247
-        }
2248
-        $notices = EE_Error::get_notices(false, false, false);
2249
-        $this->_template_args = array(
2250
-            'data'      => $json_response_data,
2251
-            'success'   => $notices['success'],
2252
-            'error'     => $notices['errors'],
2253
-            'attention' => $notices['attention'],
2254
-        );
2255
-        $this->_return_json();
2256
-    }
2257
-
2258
-
2259
-    /**
2260
-     * _registration_payment_data_array
2261
-     * adds info for 'owing' and 'paid' for each registration to the json response
2262
-     *
2263
-     * @access protected
2264
-     * @param array $REG_IDs
2265
-     * @return array
2266
-     * @throws EE_Error
2267
-     * @throws InvalidArgumentException
2268
-     * @throws InvalidDataTypeException
2269
-     * @throws InvalidInterfaceException
2270
-     * @throws ReflectionException
2271
-     */
2272
-    protected function _registration_payment_data_array($REG_IDs)
2273
-    {
2274
-        $registration_payment_data = array();
2275
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2276
-        if (! empty($REG_IDs)) {
2277
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2278
-            foreach ($registrations as $registration) {
2279
-                if ($registration instanceof EE_Registration) {
2280
-                    $registration_payment_data[ $registration->ID() ] = array(
2281
-                        'paid'  => $registration->pretty_paid(),
2282
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2283
-                    );
2284
-                }
2285
-            }
2286
-        }
2287
-
2288
-        return $registration_payment_data;
2289
-    }
2290
-
2291
-
2292
-    /**
2293
-     * _maybe_send_notifications
2294
-     * determines whether or not the admin has indicated that notifications should be sent.
2295
-     * If so, will toggle a filter switch for delivering registration notices.
2296
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2297
-     *
2298
-     * @access protected
2299
-     * @param \EE_Payment | null $payment
2300
-     */
2301
-    protected function _maybe_send_notifications($payment = null)
2302
-    {
2303
-        switch ($payment instanceof EE_Payment) {
2304
-            // payment notifications
2305
-            case true:
2306
-                if (isset(
2307
-                    $this->_req_data['txn_payments'],
2308
-                    $this->_req_data['txn_payments']['send_notifications']
2309
-                )
2310
-                    && filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2311
-                ) {
2312
-                    $this->_process_payment_notification($payment);
2313
-                }
2314
-                break;
2315
-            // registration notifications
2316
-            case false:
2317
-                if (isset(
2318
-                    $this->_req_data['txn_reg_status_change'],
2319
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
2320
-                )
2321
-                    && filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2322
-                ) {
2323
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2324
-                }
2325
-                break;
2326
-        }
2327
-    }
2328
-
2329
-
2330
-    /**
2331
-     * _send_payment_reminder
2332
-     *    generates HTML for the View Transaction Details Admin page
2333
-     *
2334
-     * @access protected
2335
-     * @return void
2336
-     * @throws EE_Error
2337
-     * @throws InvalidArgumentException
2338
-     * @throws InvalidDataTypeException
2339
-     * @throws InvalidInterfaceException
2340
-     */
2341
-    protected function _send_payment_reminder()
2342
-    {
2343
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2344
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2345
-        $query_args = isset($this->_req_data['redirect_to']) ? array(
2346
-            'action' => $this->_req_data['redirect_to'],
2347
-            'TXN_ID' => $this->_req_data['TXN_ID'],
2348
-        ) : array();
2349
-        do_action(
2350
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2351
-            $transaction
2352
-        );
2353
-        $this->_redirect_after_action(
2354
-            false,
2355
-            esc_html__('payment reminder', 'event_espresso'),
2356
-            esc_html__('sent', 'event_espresso'),
2357
-            $query_args,
2358
-            true
2359
-        );
2360
-    }
2361
-
2362
-
2363
-    /**
2364
-     *  get_transactions
2365
-     *    get transactions for given parameters (used by list table)
2366
-     *
2367
-     * @param  int     $perpage how many transactions displayed per page
2368
-     * @param  boolean $count   return the count or objects
2369
-     * @param string   $view
2370
-     * @return mixed int = count || array of transaction objects
2371
-     * @throws EE_Error
2372
-     * @throws InvalidArgumentException
2373
-     * @throws InvalidDataTypeException
2374
-     * @throws InvalidInterfaceException
2375
-     */
2376
-    public function get_transactions($perpage, $count = false, $view = '')
2377
-    {
2378
-
2379
-        $TXN = EEM_Transaction::instance();
2380
-
2381
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
2382
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2383
-            : date(
2384
-                'm/d/Y',
2385
-                strtotime('-10 year')
2386
-            );
2387
-        $end_date = isset($this->_req_data['txn-filter-end-date'])
2388
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2389
-            : date('m/d/Y');
2390
-
2391
-        // make sure our timestamps start and end right at the boundaries for each day
2392
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2393
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2394
-
2395
-
2396
-        // convert to timestamps
2397
-        $start_date = strtotime($start_date);
2398
-        $end_date = strtotime($end_date);
2399
-
2400
-        // makes sure start date is the lowest value and vice versa
2401
-        $start_date = min($start_date, $end_date);
2402
-        $end_date = max($start_date, $end_date);
2403
-
2404
-        // convert to correct format for query
2405
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2406
-            'TXN_timestamp',
2407
-            date('Y-m-d H:i:s', $start_date),
2408
-            'Y-m-d H:i:s'
2409
-        );
2410
-        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2411
-            'TXN_timestamp',
2412
-            date('Y-m-d H:i:s', $end_date),
2413
-            'Y-m-d H:i:s'
2414
-        );
2415
-
2416
-
2417
-        // set orderby
2418
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2419
-
2420
-        switch ($this->_req_data['orderby']) {
2421
-            case 'TXN_ID':
2422
-                $orderby = 'TXN_ID';
2423
-                break;
2424
-            case 'ATT_fname':
2425
-                $orderby = 'Registration.Attendee.ATT_fname';
2426
-                break;
2427
-            case 'event_name':
2428
-                $orderby = 'Registration.Event.EVT_name';
2429
-                break;
2430
-            default: // 'TXN_timestamp'
2431
-                $orderby = 'TXN_timestamp';
2432
-        }
2433
-
2434
-        $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2435
-        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2436
-        $per_page = ! empty($perpage) ? $perpage : 10;
2437
-        $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2438
-
2439
-        $offset = ($current_page - 1) * $per_page;
2440
-        $limit = array($offset, $per_page);
2441
-
2442
-        $_where = array(
2443
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2444
-            'Registration.REG_count' => 1,
2445
-        );
2446
-
2447
-        if (isset($this->_req_data['EVT_ID'])) {
2448
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2449
-        }
2450
-
2451
-        if (isset($this->_req_data['s'])) {
2452
-            $search_string = '%' . $this->_req_data['s'] . '%';
2453
-            $_where['OR'] = array(
2454
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2455
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2456
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2457
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2458
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2459
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2460
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2461
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2462
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2463
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2464
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2465
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
2466
-                'Registration.REG_code'               => array('LIKE', $search_string),
2467
-                'Registration.REG_count'              => array('LIKE', $search_string),
2468
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
2469
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2470
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2471
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
2472
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2473
-                'TXN_session_data'                    => array('LIKE', $search_string),
2474
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2475
-            );
2476
-        }
2477
-
2478
-        // failed transactions
2479
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2480
-                  || ($count && $view === 'failed');
2481
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2482
-                     || ($count && $view === 'abandoned');
2483
-        $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2484
-                      || ($count && $view === 'incomplete');
2485
-
2486
-        if ($failed) {
2487
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2488
-        } elseif ($abandoned) {
2489
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2490
-        } elseif ($incomplete) {
2491
-            $_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2492
-        } else {
2493
-            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2494
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2495
-        }
2496
-
2497
-        $query_params = apply_filters(
2498
-            'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2499
-            array(
2500
-                $_where,
2501
-                'order_by'                 => array($orderby => $sort),
2502
-                'limit'                    => $limit,
2503
-                'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2504
-            ),
2505
-            $this->_req_data,
2506
-            $view,
2507
-            $count
2508
-        );
2509
-
2510
-        $transactions = $count
2511
-            ? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2512
-            : $TXN->get_all($query_params);
2513
-
2514
-        return $transactions;
2515
-    }
17
+	/**
18
+	 * @var EE_Transaction
19
+	 */
20
+	private $_transaction;
21
+
22
+	/**
23
+	 * @var EE_Session
24
+	 */
25
+	private $_session;
26
+
27
+	/**
28
+	 * @var array $_txn_status
29
+	 */
30
+	private static $_txn_status;
31
+
32
+	/**
33
+	 * @var array $_pay_status
34
+	 */
35
+	private static $_pay_status;
36
+
37
+	/**
38
+	 * @var array $_existing_reg_payment_REG_IDs
39
+	 */
40
+	protected $_existing_reg_payment_REG_IDs = null;
41
+
42
+
43
+	/**
44
+	 * @Constructor
45
+	 * @access public
46
+	 * @param bool $routing
47
+	 * @throws EE_Error
48
+	 * @throws InvalidArgumentException
49
+	 * @throws ReflectionException
50
+	 * @throws InvalidDataTypeException
51
+	 * @throws InvalidInterfaceException
52
+	 */
53
+	public function __construct($routing = true)
54
+	{
55
+		parent::__construct($routing);
56
+	}
57
+
58
+
59
+	/**
60
+	 *    _init_page_props
61
+	 *
62
+	 * @return void
63
+	 */
64
+	protected function _init_page_props()
65
+	{
66
+		$this->page_slug = TXN_PG_SLUG;
67
+		$this->page_label = esc_html__('Transactions', 'event_espresso');
68
+		$this->_admin_base_url = TXN_ADMIN_URL;
69
+		$this->_admin_base_path = TXN_ADMIN;
70
+	}
71
+
72
+
73
+	/**
74
+	 *    _ajax_hooks
75
+	 *
76
+	 * @return void
77
+	 */
78
+	protected function _ajax_hooks()
79
+	{
80
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
+	}
84
+
85
+
86
+	/**
87
+	 *    _define_page_props
88
+	 *
89
+	 * @return void
90
+	 */
91
+	protected function _define_page_props()
92
+	{
93
+		$this->_admin_page_title = $this->page_label;
94
+		$this->_labels = array(
95
+			'buttons' => array(
96
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
+			),
100
+		);
101
+	}
102
+
103
+
104
+	/**
105
+	 *        grab url requests and route them
106
+	 *
107
+	 * @access private
108
+	 * @return void
109
+	 * @throws EE_Error
110
+	 * @throws InvalidArgumentException
111
+	 * @throws InvalidDataTypeException
112
+	 * @throws InvalidInterfaceException
113
+	 */
114
+	public function _set_page_routes()
115
+	{
116
+
117
+		$this->_set_transaction_status_array();
118
+
119
+		$txn_id = ! empty($this->_req_data['TXN_ID'])
120
+				  && ! is_array($this->_req_data['TXN_ID'])
121
+			? $this->_req_data['TXN_ID']
122
+			: 0;
123
+
124
+		$this->_page_routes = array(
125
+
126
+			'default' => array(
127
+				'func'       => '_transactions_overview_list_table',
128
+				'capability' => 'ee_read_transactions',
129
+			),
130
+
131
+			'view_transaction' => array(
132
+				'func'       => '_transaction_details',
133
+				'capability' => 'ee_read_transaction',
134
+				'obj_id'     => $txn_id,
135
+			),
136
+
137
+			'send_payment_reminder' => array(
138
+				'func'       => '_send_payment_reminder',
139
+				'noheader'   => true,
140
+				'capability' => 'ee_send_message',
141
+			),
142
+
143
+			'espresso_apply_payment' => array(
144
+				'func'       => 'apply_payments_or_refunds',
145
+				'noheader'   => true,
146
+				'capability' => 'ee_edit_payments',
147
+			),
148
+
149
+			'espresso_apply_refund' => array(
150
+				'func'       => 'apply_payments_or_refunds',
151
+				'noheader'   => true,
152
+				'capability' => 'ee_edit_payments',
153
+			),
154
+
155
+			'espresso_delete_payment' => array(
156
+				'func'       => 'delete_payment',
157
+				'noheader'   => true,
158
+				'capability' => 'ee_delete_payments',
159
+			),
160
+
161
+		);
162
+	}
163
+
164
+
165
+	protected function _set_page_config()
166
+	{
167
+		$this->_page_config = array(
168
+			'default'          => array(
169
+				'nav'           => array(
170
+					'label' => esc_html__('Overview', 'event_espresso'),
171
+					'order' => 10,
172
+				),
173
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
174
+				'help_tabs'     => array(
175
+					'transactions_overview_help_tab'                       => array(
176
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
+						'filename' => 'transactions_overview',
178
+					),
179
+					'transactions_overview_table_column_headings_help_tab' => array(
180
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
+						'filename' => 'transactions_overview_table_column_headings',
182
+					),
183
+					'transactions_overview_views_filters_help_tab'         => array(
184
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
+						'filename' => 'transactions_overview_views_filters_search',
186
+					),
187
+				),
188
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
+				/**
190
+				 * commented out because currently we are not displaying tips for transaction list table status but this
191
+				 * may change in a later iteration so want to keep the code for then.
192
+				 */
193
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
+				'require_nonce' => false,
195
+			),
196
+			'view_transaction' => array(
197
+				'nav'       => array(
198
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
199
+					'order'      => 5,
200
+					'url'        => isset($this->_req_data['TXN_ID'])
201
+						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
+						: $this->_admin_base_url,
203
+					'persistent' => false,
204
+				),
205
+				'help_tabs' => array(
206
+					'transactions_view_transaction_help_tab'                                              => array(
207
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
208
+						'filename' => 'transactions_view_transaction',
209
+					),
210
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
+						'filename' => 'transactions_view_transaction_transaction_details_table',
213
+					),
214
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
+						'filename' => 'transactions_view_transaction_attendees_registered',
217
+					),
218
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
+					),
222
+				),
223
+				'qtips'     => array('Transaction_Details_Tips'),
224
+				'help_tour' => array('Transaction_Details_Help_Tour'),
225
+				'metaboxes' => array('_transaction_details_metaboxes'),
226
+
227
+				'require_nonce' => false,
228
+			),
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * The below methods aren't used by this class currently
235
+	 */
236
+	protected function _add_screen_options()
237
+	{
238
+		// noop
239
+	}
240
+
241
+	protected function _add_feature_pointers()
242
+	{
243
+		// noop
244
+	}
245
+
246
+	public function admin_init()
247
+	{
248
+		// IF a registration was JUST added via the admin...
249
+		if (isset(
250
+			$this->_req_data['redirect_from'],
251
+			$this->_req_data['EVT_ID'],
252
+			$this->_req_data['event_name']
253
+		)) {
254
+			// then set a cookie so that we can block any attempts to use
255
+			// the back button as a way to enter another registration.
256
+			setcookie(
257
+				'ee_registration_added',
258
+				$this->_req_data['EVT_ID'],
259
+				time() + WEEK_IN_SECONDS,
260
+				'/'
261
+			);
262
+			// and update the global
263
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
+		}
265
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
+			'event_espresso'
268
+		);
269
+		EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
+			'An error occurred! Please refresh the page and try again.',
271
+			'event_espresso'
272
+		);
273
+		EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
+		EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
+		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
+		EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
+			'This transaction has been overpaid ! Payments Total',
278
+			'event_espresso'
279
+		);
280
+	}
281
+
282
+	public function admin_notices()
283
+	{
284
+		// noop
285
+	}
286
+
287
+	public function admin_footer_scripts()
288
+	{
289
+		// noop
290
+	}
291
+
292
+
293
+	/**
294
+	 * _set_transaction_status_array
295
+	 * sets list of transaction statuses
296
+	 *
297
+	 * @access private
298
+	 * @return void
299
+	 * @throws EE_Error
300
+	 * @throws InvalidArgumentException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws InvalidInterfaceException
303
+	 */
304
+	private function _set_transaction_status_array()
305
+	{
306
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
+	}
308
+
309
+
310
+	/**
311
+	 * get_transaction_status_array
312
+	 * return the transaction status array for wp_list_table
313
+	 *
314
+	 * @access public
315
+	 * @return array
316
+	 */
317
+	public function get_transaction_status_array()
318
+	{
319
+		return self::$_txn_status;
320
+	}
321
+
322
+
323
+	/**
324
+	 *    get list of payment statuses
325
+	 *
326
+	 * @access private
327
+	 * @return void
328
+	 * @throws EE_Error
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidDataTypeException
331
+	 * @throws InvalidInterfaceException
332
+	 */
333
+	private function _get_payment_status_array()
334
+	{
335
+		self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
+		$this->_template_args['payment_status'] = self::$_pay_status;
337
+	}
338
+
339
+
340
+	/**
341
+	 *    _add_screen_options_default
342
+	 *
343
+	 * @access protected
344
+	 * @return void
345
+	 * @throws InvalidArgumentException
346
+	 * @throws InvalidDataTypeException
347
+	 * @throws InvalidInterfaceException
348
+	 */
349
+	protected function _add_screen_options_default()
350
+	{
351
+		$this->_per_page_screen_option();
352
+	}
353
+
354
+
355
+	/**
356
+	 * load_scripts_styles
357
+	 *
358
+	 * @access public
359
+	 * @return void
360
+	 */
361
+	public function load_scripts_styles()
362
+	{
363
+		// enqueue style
364
+		wp_register_style(
365
+			'espresso_txn',
366
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
+			array(),
368
+			EVENT_ESPRESSO_VERSION
369
+		);
370
+		wp_enqueue_style('espresso_txn');
371
+		// scripts
372
+		wp_register_script(
373
+			'espresso_txn',
374
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
+			array(
376
+				'ee_admin_js',
377
+				'ee-datepicker',
378
+				'jquery-ui-datepicker',
379
+				'jquery-ui-draggable',
380
+				'ee-dialog',
381
+				'ee-accounting',
382
+				'ee-serialize-full-array',
383
+			),
384
+			EVENT_ESPRESSO_VERSION,
385
+			true
386
+		);
387
+		wp_enqueue_script('espresso_txn');
388
+	}
389
+
390
+
391
+	/**
392
+	 *    load_scripts_styles_view_transaction
393
+	 *
394
+	 * @access public
395
+	 * @return void
396
+	 */
397
+	public function load_scripts_styles_view_transaction()
398
+	{
399
+		// styles
400
+		wp_enqueue_style('espresso-ui-theme');
401
+	}
402
+
403
+
404
+	/**
405
+	 *    load_scripts_styles_default
406
+	 *
407
+	 * @access public
408
+	 * @return void
409
+	 */
410
+	public function load_scripts_styles_default()
411
+	{
412
+		// styles
413
+		wp_enqueue_style('espresso-ui-theme');
414
+	}
415
+
416
+
417
+	/**
418
+	 *    _set_list_table_views_default
419
+	 *
420
+	 * @access protected
421
+	 * @return void
422
+	 */
423
+	protected function _set_list_table_views_default()
424
+	{
425
+		$this->_views = array(
426
+			'all'       => array(
427
+				'slug'  => 'all',
428
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
429
+				'count' => 0,
430
+			),
431
+			'abandoned' => array(
432
+				'slug'  => 'abandoned',
433
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
+				'count' => 0,
435
+			),
436
+			'incomplete' => array(
437
+				'slug'  => 'incomplete',
438
+				'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
439
+				'count' => 0,
440
+			)
441
+		);
442
+		if (/**
443
+		 * Filters whether a link to the "Failed Transactions" list table
444
+		 * appears on the Transactions Admin Page list table.
445
+		 * List display can be turned back on via the following:
446
+		 * add_filter(
447
+		 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
448
+		 *     '__return_true'
449
+		 * );
450
+		 *
451
+		 * @since 4.9.70.p
452
+		 * @param boolean                 $display_failed_txns_list
453
+		 * @param Transactions_Admin_Page $this
454
+		 */
455
+			apply_filters(
456
+				'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
457
+				false,
458
+				$this
459
+			)
460
+		) {
461
+			$this->_views['failed'] = array(
462
+				'slug'  => 'failed',
463
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
464
+				'count' => 0,
465
+			);
466
+		}
467
+	}
468
+
469
+
470
+	/**
471
+	 * _set_transaction_object
472
+	 * This sets the _transaction property for the transaction details screen
473
+	 *
474
+	 * @access private
475
+	 * @return void
476
+	 * @throws EE_Error
477
+	 * @throws InvalidArgumentException
478
+	 * @throws RuntimeException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws InvalidInterfaceException
481
+	 * @throws ReflectionException
482
+	 */
483
+	private function _set_transaction_object()
484
+	{
485
+		if ($this->_transaction instanceof EE_Transaction) {
486
+			return;
487
+		} //get out we've already set the object
488
+
489
+		$TXN_ID = ! empty($this->_req_data['TXN_ID'])
490
+			? absint($this->_req_data['TXN_ID'])
491
+			: false;
492
+
493
+		// get transaction object
494
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
495
+		$this->_session = $this->_transaction instanceof EE_Transaction
496
+			? $this->_transaction->get('TXN_session_data')
497
+			: null;
498
+		if ($this->_transaction instanceof EE_Transaction) {
499
+			$this->_transaction->verify_abandoned_transaction_status();
500
+		}
501
+
502
+		if (! $this->_transaction instanceof EE_Transaction) {
503
+			$error_msg = sprintf(
504
+				esc_html__(
505
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
506
+					'event_espresso'
507
+				),
508
+				$TXN_ID
509
+			);
510
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
511
+		}
512
+	}
513
+
514
+
515
+	/**
516
+	 *    _transaction_legend_items
517
+	 *
518
+	 * @access protected
519
+	 * @return array
520
+	 * @throws EE_Error
521
+	 * @throws InvalidArgumentException
522
+	 * @throws ReflectionException
523
+	 * @throws InvalidDataTypeException
524
+	 * @throws InvalidInterfaceException
525
+	 */
526
+	protected function _transaction_legend_items()
527
+	{
528
+		EE_Registry::instance()->load_helper('MSG_Template');
529
+		$items = array();
530
+
531
+		if (EE_Registry::instance()->CAP->current_user_can(
532
+			'ee_read_global_messages',
533
+			'view_filtered_messages'
534
+		)) {
535
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
536
+			if (is_array($related_for_icon)
537
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
538
+			) {
539
+				$items['view_related_messages'] = array(
540
+					'class' => $related_for_icon['css_class'],
541
+					'desc'  => $related_for_icon['label'],
542
+				);
543
+			}
544
+		}
545
+
546
+		$items = apply_filters(
547
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
548
+			array_merge(
549
+				$items,
550
+				array(
551
+					'view_details'          => array(
552
+						'class' => 'dashicons dashicons-cart',
553
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
554
+					),
555
+					'view_invoice'          => array(
556
+						'class' => 'dashicons dashicons-media-spreadsheet',
557
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
558
+					),
559
+					'view_receipt'          => array(
560
+						'class' => 'dashicons dashicons-media-default',
561
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
562
+					),
563
+					'view_registration'     => array(
564
+						'class' => 'dashicons dashicons-clipboard',
565
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
566
+					),
567
+					'payment_overview_link' => array(
568
+						'class' => 'dashicons dashicons-money',
569
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
570
+					),
571
+				)
572
+			)
573
+		);
574
+
575
+		if (EE_Registry::instance()->CAP->current_user_can(
576
+			'ee_send_message',
577
+			'espresso_transactions_send_payment_reminder'
578
+		)) {
579
+			if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
580
+				$items['send_payment_reminder'] = array(
581
+					'class' => 'dashicons dashicons-email-alt',
582
+					'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
583
+				);
584
+			} else {
585
+				$items['blank*'] = array(
586
+					'class' => '',
587
+					'desc'  => '',
588
+				);
589
+			}
590
+		} else {
591
+			$items['blank*'] = array(
592
+				'class' => '',
593
+				'desc'  => '',
594
+			);
595
+		}
596
+		$more_items = apply_filters(
597
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
598
+			array(
599
+				'overpaid'   => array(
600
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
601
+					'desc'  => EEH_Template::pretty_status(
602
+						EEM_Transaction::overpaid_status_code,
603
+						false,
604
+						'sentence'
605
+					),
606
+				),
607
+				'complete'   => array(
608
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
609
+					'desc'  => EEH_Template::pretty_status(
610
+						EEM_Transaction::complete_status_code,
611
+						false,
612
+						'sentence'
613
+					),
614
+				),
615
+				'incomplete' => array(
616
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
617
+					'desc'  => EEH_Template::pretty_status(
618
+						EEM_Transaction::incomplete_status_code,
619
+						false,
620
+						'sentence'
621
+					),
622
+				),
623
+				'abandoned'  => array(
624
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
625
+					'desc'  => EEH_Template::pretty_status(
626
+						EEM_Transaction::abandoned_status_code,
627
+						false,
628
+						'sentence'
629
+					),
630
+				),
631
+				'failed'     => array(
632
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
633
+					'desc'  => EEH_Template::pretty_status(
634
+						EEM_Transaction::failed_status_code,
635
+						false,
636
+						'sentence'
637
+					),
638
+				),
639
+			)
640
+		);
641
+
642
+		return array_merge($items, $more_items);
643
+	}
644
+
645
+
646
+	/**
647
+	 *    _transactions_overview_list_table
648
+	 *
649
+	 * @access protected
650
+	 * @return void
651
+	 * @throws DomainException
652
+	 * @throws EE_Error
653
+	 * @throws InvalidArgumentException
654
+	 * @throws InvalidDataTypeException
655
+	 * @throws InvalidInterfaceException
656
+	 * @throws ReflectionException
657
+	 */
658
+	protected function _transactions_overview_list_table()
659
+	{
660
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
661
+		$event = isset($this->_req_data['EVT_ID'])
662
+			? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
663
+			: null;
664
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
665
+			? sprintf(
666
+				esc_html__(
667
+					'%sViewing Transactions for the Event: %s%s',
668
+					'event_espresso'
669
+				),
670
+				'<h3>',
671
+				'<a href="'
672
+				. EE_Admin_Page::add_query_args_and_nonce(
673
+					array('action' => 'edit', 'post' => $event->ID()),
674
+					EVENTS_ADMIN_URL
675
+				)
676
+				. '" title="'
677
+				. esc_attr__(
678
+					'Click to Edit event',
679
+					'event_espresso'
680
+				)
681
+				. '">' . $event->get('EVT_name') . '</a>',
682
+				'</h3>'
683
+			)
684
+			: '';
685
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
686
+		$this->display_admin_list_table_page_with_no_sidebar();
687
+	}
688
+
689
+
690
+	/**
691
+	 *    _transaction_details
692
+	 * generates HTML for the View Transaction Details Admin page
693
+	 *
694
+	 * @access protected
695
+	 * @return void
696
+	 * @throws DomainException
697
+	 * @throws EE_Error
698
+	 * @throws InvalidArgumentException
699
+	 * @throws InvalidDataTypeException
700
+	 * @throws InvalidInterfaceException
701
+	 * @throws RuntimeException
702
+	 * @throws ReflectionException
703
+	 */
704
+	protected function _transaction_details()
705
+	{
706
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
707
+
708
+		$this->_set_transaction_status_array();
709
+
710
+		$this->_template_args = array();
711
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
712
+
713
+		$this->_set_transaction_object();
714
+
715
+		if (! $this->_transaction instanceof EE_Transaction) {
716
+			return;
717
+		}
718
+		$primary_registration = $this->_transaction->primary_registration();
719
+		$attendee = $primary_registration instanceof EE_Registration
720
+			? $primary_registration->attendee()
721
+			: null;
722
+
723
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
724
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
725
+
726
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
727
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
728
+
729
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
730
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
731
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
732
+
733
+		$this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
734
+		$this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
735
+
736
+		$amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
737
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
738
+			$amount_due,
739
+			true
740
+		);
741
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
742
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
743
+												  . $this->_template_args['amount_due'];
744
+		} else {
745
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
746
+		}
747
+		$this->_template_args['amount_due_class'] = '';
748
+
749
+		if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
750
+			// paid in full
751
+			$this->_template_args['amount_due'] = false;
752
+		} elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
753
+			// overpaid
754
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
755
+		} elseif ($this->_transaction->get('TXN_total') > 0
756
+				  && $this->_transaction->get('TXN_paid') > 0
757
+		) {
758
+			// monies owing
759
+			$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
760
+		} elseif ($this->_transaction->get('TXN_total') > 0
761
+				  && $this->_transaction->get('TXN_paid') == 0
762
+		) {
763
+			// no payments made yet
764
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
765
+		} elseif ($this->_transaction->get('TXN_total') == 0) {
766
+			// free event
767
+			$this->_template_args['amount_due'] = false;
768
+		}
769
+
770
+		$payment_method = $this->_transaction->payment_method();
771
+
772
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
773
+			? $payment_method->admin_name()
774
+			: esc_html__('Unknown', 'event_espresso');
775
+
776
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
777
+		// link back to overview
778
+		$this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
779
+			? $_SERVER['HTTP_REFERER']
780
+			: TXN_ADMIN_URL;
781
+
782
+
783
+		// next link
784
+		$next_txn = $this->_transaction->next(
785
+			null,
786
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
787
+			'TXN_ID'
788
+		);
789
+		$this->_template_args['next_transaction'] = $next_txn
790
+			? $this->_next_link(
791
+				EE_Admin_Page::add_query_args_and_nonce(
792
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
793
+					TXN_ADMIN_URL
794
+				),
795
+				'dashicons dashicons-arrow-right ee-icon-size-22'
796
+			)
797
+			: '';
798
+		// previous link
799
+		$previous_txn = $this->_transaction->previous(
800
+			null,
801
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
802
+			'TXN_ID'
803
+		);
804
+		$this->_template_args['previous_transaction'] = $previous_txn
805
+			? $this->_previous_link(
806
+				EE_Admin_Page::add_query_args_and_nonce(
807
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
808
+					TXN_ADMIN_URL
809
+				),
810
+				'dashicons dashicons-arrow-left ee-icon-size-22'
811
+			)
812
+			: '';
813
+
814
+		// were we just redirected here after adding a new registration ???
815
+		if (isset(
816
+			$this->_req_data['redirect_from'],
817
+			$this->_req_data['EVT_ID'],
818
+			$this->_req_data['event_name']
819
+		)) {
820
+			if (EE_Registry::instance()->CAP->current_user_can(
821
+				'ee_edit_registrations',
822
+				'espresso_registrations_new_registration',
823
+				$this->_req_data['EVT_ID']
824
+			)) {
825
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
826
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
827
+					array(
828
+						'page'     => 'espresso_registrations',
829
+						'action'   => 'new_registration',
830
+						'return'   => 'default',
831
+						'TXN_ID'   => $this->_transaction->ID(),
832
+						'event_id' => $this->_req_data['EVT_ID'],
833
+					),
834
+					REG_ADMIN_URL
835
+				);
836
+				$this->_admin_page_title .= '">';
837
+
838
+				$this->_admin_page_title .= sprintf(
839
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
840
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
841
+				);
842
+				$this->_admin_page_title .= '</a>';
843
+			}
844
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
845
+		}
846
+		// grab messages at the last second
847
+		$this->_template_args['notices'] = EE_Error::get_notices();
848
+		// path to template
849
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
850
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
851
+			$template_path,
852
+			$this->_template_args,
853
+			true
854
+		);
855
+
856
+		// the details template wrapper
857
+		$this->display_admin_page_with_sidebar();
858
+	}
859
+
860
+
861
+	/**
862
+	 *        _transaction_details_metaboxes
863
+	 *
864
+	 * @access protected
865
+	 * @return void
866
+	 * @throws EE_Error
867
+	 * @throws InvalidArgumentException
868
+	 * @throws InvalidDataTypeException
869
+	 * @throws InvalidInterfaceException
870
+	 * @throws RuntimeException
871
+	 * @throws ReflectionException
872
+	 */
873
+	protected function _transaction_details_metaboxes()
874
+	{
875
+
876
+		$this->_set_transaction_object();
877
+
878
+		if (! $this->_transaction instanceof EE_Transaction) {
879
+			return;
880
+		}
881
+		add_meta_box(
882
+			'edit-txn-details-mbox',
883
+			esc_html__('Transaction Details', 'event_espresso'),
884
+			array($this, 'txn_details_meta_box'),
885
+			$this->_wp_page_slug,
886
+			'normal',
887
+			'high'
888
+		);
889
+		add_meta_box(
890
+			'edit-txn-attendees-mbox',
891
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
892
+			array($this, 'txn_attendees_meta_box'),
893
+			$this->_wp_page_slug,
894
+			'normal',
895
+			'high',
896
+			array('TXN_ID' => $this->_transaction->ID())
897
+		);
898
+		add_meta_box(
899
+			'edit-txn-registrant-mbox',
900
+			esc_html__('Primary Contact', 'event_espresso'),
901
+			array($this, 'txn_registrant_side_meta_box'),
902
+			$this->_wp_page_slug,
903
+			'side',
904
+			'high'
905
+		);
906
+		add_meta_box(
907
+			'edit-txn-billing-info-mbox',
908
+			esc_html__('Billing Information', 'event_espresso'),
909
+			array($this, 'txn_billing_info_side_meta_box'),
910
+			$this->_wp_page_slug,
911
+			'side',
912
+			'high'
913
+		);
914
+	}
915
+
916
+
917
+	/**
918
+	 * Callback for transaction actions metabox.
919
+	 *
920
+	 * @param EE_Transaction|null $transaction
921
+	 * @throws DomainException
922
+	 * @throws EE_Error
923
+	 * @throws InvalidArgumentException
924
+	 * @throws InvalidDataTypeException
925
+	 * @throws InvalidInterfaceException
926
+	 * @throws ReflectionException
927
+	 * @throws RuntimeException
928
+	 */
929
+	public function getActionButtons(EE_Transaction $transaction = null)
930
+	{
931
+		$content = '';
932
+		$actions = array();
933
+		if (! $transaction instanceof EE_Transaction) {
934
+			return $content;
935
+		}
936
+		/** @var EE_Registration $primary_registration */
937
+		$primary_registration = $transaction->primary_registration();
938
+		$attendee = $primary_registration instanceof EE_Registration
939
+			? $primary_registration->attendee()
940
+			: null;
941
+
942
+		if ($attendee instanceof EE_Attendee
943
+			&& EE_Registry::instance()->CAP->current_user_can(
944
+				'ee_send_message',
945
+				'espresso_transactions_send_payment_reminder'
946
+			)
947
+		) {
948
+			$actions['payment_reminder'] =
949
+				EEH_MSG_Template::is_mt_active('payment_reminder')
950
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
951
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
952
+					? EEH_Template::get_button_or_link(
953
+						EE_Admin_Page::add_query_args_and_nonce(
954
+							array(
955
+								'action'      => 'send_payment_reminder',
956
+								'TXN_ID'      => $this->_transaction->ID(),
957
+								'redirect_to' => 'view_transaction',
958
+							),
959
+							TXN_ADMIN_URL
960
+						),
961
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
962
+						'button secondary-button',
963
+						'dashicons dashicons-email-alt'
964
+					)
965
+					: '';
966
+		}
967
+
968
+		if ($primary_registration instanceof EE_Registration
969
+			&& EEH_MSG_Template::is_mt_active('receipt')
970
+		) {
971
+			$actions['receipt'] = EEH_Template::get_button_or_link(
972
+				$primary_registration->receipt_url(),
973
+				esc_html__('View Receipt', 'event_espresso'),
974
+				'button secondary-button',
975
+				'dashicons dashicons-media-default'
976
+			);
977
+		}
978
+
979
+		if ($primary_registration instanceof EE_Registration
980
+			&& EEH_MSG_Template::is_mt_active('invoice')
981
+		) {
982
+			$actions['invoice'] = EEH_Template::get_button_or_link(
983
+				$primary_registration->invoice_url(),
984
+				esc_html__('View Invoice', 'event_espresso'),
985
+				'button secondary-button',
986
+				'dashicons dashicons-media-spreadsheet'
987
+			);
988
+		}
989
+		$actions = array_filter(
990
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
991
+		);
992
+		if ($actions) {
993
+			$content = '<ul>';
994
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
995
+			$content .= '</uL>';
996
+		}
997
+		return $content;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * txn_details_meta_box
1003
+	 * generates HTML for the Transaction main meta box
1004
+	 *
1005
+	 * @return void
1006
+	 * @throws DomainException
1007
+	 * @throws EE_Error
1008
+	 * @throws InvalidArgumentException
1009
+	 * @throws InvalidDataTypeException
1010
+	 * @throws InvalidInterfaceException
1011
+	 * @throws RuntimeException
1012
+	 * @throws ReflectionException
1013
+	 */
1014
+	public function txn_details_meta_box()
1015
+	{
1016
+		$this->_set_transaction_object();
1017
+		$this->_template_args['TXN_ID'] = $this->_transaction->ID();
1018
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1019
+			? $this->_transaction->primary_registration()->attendee()
1020
+			: null;
1021
+		$this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
+			'ee_edit_payments',
1023
+			'apply_payment_or_refund_from_registration_details'
1024
+		);
1025
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1026
+			'ee_delete_payments',
1027
+			'delete_payment_from_registration_details'
1028
+		);
1029
+
1030
+		// get line table
1031
+		EEH_Autoloader::register_line_item_display_autoloaders();
1032
+		$Line_Item_Display = new EE_Line_Item_Display(
1033
+			'admin_table',
1034
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1035
+		);
1036
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1037
+			$this->_transaction->total_line_item()
1038
+		);
1039
+		$this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1040
+															   ->get('REG_code');
1041
+
1042
+		// process taxes
1043
+		$taxes = $this->_transaction->get_many_related(
1044
+			'Line_Item',
1045
+			array(array('LIN_type' => EEM_Line_Item::type_tax))
1046
+		);
1047
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1048
+
1049
+		$this->_template_args['grand_total'] = EEH_Template::format_currency(
1050
+			$this->_transaction->get('TXN_total'),
1051
+			false,
1052
+			false
1053
+		);
1054
+		$this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1055
+		$this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1056
+
1057
+		// process payment details
1058
+		$payments = $this->_transaction->get_many_related('Payment');
1059
+		if (! empty($payments)) {
1060
+			$this->_template_args['payments'] = $payments;
1061
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1062
+		} else {
1063
+			$this->_template_args['payments'] = false;
1064
+			$this->_template_args['existing_reg_payments'] = array();
1065
+		}
1066
+
1067
+		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1068
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1069
+			array('action' => 'espresso_delete_payment'),
1070
+			TXN_ADMIN_URL
1071
+		);
1072
+
1073
+		if (isset($txn_details['invoice_number'])) {
1074
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1075
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1076
+				'Invoice Number',
1077
+				'event_espresso'
1078
+			);
1079
+		}
1080
+
1081
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1082
+			->get_first_related('Registration')
1083
+			->get('REG_session');
1084
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1085
+			'Registration Session',
1086
+			'event_espresso'
1087
+		);
1088
+
1089
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1090
+			? $this->_session['ip_address']
1091
+			: '';
1092
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1093
+			'Transaction placed from IP',
1094
+			'event_espresso'
1095
+		);
1096
+
1097
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1098
+			? $this->_session['user_agent']
1099
+			: '';
1100
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1101
+			'Registrant User Agent',
1102
+			'event_espresso'
1103
+		);
1104
+
1105
+		$reg_steps = '<ul>';
1106
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1107
+			if ($reg_step_status === true) {
1108
+				$reg_steps .= '<li style="color:#70cc50">'
1109
+							  . sprintf(
1110
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1111
+								  ucwords(str_replace('_', ' ', $reg_step))
1112
+							  )
1113
+							  . '</li>';
1114
+			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1115
+				$reg_steps .= '<li style="color:#2EA2CC">'
1116
+							  . sprintf(
1117
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1118
+								  ucwords(str_replace('_', ' ', $reg_step)),
1119
+								  date(
1120
+									  get_option('date_format') . ' ' . get_option('time_format'),
1121
+									  ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1122
+								  )
1123
+							  )
1124
+							  . '</li>';
1125
+			} else {
1126
+				$reg_steps .= '<li style="color:#E76700">'
1127
+							  . sprintf(
1128
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1129
+								  ucwords(str_replace('_', ' ', $reg_step))
1130
+							  )
1131
+							  . '</li>';
1132
+			}
1133
+		}
1134
+		$reg_steps .= '</ul>';
1135
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1136
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1137
+			'Registration Step Progress',
1138
+			'event_espresso'
1139
+		);
1140
+
1141
+
1142
+		$this->_get_registrations_to_apply_payment_to();
1143
+		$this->_get_payment_methods($payments);
1144
+		$this->_get_payment_status_array();
1145
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1146
+
1147
+		$this->_template_args['transaction_form_url'] = add_query_arg(
1148
+			array(
1149
+				'action'  => 'edit_transaction',
1150
+				'process' => 'transaction',
1151
+			),
1152
+			TXN_ADMIN_URL
1153
+		);
1154
+		$this->_template_args['apply_payment_form_url'] = add_query_arg(
1155
+			array(
1156
+				'page'   => 'espresso_transactions',
1157
+				'action' => 'espresso_apply_payment',
1158
+			),
1159
+			WP_AJAX_URL
1160
+		);
1161
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1162
+			array(
1163
+				'page'   => 'espresso_transactions',
1164
+				'action' => 'espresso_delete_payment',
1165
+			),
1166
+			WP_AJAX_URL
1167
+		);
1168
+
1169
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1170
+
1171
+		// 'espresso_delete_payment_nonce'
1172
+
1173
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1174
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * _get_registration_payment_IDs
1180
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1181
+	 *
1182
+	 * @access protected
1183
+	 * @param EE_Payment[] $payments
1184
+	 * @return array
1185
+	 * @throws EE_Error
1186
+	 * @throws InvalidArgumentException
1187
+	 * @throws InvalidDataTypeException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws ReflectionException
1190
+	 */
1191
+	protected function _get_registration_payment_IDs($payments = array())
1192
+	{
1193
+		$existing_reg_payments = array();
1194
+		// get all reg payments for these payments
1195
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1196
+			array(
1197
+				array(
1198
+					'PAY_ID' => array(
1199
+						'IN',
1200
+						array_keys($payments),
1201
+					),
1202
+				),
1203
+			)
1204
+		);
1205
+		if (! empty($reg_payments)) {
1206
+			foreach ($payments as $payment) {
1207
+				if (! $payment instanceof EE_Payment) {
1208
+					continue;
1209
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1210
+					$existing_reg_payments[ $payment->ID() ] = array();
1211
+				}
1212
+				foreach ($reg_payments as $reg_payment) {
1213
+					if ($reg_payment instanceof EE_Registration_Payment
1214
+						&& $reg_payment->payment_ID() === $payment->ID()
1215
+					) {
1216
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1217
+					}
1218
+				}
1219
+			}
1220
+		}
1221
+
1222
+		return $existing_reg_payments;
1223
+	}
1224
+
1225
+
1226
+	/**
1227
+	 * _get_registrations_to_apply_payment_to
1228
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1229
+	 * which allows the admin to only apply the payment to the specific registrations
1230
+	 *
1231
+	 * @access protected
1232
+	 * @return void
1233
+	 * @throws \EE_Error
1234
+	 */
1235
+	protected function _get_registrations_to_apply_payment_to()
1236
+	{
1237
+		// we want any registration with an active status (ie: not deleted or cancelled)
1238
+		$query_params = array(
1239
+			array(
1240
+				'STS_ID' => array(
1241
+					'IN',
1242
+					array(
1243
+						EEM_Registration::status_id_approved,
1244
+						EEM_Registration::status_id_pending_payment,
1245
+						EEM_Registration::status_id_not_approved,
1246
+					),
1247
+				),
1248
+			),
1249
+		);
1250
+		$registrations_to_apply_payment_to = EEH_HTML::br()
1251
+											 . EEH_HTML::div(
1252
+												 '',
1253
+												 'txn-admin-apply-payment-to-registrations-dv',
1254
+												 '',
1255
+												 'clear: both; margin: 1.5em 0 0; display: none;'
1256
+											 );
1257
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1258
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1259
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1260
+			EEH_HTML::tr(
1261
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1262
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1263
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1264
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1265
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1266
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1267
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1268
+			)
1269
+		);
1270
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1271
+		// get registrations for TXN
1272
+		$registrations = $this->_transaction->registrations($query_params);
1273
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1274
+		foreach ($registrations as $registration) {
1275
+			if ($registration instanceof EE_Registration) {
1276
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
1277
+					? $registration->attendee()->full_name()
1278
+					: esc_html__('Unknown Attendee', 'event_espresso');
1279
+				$owing = $registration->final_price() - $registration->paid();
1280
+				$taxable = $registration->ticket()->taxable()
1281
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1282
+					: '';
1283
+				$checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1284
+					? ' checked="checked"'
1285
+					: '';
1286
+				$disabled = $registration->final_price() > 0 ? '' : ' disabled';
1287
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
+					EEH_HTML::td($registration->ID()) .
1289
+					EEH_HTML::td($attendee_name) .
1290
+					EEH_HTML::td(
1291
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
+					) .
1293
+					EEH_HTML::td($registration->event_name()) .
1294
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1295
+					EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1296
+					EEH_HTML::td(
1297
+						'<input type="checkbox" value="' . $registration->ID()
1298
+						. '" name="txn_admin_payment[registrations]"'
1299
+						. $checked . $disabled . '>',
1300
+						'',
1301
+						'jst-cntr'
1302
+					),
1303
+					'apply-payment-registration-row-' . $registration->ID()
1304
+				);
1305
+			}
1306
+		}
1307
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1308
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1309
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1310
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1311
+			esc_html__(
1312
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1313
+				'event_espresso'
1314
+			),
1315
+			'',
1316
+			'clear description'
1317
+		);
1318
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1319
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * _get_reg_status_selection
1325
+	 *
1326
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1327
+	 *         instead of events.
1328
+	 * @access protected
1329
+	 * @return void
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	protected function _get_reg_status_selection()
1333
+	{
1334
+		// first get all possible statuses
1335
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1336
+		// let's add a "don't change" option.
1337
+		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1338
+		$status_array = array_merge($status_array, $statuses);
1339
+		$this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1340
+			'txn_reg_status_change[reg_status]',
1341
+			$status_array,
1342
+			'NAN',
1343
+			'id="txn-admin-payment-reg-status-inp"',
1344
+			'txn-reg-status-change-reg-status'
1345
+		);
1346
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1347
+			'delete_txn_reg_status_change[reg_status]',
1348
+			$status_array,
1349
+			'NAN',
1350
+			'delete-txn-admin-payment-reg-status-inp',
1351
+			'delete-txn-reg-status-change-reg-status'
1352
+		);
1353
+	}
1354
+
1355
+
1356
+	/**
1357
+	 *    _get_payment_methods
1358
+	 * Gets all the payment methods available generally, or the ones that are already
1359
+	 * selected on these payments (in case their payment methods are no longer active).
1360
+	 * Has the side-effect of updating the template args' payment_methods item
1361
+	 *
1362
+	 * @access private
1363
+	 * @param EE_Payment[] to show on this page
1364
+	 * @return void
1365
+	 * @throws EE_Error
1366
+	 * @throws InvalidArgumentException
1367
+	 * @throws InvalidDataTypeException
1368
+	 * @throws InvalidInterfaceException
1369
+	 * @throws ReflectionException
1370
+	 */
1371
+	private function _get_payment_methods($payments = array())
1372
+	{
1373
+		$payment_methods_of_payments = array();
1374
+		foreach ($payments as $payment) {
1375
+			if ($payment instanceof EE_Payment) {
1376
+				$payment_methods_of_payments[] = $payment->get('PMD_ID');
1377
+			}
1378
+		}
1379
+		if ($payment_methods_of_payments) {
1380
+			$query_args = array(
1381
+				array(
1382
+					'OR*payment_method_for_payment' => array(
1383
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1384
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1385
+					),
1386
+				),
1387
+			);
1388
+		} else {
1389
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1390
+		}
1391
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * txn_attendees_meta_box
1397
+	 *    generates HTML for the Attendees Transaction main meta box
1398
+	 *
1399
+	 * @access public
1400
+	 * @param WP_Post $post
1401
+	 * @param array   $metabox
1402
+	 * @return void
1403
+	 * @throws DomainException
1404
+	 * @throws EE_Error
1405
+	 */
1406
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1407
+	{
1408
+
1409
+		/** @noinspection NonSecureExtractUsageInspection */
1410
+		extract($metabox['args']);
1411
+		$this->_template_args['post'] = $post;
1412
+		$this->_template_args['event_attendees'] = array();
1413
+		// process items in cart
1414
+		$line_items = $this->_transaction->get_many_related(
1415
+			'Line_Item',
1416
+			array(array('LIN_type' => 'line-item'))
1417
+		);
1418
+		if (! empty($line_items)) {
1419
+			foreach ($line_items as $item) {
1420
+				if ($item instanceof EE_Line_Item) {
1421
+					switch ($item->OBJ_type()) {
1422
+						case 'Event':
1423
+							break;
1424
+						case 'Ticket':
1425
+							$ticket = $item->ticket();
1426
+							// right now we're only handling tickets here.
1427
+							// Cause its expected that only tickets will have attendees right?
1428
+							if (! $ticket instanceof EE_Ticket) {
1429
+								continue;
1430
+							}
1431
+							try {
1432
+								$event_name = $ticket->get_event_name();
1433
+							} catch (Exception $e) {
1434
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1435
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1436
+							}
1437
+							$event_name .= ' - ' . $item->get('LIN_name');
1438
+							$ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1439
+							// now get all of the registrations for this transaction that use this ticket
1440
+							$registrations = $ticket->get_many_related(
1441
+								'Registration',
1442
+								array(array('TXN_ID' => $this->_transaction->ID()))
1443
+							);
1444
+							foreach ($registrations as $registration) {
1445
+								if (! $registration instanceof EE_Registration) {
1446
+									continue;
1447
+								}
1448
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1449
+									= $registration->status_ID();
1450
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1451
+									= $registration->count();
1452
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1453
+									= $event_name;
1454
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1455
+									= $ticket_price;
1456
+								// attendee info
1457
+								$attendee = $registration->get_first_related('Attendee');
1458
+								if ($attendee instanceof EE_Attendee) {
1459
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1460
+										= $attendee->ID();
1461
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1462
+										= $attendee->full_name();
1463
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1464
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1465
+										  . esc_html__(
1466
+											  ' Event',
1467
+											  'event_espresso'
1468
+										  )
1469
+										  . '">' . $attendee->email() . '</a>';
1470
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1471
+										= EEH_Address::format($attendee, 'inline', false, false);
1472
+								} else {
1473
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1474
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1475
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1476
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1477
+								}
1478
+							}
1479
+							break;
1480
+					}
1481
+				}
1482
+			}
1483
+
1484
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1485
+				array(
1486
+					'action'  => 'edit_transaction',
1487
+					'process' => 'attendees',
1488
+				),
1489
+				TXN_ADMIN_URL
1490
+			);
1491
+			echo EEH_Template::display_template(
1492
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1493
+				$this->_template_args,
1494
+				true
1495
+			);
1496
+		} else {
1497
+			echo sprintf(
1498
+				esc_html__(
1499
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1500
+					'event_espresso'
1501
+				),
1502
+				'<p class="important-notice">',
1503
+				'</p>'
1504
+			);
1505
+		}
1506
+	}
1507
+
1508
+
1509
+	/**
1510
+	 * txn_registrant_side_meta_box
1511
+	 * generates HTML for the Edit Transaction side meta box
1512
+	 *
1513
+	 * @access public
1514
+	 * @return void
1515
+	 * @throws DomainException
1516
+	 * @throws EE_Error
1517
+	 * @throws InvalidArgumentException
1518
+	 * @throws InvalidDataTypeException
1519
+	 * @throws InvalidInterfaceException
1520
+	 * @throws ReflectionException
1521
+	 */
1522
+	public function txn_registrant_side_meta_box()
1523
+	{
1524
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1525
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1526
+			: null;
1527
+		if (! $primary_att instanceof EE_Attendee) {
1528
+			$this->_template_args['no_attendee_message'] = esc_html__(
1529
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1530
+				'event_espresso'
1531
+			);
1532
+			$primary_att = EEM_Attendee::instance()->create_default_object();
1533
+		}
1534
+		$this->_template_args['ATT_ID'] = $primary_att->ID();
1535
+		$this->_template_args['prime_reg_fname'] = $primary_att->fname();
1536
+		$this->_template_args['prime_reg_lname'] = $primary_att->lname();
1537
+		$this->_template_args['prime_reg_email'] = $primary_att->email();
1538
+		$this->_template_args['prime_reg_phone'] = $primary_att->phone();
1539
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1540
+			array(
1541
+				'action' => 'edit_attendee',
1542
+				'post'   => $primary_att->ID(),
1543
+			),
1544
+			REG_ADMIN_URL
1545
+		);
1546
+		// get formatted address for registrant
1547
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1548
+		echo EEH_Template::display_template(
1549
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1550
+			$this->_template_args,
1551
+			true
1552
+		);
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 * txn_billing_info_side_meta_box
1558
+	 *    generates HTML for the Edit Transaction side meta box
1559
+	 *
1560
+	 * @access public
1561
+	 * @return void
1562
+	 * @throws DomainException
1563
+	 * @throws EE_Error
1564
+	 */
1565
+	public function txn_billing_info_side_meta_box()
1566
+	{
1567
+
1568
+		$this->_template_args['billing_form'] = $this->_transaction->billing_info();
1569
+		$this->_template_args['billing_form_url'] = add_query_arg(
1570
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1571
+			TXN_ADMIN_URL
1572
+		);
1573
+
1574
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1575
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1576
+	}
1577
+
1578
+
1579
+	/**
1580
+	 * apply_payments_or_refunds
1581
+	 *    registers a payment or refund made towards a transaction
1582
+	 *
1583
+	 * @access public
1584
+	 * @return void
1585
+	 * @throws EE_Error
1586
+	 * @throws InvalidArgumentException
1587
+	 * @throws ReflectionException
1588
+	 * @throws RuntimeException
1589
+	 * @throws InvalidDataTypeException
1590
+	 * @throws InvalidInterfaceException
1591
+	 */
1592
+	public function apply_payments_or_refunds()
1593
+	{
1594
+		$json_response_data = array('return_data' => false);
1595
+		$valid_data = $this->_validate_payment_request_data();
1596
+		$has_access = EE_Registry::instance()->CAP->current_user_can(
1597
+			'ee_edit_payments',
1598
+			'apply_payment_or_refund_from_registration_details'
1599
+		);
1600
+		if (! empty($valid_data) && $has_access) {
1601
+			$PAY_ID = $valid_data['PAY_ID'];
1602
+			// save  the new payment
1603
+			$payment = $this->_create_payment_from_request_data($valid_data);
1604
+			// get the TXN for this payment
1605
+			$transaction = $payment->transaction();
1606
+			// verify transaction
1607
+			if ($transaction instanceof EE_Transaction) {
1608
+				// calculate_total_payments_and_update_status
1609
+				$this->_process_transaction_payments($transaction);
1610
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1611
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1612
+				// apply payment to registrations (if applicable)
1613
+				if (! empty($REG_IDs)) {
1614
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1615
+					$this->_maybe_send_notifications();
1616
+					// now process status changes for the same registrations
1617
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1618
+				}
1619
+				$this->_maybe_send_notifications($payment);
1620
+				// prepare to render page
1621
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1622
+				do_action(
1623
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1624
+					$transaction,
1625
+					$payment
1626
+				);
1627
+			} else {
1628
+				EE_Error::add_error(
1629
+					esc_html__(
1630
+						'A valid Transaction for this payment could not be retrieved.',
1631
+						'event_espresso'
1632
+					),
1633
+					__FILE__,
1634
+					__FUNCTION__,
1635
+					__LINE__
1636
+				);
1637
+			}
1638
+		} else {
1639
+			if ($has_access) {
1640
+				EE_Error::add_error(
1641
+					esc_html__(
1642
+						'The payment form data could not be processed. Please try again.',
1643
+						'event_espresso'
1644
+					),
1645
+					__FILE__,
1646
+					__FUNCTION__,
1647
+					__LINE__
1648
+				);
1649
+			} else {
1650
+				EE_Error::add_error(
1651
+					esc_html__(
1652
+						'You do not have access to apply payments or refunds to a registration.',
1653
+						'event_espresso'
1654
+					),
1655
+					__FILE__,
1656
+					__FUNCTION__,
1657
+					__LINE__
1658
+				);
1659
+			}
1660
+		}
1661
+		$notices = EE_Error::get_notices(
1662
+			false,
1663
+			false,
1664
+			false
1665
+		);
1666
+		$this->_template_args = array(
1667
+			'data'    => $json_response_data,
1668
+			'error'   => $notices['errors'],
1669
+			'success' => $notices['success'],
1670
+		);
1671
+		$this->_return_json();
1672
+	}
1673
+
1674
+
1675
+	/**
1676
+	 * _validate_payment_request_data
1677
+	 *
1678
+	 * @return array
1679
+	 * @throws EE_Error
1680
+	 */
1681
+	protected function _validate_payment_request_data()
1682
+	{
1683
+		if (! isset($this->_req_data['txn_admin_payment'])) {
1684
+			return false;
1685
+		}
1686
+		$payment_form = $this->_generate_payment_form_section();
1687
+		try {
1688
+			if ($payment_form->was_submitted()) {
1689
+				$payment_form->receive_form_submission();
1690
+				if (! $payment_form->is_valid()) {
1691
+					$submission_error_messages = array();
1692
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1693
+						if ($validation_error instanceof EE_Validation_Error) {
1694
+							$submission_error_messages[] = sprintf(
1695
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1696
+								$validation_error->get_form_section()->html_label_text(),
1697
+								$validation_error->getMessage()
1698
+							);
1699
+						}
1700
+					}
1701
+					EE_Error::add_error(
1702
+						implode('<br />', $submission_error_messages),
1703
+						__FILE__,
1704
+						__FUNCTION__,
1705
+						__LINE__
1706
+					);
1707
+
1708
+					return array();
1709
+				}
1710
+			}
1711
+		} catch (EE_Error $e) {
1712
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1713
+
1714
+			return array();
1715
+		}
1716
+
1717
+		return $payment_form->valid_data();
1718
+	}
1719
+
1720
+
1721
+	/**
1722
+	 * _generate_payment_form_section
1723
+	 *
1724
+	 * @return EE_Form_Section_Proper
1725
+	 * @throws EE_Error
1726
+	 */
1727
+	protected function _generate_payment_form_section()
1728
+	{
1729
+		return new EE_Form_Section_Proper(
1730
+			array(
1731
+				'name'        => 'txn_admin_payment',
1732
+				'subsections' => array(
1733
+					'PAY_ID'          => new EE_Text_Input(
1734
+						array(
1735
+							'default'               => 0,
1736
+							'required'              => false,
1737
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1738
+							'validation_strategies' => array(new EE_Int_Normalization()),
1739
+						)
1740
+					),
1741
+					'TXN_ID'          => new EE_Text_Input(
1742
+						array(
1743
+							'default'               => 0,
1744
+							'required'              => true,
1745
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1746
+							'validation_strategies' => array(new EE_Int_Normalization()),
1747
+						)
1748
+					),
1749
+					'type'            => new EE_Text_Input(
1750
+						array(
1751
+							'default'               => 1,
1752
+							'required'              => true,
1753
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1754
+							'validation_strategies' => array(new EE_Int_Normalization()),
1755
+						)
1756
+					),
1757
+					'amount'          => new EE_Text_Input(
1758
+						array(
1759
+							'default'               => 0,
1760
+							'required'              => true,
1761
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1762
+							'validation_strategies' => array(new EE_Float_Normalization()),
1763
+						)
1764
+					),
1765
+					'status'          => new EE_Text_Input(
1766
+						array(
1767
+							'default'         => EEM_Payment::status_id_approved,
1768
+							'required'        => true,
1769
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1770
+						)
1771
+					),
1772
+					'PMD_ID'          => new EE_Text_Input(
1773
+						array(
1774
+							'default'               => 2,
1775
+							'required'              => true,
1776
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1777
+							'validation_strategies' => array(new EE_Int_Normalization()),
1778
+						)
1779
+					),
1780
+					'date'            => new EE_Text_Input(
1781
+						array(
1782
+							'default'         => time(),
1783
+							'required'        => true,
1784
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1785
+						)
1786
+					),
1787
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1788
+						array(
1789
+							'default'               => '',
1790
+							'required'              => false,
1791
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1792
+							'validation_strategies' => array(
1793
+								new EE_Max_Length_Validation_Strategy(
1794
+									esc_html__('Input too long', 'event_espresso'),
1795
+									100
1796
+								),
1797
+							),
1798
+						)
1799
+					),
1800
+					'po_number'       => new EE_Text_Input(
1801
+						array(
1802
+							'default'               => '',
1803
+							'required'              => false,
1804
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1805
+							'validation_strategies' => array(
1806
+								new EE_Max_Length_Validation_Strategy(
1807
+									esc_html__('Input too long', 'event_espresso'),
1808
+									100
1809
+								),
1810
+							),
1811
+						)
1812
+					),
1813
+					'accounting'      => new EE_Text_Input(
1814
+						array(
1815
+							'default'               => '',
1816
+							'required'              => false,
1817
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1818
+							'validation_strategies' => array(
1819
+								new EE_Max_Length_Validation_Strategy(
1820
+									esc_html__('Input too long', 'event_espresso'),
1821
+									100
1822
+								),
1823
+							),
1824
+						)
1825
+					),
1826
+				),
1827
+			)
1828
+		);
1829
+	}
1830
+
1831
+
1832
+	/**
1833
+	 * _create_payment_from_request_data
1834
+	 *
1835
+	 * @param array $valid_data
1836
+	 * @return EE_Payment
1837
+	 * @throws EE_Error
1838
+	 */
1839
+	protected function _create_payment_from_request_data($valid_data)
1840
+	{
1841
+		$PAY_ID = $valid_data['PAY_ID'];
1842
+		// get payment amount
1843
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1844
+		// payments have a type value of 1 and refunds have a type value of -1
1845
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1846
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1847
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1848
+		$date = $valid_data['date']
1849
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1850
+			: date('Y-m-d g:i a', current_time('timestamp'));
1851
+		$payment = EE_Payment::new_instance(
1852
+			array(
1853
+				'TXN_ID'              => $valid_data['TXN_ID'],
1854
+				'STS_ID'              => $valid_data['status'],
1855
+				'PAY_timestamp'       => $date,
1856
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1857
+				'PMD_ID'              => $valid_data['PMD_ID'],
1858
+				'PAY_amount'          => $amount,
1859
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1860
+				'PAY_po_number'       => $valid_data['po_number'],
1861
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1862
+				'PAY_details'         => $valid_data,
1863
+				'PAY_ID'              => $PAY_ID,
1864
+			),
1865
+			'',
1866
+			array('Y-m-d', 'g:i a')
1867
+		);
1868
+
1869
+		if (! $payment->save()) {
1870
+			EE_Error::add_error(
1871
+				sprintf(
1872
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1873
+					$payment->ID()
1874
+				),
1875
+				__FILE__,
1876
+				__FUNCTION__,
1877
+				__LINE__
1878
+			);
1879
+		}
1880
+
1881
+		return $payment;
1882
+	}
1883
+
1884
+
1885
+	/**
1886
+	 * _process_transaction_payments
1887
+	 *
1888
+	 * @param \EE_Transaction $transaction
1889
+	 * @return void
1890
+	 * @throws EE_Error
1891
+	 * @throws InvalidArgumentException
1892
+	 * @throws ReflectionException
1893
+	 * @throws InvalidDataTypeException
1894
+	 * @throws InvalidInterfaceException
1895
+	 */
1896
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1897
+	{
1898
+		/** @type EE_Transaction_Payments $transaction_payments */
1899
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1900
+		// update the transaction with this payment
1901
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1902
+			EE_Error::add_success(
1903
+				esc_html__(
1904
+					'The payment has been processed successfully.',
1905
+					'event_espresso'
1906
+				),
1907
+				__FILE__,
1908
+				__FUNCTION__,
1909
+				__LINE__
1910
+			);
1911
+		} else {
1912
+			EE_Error::add_error(
1913
+				esc_html__(
1914
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1915
+					'event_espresso'
1916
+				),
1917
+				__FILE__,
1918
+				__FUNCTION__,
1919
+				__LINE__
1920
+			);
1921
+		}
1922
+	}
1923
+
1924
+
1925
+	/**
1926
+	 * _get_REG_IDs_to_apply_payment_to
1927
+	 * returns a list of registration IDs that the payment will apply to
1928
+	 *
1929
+	 * @param \EE_Payment $payment
1930
+	 * @return array
1931
+	 * @throws EE_Error
1932
+	 */
1933
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1934
+	{
1935
+		$REG_IDs = array();
1936
+		// grab array of IDs for specific registrations to apply changes to
1937
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1938
+			$REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1939
+		}
1940
+		// nothing specified ? then get all reg IDs
1941
+		if (empty($REG_IDs)) {
1942
+			$registrations = $payment->transaction()->registrations();
1943
+			$REG_IDs = ! empty($registrations)
1944
+				? array_keys($registrations)
1945
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1946
+		}
1947
+
1948
+		// ensure that REG_IDs are integers and NOT strings
1949
+		return array_map('intval', $REG_IDs);
1950
+	}
1951
+
1952
+
1953
+	/**
1954
+	 * @return array
1955
+	 */
1956
+	public function existing_reg_payment_REG_IDs()
1957
+	{
1958
+		return $this->_existing_reg_payment_REG_IDs;
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 * @param array $existing_reg_payment_REG_IDs
1964
+	 */
1965
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1966
+	{
1967
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * _get_existing_reg_payment_REG_IDs
1973
+	 * returns a list of registration IDs that the payment is currently related to
1974
+	 * as recorded in the database
1975
+	 *
1976
+	 * @param \EE_Payment $payment
1977
+	 * @return array
1978
+	 * @throws EE_Error
1979
+	 */
1980
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1981
+	{
1982
+		if ($this->existing_reg_payment_REG_IDs() === null) {
1983
+			// let's get any existing reg payment records for this payment
1984
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1985
+			// but we only want the REG IDs, so grab the array keys
1986
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1987
+				? array_keys($existing_reg_payment_REG_IDs)
1988
+				: array();
1989
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1990
+		}
1991
+
1992
+		return $this->existing_reg_payment_REG_IDs();
1993
+	}
1994
+
1995
+
1996
+	/**
1997
+	 * _remove_existing_registration_payments
1998
+	 * this calculates the difference between existing relations
1999
+	 * to the supplied payment and the new list registration IDs,
2000
+	 * removes any related registrations that no longer apply,
2001
+	 * and then updates the registration paid fields
2002
+	 *
2003
+	 * @param \EE_Payment $payment
2004
+	 * @param int         $PAY_ID
2005
+	 * @return bool;
2006
+	 * @throws EE_Error
2007
+	 * @throws InvalidArgumentException
2008
+	 * @throws ReflectionException
2009
+	 * @throws InvalidDataTypeException
2010
+	 * @throws InvalidInterfaceException
2011
+	 */
2012
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2013
+	{
2014
+		// newly created payments will have nothing recorded for $PAY_ID
2015
+		if ($PAY_ID == 0) {
2016
+			return false;
2017
+		}
2018
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2019
+		if (empty($existing_reg_payment_REG_IDs)) {
2020
+			return false;
2021
+		}
2022
+		/** @type EE_Transaction_Payments $transaction_payments */
2023
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2024
+
2025
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2026
+			$payment,
2027
+			array(
2028
+				array(
2029
+					'PAY_ID' => $payment->ID(),
2030
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2031
+				),
2032
+			)
2033
+		);
2034
+	}
2035
+
2036
+
2037
+	/**
2038
+	 * _update_registration_payments
2039
+	 * this applies the payments to the selected registrations
2040
+	 * but only if they have not already been paid for
2041
+	 *
2042
+	 * @param  EE_Transaction $transaction
2043
+	 * @param \EE_Payment     $payment
2044
+	 * @param array           $REG_IDs
2045
+	 * @return void
2046
+	 * @throws EE_Error
2047
+	 * @throws InvalidArgumentException
2048
+	 * @throws ReflectionException
2049
+	 * @throws RuntimeException
2050
+	 * @throws InvalidDataTypeException
2051
+	 * @throws InvalidInterfaceException
2052
+	 */
2053
+	protected function _update_registration_payments(
2054
+		EE_Transaction $transaction,
2055
+		EE_Payment $payment,
2056
+		$REG_IDs = array()
2057
+	) {
2058
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2059
+		// so let's do that using our set of REG_IDs from the form
2060
+		$registration_query_where_params = array(
2061
+			'REG_ID' => array('IN', $REG_IDs),
2062
+		);
2063
+		// but add in some conditions regarding payment,
2064
+		// so that we don't apply payments to registrations that are free or have already been paid for
2065
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2066
+		if (! $payment->is_a_refund()) {
2067
+			$registration_query_where_params['REG_final_price'] = array('!=', 0);
2068
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2069
+		}
2070
+		$registrations = $transaction->registrations(array($registration_query_where_params));
2071
+		if (! empty($registrations)) {
2072
+			/** @type EE_Payment_Processor $payment_processor */
2073
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2074
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2075
+		}
2076
+	}
2077
+
2078
+
2079
+	/**
2080
+	 * _process_registration_status_change
2081
+	 * This processes requested registration status changes for all the registrations
2082
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2083
+	 *
2084
+	 * @param  EE_Transaction $transaction
2085
+	 * @param array           $REG_IDs
2086
+	 * @return bool
2087
+	 * @throws EE_Error
2088
+	 * @throws InvalidArgumentException
2089
+	 * @throws ReflectionException
2090
+	 * @throws InvalidDataTypeException
2091
+	 * @throws InvalidInterfaceException
2092
+	 */
2093
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2094
+	{
2095
+		// first if there is no change in status then we get out.
2096
+		if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2097
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2098
+		) {
2099
+			// no error message, no change requested, just nothing to do man.
2100
+			return false;
2101
+		}
2102
+		/** @type EE_Transaction_Processor $transaction_processor */
2103
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2104
+
2105
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2106
+		return $transaction_processor->manually_update_registration_statuses(
2107
+			$transaction,
2108
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2109
+			array(array('REG_ID' => array('IN', $REG_IDs)))
2110
+		);
2111
+	}
2112
+
2113
+
2114
+	/**
2115
+	 * _build_payment_json_response
2116
+	 *
2117
+	 * @access public
2118
+	 * @param \EE_Payment $payment
2119
+	 * @param array       $REG_IDs
2120
+	 * @param bool | null $delete_txn_reg_status_change
2121
+	 * @return array
2122
+	 * @throws EE_Error
2123
+	 * @throws InvalidArgumentException
2124
+	 * @throws InvalidDataTypeException
2125
+	 * @throws InvalidInterfaceException
2126
+	 * @throws ReflectionException
2127
+	 */
2128
+	protected function _build_payment_json_response(
2129
+		EE_Payment $payment,
2130
+		$REG_IDs = array(),
2131
+		$delete_txn_reg_status_change = null
2132
+	) {
2133
+		// was the payment deleted ?
2134
+		if (is_bool($delete_txn_reg_status_change)) {
2135
+			return array(
2136
+				'PAY_ID'                       => $payment->ID(),
2137
+				'amount'                       => $payment->amount(),
2138
+				'total_paid'                   => $payment->transaction()->paid(),
2139
+				'txn_status'                   => $payment->transaction()->status_ID(),
2140
+				'pay_status'                   => $payment->STS_ID(),
2141
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2142
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2143
+			);
2144
+		} else {
2145
+			$this->_get_payment_status_array();
2146
+
2147
+			return array(
2148
+				'amount'           => $payment->amount(),
2149
+				'total_paid'       => $payment->transaction()->paid(),
2150
+				'txn_status'       => $payment->transaction()->status_ID(),
2151
+				'pay_status'       => $payment->STS_ID(),
2152
+				'PAY_ID'           => $payment->ID(),
2153
+				'STS_ID'           => $payment->STS_ID(),
2154
+				'status'           => self::$_pay_status[ $payment->STS_ID() ],
2155
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2156
+				'method'           => strtoupper($payment->source()),
2157
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2158
+				'gateway'          => $payment->payment_method()
2159
+					? $payment->payment_method()->admin_name()
2160
+					: esc_html__("Unknown", 'event_espresso'),
2161
+				'gateway_response' => $payment->gateway_response(),
2162
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2163
+				'po_number'        => $payment->po_number(),
2164
+				'extra_accntng'    => $payment->extra_accntng(),
2165
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2166
+			);
2167
+		}
2168
+	}
2169
+
2170
+
2171
+	/**
2172
+	 * delete_payment
2173
+	 *    delete a payment or refund made towards a transaction
2174
+	 *
2175
+	 * @access public
2176
+	 * @return void
2177
+	 * @throws EE_Error
2178
+	 * @throws InvalidArgumentException
2179
+	 * @throws ReflectionException
2180
+	 * @throws InvalidDataTypeException
2181
+	 * @throws InvalidInterfaceException
2182
+	 */
2183
+	public function delete_payment()
2184
+	{
2185
+		$json_response_data = array('return_data' => false);
2186
+		$PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2187
+			? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2188
+			: 0;
2189
+		$can_delete = EE_Registry::instance()->CAP->current_user_can(
2190
+			'ee_delete_payments',
2191
+			'delete_payment_from_registration_details'
2192
+		);
2193
+		if ($PAY_ID && $can_delete) {
2194
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2195
+				? $this->_req_data['delete_txn_reg_status_change']
2196
+				: false;
2197
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2198
+			if ($payment instanceof EE_Payment) {
2199
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2200
+				/** @type EE_Transaction_Payments $transaction_payments */
2201
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2202
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2203
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2204
+						$payment,
2205
+						$REG_IDs,
2206
+						$delete_txn_reg_status_change
2207
+					);
2208
+					if ($delete_txn_reg_status_change) {
2209
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2210
+						// MAKE sure we also add the delete_txn_req_status_change to the
2211
+						// $_REQUEST global because that's how messages will be looking for it.
2212
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2213
+						$this->_maybe_send_notifications();
2214
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2215
+					}
2216
+				}
2217
+			} else {
2218
+				EE_Error::add_error(
2219
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2220
+					__FILE__,
2221
+					__FUNCTION__,
2222
+					__LINE__
2223
+				);
2224
+			}
2225
+		} else {
2226
+			if ($can_delete) {
2227
+				EE_Error::add_error(
2228
+					esc_html__(
2229
+						'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2230
+						'event_espresso'
2231
+					),
2232
+					__FILE__,
2233
+					__FUNCTION__,
2234
+					__LINE__
2235
+				);
2236
+			} else {
2237
+				EE_Error::add_error(
2238
+					esc_html__(
2239
+						'You do not have access to delete a payment.',
2240
+						'event_espresso'
2241
+					),
2242
+					__FILE__,
2243
+					__FUNCTION__,
2244
+					__LINE__
2245
+				);
2246
+			}
2247
+		}
2248
+		$notices = EE_Error::get_notices(false, false, false);
2249
+		$this->_template_args = array(
2250
+			'data'      => $json_response_data,
2251
+			'success'   => $notices['success'],
2252
+			'error'     => $notices['errors'],
2253
+			'attention' => $notices['attention'],
2254
+		);
2255
+		$this->_return_json();
2256
+	}
2257
+
2258
+
2259
+	/**
2260
+	 * _registration_payment_data_array
2261
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2262
+	 *
2263
+	 * @access protected
2264
+	 * @param array $REG_IDs
2265
+	 * @return array
2266
+	 * @throws EE_Error
2267
+	 * @throws InvalidArgumentException
2268
+	 * @throws InvalidDataTypeException
2269
+	 * @throws InvalidInterfaceException
2270
+	 * @throws ReflectionException
2271
+	 */
2272
+	protected function _registration_payment_data_array($REG_IDs)
2273
+	{
2274
+		$registration_payment_data = array();
2275
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2276
+		if (! empty($REG_IDs)) {
2277
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2278
+			foreach ($registrations as $registration) {
2279
+				if ($registration instanceof EE_Registration) {
2280
+					$registration_payment_data[ $registration->ID() ] = array(
2281
+						'paid'  => $registration->pretty_paid(),
2282
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2283
+					);
2284
+				}
2285
+			}
2286
+		}
2287
+
2288
+		return $registration_payment_data;
2289
+	}
2290
+
2291
+
2292
+	/**
2293
+	 * _maybe_send_notifications
2294
+	 * determines whether or not the admin has indicated that notifications should be sent.
2295
+	 * If so, will toggle a filter switch for delivering registration notices.
2296
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2297
+	 *
2298
+	 * @access protected
2299
+	 * @param \EE_Payment | null $payment
2300
+	 */
2301
+	protected function _maybe_send_notifications($payment = null)
2302
+	{
2303
+		switch ($payment instanceof EE_Payment) {
2304
+			// payment notifications
2305
+			case true:
2306
+				if (isset(
2307
+					$this->_req_data['txn_payments'],
2308
+					$this->_req_data['txn_payments']['send_notifications']
2309
+				)
2310
+					&& filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2311
+				) {
2312
+					$this->_process_payment_notification($payment);
2313
+				}
2314
+				break;
2315
+			// registration notifications
2316
+			case false:
2317
+				if (isset(
2318
+					$this->_req_data['txn_reg_status_change'],
2319
+					$this->_req_data['txn_reg_status_change']['send_notifications']
2320
+				)
2321
+					&& filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2322
+				) {
2323
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2324
+				}
2325
+				break;
2326
+		}
2327
+	}
2328
+
2329
+
2330
+	/**
2331
+	 * _send_payment_reminder
2332
+	 *    generates HTML for the View Transaction Details Admin page
2333
+	 *
2334
+	 * @access protected
2335
+	 * @return void
2336
+	 * @throws EE_Error
2337
+	 * @throws InvalidArgumentException
2338
+	 * @throws InvalidDataTypeException
2339
+	 * @throws InvalidInterfaceException
2340
+	 */
2341
+	protected function _send_payment_reminder()
2342
+	{
2343
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2344
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2345
+		$query_args = isset($this->_req_data['redirect_to']) ? array(
2346
+			'action' => $this->_req_data['redirect_to'],
2347
+			'TXN_ID' => $this->_req_data['TXN_ID'],
2348
+		) : array();
2349
+		do_action(
2350
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2351
+			$transaction
2352
+		);
2353
+		$this->_redirect_after_action(
2354
+			false,
2355
+			esc_html__('payment reminder', 'event_espresso'),
2356
+			esc_html__('sent', 'event_espresso'),
2357
+			$query_args,
2358
+			true
2359
+		);
2360
+	}
2361
+
2362
+
2363
+	/**
2364
+	 *  get_transactions
2365
+	 *    get transactions for given parameters (used by list table)
2366
+	 *
2367
+	 * @param  int     $perpage how many transactions displayed per page
2368
+	 * @param  boolean $count   return the count or objects
2369
+	 * @param string   $view
2370
+	 * @return mixed int = count || array of transaction objects
2371
+	 * @throws EE_Error
2372
+	 * @throws InvalidArgumentException
2373
+	 * @throws InvalidDataTypeException
2374
+	 * @throws InvalidInterfaceException
2375
+	 */
2376
+	public function get_transactions($perpage, $count = false, $view = '')
2377
+	{
2378
+
2379
+		$TXN = EEM_Transaction::instance();
2380
+
2381
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
2382
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2383
+			: date(
2384
+				'm/d/Y',
2385
+				strtotime('-10 year')
2386
+			);
2387
+		$end_date = isset($this->_req_data['txn-filter-end-date'])
2388
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2389
+			: date('m/d/Y');
2390
+
2391
+		// make sure our timestamps start and end right at the boundaries for each day
2392
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2393
+		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2394
+
2395
+
2396
+		// convert to timestamps
2397
+		$start_date = strtotime($start_date);
2398
+		$end_date = strtotime($end_date);
2399
+
2400
+		// makes sure start date is the lowest value and vice versa
2401
+		$start_date = min($start_date, $end_date);
2402
+		$end_date = max($start_date, $end_date);
2403
+
2404
+		// convert to correct format for query
2405
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2406
+			'TXN_timestamp',
2407
+			date('Y-m-d H:i:s', $start_date),
2408
+			'Y-m-d H:i:s'
2409
+		);
2410
+		$end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2411
+			'TXN_timestamp',
2412
+			date('Y-m-d H:i:s', $end_date),
2413
+			'Y-m-d H:i:s'
2414
+		);
2415
+
2416
+
2417
+		// set orderby
2418
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2419
+
2420
+		switch ($this->_req_data['orderby']) {
2421
+			case 'TXN_ID':
2422
+				$orderby = 'TXN_ID';
2423
+				break;
2424
+			case 'ATT_fname':
2425
+				$orderby = 'Registration.Attendee.ATT_fname';
2426
+				break;
2427
+			case 'event_name':
2428
+				$orderby = 'Registration.Event.EVT_name';
2429
+				break;
2430
+			default: // 'TXN_timestamp'
2431
+				$orderby = 'TXN_timestamp';
2432
+		}
2433
+
2434
+		$sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2435
+		$current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2436
+		$per_page = ! empty($perpage) ? $perpage : 10;
2437
+		$per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2438
+
2439
+		$offset = ($current_page - 1) * $per_page;
2440
+		$limit = array($offset, $per_page);
2441
+
2442
+		$_where = array(
2443
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2444
+			'Registration.REG_count' => 1,
2445
+		);
2446
+
2447
+		if (isset($this->_req_data['EVT_ID'])) {
2448
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2449
+		}
2450
+
2451
+		if (isset($this->_req_data['s'])) {
2452
+			$search_string = '%' . $this->_req_data['s'] . '%';
2453
+			$_where['OR'] = array(
2454
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2455
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2456
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2457
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2458
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2459
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2460
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2461
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2462
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2463
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2464
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2465
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
2466
+				'Registration.REG_code'               => array('LIKE', $search_string),
2467
+				'Registration.REG_count'              => array('LIKE', $search_string),
2468
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
2469
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2470
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2471
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
2472
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2473
+				'TXN_session_data'                    => array('LIKE', $search_string),
2474
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2475
+			);
2476
+		}
2477
+
2478
+		// failed transactions
2479
+		$failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2480
+				  || ($count && $view === 'failed');
2481
+		$abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2482
+					 || ($count && $view === 'abandoned');
2483
+		$incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2484
+					  || ($count && $view === 'incomplete');
2485
+
2486
+		if ($failed) {
2487
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2488
+		} elseif ($abandoned) {
2489
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2490
+		} elseif ($incomplete) {
2491
+			$_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2492
+		} else {
2493
+			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2494
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2495
+		}
2496
+
2497
+		$query_params = apply_filters(
2498
+			'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2499
+			array(
2500
+				$_where,
2501
+				'order_by'                 => array($orderby => $sort),
2502
+				'limit'                    => $limit,
2503
+				'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2504
+			),
2505
+			$this->_req_data,
2506
+			$view,
2507
+			$count
2508
+		);
2509
+
2510
+		$transactions = $count
2511
+			? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2512
+			: $TXN->get_all($query_params);
2513
+
2514
+		return $transactions;
2515
+	}
2516 2516
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.71.rc.000');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.71.rc.000');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.
core/services/validators/JsonValidator.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -18,76 +18,76 @@
 block discarded – undo
18 18
 class JsonValidator
19 19
 {
20 20
 
21
-    /**
22
-     * Call this method IMMEDIATELY after json_decode() and
23
-     * it will will return true if the decoded JSON was valid,
24
-     * or return false after adding an error if not valid.
25
-     * The actual JSON file does not need to be supplied,
26
-     * but details re: code execution location are required.
27
-     * ex:
28
-     * JsonValidator::isValid(__FILE__, __METHOD__, __LINE__)
29
-     *
30
-     * @param string $file
31
-     * @param string $func
32
-     * @param string $line
33
-     * @return boolean
34
-     * @since 4.9.70.p
35
-     */
36
-    public function isValid($file, $func, $line)
37
-    {
38
-        if (! defined('JSON_ERROR_RECURSION')) {
39
-            define('JSON_ERROR_RECURSION', 6);
40
-        }
41
-        if (! defined('JSON_ERROR_INF_OR_NAN')) {
42
-            define('JSON_ERROR_INF_OR_NAN', 7);
43
-        }
44
-        if (! defined('JSON_ERROR_UNSUPPORTED_TYPE')) {
45
-            define('JSON_ERROR_UNSUPPORTED_TYPE', 8);
46
-        }
47
-        if (! defined('JSON_ERROR_INVALID_PROPERTY_NAME')) {
48
-            define('JSON_ERROR_INVALID_PROPERTY_NAME', 9);
49
-        }
50
-        if (! defined('JSON_ERROR_UTF16')) {
51
-            define('JSON_ERROR_UTF16', 10);
52
-        }
53
-        switch (json_last_error()) {
54
-            case JSON_ERROR_NONE:
55
-                return true;
56
-            case JSON_ERROR_DEPTH:
57
-                $error = ': Maximum stack depth exceeded';
58
-                break;
59
-            case JSON_ERROR_STATE_MISMATCH:
60
-                $error = ': Invalid or malformed JSON';
61
-                break;
62
-            case JSON_ERROR_CTRL_CHAR:
63
-                $error = ': Control character error, possible malformed JSON';
64
-                break;
65
-            case JSON_ERROR_SYNTAX:
66
-                $error = ': Syntax error, malformed JSON';
67
-                break;
68
-            case JSON_ERROR_UTF8:
69
-                $error = ': Malformed UTF-8 characters, possible malformed JSON';
70
-                break;
71
-            case JSON_ERROR_RECURSION:
72
-                $error = ': One or more recursive references in the value to be encoded';
73
-                break;
74
-            case JSON_ERROR_INF_OR_NAN:
75
-                $error = ': One or more NAN or INF values in the value to be encoded';
76
-                break;
77
-            case JSON_ERROR_UNSUPPORTED_TYPE:
78
-                $error = ': A value of a type that cannot be encoded was given';
79
-                break;
80
-            case JSON_ERROR_INVALID_PROPERTY_NAME:
81
-                $error = ': A property name that cannot be encoded was given';
82
-                break;
83
-            case JSON_ERROR_UTF16:
84
-                $error = ': Malformed UTF-16 characters, possibly incorrectly encoded';
85
-                break;
86
-            default:
87
-                $error = ': Unknown error';
88
-                break;
89
-        }
90
-        EE_Error::add_error('JSON decoding failed' . $error, $file, $func, $line);
91
-        return false;
92
-    }
21
+	/**
22
+	 * Call this method IMMEDIATELY after json_decode() and
23
+	 * it will will return true if the decoded JSON was valid,
24
+	 * or return false after adding an error if not valid.
25
+	 * The actual JSON file does not need to be supplied,
26
+	 * but details re: code execution location are required.
27
+	 * ex:
28
+	 * JsonValidator::isValid(__FILE__, __METHOD__, __LINE__)
29
+	 *
30
+	 * @param string $file
31
+	 * @param string $func
32
+	 * @param string $line
33
+	 * @return boolean
34
+	 * @since 4.9.70.p
35
+	 */
36
+	public function isValid($file, $func, $line)
37
+	{
38
+		if (! defined('JSON_ERROR_RECURSION')) {
39
+			define('JSON_ERROR_RECURSION', 6);
40
+		}
41
+		if (! defined('JSON_ERROR_INF_OR_NAN')) {
42
+			define('JSON_ERROR_INF_OR_NAN', 7);
43
+		}
44
+		if (! defined('JSON_ERROR_UNSUPPORTED_TYPE')) {
45
+			define('JSON_ERROR_UNSUPPORTED_TYPE', 8);
46
+		}
47
+		if (! defined('JSON_ERROR_INVALID_PROPERTY_NAME')) {
48
+			define('JSON_ERROR_INVALID_PROPERTY_NAME', 9);
49
+		}
50
+		if (! defined('JSON_ERROR_UTF16')) {
51
+			define('JSON_ERROR_UTF16', 10);
52
+		}
53
+		switch (json_last_error()) {
54
+			case JSON_ERROR_NONE:
55
+				return true;
56
+			case JSON_ERROR_DEPTH:
57
+				$error = ': Maximum stack depth exceeded';
58
+				break;
59
+			case JSON_ERROR_STATE_MISMATCH:
60
+				$error = ': Invalid or malformed JSON';
61
+				break;
62
+			case JSON_ERROR_CTRL_CHAR:
63
+				$error = ': Control character error, possible malformed JSON';
64
+				break;
65
+			case JSON_ERROR_SYNTAX:
66
+				$error = ': Syntax error, malformed JSON';
67
+				break;
68
+			case JSON_ERROR_UTF8:
69
+				$error = ': Malformed UTF-8 characters, possible malformed JSON';
70
+				break;
71
+			case JSON_ERROR_RECURSION:
72
+				$error = ': One or more recursive references in the value to be encoded';
73
+				break;
74
+			case JSON_ERROR_INF_OR_NAN:
75
+				$error = ': One or more NAN or INF values in the value to be encoded';
76
+				break;
77
+			case JSON_ERROR_UNSUPPORTED_TYPE:
78
+				$error = ': A value of a type that cannot be encoded was given';
79
+				break;
80
+			case JSON_ERROR_INVALID_PROPERTY_NAME:
81
+				$error = ': A property name that cannot be encoded was given';
82
+				break;
83
+			case JSON_ERROR_UTF16:
84
+				$error = ': Malformed UTF-16 characters, possibly incorrectly encoded';
85
+				break;
86
+			default:
87
+				$error = ': Unknown error';
88
+				break;
89
+		}
90
+		EE_Error::add_error('JSON decoding failed' . $error, $file, $func, $line);
91
+		return false;
92
+	}
93 93
 }
Please login to merge, or discard this patch.
core/services/address/CountrySubRegionDao.php 1 patch
Indentation   +204 added lines, -204 removed lines patch added patch discarded remove patch
@@ -24,208 +24,208 @@
 block discarded – undo
24 24
 class CountrySubRegionDao
25 25
 {
26 26
 
27
-    const REPO_URL = 'https://raw.githubusercontent.com/eventespresso/countries-and-subregions/master/';
28
-
29
-    const OPTION_NAME_COUNTRY_DATA_VERSION = 'espresso-country-sub-region-data-version';
30
-
31
-    /**
32
-     * @var EEM_State $state_model
33
-     */
34
-    private $state_model;
35
-
36
-    /**
37
-     * @var JsonValidator $json_validator
38
-     */
39
-    private $json_validator;
40
-
41
-    /**
42
-     * @var string $data_version
43
-     */
44
-    private $data_version;
45
-
46
-    /**
47
-     * @var array $countries
48
-     */
49
-    private $countries = array();
50
-
51
-
52
-    /**
53
-     * CountrySubRegionDao constructor.
54
-     *
55
-     * @param EEM_State     $state_model
56
-     * @param JsonValidator $json_validator
57
-     */
58
-    public function __construct(EEM_State $state_model, JsonValidator $json_validator)
59
-    {
60
-        $this->state_model = $state_model;
61
-        $this->json_validator = $json_validator;
62
-    }
63
-
64
-
65
-    /**
66
-     * @param EE_Country $country_object
67
-     * @return void
68
-     * @throws EE_Error
69
-     * @throws InvalidArgumentException
70
-     * @throws InvalidDataTypeException
71
-     * @throws InvalidInterfaceException
72
-     * @throws ReflectionException
73
-     */
74
-    public function saveCountrySubRegions(EE_Country $country_object)
75
-    {
76
-        $CNT_ISO = $country_object->ID();
77
-        $has_sub_regions = $this->state_model->count(array(array('Country.CNT_ISO' => $CNT_ISO)));
78
-        $data = [];
79
-        if (empty($this->countries)) {
80
-            $this->data_version = $this->getCountrySubRegionDataVersion();
81
-            $data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
82
-        }
83
-        if (empty($data)) {
84
-            EE_Error::add_error(
85
-                'Country Subregion Data could not be retrieved',
86
-                __FILE__,
87
-                __METHOD__,
88
-                __LINE__
89
-            );
90
-        }
91
-        if (! $has_sub_regions
92
-            || (isset($data->version) && version_compare($data->version, $this->data_version))
93
-        ) {
94
-            if (isset($data->countries)
95
-                && $this->processCountryData($CNT_ISO, $data->countries) > 0
96
-            ) {
97
-                $this->countries = $data->countries;
98
-                $this->updateCountrySubRegionDataVersion($data->version);
99
-            }
100
-        }
101
-    }
102
-
103
-
104
-    /**
105
-     * @since 4.9.70.p
106
-     * @return string
107
-     */
108
-    private function getCountrySubRegionDataVersion()
109
-    {
110
-        return get_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, null);
111
-    }
112
-
113
-
114
-    /**
115
-     * @param string $version
116
-     */
117
-    private function updateCountrySubRegionDataVersion($version = '')
118
-    {
119
-        // add version option if it has never been added before, or update existing
120
-        if ($this->data_version === null) {
121
-            add_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version, '', false);
122
-        } else {
123
-            update_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version);
124
-        }
125
-    }
126
-
127
-
128
-    /**
129
-     * @param string $CNT_ISO
130
-     * @param array  $countries
131
-     * @since 4.9.70.p
132
-     * @return int
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidDataTypeException
136
-     * @throws InvalidInterfaceException
137
-     */
138
-    private function processCountryData($CNT_ISO, $countries = array())
139
-    {
140
-        if (! empty($countries)) {
141
-            foreach ($countries as $key => $country) {
142
-                if ($country instanceof stdClass
143
-                    && $country->code === $CNT_ISO
144
-                    && empty($country->sub_regions)
145
-                    && ! empty($country->filename)
146
-                ) {
147
-                    $country->sub_regions = $this->retrieveJsonData(
148
-                        self::REPO_URL . 'countries/' . $country->filename . '.json'
149
-                    );
150
-                    return $this->saveSubRegionData($country, $country->sub_regions);
151
-                }
152
-            }
153
-        }
154
-        return 0;
155
-    }
156
-
157
-
158
-    /**
159
-     * @param string $url
160
-     * @return array
161
-     */
162
-    private function retrieveJsonData($url)
163
-    {
164
-        if (empty($url)) {
165
-            EE_Error::add_error(
166
-                'No URL was provided!',
167
-                __FILE__,
168
-                __METHOD__,
169
-                __LINE__
170
-            );
171
-            return array();
172
-        }
173
-        $request = wp_safe_remote_get($url);
174
-        if ($request instanceof WP_Error) {
175
-            EE_Error::add_error(
176
-                $request->get_error_message(),
177
-                __FILE__,
178
-                __METHOD__,
179
-                __LINE__
180
-            );
181
-            return array();
182
-        }
183
-        $body = wp_remote_retrieve_body($request);
184
-        $json = json_decode($body);
185
-        if ($this->json_validator->isValid(__FILE__, __METHOD__, __LINE__)) {
186
-            return $json;
187
-        }
188
-        return array();
189
-    }
190
-
191
-
192
-    /**
193
-     * @param stdClass $country
194
-     * @param array    $sub_regions
195
-     * @return int
196
-     * @throws EE_Error
197
-     * @throws InvalidArgumentException
198
-     * @throws InvalidDataTypeException
199
-     * @throws InvalidInterfaceException
200
-     */
201
-    private function saveSubRegionData(stdClass $country, $sub_regions = array())
202
-    {
203
-        $results = 0;
204
-        if (is_array($sub_regions)) {
205
-            foreach ($sub_regions as $sub_region) {
206
-                // remove country code from sub region code
207
-                $abbrev = str_replace(
208
-                    $country->code . '-',
209
-                    '',
210
-                    sanitize_text_field($sub_region->code)
211
-                );
212
-                // but NOT if sub region code results in only a number
213
-                if (absint($abbrev) !== 0) {
214
-                    $abbrev = sanitize_text_field($sub_region->code);
215
-                }
216
-                if ($this->state_model->insert(
217
-                    array(
218
-                        // STA_ID CNT_ISO STA_abbrev STA_name STA_active
219
-                        'CNT_ISO'    => $country->code,
220
-                        'STA_abbrev' => $abbrev,
221
-                        'STA_name'   => sanitize_text_field($sub_region->name),
222
-                        'STA_active' => 1,
223
-                    )
224
-                )) {
225
-                    $results++;
226
-                }
227
-            }
228
-        }
229
-        return $results;
230
-    }
27
+	const REPO_URL = 'https://raw.githubusercontent.com/eventespresso/countries-and-subregions/master/';
28
+
29
+	const OPTION_NAME_COUNTRY_DATA_VERSION = 'espresso-country-sub-region-data-version';
30
+
31
+	/**
32
+	 * @var EEM_State $state_model
33
+	 */
34
+	private $state_model;
35
+
36
+	/**
37
+	 * @var JsonValidator $json_validator
38
+	 */
39
+	private $json_validator;
40
+
41
+	/**
42
+	 * @var string $data_version
43
+	 */
44
+	private $data_version;
45
+
46
+	/**
47
+	 * @var array $countries
48
+	 */
49
+	private $countries = array();
50
+
51
+
52
+	/**
53
+	 * CountrySubRegionDao constructor.
54
+	 *
55
+	 * @param EEM_State     $state_model
56
+	 * @param JsonValidator $json_validator
57
+	 */
58
+	public function __construct(EEM_State $state_model, JsonValidator $json_validator)
59
+	{
60
+		$this->state_model = $state_model;
61
+		$this->json_validator = $json_validator;
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param EE_Country $country_object
67
+	 * @return void
68
+	 * @throws EE_Error
69
+	 * @throws InvalidArgumentException
70
+	 * @throws InvalidDataTypeException
71
+	 * @throws InvalidInterfaceException
72
+	 * @throws ReflectionException
73
+	 */
74
+	public function saveCountrySubRegions(EE_Country $country_object)
75
+	{
76
+		$CNT_ISO = $country_object->ID();
77
+		$has_sub_regions = $this->state_model->count(array(array('Country.CNT_ISO' => $CNT_ISO)));
78
+		$data = [];
79
+		if (empty($this->countries)) {
80
+			$this->data_version = $this->getCountrySubRegionDataVersion();
81
+			$data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
82
+		}
83
+		if (empty($data)) {
84
+			EE_Error::add_error(
85
+				'Country Subregion Data could not be retrieved',
86
+				__FILE__,
87
+				__METHOD__,
88
+				__LINE__
89
+			);
90
+		}
91
+		if (! $has_sub_regions
92
+			|| (isset($data->version) && version_compare($data->version, $this->data_version))
93
+		) {
94
+			if (isset($data->countries)
95
+				&& $this->processCountryData($CNT_ISO, $data->countries) > 0
96
+			) {
97
+				$this->countries = $data->countries;
98
+				$this->updateCountrySubRegionDataVersion($data->version);
99
+			}
100
+		}
101
+	}
102
+
103
+
104
+	/**
105
+	 * @since 4.9.70.p
106
+	 * @return string
107
+	 */
108
+	private function getCountrySubRegionDataVersion()
109
+	{
110
+		return get_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, null);
111
+	}
112
+
113
+
114
+	/**
115
+	 * @param string $version
116
+	 */
117
+	private function updateCountrySubRegionDataVersion($version = '')
118
+	{
119
+		// add version option if it has never been added before, or update existing
120
+		if ($this->data_version === null) {
121
+			add_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version, '', false);
122
+		} else {
123
+			update_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version);
124
+		}
125
+	}
126
+
127
+
128
+	/**
129
+	 * @param string $CNT_ISO
130
+	 * @param array  $countries
131
+	 * @since 4.9.70.p
132
+	 * @return int
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws InvalidInterfaceException
137
+	 */
138
+	private function processCountryData($CNT_ISO, $countries = array())
139
+	{
140
+		if (! empty($countries)) {
141
+			foreach ($countries as $key => $country) {
142
+				if ($country instanceof stdClass
143
+					&& $country->code === $CNT_ISO
144
+					&& empty($country->sub_regions)
145
+					&& ! empty($country->filename)
146
+				) {
147
+					$country->sub_regions = $this->retrieveJsonData(
148
+						self::REPO_URL . 'countries/' . $country->filename . '.json'
149
+					);
150
+					return $this->saveSubRegionData($country, $country->sub_regions);
151
+				}
152
+			}
153
+		}
154
+		return 0;
155
+	}
156
+
157
+
158
+	/**
159
+	 * @param string $url
160
+	 * @return array
161
+	 */
162
+	private function retrieveJsonData($url)
163
+	{
164
+		if (empty($url)) {
165
+			EE_Error::add_error(
166
+				'No URL was provided!',
167
+				__FILE__,
168
+				__METHOD__,
169
+				__LINE__
170
+			);
171
+			return array();
172
+		}
173
+		$request = wp_safe_remote_get($url);
174
+		if ($request instanceof WP_Error) {
175
+			EE_Error::add_error(
176
+				$request->get_error_message(),
177
+				__FILE__,
178
+				__METHOD__,
179
+				__LINE__
180
+			);
181
+			return array();
182
+		}
183
+		$body = wp_remote_retrieve_body($request);
184
+		$json = json_decode($body);
185
+		if ($this->json_validator->isValid(__FILE__, __METHOD__, __LINE__)) {
186
+			return $json;
187
+		}
188
+		return array();
189
+	}
190
+
191
+
192
+	/**
193
+	 * @param stdClass $country
194
+	 * @param array    $sub_regions
195
+	 * @return int
196
+	 * @throws EE_Error
197
+	 * @throws InvalidArgumentException
198
+	 * @throws InvalidDataTypeException
199
+	 * @throws InvalidInterfaceException
200
+	 */
201
+	private function saveSubRegionData(stdClass $country, $sub_regions = array())
202
+	{
203
+		$results = 0;
204
+		if (is_array($sub_regions)) {
205
+			foreach ($sub_regions as $sub_region) {
206
+				// remove country code from sub region code
207
+				$abbrev = str_replace(
208
+					$country->code . '-',
209
+					'',
210
+					sanitize_text_field($sub_region->code)
211
+				);
212
+				// but NOT if sub region code results in only a number
213
+				if (absint($abbrev) !== 0) {
214
+					$abbrev = sanitize_text_field($sub_region->code);
215
+				}
216
+				if ($this->state_model->insert(
217
+					array(
218
+						// STA_ID CNT_ISO STA_abbrev STA_name STA_active
219
+						'CNT_ISO'    => $country->code,
220
+						'STA_abbrev' => $abbrev,
221
+						'STA_name'   => sanitize_text_field($sub_region->name),
222
+						'STA_active' => 1,
223
+					)
224
+				)) {
225
+					$results++;
226
+				}
227
+			}
228
+		}
229
+		return $results;
230
+	}
231 231
 }
Please login to merge, or discard this patch.