Completed
Branch BUG-10381-asset-loading (f91422)
by
unknown
170:16 queued 157:41
created

EED_Thank_You_Page::init()   F

Complexity

Conditions 19
Paths 897

Size

Total Lines 85
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 60
c 0
b 0
f 0
nc 897
nop 0
dl 0
loc 85
rs 2.3529

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
defined('EVENT_ESPRESSO_VERSION') || exit;
3
4
5
6
/**
7
 * Class EED_Thank_You_Page
8
 * Description
9
 *
10
 * @package       Event Espresso
11
 * @author        Brent Christensen
12
 * @since         $VID:$
13
 */
14
class EED_Thank_You_Page extends EED_Module
15
{
16
17
    /**
18
     * time in seconds to wait for the IPN to arrive before telling the registrant to bugger off ( 1200s = 20 minutes )
19
     */
20
    const IPN_wait_time = 1200;
21
22
    /**
23
     * The transaction specified by the reg_url_link passed from the Request, or from the Session
24
     *
25
     * @var EE_Transaction $_current_txn
26
     */
27
    private $_current_txn;
28
29
    /**
30
     * @var EE_Registration $_primary_registrant
31
     */
32
    private $_primary_registrant;
33
34
    /**
35
     * The reg_url_link passed from the Request, or from the Session
36
     *
37
     * @var string $_reg_url_link
38
     */
39
    private $_reg_url_link;
40
41
    /**
42
     * whether the incoming reg_url_link is for the primary registrant or not
43
     *
44
     * @var boolean $_is_primary
45
     */
46
    private $_is_primary;
47
48
    /**
49
     * The URL for revisiting the SPCO attendee information step
50
     *
51
     * @var string $_SPCO_attendee_information_url
52
     */
53
    private $_SPCO_attendee_information_url;
54
55
    /**
56
     * The URL for revisiting the SPCO payment options step
57
     *
58
     * @var string $_SPCO_payment_options_url
59
     */
60
    private $_SPCO_payment_options_url;
61
62
    /**
63
     * whether to display the Payment Options link
64
     *
65
     * @var boolean $_show_try_pay_again_link
66
     */
67
    private $_show_try_pay_again_link = false;
68
69
    /**
70
     * whether payments are allowed at this time
71
     *
72
     * @var boolean $_payments_closed
73
     */
74
    private $_payments_closed = false;
75
76
    /**
77
     * whether the selected payment method is Bank, Check , Invoice, etc
78
     *
79
     * @var boolean $_is_offline_payment_method
80
     */
81
    private $_is_offline_payment_method = true;
82
83
84
85
    /**
86
     * @return EED_Module|EED_Thank_You_Page
87
     */
88
    public static function instance()
89
    {
90
        return parent::get_instance(__CLASS__);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (get_instance() instead of instance()). Are you sure this is correct? If so, you might want to change this to $this->get_instance().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
91
    }
92
93
94
    /**
95
     * set_hooks - for hooking into EE Core, modules, etc
96
     *
97
     * @return void
98
     */
99
    public static function set_hooks()
100
    {
101
        add_action('wp_loaded', array('EED_Thank_You_Page', 'set_definitions'), 2);
102
    }
103
104
105
106
    /**
107
     * set_hooks_admin - for hooking into EE Admin Core, modules, etc
108
     *
109
     * @return void
110
     */
111
    public static function set_hooks_admin()
112
    {
113
        // AJAX for IPN monitoring
114
        add_filter('heartbeat_received', array('EED_Thank_You_Page', 'thank_you_page_IPN_monitor'), 10, 3);
115
        add_filter(
116
            'heartbeat_nopriv_received',
117
            array('EED_Thank_You_Page', 'thank_you_page_IPN_monitor'),
118
            10,
119
            3
120
        );
121
        add_action(
122
            'wp_ajax_espresso_resend_reg_confirmation_email',
123
            array('EED_Thank_You_Page', 'resend_reg_confirmation_email'),
124
            10,
125
            2
126
        );
127
        add_action(
128
            'wp_ajax_nopriv_espresso_resend_reg_confirmation_email',
129
            array('EED_Thank_You_Page', 'resend_reg_confirmation_email'),
130
            10,
131
            2
132
        );
133
    }
134
135
136
137
    /**
138
     * set_definitions
139
     *
140
     * @return void
141
     */
142
    public static function set_definitions()
143
    {
144
        define('THANK_YOU_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
145
        define('THANK_YOU_TEMPLATES_PATH', str_replace('\\', DS, plugin_dir_path(__FILE__)) . 'templates' . DS);
146
    }
147
148
149
150
    /**
151
     * get_txn
152
     *
153
     * @return EE_Transaction
154
     */
155
    public function get_txn()
156
    {
157
        if ($this->_current_txn instanceof EE_Transaction) {
158
            return $this->_current_txn;
159
        }
160
        $TXN_model = EE_Registry::instance()->load_model('Transaction');
161
        if ( ! $TXN_model instanceof EEM_Transaction) {
162
            EE_Error::add_error(
163
                __('The transaction model could not be established.', 'event_espresso'),
164
                __FILE__,
165
                __FUNCTION__,
166
                __LINE__
167
            );
168
            return null;
169
        }
170
        //get the transaction. yes, we may have just loaded it, but it may have been updated, or this may be via an ajax request
171
        $this->_current_txn = $TXN_model->get_transaction_from_reg_url_link($this->_reg_url_link);
172
        // verify TXN
173
        if (WP_DEBUG && ! $this->_current_txn instanceof EE_Transaction) {
174
            EE_Error::add_error(
175
                __(
176
                    'No transaction information could be retrieved or the transaction data is not of the correct type.',
177
                    'event_espresso'
178
                ),
179
                __FILE__,
180
                __FUNCTION__,
181
                __LINE__
182
            );
183
            return null;
184
        }
185
        return $this->_current_txn;
186
    }
187
188
189
190
    /**
191
     * get_txn_payments
192
     *
193
     * @param int $since
194
     * @return mixed array of EE_Payment || FALSE
195
     * @throws \EE_Error
196
     */
197
    public function get_txn_payments($since = 0)
198
    {
199
        if ( ! $this->get_txn()) {
200
            return false;
201
        }
202
        $args = array('order_by' => array('PAY_timestamp' => 'ASC'));
203
        if ($since > 0) {
204
            $args[0] = array('PAY_timestamp' => array('>', $since));
205
        }
206
        // get array of payments with most recent first
207
        return $this->_current_txn->payments($args);
208
    }
209
210
211
212
    /**
213
     * get_reg_url_link
214
     *
215
     * @return void
216
     */
217
    private function _get_reg_url_link()
218
    {
219
        if ( ! empty($this->_reg_url_link)) {
220
            return;
221
        }
222
        // only do thank you page stuff if we have a REG_url_link in the url
223 View Code Duplication
        if (WP_DEBUG && ! EE_Registry::instance()->REQ->is_set('e_reg_url_link')) {
224
            EE_Error::add_error(
225
                __(
226
                    'No transaction information could be retrieved because the registration URL link is missing or invalid.',
227
                    'event_espresso'
228
                ),
229
                __FILE__,
230
                __FUNCTION__,
231
                __LINE__
232
            );
233
            return;
234
        }
235
        // check for reg_url_link
236
        $this->_reg_url_link = EE_Registry::instance()->REQ->get('e_reg_url_link');
237
    }
238
239
240
241
    /**
242
     * set_reg_url_link
243
     *
244
     * @param string $reg_url_link
245
     */
246
    public function set_reg_url_link($reg_url_link = null)
247
    {
248
        $this->_reg_url_link = ! empty($reg_url_link) ? $reg_url_link : $this->_reg_url_link;
249
    }
250
251
252
253
    /**
254
     * run - initial module setup
255
     * this method is primarily used for activating resources in the EE_Front_Controller thru the use of filters
256
     *
257
     * @param WP $WP
258
     * @return void
259
     * @throws \EE_Error
260
     */
261
    public function run($WP)
262
    {
263
264
    }
265
266
267
268
    /**
269
     * load_resources
270
     *
271
     * @return void
272
     * @throws \EE_Error
273
     */
274
    public function load_resources() {
275
        $this->_get_reg_url_link();
276
        // resend_reg_confirmation_email ?
277
        if (EE_Registry::instance()->REQ->is_set('resend')) {
278
            EED_Thank_You_Page::resend_reg_confirmation_email();
279
        }
280
        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
281
        $this->_translate_strings();
282
        // load assets
283
        add_action('wp_enqueue_scripts', array($this, 'load_js'), 10);
284
    }
285
286
287
288
    /**
289
     * load_js
290
     *
291
     * @return void
292
     */
293
    protected function _translate_strings()
294
    {
295
        EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->_reg_url_link;
296
        EE_Registry::$i18n_js_strings['initial_access'] = time();
297
        EE_Registry::$i18n_js_strings['IPN_wait_time'] = EED_Thank_You_Page::IPN_wait_time;
298
        EE_Registry::$i18n_js_strings['TXN_complete'] = EEM_Transaction::complete_status_code;
299
        EE_Registry::$i18n_js_strings['TXN_incomplete'] = EEM_Transaction::incomplete_status_code;
300
        EE_Registry::$i18n_js_strings['checking_for_new_payments'] = __(
301
            'checking for new payments...',
302
            'event_espresso'
303
        );
304
        EE_Registry::$i18n_js_strings['loading_payment_info'] = __(
305
            'loading payment information...',
306
            'event_espresso'
307
        );
308
        EE_Registry::$i18n_js_strings['server_error'] = __(
309
            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again.',
310
            'event_espresso'
311
        );
312
        EE_Registry::$i18n_js_strings['slow_IPN'] = apply_filters(
313
            'EED_Thank_You_Page__load_js__slow_IPN',
314
            sprintf(
315
                __(
316
                    '%sThe Payment Notification appears to be taking longer than usual to arrive. Maybe check back later or just wait for your payment and registration confirmation results to be sent to you via email. We apologize for any inconvenience this may have caused.%s',
317
                    'event_espresso'
318
                ),
319
                '<div id="espresso-thank-you-page-slow-IPN-dv" class="ee-attention jst-left">',
320
                '</div>'
321
            )
322
        );
323
    }
324
325
326
327
    /**
328
     * load_js
329
     *
330
     * @return void
331
     */
332
    public function load_js()
333
    {
334
        wp_register_script(
335
            'thank_you_page',
336
            THANK_YOU_ASSETS_URL . 'thank_you_page.js',
337
            array('espresso_core', 'heartbeat'),
338
            EVENT_ESPRESSO_VERSION,
339
            true
340
        );
341
        wp_enqueue_script('thank_you_page');
342
    }
343
344
345
346
    /**
347
     * init
348
     *
349
     * @return void
350
     * @throws \EE_Error
351
     */
352
    public function init()
353
    {
354
        $this->_get_reg_url_link();
355
        if ( ! $this->get_txn()) {
356
            echo EEH_HTML::div(
357
                EEH_HTML::h4(__('We\'re sorry...', 'event_espresso'), '', '') .
358
                sprintf(
359
                    __(
360
                        'This is a system page for displaying transaction information after a purchase.%1$sYou are most likely seeing this notice because you have navigated to this page%1$sthrough some means other than completing a transaction.%1$sSorry for the disappointment, but you will most likely find nothing of interest here.%1$s%1$s',
361
                        'event_espresso'
362
                    ),
363
                    '<br/>'
364
                ),
365
                '',
366
                'ee-attention'
367
            );
368
            return null;
369
        }
370
        // if we've made it to the Thank You page, then let's toggle any "Failed" transactions to "Incomplete"
371
        if ($this->_current_txn->status_ID() === EEM_Transaction::failed_status_code) {
372
            $this->_current_txn->set_status(EEM_Transaction::incomplete_status_code);
373
            $this->_current_txn->save();
374
        }
375
        $this->_primary_registrant = $this->_current_txn->primary_registration() instanceof EE_Registration
376
            ? $this->_current_txn->primary_registration()
377
            : null;
378
        $this->_is_primary = $this->_primary_registrant->reg_url_link() === $this->_reg_url_link ? true : false;
379
        $show_try_pay_again_link_default = apply_filters(
380
            'AFEE__EED_Thank_You_Page__init__show_try_pay_again_link_default',
381
            true
382
        );
383
        $this->_show_try_pay_again_link = $show_try_pay_again_link_default;
384
        // txn status ?
385
        if ($this->_current_txn->is_completed()) {
386
            $this->_show_try_pay_again_link = $show_try_pay_again_link_default;
387
        } else if (
388
            $this->_current_txn->is_incomplete()
389
            && ($this->_primary_registrant->is_approved()
390
                || $this->_primary_registrant->is_pending_payment())
391
        ) {
392
            $this->_show_try_pay_again_link = true;
393
        } else if ($this->_primary_registrant->is_approved() || $this->_primary_registrant->is_pending_payment()) {
394
            // its pending
395
            $this->_show_try_pay_again_link = isset(
396
                                                  EE_Registry::instance()->CFG->registration->show_pending_payment_options
397
                                              )
398
                                              && EE_Registry::instance()->CFG->registration->show_pending_payment_options
399
                ? true
400
                : $show_try_pay_again_link_default;
401
        }
402
        $this->_payments_closed = ! $this->_current_txn->payment_method() instanceof EE_Payment_Method
403
            ? true
404
            : false;
405
        $this->_is_offline_payment_method = false;
406
        if (
407
            // if payment method is unknown
408
            ! $this->_current_txn->payment_method() instanceof EE_Payment_Method
409
            || (
410
                // or is an offline payment method
411
                $this->_current_txn->payment_method() instanceof EE_Payment_Method
412
                && $this->_current_txn->payment_method()->is_off_line()
413
            )
414
        ) {
415
            $this->_is_offline_payment_method = true;
416
        }
417
        // link to SPCO
418
        $revisit_spco_url = add_query_arg(
419
            array('ee' => '_register', 'revisit' => true, 'e_reg_url_link' => $this->_reg_url_link),
420
            EE_Registry::instance()->CFG->core->reg_page_url()
421
        );
422
        // link to SPCO payment_options
423
        $this->_SPCO_payment_options_url = $this->_primary_registrant instanceof EE_Registration
424
            ? $this->_primary_registrant->payment_overview_url()
425
            : add_query_arg(
426
                array('step' => 'payment_options'),
427
                $revisit_spco_url
428
            );
429
        // link to SPCO attendee_information
430
        $this->_SPCO_attendee_information_url = $this->_primary_registrant instanceof EE_Registration
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->_primary_registra...formation_url() : false can also be of type false. However, the property $_SPCO_attendee_information_url is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
431
            ? $this->_primary_registrant->edit_attendee_information_url()
432
            : false;
433
        do_action('AHEE__EED_Thank_You_Page__init_end', $this->_current_txn);
434
        // set no cache headers and constants
435
        EE_System::do_not_cache();
436
    }
437
438
439
440
    /**
441
     * display_thank_you_page_results
442
     *
443
     * @return string
444
     * @throws \EE_Error
445
     */
446
    public function thank_you_page_results()
447
    {
448
        $this->init();
449
        if ( ! $this->_current_txn instanceof EE_Transaction) {
450
            return EE_Error::get_notices();
0 ignored issues
show
Bug Compatibility introduced by
The expression \EE_Error::get_notices(); of type null|string|array<string,string> adds the type array<string,string> to the return on line 450 which is incompatible with the return type documented by EED_Thank_You_Page::thank_you_page_results of type string.
Loading history...
451
        }
452
        // link to receipt
453
        $template_args['TXN_receipt_url'] = $this->_current_txn->receipt_url('html');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$template_args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $template_args = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
454
        if ( ! empty($template_args['TXN_receipt_url'])) {
455
            $template_args['order_conf_desc'] = __(
456
                '%1$sCongratulations%2$sYour registration has been successfully processed.%3$sCheck your email for your registration confirmation or click the button below to view / download / print a full description of your purchases and registration information.',
457
                'event_espresso'
458
            );
459
        } else {
460
            $template_args['order_conf_desc'] = __(
461
                '%1$sCongratulations%2$sYour registration has been successfully processed.%3$sCheck your email for your registration confirmation.',
462
                'event_espresso'
463
            );
464
        }
465
        $template_args['transaction'] = $this->_current_txn;
466
        $template_args['revisit'] = EE_Registry::instance()->REQ->get('revisit', false);
467
        add_action('AHEE__thank_you_page_overview_template__content', array($this, 'get_registration_details'));
468
        if ($this->_is_primary && ! $this->_current_txn->is_free()) {
469
            add_action('AHEE__thank_you_page_overview_template__content', array($this, 'get_ajax_content'));
470
        }
471
        return EEH_Template::locate_template(
472
            THANK_YOU_TEMPLATES_PATH . 'thank-you-page-overview.template.php',
473
            $template_args,
474
            true,
475
            true
476
        );
477
    }
478
479
480
481
    /**
482
     * thank_you_page_IPN_monitor
483
     * this basically just pulls the TXN based on the reg_url_link sent from the server,
484
     * then checks that the TXN status is not failed, and that no other errors have been generated.
485
     * it also calculates the IPN wait time since the Thank You page was first loaded
486
     *
487
     * @param array $response
488
     * @param array $data
489
     * @return array
490
     * @throws \EE_Error
491
     */
492
    public static function thank_you_page_IPN_monitor($response = array(), $data = array())
493
    {
494
        // does this heartbeat contain our data ?
495
        if ( ! isset($data['espresso_thank_you_page'])) {
496
            return $response;
497
        }
498
        // check for reg_url_link in the incoming heartbeat data
499
        if ( ! isset($data['espresso_thank_you_page']['e_reg_url_link'])) {
500
            $response['espresso_thank_you_page'] = array(
501
                'errors' => ! empty($notices['errors'])
0 ignored issues
show
Bug introduced by
The variable $notices seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
502
                    ? $notices['errors']
503
                    : __(
504
                        'No transaction information could be retrieved because the registration URL link is missing or invalid.',
505
                        'event_espresso'
506
                    )
507
            );
508
            return $response;
509
        }
510
        // kk heartbeat has our data
511
        $response['espresso_thank_you_page'] = array();
512
        // set_definitions, instantiate the thank you page class, and get the ball rolling
513
        EED_Thank_You_Page::set_definitions();
514
        /** @var $espresso_thank_you_page EED_Thank_You_Page */
515
        $espresso_thank_you_page = EED_Thank_You_Page::instance();
516
        $espresso_thank_you_page->set_reg_url_link($data['espresso_thank_you_page']['e_reg_url_link']);
517
        $espresso_thank_you_page->init();
518
        //get TXN
519
        $TXN = $espresso_thank_you_page->get_txn();
520
        // no TXN? then get out
521
        if ( ! $TXN instanceof EE_Transaction) {
522
            $notices = EE_Error::get_notices();
523
            $response['espresso_thank_you_page'] = array(
524
                'errors' => ! empty($notices['errors'])
525
                    ? $notices['errors']
526
                    : sprintf(
527
                        __(
528
                            'The information for your transaction could not be retrieved from the server or the transaction data received was invalid because of a technical reason. (%s)',
529
                            'event_espresso'
530
                        ),
531
                        __LINE__
532
                    )
533
            );
534
            return $response;
535
        }
536
        // grab transient of TXN's status
537
        $txn_status = isset($data['espresso_thank_you_page']['txn_status'])
538
            ? $data['espresso_thank_you_page']['txn_status']
539
            : null;
540
        // has the TXN status changed since we last checked (or empty because this is the first time running through this code)?
541
        if ($txn_status !== $TXN->status_ID()) {
542
            // switch between two possible basic outcomes
543
            switch ($TXN->status_ID()) {
544
                // TXN has been updated in some way
545
                case EEM_Transaction::overpaid_status_code:
546
                case EEM_Transaction::complete_status_code:
547
                case EEM_Transaction::incomplete_status_code:
548
                    // send updated TXN results back to client,
549
                    $response['espresso_thank_you_page'] = array(
550
                        'transaction_details' => $espresso_thank_you_page->get_transaction_details(),
551
                        'txn_status'          => $TXN->status_ID()
552
                    );
553
                    break;
554
                // or we have a bad TXN, or really slow IPN, so calculate the wait time and send that back...
555
                case EEM_Transaction::failed_status_code:
556
                default:
557
                    // keep on waiting...
558
                    return $espresso_thank_you_page->_update_server_wait_time($data['espresso_thank_you_page']);
559
            }
560
            // or is the TXN still failed (never been updated) ???
561
        } else if ($TXN->failed()) {
562
            // keep on waiting...
563
            return $espresso_thank_you_page->_update_server_wait_time($data['espresso_thank_you_page']);
564
        }
565
        // TXN is happening so let's get the payments now
566
        // if we've already gotten payments then the heartbeat data will contain the timestamp of the last time we checked
567
        $since = isset($data['espresso_thank_you_page']['get_payments_since'])
568
            ? $data['espresso_thank_you_page']['get_payments_since']
569
            : 0;
570
        // then check for payments
571
        $payments = $espresso_thank_you_page->get_txn_payments($since);
572
        // has a payment been processed ?
573
        if ( ! empty($payments) || $espresso_thank_you_page->_is_offline_payment_method) {
574
            if ($since) {
575
                $response['espresso_thank_you_page'] = array(
576
                    'new_payments'        => $espresso_thank_you_page->get_new_payments($payments),
0 ignored issues
show
Security Bug introduced by
It seems like $payments defined by $espresso_thank_you_page...et_txn_payments($since) on line 571 can also be of type false; however, EED_Thank_You_Page::get_new_payments() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
577
                    'transaction_details' => $espresso_thank_you_page->get_transaction_details(),
578
                    'txn_status'          => $TXN->status_ID()
579
                );
580
            } else {
581
                $response['espresso_thank_you_page']['payment_details'] = $espresso_thank_you_page->get_payment_details(
582
                    $payments
0 ignored issues
show
Security Bug introduced by
It seems like $payments defined by $espresso_thank_you_page...et_txn_payments($since) on line 571 can also be of type false; however, EED_Thank_You_Page::get_payment_details() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
583
                );
584
            }
585
            // reset time to check for payments
586
            $response['espresso_thank_you_page']['get_payments_since'] = time();
587
        } else {
588
            $response['espresso_thank_you_page']['get_payments_since'] = $since;
589
        }
590
        return $response;
591
    }
592
593
594
595
    /**
596
     * _update_server_wait_time
597
     *
598
     * @param array $thank_you_page_data thank you page portion of the incoming JSON array from the WP heartbeat data
599
     * @return array
600
     * @throws \EE_Error
601
     */
602
    private function _update_server_wait_time($thank_you_page_data = array())
603
    {
604
        $response['espresso_thank_you_page'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
605
            'still_waiting' => isset($thank_you_page_data['initial_access'])
606
                ? time() - $thank_you_page_data['initial_access']
607
                : 0,
608
            'txn_status'    => $this->_current_txn->status_ID()
609
        );
610
        return $response;
611
    }
612
613
614
615
    /**
616
     * get_registration_details
617
     *
618
     * @throws \EE_Error
619
     */
620
    public function get_registration_details()
621
    {
622
        //prepare variables for displaying
623
        $template_args = array();
624
        $template_args['transaction'] = $this->_current_txn;
625
        $template_args['reg_url_link'] = $this->_reg_url_link;
626
        $template_args['is_primary'] = $this->_is_primary;
627
        $template_args['SPCO_attendee_information_url'] = $this->_SPCO_attendee_information_url;
628
        $template_args['resend_reg_confirmation_url'] = add_query_arg(
629
            array('token' => $this->_reg_url_link, 'resend_reg_confirmation' => 'true'),
630
            EE_Registry::instance()->CFG->core->thank_you_page_url()
631
        );
632
        // verify template arguments
633
        EEH_Template_Validator::verify_instanceof($template_args['transaction'], '$transaction', 'EE_Transaction');
634
        EEH_Template_Validator::verify_isnt_null(
635
            $template_args['SPCO_attendee_information_url'],
636
            '$SPCO_attendee_information_url'
637
        );
638
        echo EEH_Template::locate_template(
639
            THANK_YOU_TEMPLATES_PATH . 'thank-you-page-registration-details.template.php',
640
            $template_args,
641
            true,
642
            true
643
        );
644
    }
645
646
647
648
    /**
649
     * resend_reg_confirmation_email
650
     *
651
     * @throws \EE_Error
652
     */
653
    public static function resend_reg_confirmation_email()
654
    {
655
        EE_Registry::instance()->load_core('Request_Handler');
656
        $reg_url_link = EE_Registry::instance()->REQ->get('token');
657
        // was a REG_ID passed ?
658
        if ($reg_url_link) {
659
            $registration = EE_Registry::instance()->load_model('Registration')->get_one(
660
                array(array('REG_url_link' => $reg_url_link))
661
            );
662
            if ($registration instanceof EE_Registration) {
663
                // resend email
664
                EED_Messages::process_resend(array('_REG_ID' => $registration->ID()));
665
            } else {
666
                EE_Error::add_error(
667
                    __(
668
                        'The Registration Confirmation email could not be sent because a valid Registration could not be retrieved from the database.',
669
                        'event_espresso'
670
                    ),
671
                    __FILE__,
672
                    __FUNCTION__,
673
                    __LINE__
674
                );
675
            }
676
        } else {
677
            EE_Error::add_error(
678
                __(
679
                    'The Registration Confirmation email could not be sent because a registration token is missing or invalid.',
680
                    'event_espresso'
681
                ),
682
                __FILE__,
683
                __FUNCTION__,
684
                __LINE__
685
            );
686
        }
687
        // request sent via AJAX ?
688
        if (EE_FRONT_AJAX) {
689
            echo wp_json_encode(EE_Error::get_notices(false));
690
            die();
691
            // or was JS disabled ?
692
        } else {
693
            // save errors so that they get picked up on the next request
694
            EE_Error::get_notices(true, true);
695
            wp_safe_redirect(
696
                add_query_arg(
697
                    array('e_reg_url_link' => $reg_url_link),
698
                    EE_Registry::instance()->CFG->core->thank_you_page_url()
699
                )
700
            );
701
        }
702
    }
703
704
705
706
    /**
707
     * get_ajax_content
708
     *
709
     * @return void
710
     * @throws \EE_Error
711
     */
712
    public function get_ajax_content()
713
    {
714
        if ( ! $this->get_txn()) {
715
            return;
716
        }
717
        // first determine which event(s) require pre-approval or not
718
        $events = array();
719
        $events_requiring_pre_approval = array();
720
        foreach ($this->_current_txn->registrations() as $registration) {
721
            if ($registration instanceof EE_Registration) {
722
                $event = $registration->event();
723
                if ($event instanceof EE_Event) {
724
                    if ($registration->is_not_approved() && $registration->event() instanceof EE_Event) {
725
                        $events_requiring_pre_approval[$event->ID()] = $event;
726
                    } else {
727
                        $events[$event->ID()] = $event;
728
                    }
729
                }
730
            }
731
        }
732
        $this->display_details_for_events_requiring_pre_approval($events_requiring_pre_approval);
733
        $this->display_details_for_events($events);
734
    }
735
736
737
738
    /**
739
     * display_details_for_events
740
     *
741
     * @param EE_Event[] $events
742
     * @return void
743
     */
744
    public function display_details_for_events($events = array())
745
    {
746
        if ( ! empty($events)) {
747
            ?>
748
            <div id="espresso-thank-you-page-ajax-content-dv">
749
                <div id="espresso-thank-you-page-ajax-transaction-dv"></div>
750
                <div id="espresso-thank-you-page-ajax-payment-dv"></div>
751
                <div id="espresso-thank-you-page-ajax-loading-dv">
752
                    <div id="ee-ajax-loading-dv" class="float-left lt-blue-text">
753
                        <span class="dashicons dashicons-upload"></span><span id="ee-ajax-loading-msg-spn"><?php _e(
754
                                'loading transaction and payment information...',
755
                                'event_espresso'
756
                            ); ?></span>
757
                    </div>
758
                    <?php if ( ! $this->_is_offline_payment_method && ! $this->_payments_closed) : ?>
759
                        <p id="ee-ajax-loading-pg" class="highlight-bg small-text clear">
760
                            <?php echo apply_filters(
761
                                'EED_Thank_You_Page__get_ajax_content__waiting_for_IPN_msg',
762
                                __(
763
                                    'Some payment gateways can take 15 minutes or more to return their payment notification, so please be patient if you require payment confirmation as soon as possible. Please note that as soon as everything is finalized, we will send your full payment and registration confirmation results to you via email.',
764
                                    'event_espresso'
765
                                )
766
                            ); ?>
767
                            <br/>
768
                            <span class="jst-rght ee-block small-text lt-grey-text">
769
								<?php _e('current wait time ', 'event_espresso'); ?>
770
                                <span id="espresso-thank-you-page-ajax-time-dv">00:00:00</span></span>
771
                        </p>
772
                    <?php endif; ?>
773
                </div>
774
                <div class="clear"></div>
775
            </div>
776
            <?php
777
        }
778
    }
779
780
781
782
    /**
783
     * display_details_for_events_requiring_pre_approval
784
     *
785
     * @param EE_Event[] $events
786
     * @return void
787
     */
788
    public function display_details_for_events_requiring_pre_approval($events = array())
789
    {
790 View Code Duplication
        if ( ! empty($events)) {
791
            ?>
792
            <div id="espresso-thank-you-page-not-approved-message-dv">
793
                <h4 class="orange-text"><?php _e('Important Notice:', 'event_espresso'); ?></h4>
794
                <p id="events-requiring-pre-approval-pg" class="small-text">
795
                    <?php echo apply_filters(
796
                        'AHEE__EED_Thank_You_Page__get_ajax_content__not_approved_message',
797
                        __(
798
                            'The following Event(s) you have registered for do not require payment at this time and will not be billed for during this transaction. Billing will only occur after all attendees have been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
799
                            'event_espresso'
800
                        )
801
                    ); ?>
802
                </p>
803
                <ul class="events-requiring-pre-approval-ul">
804
                    <?php foreach ($events as $event) {
805
                        if ($event instanceof EE_Event) {
806
                            echo '<li><span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>',
807
                            $event->name(),
808
                            '</li>';
809
                        }
810
                    } ?>
811
                </ul>
812
                <div class="clear"></div>
813
            </div>
814
            <?php
815
        }
816
    }
817
818
819
820
    /**
821
     * get_transaction_details
822
     *
823
     * @return string
824
     * @throws \EE_Error
825
     */
826
    public function get_transaction_details()
827
    {
828
        //prepare variables for displaying
829
        $template_args = array();
830
        $template_args['transaction'] = $this->_current_txn;
831
        $template_args['reg_url_link'] = $this->_reg_url_link;
832
        $template_args['primary_registrant_name'] = $this->_primary_registrant->attendee()->full_name(true);
833
        // link to SPCO payment_options
834
        $template_args['show_try_pay_again_link'] = $this->_show_try_pay_again_link;
835
        $template_args['SPCO_payment_options_url'] = $this->_SPCO_payment_options_url;
836
        // verify template arguments
837
        EEH_Template_Validator::verify_instanceof($template_args['transaction'], '$transaction', 'EE_Transaction');
838
        EEH_Template_Validator::verify_isnt_null(
839
            $template_args['show_try_pay_again_link'],
840
            '$show_try_pay_again_link'
841
        );
842
        EEH_Template_Validator::verify_isnt_null(
843
            $template_args['SPCO_payment_options_url'],
844
            '$SPCO_payment_options_url'
845
        );
846
        return EEH_Template::locate_template(
847
            THANK_YOU_TEMPLATES_PATH . 'thank-you-page-transaction-details.template.php',
848
            $template_args,
849
            true,
850
            true
851
        );
852
    }
853
854
855
856
    /**
857
     * get_payment_row_html
858
     *
859
     * @param EE_Payment $payment
860
     * @return string
861
     * @throws \EE_Error
862
     */
863
    public function get_payment_row_html($payment = null)
864
    {
865
        $html = '';
866
        if ($payment instanceof EE_Payment) {
867
            if (
868
                $payment->payment_method() instanceof EE_Payment_Method
869
                && $payment->status() === EEM_Payment::status_id_failed
870
                && $payment->payment_method()->is_off_site()
871
            ) {
872
                // considering the registrant has made it to the Thank You page,
873
                // any failed payments may actually be pending and the IPN is just slow
874
                // so let's
875
                $payment->set_status(EEM_Payment::status_id_pending);
876
            }
877
            $payment_declined_msg = $payment->STS_ID() === EEM_Payment::status_id_declined
878
                ? '<br /><span class="small-text">' . $payment->gateway_response() . '</span>'
879
                : '';
880
            $html .= '
881
				<tr>
882
					<td>
883
						' . $payment->timestamp() . '
884
					</td>
885
					<td>
886
						' . (
887
                $payment->payment_method() instanceof EE_Payment_Method
888
                    ? $payment->payment_method()->name()
889
                    : __('Unknown', 'event_espresso')
890
                ) . '
891
					</td>
892
					<td class="jst-rght">
893
						' . EEH_Template::format_currency($payment->amount()) . '
894
					</td>
895
					<td class="jst-rght" style="line-height:1;">
896
						' . $payment->pretty_status(true) . $payment_declined_msg . '
897
					</td>
898
				</tr>';
899
            do_action('AHEE__thank_you_page_payment_details_template__after_each_payment', $payment);
900
        }
901
        return $html;
902
    }
903
904
905
906
    /**
907
     * get_payment_details
908
     *
909
     * @param array $payments
910
     * @return string
911
     * @throws \EE_Error
912
     */
913
    public function get_payment_details($payments = array())
914
    {
915
        //prepare variables for displaying
916
        $template_args = array();
917
        $template_args['transaction'] = $this->_current_txn;
918
        $template_args['reg_url_link'] = $this->_reg_url_link;
919
        $template_args['payments'] = array();
920
        foreach ($payments as $payment) {
921
            $template_args['payments'][] = $this->get_payment_row_html($payment);
922
        }
923
        //create a hacky payment object, but dont save it
924
        $payment = EE_Payment::new_instance(
925
            array(
926
                'TXN_ID'        => $this->_current_txn->ID(),
927
                'STS_ID'        => EEM_Payment::status_id_pending,
928
                'PAY_timestamp' => time(),
929
                'PAY_amount'    => $this->_current_txn->total(),
930
                'PMD_ID'        => $this->_current_txn->payment_method_ID()
931
            )
932
        );
933
        $payment_method = $this->_current_txn->payment_method();
934
        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj() instanceof EE_PMT_Base) {
935
            $template_args['gateway_content'] = $payment_method->type_obj()->payment_overview_content($payment);
936
        } else {
937
            $template_args['gateway_content'] = '';
938
        }
939
        // link to SPCO payment_options
940
        $template_args['show_try_pay_again_link'] = $this->_show_try_pay_again_link;
941
        $template_args['SPCO_payment_options_url'] = $this->_SPCO_payment_options_url;
942
        // verify template arguments
943
        EEH_Template_Validator::verify_instanceof($template_args['transaction'], '$transaction', 'EE_Transaction');
944
        EEH_Template_Validator::verify_isnt_null($template_args['payments'], '$payments');
945
        EEH_Template_Validator::verify_isnt_null(
946
            $template_args['show_try_pay_again_link'],
947
            '$show_try_pay_again_link'
948
        );
949
        EEH_Template_Validator::verify_isnt_null($template_args['gateway_content'], '$gateway_content');
950
        EEH_Template_Validator::verify_isnt_null(
951
            $template_args['SPCO_payment_options_url'],
952
            '$SPCO_payment_options_url'
953
        );
954
        return EEH_Template::locate_template(
955
            THANK_YOU_TEMPLATES_PATH . 'thank-you-page-payment-details.template.php',
956
            $template_args,
957
            true,
958
            true
959
        );
960
    }
961
962
963
964
    /**
965
     * get_payment_details
966
     *
967
     * @param array $payments
968
     * @return string
969
     * @throws \EE_Error
970
     */
971
    public function get_new_payments($payments = array())
972
    {
973
        $payments_html = '';
974
        //prepare variables for displaying
975
        foreach ($payments as $payment) {
976
            $payments_html .= $this->get_payment_row_html($payment);
977
        }
978
        return $payments_html;
979
    }
980
981
982
}
983
// End of file EED_Thank_You_Page.php
984
// Location: ${NAMESPACE}/EED_Thank_You_Page.php