Completed
Branch FET-10416-autoload-b4-bootstra... (130b1a)
by
unknown
107:49 queued 97:15
created
core/domain/services/event/EventSpacesCalculator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@
 block discarded – undo
164 164
 
165 165
 
166 166
     /**
167
-     * @param $ticket
167
+     * @param \EE_Base_Class $ticket
168 168
      * @throws DomainException
169 169
      * @throws EE_Error
170 170
      * @throws UnexpectedEntityException
Please login to merge, or discard this patch.
Indentation   +614 added lines, -614 removed lines patch added patch discarded remove patch
@@ -31,620 +31,620 @@
 block discarded – undo
31 31
 class EventSpacesCalculator
32 32
 {
33 33
 
34
-    /**
35
-     * @var EE_Event $event
36
-     */
37
-    private $event;
38
-
39
-    /**
40
-     * @var array $datetime_query_params
41
-     */
42
-    private $datetime_query_params;
43
-
44
-    /**
45
-     * @var EE_Ticket[] $active_tickets
46
-     */
47
-    private $active_tickets = array();
48
-
49
-    /**
50
-     * @var EE_Datetime[] $datetimes
51
-     */
52
-    private $datetimes = array();
53
-
54
-    /**
55
-     * Array of Ticket IDs grouped by Datetime
56
-     *
57
-     * @var array $datetimes
58
-     */
59
-    private $datetime_tickets = array();
60
-
61
-    /**
62
-     * Max spaces for each Datetime (reg limit - previous sold)
63
-     *
64
-     * @var array $datetime_spaces
65
-     */
66
-    private $datetime_spaces = array();
67
-
68
-    /**
69
-     * Array of Datetime IDs grouped by Ticket
70
-     *
71
-     * @var array $ticket_datetimes
72
-     */
73
-    private $ticket_datetimes = array();
74
-
75
-    /**
76
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
77
-     *
78
-     * @var array $ticket_quantities
79
-     */
80
-    private $ticket_quantities = array();
81
-
82
-    /**
83
-     * total quantity of sold and reserved for each ticket
84
-     *
85
-     * @var array $tickets_sold
86
-     */
87
-    private $tickets_sold = array();
88
-
89
-    /**
90
-     * total spaces available across all datetimes
91
-     *
92
-     * @var array $total_spaces
93
-     */
94
-    private $total_spaces = array();
95
-
96
-    /**
97
-     * @var boolean $debug
98
-     */
99
-    private $debug = false;
100
-
101
-
102
-
103
-    /**
104
-     * EventSpacesCalculator constructor.
105
-     *
106
-     * @param EE_Event $event
107
-     * @param array    $datetime_query_params
108
-     * @throws EE_Error
109
-     */
110
-    public function __construct(EE_Event $event, array $datetime_query_params = array())
111
-    {
112
-        $this->event                 = $event;
113
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * @return EE_Ticket[]
120
-     * @throws EE_Error
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     * @throws InvalidArgumentException
124
-     */
125
-    public function getActiveTickets()
126
-    {
127
-        if (empty($this->active_tickets)) {
128
-            $this->active_tickets = $this->event->tickets(
129
-                array(
130
-                    array(
131
-                        'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
132
-                        'TKT_deleted'  => false,
133
-                    ),
134
-                    'order_by' => array('TKT_qty' => 'ASC'),
135
-                )
136
-            );
137
-        }
138
-        return $this->active_tickets;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * @param EE_Ticket[] $active_tickets
145
-     * @throws EE_Error
146
-     * @throws DomainException
147
-     * @throws UnexpectedEntityException
148
-     */
149
-    public function setActiveTickets(array $active_tickets = array())
150
-    {
151
-        if ( ! empty($active_tickets)) {
152
-            foreach ($active_tickets as $active_ticket) {
153
-                $this->validateTicket($active_ticket);
154
-            }
155
-            // sort incoming array by ticket quantity (asc)
156
-            usort(
157
-                $active_tickets,
158
-                function (EE_Ticket $a, EE_Ticket $b) {
159
-                    if ($a->qty() === $b->qty()) {
160
-                        return 0;
161
-                    }
162
-                    return ($a->qty() < $b->qty())
163
-                        ? -1
164
-                        : 1;
165
-                }
166
-            );
167
-        }
168
-        $this->active_tickets = $active_tickets;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * @param $ticket
175
-     * @throws DomainException
176
-     * @throws EE_Error
177
-     * @throws UnexpectedEntityException
178
-     */
179
-    private function validateTicket($ticket)
180
-    {
181
-        if ( ! $ticket instanceof EE_Ticket) {
182
-            throw new DomainException(
183
-                esc_html__(
184
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
185
-                    'event_espresso'
186
-                )
187
-            );
188
-        }
189
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
190
-            throw new DomainException(
191
-                sprintf(
192
-                    esc_html__(
193
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
194
-                        'event_espresso'
195
-                    ),
196
-                    $ticket->get_event_ID(),
197
-                    $this->event->ID()
198
-                )
199
-            );
200
-        }
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * @return EE_Datetime[]
207
-     */
208
-    public function getDatetimes()
209
-    {
210
-        return $this->datetimes;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * @param EE_Datetime $datetime
217
-     * @throws EE_Error
218
-     * @throws DomainException
219
-     */
220
-    public function setDatetime(EE_Datetime $datetime)
221
-    {
222
-        if ($datetime->event()->ID() !== $this->event->ID()) {
223
-            throw new DomainException(
224
-                sprintf(
225
-                    esc_html__(
226
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
227
-                        'event_espresso'
228
-                    ),
229
-                    $datetime->event()->ID(),
230
-                    $this->event->ID()
231
-                )
232
-            );
233
-        }
234
-        $this->datetimes[ $datetime->ID() ] = $datetime;
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * calculate spaces remaining based on "saleable" tickets
241
-     *
242
-     * @return float|int
243
-     * @throws EE_Error
244
-     * @throws DomainException
245
-     * @throws UnexpectedEntityException
246
-     * @throws InvalidDataTypeException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidArgumentException
249
-     */
250
-    public function spacesRemaining()
251
-    {
252
-        $this->initialize();
253
-        return $this->calculate();
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     * calculates total available spaces for an event with no regard for sold tickets
260
-     *
261
-     * @return int|float
262
-     * @throws EE_Error
263
-     * @throws DomainException
264
-     * @throws UnexpectedEntityException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws InvalidArgumentException
268
-     */
269
-    public function totalSpacesAvailable()
270
-    {
271
-        $this->initialize();
272
-        return $this->calculate(false);
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * Loops through the active tickets for the event
279
-     * and builds a series of data arrays that will be used for calculating
280
-     * the total maximum available spaces, as well as the spaces remaining.
281
-     * Because ticket quantities affect datetime spaces and vice versa,
282
-     * we need to be constantly updating these data arrays as things change,
283
-     * which is the entire reason for their existence.
284
-     *
285
-     * @throws EE_Error
286
-     * @throws DomainException
287
-     * @throws UnexpectedEntityException
288
-     * @throws InvalidDataTypeException
289
-     * @throws InvalidInterfaceException
290
-     * @throws InvalidArgumentException
291
-     */
292
-    private function initialize()
293
-    {
294
-        if ($this->debug) {
295
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
296
-        }
297
-        $this->datetime_tickets  = array();
298
-        $this->datetime_spaces   = array();
299
-        $this->ticket_datetimes  = array();
300
-        $this->ticket_quantities = array();
301
-        $this->tickets_sold      = array();
302
-        $this->total_spaces      = array();
303
-        $active_tickets          = $this->getActiveTickets();
304
-        if ( ! empty($active_tickets)) {
305
-            foreach ($active_tickets as $ticket) {
306
-                $this->validateTicket($ticket);
307
-                // we need to index our data arrays using strings for the purpose of sorting,
308
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
309
-                $ticket_identifier = "T{$ticket->ID()}";
310
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket
311
-                $max_tickets = $ticket->qty();
312
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
313
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
314
-                foreach ($ticket_datetimes as $datetime) {
315
-                    // save all datetimes
316
-                    $this->setDatetime($datetime);
317
-                    $datetime_identifier = "D{$datetime->ID()}";
318
-                    $reg_limit           = $datetime->reg_limit();
319
-                    // ticket quantity can not exceed datetime reg limit
320
-                    $max_tickets = min($max_tickets, $reg_limit);
321
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
322
-                    // we are going to move all of our data into the following arrays:
323
-                    // datetime spaces initially represents the reg limit for each datetime,
324
-                    // but this will get adjusted as tickets are accounted for
325
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
326
-                    // just an array of ticket IDs grouped by datetime
327
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
328
-                    // and an array of datetime IDs grouped by ticket
329
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
330
-                }
331
-                // total quantity of sold and reserved for each ticket
332
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
333
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
334
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
335
-            }
336
-        }
337
-        // sort datetime spaces by reg limit, but maintain our string indexes
338
-        asort($this->datetime_spaces, SORT_NUMERIC);
339
-        // datetime tickets need to be sorted in the SAME order as the above array...
340
-        // so we'll just use array_merge() to take the structure of datetime_spaces
341
-        // but overwrite all of the data with that from datetime_tickets
342
-        $this->datetime_tickets = array_merge(
343
-            $this->datetime_spaces,
344
-            $this->datetime_tickets
345
-        );
346
-        if ($this->debug) {
347
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
348
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
349
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
350
-        }
351
-    }
352
-
353
-
354
-
355
-    /**
356
-     * performs calculations on initialized data
357
-     *
358
-     * @param bool $consider_sold
359
-     * @return int|float
360
-     */
361
-    private function calculate($consider_sold = true)
362
-    {
363
-        if ($this->debug) {
364
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
365
-        }
366
-        if ($consider_sold) {
367
-            // subtract amounts sold from all ticket quantities and datetime spaces
368
-            $this->adjustTicketQuantitiesDueToSales();
369
-        }
370
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
371
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
372
-        }
373
-        // total spaces available is just the sum of the spaces available for each datetime
374
-        $spaces_remaining = array_sum($this->total_spaces);
375
-        if ($this->debug) {
376
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
377
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
378
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
379
-        }
380
-        return $spaces_remaining;
381
-    }
382
-
383
-
384
-    /**
385
-     * subtracts amount of  tickets sold from ticket quantities and datetime spaces
386
-     */
387
-    private function adjustTicketQuantitiesDueToSales()
388
-    {
389
-        if ($this->debug) {
390
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
-        }
392
-        foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
393
-            if (isset($this->ticket_quantities[ $ticket_identifier ])){
394
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
395
-                if ($this->debug) {
396
-                    \EEH_Debug_Tools::printr("{$tickets_sold} sales for ticket {$ticket_identifier} ", 'subtracting', __FILE__, __LINE__);
397
-                }
398
-            }
399
-            if (
400
-                isset($this->ticket_datetimes[ $ticket_identifier ])
401
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
402
-            ){
403
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
404
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
405
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
406
-                        if ($this->debug) {
407
-                            \EEH_Debug_Tools::printr("{$tickets_sold} sales for datetime {$ticket_datetime} ",
408
-                                'subtracting', __FILE__, __LINE__);
409
-                        }
410
-                    }
411
-                }
412
-            }
413
-        }
414
-    }
415
-
416
-
417
-
418
-    /**
419
-     * @param string $datetime_identifier
420
-     * @param array  $tickets
421
-     */
422
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
423
-    {
424
-        // make sure a reg limit is set for the datetime
425
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
426
-            ? $this->datetime_spaces[ $datetime_identifier ]
427
-            : 0;
428
-        // and bail if it is not
429
-        if ( ! $reg_limit) {
430
-            if ($this->debug) {
431
-                \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
432
-            }
433
-            return;
434
-        }
435
-        if ($this->debug) {
436
-            \EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
437
-            \EEH_Debug_Tools::printr("{$reg_limit}", 'REG LIMIT', __FILE__, __LINE__);
438
-        }
439
-        // number of allocated spaces always starts at zero
440
-        $spaces_allocated                           = 0;
441
-        $this->total_spaces[ $datetime_identifier ] = 0;
442
-        foreach ($tickets as $ticket_identifier) {
443
-            $spaces_allocated = $this->calculateAvailableSpacesForTicket(
444
-                $datetime_identifier,
445
-                $reg_limit,
446
-                $ticket_identifier,
447
-                $spaces_allocated
448
-            );
449
-        }
450
-        // spaces can't be negative
451
-        $spaces_allocated = max($spaces_allocated, 0);
452
-        if ($spaces_allocated) {
453
-            // track any non-zero values
454
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
455
-            if ($this->debug) {
456
-                \EEH_Debug_Tools::printr((string)$spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
457
-            }
458
-        } else {
459
-            if ($this->debug) {
460
-                \EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
461
-            }
462
-        }
463
-        if ($this->debug) {
464
-            \EEH_Debug_Tools::printr($this->total_spaces[ $datetime_identifier ], '$total_spaces', __FILE__,
465
-                __LINE__);
466
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
467
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
468
-        }
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * @param string $datetime_identifier
475
-     * @param int    $reg_limit
476
-     * @param string $ticket_identifier
477
-     * @param int    $spaces_allocated
478
-     * @return int
479
-     */
480
-    private function calculateAvailableSpacesForTicket(
481
-        $datetime_identifier,
482
-        $reg_limit,
483
-        $ticket_identifier,
484
-        $spaces_allocated
485
-    ) {
486
-        // make sure ticket quantity is set
487
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
488
-            ? $this->ticket_quantities[ $ticket_identifier ]
489
-            : 0;
490
-        if ($this->debug) {
491
-            \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
492
-            \EEH_Debug_Tools::printr("{$ticket_quantity}", "ticket $ticket_identifier quantity: ",
493
-                __FILE__, __LINE__, 2);
494
-        }
495
-        if ($ticket_quantity) {
496
-            if ($this->debug) {
497
-                \EEH_Debug_Tools::printr(
498
-                    ($spaces_allocated <= $reg_limit)
499
-                        ? 'true'
500
-                        : 'false',
501
-                    ' . spaces_allocated <= reg_limit = ',
502
-                    __FILE__, __LINE__
503
-                );
504
-            }
505
-            // if the datetime is NOT at full capacity yet
506
-            if ($spaces_allocated <= $reg_limit) {
507
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
508
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
509
-                //  or the maximum ticket quantity
510
-                $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
511
-                // adjust the available quantity in our tracking array
512
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
513
-                // and increment spaces allocated for this datetime
514
-                $spaces_allocated += $ticket_quantity;
515
-                $at_capacity = $spaces_allocated >= $reg_limit;
516
-                if ($this->debug) {
517
-                    \EEH_Debug_Tools::printr("{$ticket_quantity} {$ticket_identifier} tickets", ' > > allocate ',
518
-                        __FILE__, __LINE__,   3);
519
-                    if ($at_capacity) {
520
-                        \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
521
-                    }
522
-                }
523
-                // now adjust all other datetimes that allow access to this ticket
524
-                $this->adjustDatetimes(
525
-                    $datetime_identifier,
526
-                    $ticket_identifier,
527
-                    $ticket_quantity,
528
-                    $at_capacity
529
-                );
530
-            }
531
-        }
532
-        return $spaces_allocated;
533
-    }
534
-
535
-
536
-
537
-    /**
538
-     * subtracts ticket amounts from all datetime reg limits
539
-     * that allow access to the ticket specified,
540
-     * because that ticket could be used
541
-     * to attend any of the datetimes it has access to
542
-     *
543
-     * @param string $datetime_identifier
544
-     * @param string $ticket_identifier
545
-     * @param bool   $at_capacity
546
-     * @param int    $ticket_quantity
547
-     */
548
-    private function adjustDatetimes(
549
-        $datetime_identifier,
550
-        $ticket_identifier,
551
-        $ticket_quantity,
552
-        $at_capacity
553
-    ) {
554
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
555
-            if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
556
-                continue;
557
-            }
558
-            $adjusted = $this->adjustDatetimeSpaces(
559
-                $datetime_ID,
560
-                $ticket_identifier,
561
-                $ticket_quantity
562
-            );
563
-            // skip to next ticket if nothing changed
564
-            if (! ($adjusted || $at_capacity)) {
565
-                continue;
566
-            }
567
-            // then all of it's tickets are now unavailable
568
-            foreach ($datetime_tickets as $datetime_ticket) {
569
-                if (
570
-                    ($ticket_identifier === $datetime_ticket || $at_capacity)
571
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
572
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
573
-                ) {
574
-                    if ($this->debug) {
575
-                        \EEH_Debug_Tools::printr($datetime_ticket, ' . . . adjust ticket quantities for', __FILE__,
576
-                            __LINE__);
577
-                    }
578
-                    // if this datetime is at full capacity, set any tracked available quantities to zero
579
-                    // otherwise just subtract the ticket quantity
580
-                    $new_quantity = $at_capacity
581
-                        ? 0
582
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
583
-                    // don't let ticket quantity go below zero
584
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
585
-                    if ($this->debug) {
586
-                        \EEH_Debug_Tools::printr(
587
-                            $at_capacity
588
-                                ? "0 because Datetime {$datetime_identifier} is at capacity"
589
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
590
-                            " . . . . {$datetime_ticket} quantity set to ",
591
-                            __FILE__, __LINE__
592
-                        );
593
-                    }
594
-                }
595
-                // but we also need to adjust spaces for any other datetimes this ticket has access to
596
-                if ($datetime_ticket === $ticket_identifier) {
597
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
598
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
599
-                    ) {
600
-                        if ($this->debug) {
601
-                            \EEH_Debug_Tools::printr($datetime_ticket, ' . . adjust other Datetimes for', __FILE__,
602
-                                __LINE__);
603
-                        }
604
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
605
-                            // don't adjust the current datetime twice
606
-                            if ($datetime !== $datetime_identifier) {
607
-                                $this->adjustDatetimeSpaces(
608
-                                    $datetime,
609
-                                    $datetime_ticket,
610
-                                    $ticket_quantity
611
-                                );
612
-                            }
613
-                        }
614
-                    }
615
-                }
616
-            }
617
-        }
618
-    }
619
-
620
-    private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
621
-    {
622
-        // does datetime have spaces available?
623
-        // and does the supplied ticket have access to this datetime ?
624
-        if (
625
-            $this->datetime_spaces[ $datetime_identifier ] > 0
626
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
627
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
628
-            ) {
629
-            if ($this->debug) {
630
-                \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
631
-                \EEH_Debug_Tools::printr("{$this->datetime_spaces[ $datetime_identifier ]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
632
-            }
633
-            // then decrement the available spaces for the datetime
634
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
635
-            // but don't let quantities go below zero
636
-            $this->datetime_spaces[ $datetime_identifier ] = max(
637
-                $this->datetime_spaces[ $datetime_identifier ],
638
-                0
639
-            );
640
-            if ($this->debug) {
641
-                \EEH_Debug_Tools::printr("{$ticket_quantity}",
642
-                    " . . . {$datetime_identifier} capacity reduced by", __FILE__, __LINE__);
643
-            }
644
-            return true;
645
-        }
646
-        return false;
647
-    }
34
+	/**
35
+	 * @var EE_Event $event
36
+	 */
37
+	private $event;
38
+
39
+	/**
40
+	 * @var array $datetime_query_params
41
+	 */
42
+	private $datetime_query_params;
43
+
44
+	/**
45
+	 * @var EE_Ticket[] $active_tickets
46
+	 */
47
+	private $active_tickets = array();
48
+
49
+	/**
50
+	 * @var EE_Datetime[] $datetimes
51
+	 */
52
+	private $datetimes = array();
53
+
54
+	/**
55
+	 * Array of Ticket IDs grouped by Datetime
56
+	 *
57
+	 * @var array $datetimes
58
+	 */
59
+	private $datetime_tickets = array();
60
+
61
+	/**
62
+	 * Max spaces for each Datetime (reg limit - previous sold)
63
+	 *
64
+	 * @var array $datetime_spaces
65
+	 */
66
+	private $datetime_spaces = array();
67
+
68
+	/**
69
+	 * Array of Datetime IDs grouped by Ticket
70
+	 *
71
+	 * @var array $ticket_datetimes
72
+	 */
73
+	private $ticket_datetimes = array();
74
+
75
+	/**
76
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
77
+	 *
78
+	 * @var array $ticket_quantities
79
+	 */
80
+	private $ticket_quantities = array();
81
+
82
+	/**
83
+	 * total quantity of sold and reserved for each ticket
84
+	 *
85
+	 * @var array $tickets_sold
86
+	 */
87
+	private $tickets_sold = array();
88
+
89
+	/**
90
+	 * total spaces available across all datetimes
91
+	 *
92
+	 * @var array $total_spaces
93
+	 */
94
+	private $total_spaces = array();
95
+
96
+	/**
97
+	 * @var boolean $debug
98
+	 */
99
+	private $debug = false;
100
+
101
+
102
+
103
+	/**
104
+	 * EventSpacesCalculator constructor.
105
+	 *
106
+	 * @param EE_Event $event
107
+	 * @param array    $datetime_query_params
108
+	 * @throws EE_Error
109
+	 */
110
+	public function __construct(EE_Event $event, array $datetime_query_params = array())
111
+	{
112
+		$this->event                 = $event;
113
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * @return EE_Ticket[]
120
+	 * @throws EE_Error
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 * @throws InvalidArgumentException
124
+	 */
125
+	public function getActiveTickets()
126
+	{
127
+		if (empty($this->active_tickets)) {
128
+			$this->active_tickets = $this->event->tickets(
129
+				array(
130
+					array(
131
+						'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
132
+						'TKT_deleted'  => false,
133
+					),
134
+					'order_by' => array('TKT_qty' => 'ASC'),
135
+				)
136
+			);
137
+		}
138
+		return $this->active_tickets;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * @param EE_Ticket[] $active_tickets
145
+	 * @throws EE_Error
146
+	 * @throws DomainException
147
+	 * @throws UnexpectedEntityException
148
+	 */
149
+	public function setActiveTickets(array $active_tickets = array())
150
+	{
151
+		if ( ! empty($active_tickets)) {
152
+			foreach ($active_tickets as $active_ticket) {
153
+				$this->validateTicket($active_ticket);
154
+			}
155
+			// sort incoming array by ticket quantity (asc)
156
+			usort(
157
+				$active_tickets,
158
+				function (EE_Ticket $a, EE_Ticket $b) {
159
+					if ($a->qty() === $b->qty()) {
160
+						return 0;
161
+					}
162
+					return ($a->qty() < $b->qty())
163
+						? -1
164
+						: 1;
165
+				}
166
+			);
167
+		}
168
+		$this->active_tickets = $active_tickets;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * @param $ticket
175
+	 * @throws DomainException
176
+	 * @throws EE_Error
177
+	 * @throws UnexpectedEntityException
178
+	 */
179
+	private function validateTicket($ticket)
180
+	{
181
+		if ( ! $ticket instanceof EE_Ticket) {
182
+			throw new DomainException(
183
+				esc_html__(
184
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
185
+					'event_espresso'
186
+				)
187
+			);
188
+		}
189
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
190
+			throw new DomainException(
191
+				sprintf(
192
+					esc_html__(
193
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
194
+						'event_espresso'
195
+					),
196
+					$ticket->get_event_ID(),
197
+					$this->event->ID()
198
+				)
199
+			);
200
+		}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * @return EE_Datetime[]
207
+	 */
208
+	public function getDatetimes()
209
+	{
210
+		return $this->datetimes;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * @param EE_Datetime $datetime
217
+	 * @throws EE_Error
218
+	 * @throws DomainException
219
+	 */
220
+	public function setDatetime(EE_Datetime $datetime)
221
+	{
222
+		if ($datetime->event()->ID() !== $this->event->ID()) {
223
+			throw new DomainException(
224
+				sprintf(
225
+					esc_html__(
226
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
227
+						'event_espresso'
228
+					),
229
+					$datetime->event()->ID(),
230
+					$this->event->ID()
231
+				)
232
+			);
233
+		}
234
+		$this->datetimes[ $datetime->ID() ] = $datetime;
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * calculate spaces remaining based on "saleable" tickets
241
+	 *
242
+	 * @return float|int
243
+	 * @throws EE_Error
244
+	 * @throws DomainException
245
+	 * @throws UnexpectedEntityException
246
+	 * @throws InvalidDataTypeException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidArgumentException
249
+	 */
250
+	public function spacesRemaining()
251
+	{
252
+		$this->initialize();
253
+		return $this->calculate();
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 * calculates total available spaces for an event with no regard for sold tickets
260
+	 *
261
+	 * @return int|float
262
+	 * @throws EE_Error
263
+	 * @throws DomainException
264
+	 * @throws UnexpectedEntityException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws InvalidArgumentException
268
+	 */
269
+	public function totalSpacesAvailable()
270
+	{
271
+		$this->initialize();
272
+		return $this->calculate(false);
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * Loops through the active tickets for the event
279
+	 * and builds a series of data arrays that will be used for calculating
280
+	 * the total maximum available spaces, as well as the spaces remaining.
281
+	 * Because ticket quantities affect datetime spaces and vice versa,
282
+	 * we need to be constantly updating these data arrays as things change,
283
+	 * which is the entire reason for their existence.
284
+	 *
285
+	 * @throws EE_Error
286
+	 * @throws DomainException
287
+	 * @throws UnexpectedEntityException
288
+	 * @throws InvalidDataTypeException
289
+	 * @throws InvalidInterfaceException
290
+	 * @throws InvalidArgumentException
291
+	 */
292
+	private function initialize()
293
+	{
294
+		if ($this->debug) {
295
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
296
+		}
297
+		$this->datetime_tickets  = array();
298
+		$this->datetime_spaces   = array();
299
+		$this->ticket_datetimes  = array();
300
+		$this->ticket_quantities = array();
301
+		$this->tickets_sold      = array();
302
+		$this->total_spaces      = array();
303
+		$active_tickets          = $this->getActiveTickets();
304
+		if ( ! empty($active_tickets)) {
305
+			foreach ($active_tickets as $ticket) {
306
+				$this->validateTicket($ticket);
307
+				// we need to index our data arrays using strings for the purpose of sorting,
308
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
309
+				$ticket_identifier = "T{$ticket->ID()}";
310
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket
311
+				$max_tickets = $ticket->qty();
312
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
313
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
314
+				foreach ($ticket_datetimes as $datetime) {
315
+					// save all datetimes
316
+					$this->setDatetime($datetime);
317
+					$datetime_identifier = "D{$datetime->ID()}";
318
+					$reg_limit           = $datetime->reg_limit();
319
+					// ticket quantity can not exceed datetime reg limit
320
+					$max_tickets = min($max_tickets, $reg_limit);
321
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
322
+					// we are going to move all of our data into the following arrays:
323
+					// datetime spaces initially represents the reg limit for each datetime,
324
+					// but this will get adjusted as tickets are accounted for
325
+					$this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
326
+					// just an array of ticket IDs grouped by datetime
327
+					$this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
328
+					// and an array of datetime IDs grouped by ticket
329
+					$this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
330
+				}
331
+				// total quantity of sold and reserved for each ticket
332
+				$this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
333
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
334
+				$this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
335
+			}
336
+		}
337
+		// sort datetime spaces by reg limit, but maintain our string indexes
338
+		asort($this->datetime_spaces, SORT_NUMERIC);
339
+		// datetime tickets need to be sorted in the SAME order as the above array...
340
+		// so we'll just use array_merge() to take the structure of datetime_spaces
341
+		// but overwrite all of the data with that from datetime_tickets
342
+		$this->datetime_tickets = array_merge(
343
+			$this->datetime_spaces,
344
+			$this->datetime_tickets
345
+		);
346
+		if ($this->debug) {
347
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
348
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
349
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
350
+		}
351
+	}
352
+
353
+
354
+
355
+	/**
356
+	 * performs calculations on initialized data
357
+	 *
358
+	 * @param bool $consider_sold
359
+	 * @return int|float
360
+	 */
361
+	private function calculate($consider_sold = true)
362
+	{
363
+		if ($this->debug) {
364
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
365
+		}
366
+		if ($consider_sold) {
367
+			// subtract amounts sold from all ticket quantities and datetime spaces
368
+			$this->adjustTicketQuantitiesDueToSales();
369
+		}
370
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
371
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
372
+		}
373
+		// total spaces available is just the sum of the spaces available for each datetime
374
+		$spaces_remaining = array_sum($this->total_spaces);
375
+		if ($this->debug) {
376
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
377
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
378
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
379
+		}
380
+		return $spaces_remaining;
381
+	}
382
+
383
+
384
+	/**
385
+	 * subtracts amount of  tickets sold from ticket quantities and datetime spaces
386
+	 */
387
+	private function adjustTicketQuantitiesDueToSales()
388
+	{
389
+		if ($this->debug) {
390
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
+		}
392
+		foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
393
+			if (isset($this->ticket_quantities[ $ticket_identifier ])){
394
+				$this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
395
+				if ($this->debug) {
396
+					\EEH_Debug_Tools::printr("{$tickets_sold} sales for ticket {$ticket_identifier} ", 'subtracting', __FILE__, __LINE__);
397
+				}
398
+			}
399
+			if (
400
+				isset($this->ticket_datetimes[ $ticket_identifier ])
401
+				&& is_array($this->ticket_datetimes[ $ticket_identifier ])
402
+			){
403
+				foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
404
+					if (isset($this->ticket_quantities[ $ticket_identifier ])) {
405
+						$this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
406
+						if ($this->debug) {
407
+							\EEH_Debug_Tools::printr("{$tickets_sold} sales for datetime {$ticket_datetime} ",
408
+								'subtracting', __FILE__, __LINE__);
409
+						}
410
+					}
411
+				}
412
+			}
413
+		}
414
+	}
415
+
416
+
417
+
418
+	/**
419
+	 * @param string $datetime_identifier
420
+	 * @param array  $tickets
421
+	 */
422
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
423
+	{
424
+		// make sure a reg limit is set for the datetime
425
+		$reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
426
+			? $this->datetime_spaces[ $datetime_identifier ]
427
+			: 0;
428
+		// and bail if it is not
429
+		if ( ! $reg_limit) {
430
+			if ($this->debug) {
431
+				\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
432
+			}
433
+			return;
434
+		}
435
+		if ($this->debug) {
436
+			\EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
437
+			\EEH_Debug_Tools::printr("{$reg_limit}", 'REG LIMIT', __FILE__, __LINE__);
438
+		}
439
+		// number of allocated spaces always starts at zero
440
+		$spaces_allocated                           = 0;
441
+		$this->total_spaces[ $datetime_identifier ] = 0;
442
+		foreach ($tickets as $ticket_identifier) {
443
+			$spaces_allocated = $this->calculateAvailableSpacesForTicket(
444
+				$datetime_identifier,
445
+				$reg_limit,
446
+				$ticket_identifier,
447
+				$spaces_allocated
448
+			);
449
+		}
450
+		// spaces can't be negative
451
+		$spaces_allocated = max($spaces_allocated, 0);
452
+		if ($spaces_allocated) {
453
+			// track any non-zero values
454
+			$this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
455
+			if ($this->debug) {
456
+				\EEH_Debug_Tools::printr((string)$spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
457
+			}
458
+		} else {
459
+			if ($this->debug) {
460
+				\EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
461
+			}
462
+		}
463
+		if ($this->debug) {
464
+			\EEH_Debug_Tools::printr($this->total_spaces[ $datetime_identifier ], '$total_spaces', __FILE__,
465
+				__LINE__);
466
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
467
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
468
+		}
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * @param string $datetime_identifier
475
+	 * @param int    $reg_limit
476
+	 * @param string $ticket_identifier
477
+	 * @param int    $spaces_allocated
478
+	 * @return int
479
+	 */
480
+	private function calculateAvailableSpacesForTicket(
481
+		$datetime_identifier,
482
+		$reg_limit,
483
+		$ticket_identifier,
484
+		$spaces_allocated
485
+	) {
486
+		// make sure ticket quantity is set
487
+		$ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
488
+			? $this->ticket_quantities[ $ticket_identifier ]
489
+			: 0;
490
+		if ($this->debug) {
491
+			\EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
492
+			\EEH_Debug_Tools::printr("{$ticket_quantity}", "ticket $ticket_identifier quantity: ",
493
+				__FILE__, __LINE__, 2);
494
+		}
495
+		if ($ticket_quantity) {
496
+			if ($this->debug) {
497
+				\EEH_Debug_Tools::printr(
498
+					($spaces_allocated <= $reg_limit)
499
+						? 'true'
500
+						: 'false',
501
+					' . spaces_allocated <= reg_limit = ',
502
+					__FILE__, __LINE__
503
+				);
504
+			}
505
+			// if the datetime is NOT at full capacity yet
506
+			if ($spaces_allocated <= $reg_limit) {
507
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
508
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
509
+				//  or the maximum ticket quantity
510
+				$ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
511
+				// adjust the available quantity in our tracking array
512
+				$this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
513
+				// and increment spaces allocated for this datetime
514
+				$spaces_allocated += $ticket_quantity;
515
+				$at_capacity = $spaces_allocated >= $reg_limit;
516
+				if ($this->debug) {
517
+					\EEH_Debug_Tools::printr("{$ticket_quantity} {$ticket_identifier} tickets", ' > > allocate ',
518
+						__FILE__, __LINE__,   3);
519
+					if ($at_capacity) {
520
+						\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
521
+					}
522
+				}
523
+				// now adjust all other datetimes that allow access to this ticket
524
+				$this->adjustDatetimes(
525
+					$datetime_identifier,
526
+					$ticket_identifier,
527
+					$ticket_quantity,
528
+					$at_capacity
529
+				);
530
+			}
531
+		}
532
+		return $spaces_allocated;
533
+	}
534
+
535
+
536
+
537
+	/**
538
+	 * subtracts ticket amounts from all datetime reg limits
539
+	 * that allow access to the ticket specified,
540
+	 * because that ticket could be used
541
+	 * to attend any of the datetimes it has access to
542
+	 *
543
+	 * @param string $datetime_identifier
544
+	 * @param string $ticket_identifier
545
+	 * @param bool   $at_capacity
546
+	 * @param int    $ticket_quantity
547
+	 */
548
+	private function adjustDatetimes(
549
+		$datetime_identifier,
550
+		$ticket_identifier,
551
+		$ticket_quantity,
552
+		$at_capacity
553
+	) {
554
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
555
+			if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
556
+				continue;
557
+			}
558
+			$adjusted = $this->adjustDatetimeSpaces(
559
+				$datetime_ID,
560
+				$ticket_identifier,
561
+				$ticket_quantity
562
+			);
563
+			// skip to next ticket if nothing changed
564
+			if (! ($adjusted || $at_capacity)) {
565
+				continue;
566
+			}
567
+			// then all of it's tickets are now unavailable
568
+			foreach ($datetime_tickets as $datetime_ticket) {
569
+				if (
570
+					($ticket_identifier === $datetime_ticket || $at_capacity)
571
+					&& isset($this->ticket_quantities[ $datetime_ticket ])
572
+					&& $this->ticket_quantities[ $datetime_ticket ] > 0
573
+				) {
574
+					if ($this->debug) {
575
+						\EEH_Debug_Tools::printr($datetime_ticket, ' . . . adjust ticket quantities for', __FILE__,
576
+							__LINE__);
577
+					}
578
+					// if this datetime is at full capacity, set any tracked available quantities to zero
579
+					// otherwise just subtract the ticket quantity
580
+					$new_quantity = $at_capacity
581
+						? 0
582
+						: $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
583
+					// don't let ticket quantity go below zero
584
+					$this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
585
+					if ($this->debug) {
586
+						\EEH_Debug_Tools::printr(
587
+							$at_capacity
588
+								? "0 because Datetime {$datetime_identifier} is at capacity"
589
+								: "{$this->ticket_quantities[ $datetime_ticket ]}",
590
+							" . . . . {$datetime_ticket} quantity set to ",
591
+							__FILE__, __LINE__
592
+						);
593
+					}
594
+				}
595
+				// but we also need to adjust spaces for any other datetimes this ticket has access to
596
+				if ($datetime_ticket === $ticket_identifier) {
597
+					if (isset($this->ticket_datetimes[ $datetime_ticket ])
598
+						&& is_array($this->ticket_datetimes[ $datetime_ticket ])
599
+					) {
600
+						if ($this->debug) {
601
+							\EEH_Debug_Tools::printr($datetime_ticket, ' . . adjust other Datetimes for', __FILE__,
602
+								__LINE__);
603
+						}
604
+						foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
605
+							// don't adjust the current datetime twice
606
+							if ($datetime !== $datetime_identifier) {
607
+								$this->adjustDatetimeSpaces(
608
+									$datetime,
609
+									$datetime_ticket,
610
+									$ticket_quantity
611
+								);
612
+							}
613
+						}
614
+					}
615
+				}
616
+			}
617
+		}
618
+	}
619
+
620
+	private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
621
+	{
622
+		// does datetime have spaces available?
623
+		// and does the supplied ticket have access to this datetime ?
624
+		if (
625
+			$this->datetime_spaces[ $datetime_identifier ] > 0
626
+			&& isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
627
+			&& in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
628
+			) {
629
+			if ($this->debug) {
630
+				\EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
631
+				\EEH_Debug_Tools::printr("{$this->datetime_spaces[ $datetime_identifier ]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
632
+			}
633
+			// then decrement the available spaces for the datetime
634
+			$this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
635
+			// but don't let quantities go below zero
636
+			$this->datetime_spaces[ $datetime_identifier ] = max(
637
+				$this->datetime_spaces[ $datetime_identifier ],
638
+				0
639
+			);
640
+			if ($this->debug) {
641
+				\EEH_Debug_Tools::printr("{$ticket_quantity}",
642
+					" . . . {$datetime_identifier} capacity reduced by", __FILE__, __LINE__);
643
+			}
644
+			return true;
645
+		}
646
+		return false;
647
+	}
648 648
 
649 649
 }
650 650
 // Location: EventSpacesCalculator.php
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
             // sort incoming array by ticket quantity (asc)
156 156
             usort(
157 157
                 $active_tickets,
158
-                function (EE_Ticket $a, EE_Ticket $b) {
158
+                function(EE_Ticket $a, EE_Ticket $b) {
159 159
                     if ($a->qty() === $b->qty()) {
160 160
                         return 0;
161 161
                     }
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
                 )
232 232
             );
233 233
         }
234
-        $this->datetimes[ $datetime->ID() ] = $datetime;
234
+        $this->datetimes[$datetime->ID()] = $datetime;
235 235
     }
236 236
 
237 237
 
@@ -322,16 +322,16 @@  discard block
 block discarded – undo
322 322
                     // we are going to move all of our data into the following arrays:
323 323
                     // datetime spaces initially represents the reg limit for each datetime,
324 324
                     // but this will get adjusted as tickets are accounted for
325
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
325
+                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
326 326
                     // just an array of ticket IDs grouped by datetime
327
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
327
+                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
328 328
                     // and an array of datetime IDs grouped by ticket
329
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
329
+                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
330 330
                 }
331 331
                 // total quantity of sold and reserved for each ticket
332
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
332
+                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
333 333
                 // and the maximum ticket quantities for each ticket (adjusted for reg limit)
334
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
334
+                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
335 335
             }
336 336
         }
337 337
         // sort datetime spaces by reg limit, but maintain our string indexes
@@ -390,19 +390,19 @@  discard block
 block discarded – undo
390 390
             \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391 391
         }
392 392
         foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
393
-            if (isset($this->ticket_quantities[ $ticket_identifier ])){
394
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
393
+            if (isset($this->ticket_quantities[$ticket_identifier])) {
394
+                $this->ticket_quantities[$ticket_identifier] -= $tickets_sold;
395 395
                 if ($this->debug) {
396 396
                     \EEH_Debug_Tools::printr("{$tickets_sold} sales for ticket {$ticket_identifier} ", 'subtracting', __FILE__, __LINE__);
397 397
                 }
398 398
             }
399 399
             if (
400
-                isset($this->ticket_datetimes[ $ticket_identifier ])
401
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
402
-            ){
403
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
404
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
405
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
400
+                isset($this->ticket_datetimes[$ticket_identifier])
401
+                && is_array($this->ticket_datetimes[$ticket_identifier])
402
+            ) {
403
+                foreach ($this->ticket_datetimes[$ticket_identifier] as $ticket_datetime) {
404
+                    if (isset($this->ticket_quantities[$ticket_identifier])) {
405
+                        $this->datetime_spaces[$ticket_datetime] -= $tickets_sold;
406 406
                         if ($this->debug) {
407 407
                             \EEH_Debug_Tools::printr("{$tickets_sold} sales for datetime {$ticket_datetime} ",
408 408
                                 'subtracting', __FILE__, __LINE__);
@@ -422,8 +422,8 @@  discard block
 block discarded – undo
422 422
     private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
423 423
     {
424 424
         // make sure a reg limit is set for the datetime
425
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
426
-            ? $this->datetime_spaces[ $datetime_identifier ]
425
+        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
426
+            ? $this->datetime_spaces[$datetime_identifier]
427 427
             : 0;
428 428
         // and bail if it is not
429 429
         if ( ! $reg_limit) {
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
         }
439 439
         // number of allocated spaces always starts at zero
440 440
         $spaces_allocated                           = 0;
441
-        $this->total_spaces[ $datetime_identifier ] = 0;
441
+        $this->total_spaces[$datetime_identifier] = 0;
442 442
         foreach ($tickets as $ticket_identifier) {
443 443
             $spaces_allocated = $this->calculateAvailableSpacesForTicket(
444 444
                 $datetime_identifier,
@@ -451,9 +451,9 @@  discard block
 block discarded – undo
451 451
         $spaces_allocated = max($spaces_allocated, 0);
452 452
         if ($spaces_allocated) {
453 453
             // track any non-zero values
454
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
454
+            $this->total_spaces[$datetime_identifier] += $spaces_allocated;
455 455
             if ($this->debug) {
456
-                \EEH_Debug_Tools::printr((string)$spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
456
+                \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
457 457
             }
458 458
         } else {
459 459
             if ($this->debug) {
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
             }
462 462
         }
463 463
         if ($this->debug) {
464
-            \EEH_Debug_Tools::printr($this->total_spaces[ $datetime_identifier ], '$total_spaces', __FILE__,
464
+            \EEH_Debug_Tools::printr($this->total_spaces[$datetime_identifier], '$total_spaces', __FILE__,
465 465
                 __LINE__);
466 466
             \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
467 467
             \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
@@ -484,8 +484,8 @@  discard block
 block discarded – undo
484 484
         $spaces_allocated
485 485
     ) {
486 486
         // make sure ticket quantity is set
487
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
488
-            ? $this->ticket_quantities[ $ticket_identifier ]
487
+        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
488
+            ? $this->ticket_quantities[$ticket_identifier]
489 489
             : 0;
490 490
         if ($this->debug) {
491 491
             \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
@@ -509,13 +509,13 @@  discard block
 block discarded – undo
509 509
                 //  or the maximum ticket quantity
510 510
                 $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
511 511
                 // adjust the available quantity in our tracking array
512
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
512
+                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
513 513
                 // and increment spaces allocated for this datetime
514 514
                 $spaces_allocated += $ticket_quantity;
515 515
                 $at_capacity = $spaces_allocated >= $reg_limit;
516 516
                 if ($this->debug) {
517 517
                     \EEH_Debug_Tools::printr("{$ticket_quantity} {$ticket_identifier} tickets", ' > > allocate ',
518
-                        __FILE__, __LINE__,   3);
518
+                        __FILE__, __LINE__, 3);
519 519
                     if ($at_capacity) {
520 520
                         \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
521 521
                     }
@@ -561,15 +561,15 @@  discard block
 block discarded – undo
561 561
                 $ticket_quantity
562 562
             );
563 563
             // skip to next ticket if nothing changed
564
-            if (! ($adjusted || $at_capacity)) {
564
+            if ( ! ($adjusted || $at_capacity)) {
565 565
                 continue;
566 566
             }
567 567
             // then all of it's tickets are now unavailable
568 568
             foreach ($datetime_tickets as $datetime_ticket) {
569 569
                 if (
570 570
                     ($ticket_identifier === $datetime_ticket || $at_capacity)
571
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
572
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
571
+                    && isset($this->ticket_quantities[$datetime_ticket])
572
+                    && $this->ticket_quantities[$datetime_ticket] > 0
573 573
                 ) {
574 574
                     if ($this->debug) {
575 575
                         \EEH_Debug_Tools::printr($datetime_ticket, ' . . . adjust ticket quantities for', __FILE__,
@@ -579,14 +579,14 @@  discard block
 block discarded – undo
579 579
                     // otherwise just subtract the ticket quantity
580 580
                     $new_quantity = $at_capacity
581 581
                         ? 0
582
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
582
+                        : $this->ticket_quantities[$datetime_ticket] - $ticket_quantity;
583 583
                     // don't let ticket quantity go below zero
584
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
584
+                    $this->ticket_quantities[$datetime_ticket] = max($new_quantity, 0);
585 585
                     if ($this->debug) {
586 586
                         \EEH_Debug_Tools::printr(
587 587
                             $at_capacity
588 588
                                 ? "0 because Datetime {$datetime_identifier} is at capacity"
589
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
589
+                                : "{$this->ticket_quantities[$datetime_ticket]}",
590 590
                             " . . . . {$datetime_ticket} quantity set to ",
591 591
                             __FILE__, __LINE__
592 592
                         );
@@ -594,14 +594,14 @@  discard block
 block discarded – undo
594 594
                 }
595 595
                 // but we also need to adjust spaces for any other datetimes this ticket has access to
596 596
                 if ($datetime_ticket === $ticket_identifier) {
597
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
598
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
597
+                    if (isset($this->ticket_datetimes[$datetime_ticket])
598
+                        && is_array($this->ticket_datetimes[$datetime_ticket])
599 599
                     ) {
600 600
                         if ($this->debug) {
601 601
                             \EEH_Debug_Tools::printr($datetime_ticket, ' . . adjust other Datetimes for', __FILE__,
602 602
                                 __LINE__);
603 603
                         }
604
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
604
+                        foreach ($this->ticket_datetimes[$datetime_ticket] as $datetime) {
605 605
                             // don't adjust the current datetime twice
606 606
                             if ($datetime !== $datetime_identifier) {
607 607
                                 $this->adjustDatetimeSpaces(
@@ -622,19 +622,19 @@  discard block
 block discarded – undo
622 622
         // does datetime have spaces available?
623 623
         // and does the supplied ticket have access to this datetime ?
624 624
         if (
625
-            $this->datetime_spaces[ $datetime_identifier ] > 0
626
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
627
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
625
+            $this->datetime_spaces[$datetime_identifier] > 0
626
+            && isset($this->datetime_spaces[$datetime_identifier], $this->datetime_tickets[$datetime_identifier])
627
+            && in_array($ticket_identifier, $this->datetime_tickets[$datetime_identifier], true)
628 628
             ) {
629 629
             if ($this->debug) {
630 630
                 \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
631
-                \EEH_Debug_Tools::printr("{$this->datetime_spaces[ $datetime_identifier ]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
631
+                \EEH_Debug_Tools::printr("{$this->datetime_spaces[$datetime_identifier]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
632 632
             }
633 633
             // then decrement the available spaces for the datetime
634
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
634
+            $this->datetime_spaces[$datetime_identifier] -= $ticket_quantity;
635 635
             // but don't let quantities go below zero
636
-            $this->datetime_spaces[ $datetime_identifier ] = max(
637
-                $this->datetime_spaces[ $datetime_identifier ],
636
+            $this->datetime_spaces[$datetime_identifier] = max(
637
+                $this->datetime_spaces[$datetime_identifier],
638 638
                 0
639 639
             );
640 640
             if ($this->debug) {
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 2 patches
Indentation   +1285 added lines, -1285 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6 6
 if (!defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -18,1289 +18,1289 @@  discard block
 block discarded – undo
18 18
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
19 19
 {
20 20
 
21
-    /**
22
-     * cached value for the the logical active status for the event
23
-     *
24
-     * @see get_active_status()
25
-     * @var string
26
-     */
27
-    protected $_active_status = '';
28
-
29
-    /**
30
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
-     *
32
-     * @var EE_Datetime
33
-     */
34
-    protected $_Primary_Datetime;
35
-
36
-    /**
37
-     * @var EventSpacesCalculator $available_spaces_calculator
38
-     */
39
-    protected $available_spaces_calculator;
40
-
41
-
42
-    /**
43
-     * @param array $props_n_values incoming values
44
-     * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
-     *                                        used.)
46
-     * @param array $date_formats incoming date_formats in an array where the first value is the
47
-     *                                        date_format and the second value is the time format
48
-     * @return EE_Event
49
-     * @throws EE_Error
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param array $props_n_values incoming values from the database
60
-     * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
-     *                                the website will be used.
62
-     * @return EE_Event
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * @return EventSpacesCalculator
74
-     * @throws \EE_Error
75
-     */
76
-    public function getAvailableSpacesCalculator()
77
-    {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
-     *
89
-     * @param string $field_name
90
-     * @param mixed $field_value
91
-     * @param bool $use_default
92
-     * @throws EE_Error
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status' :
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default :
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @access public
113
-     * @param string $new_status
114
-     * @param bool $use_default
115
-     * @return void
116
-     * @throws EE_Error
117
-     */
118
-    public function set_status($new_status = null, $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $new_status) {
128
-            // TO sold_out
129
-            if ($new_status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
-                // OR FROM  sold_out
134
-            } else if ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
-            }
138
-            // update status
139
-            parent::set('status', $new_status, $use_default);
140
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
141
-            return;
142
-        }
143
-        // even though the old value matches the new value, it's still good to
144
-        // allow the parent set method to have a say
145
-        parent::set('status', $new_status, $use_default);
146
-    }
147
-
148
-
149
-    /**
150
-     * Gets all the datetimes for this event
151
-     *
152
-     * @param array $query_params like EEM_Base::get_all
153
-     * @return EE_Base_Class[]|EE_Datetime[]
154
-     * @throws EE_Error
155
-     */
156
-    public function datetimes($query_params = array())
157
-    {
158
-        return $this->get_many_related('Datetime', $query_params);
159
-    }
160
-
161
-
162
-    /**
163
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
-     *
165
-     * @return EE_Base_Class[]|EE_Datetime[]
166
-     * @throws EE_Error
167
-     */
168
-    public function datetimes_in_chronological_order()
169
-    {
170
-        return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
-    }
172
-
173
-
174
-    /**
175
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
-     * after running our query, so that this timezone isn't set for EVERY query
178
-     * on EEM_Datetime for the rest of the request, no?
179
-     *
180
-     * @param boolean $show_expired whether or not to include expired events
181
-     * @param boolean $show_deleted whether or not to include deleted events
182
-     * @param null $limit
183
-     * @return EE_Datetime[]
184
-     * @throws EE_Error
185
-     */
186
-    public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
-    {
188
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
-            $this->ID(),
190
-            $show_expired,
191
-            $show_deleted,
192
-            $limit
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * Returns one related datetime. Mostly only used by some legacy code.
199
-     *
200
-     * @return EE_Base_Class|EE_Datetime
201
-     * @throws EE_Error
202
-     */
203
-    public function first_datetime()
204
-    {
205
-        return $this->get_first_related('Datetime');
206
-    }
207
-
208
-
209
-    /**
210
-     * Returns the 'primary' datetime for the event
211
-     *
212
-     * @param bool $try_to_exclude_expired
213
-     * @param bool $try_to_exclude_deleted
214
-     * @return EE_Datetime
215
-     * @throws EE_Error
216
-     */
217
-    public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
-    {
219
-        if (!empty ($this->_Primary_Datetime)) {
220
-            return $this->_Primary_Datetime;
221
-        }
222
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
-            $this->ID(),
224
-            $try_to_exclude_expired,
225
-            $try_to_exclude_deleted
226
-        );
227
-        return $this->_Primary_Datetime;
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets all the tickets available for purchase of this event
233
-     *
234
-     * @param array $query_params like EEM_Base::get_all
235
-     * @return EE_Base_Class[]|EE_Ticket[]
236
-     * @throws EE_Error
237
-     */
238
-    public function tickets($query_params = array())
239
-    {
240
-        //first get all datetimes
241
-        $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
243
-            return array();
244
-        }
245
-        $datetime_ids = array();
246
-        foreach ($datetimes as $datetime) {
247
-            $datetime_ids[] = $datetime->ID();
248
-        }
249
-        $where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
-        //if incoming $query_params has where conditions let's merge but not override existing.
251
-        if (is_array($query_params) && isset($query_params[0])) {
252
-            $where_params = array_merge($query_params[0], $where_params);
253
-            unset($query_params[0]);
254
-        }
255
-        //now add $where_params to $query_params
256
-        $query_params[0] = $where_params;
257
-        return EEM_Ticket::instance()->get_all($query_params);
258
-    }
259
-
260
-
261
-    /**
262
-     * get all unexpired untrashed tickets
263
-     *
264
-     * @return EE_Ticket[]
265
-     * @throws EE_Error
266
-     */
267
-    public function active_tickets()
268
-    {
269
-        return $this->tickets(array(
270
-            array(
271
-                'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
-                'TKT_deleted' => false,
273
-            ),
274
-        ));
275
-    }
276
-
277
-
278
-    /**
279
-     * @return bool
280
-     * @throws EE_Error
281
-     */
282
-    public function additional_limit()
283
-    {
284
-        return $this->get('EVT_additional_limit');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return bool
290
-     * @throws EE_Error
291
-     */
292
-    public function allow_overflow()
293
-    {
294
-        return $this->get('EVT_allow_overflow');
295
-    }
296
-
297
-
298
-    /**
299
-     * @return bool
300
-     * @throws EE_Error
301
-     */
302
-    public function created()
303
-    {
304
-        return $this->get('EVT_created');
305
-    }
306
-
307
-
308
-    /**
309
-     * @return bool
310
-     * @throws EE_Error
311
-     */
312
-    public function description()
313
-    {
314
-        return $this->get('EVT_desc');
315
-    }
316
-
317
-
318
-    /**
319
-     * Runs do_shortcode and wpautop on the description
320
-     *
321
-     * @return string of html
322
-     * @throws EE_Error
323
-     */
324
-    public function description_filtered()
325
-    {
326
-        return $this->get_pretty('EVT_desc');
327
-    }
328
-
329
-
330
-    /**
331
-     * @return bool
332
-     * @throws EE_Error
333
-     */
334
-    public function display_description()
335
-    {
336
-        return $this->get('EVT_display_desc');
337
-    }
338
-
339
-
340
-    /**
341
-     * @return bool
342
-     * @throws EE_Error
343
-     */
344
-    public function display_ticket_selector()
345
-    {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
347
-    }
348
-
349
-
350
-    /**
351
-     * @return bool
352
-     * @throws EE_Error
353
-     */
354
-    public function external_url()
355
-    {
356
-        return $this->get('EVT_external_URL');
357
-    }
358
-
359
-
360
-    /**
361
-     * @return bool
362
-     * @throws EE_Error
363
-     */
364
-    public function member_only()
365
-    {
366
-        return $this->get('EVT_member_only');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return bool
372
-     * @throws EE_Error
373
-     */
374
-    public function phone()
375
-    {
376
-        return $this->get('EVT_phone');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     */
384
-    public function modified()
385
-    {
386
-        return $this->get('EVT_modified');
387
-    }
388
-
389
-
390
-    /**
391
-     * @return bool
392
-     * @throws EE_Error
393
-     */
394
-    public function name()
395
-    {
396
-        return $this->get('EVT_name');
397
-    }
398
-
399
-
400
-    /**
401
-     * @return bool
402
-     * @throws EE_Error
403
-     */
404
-    public function order()
405
-    {
406
-        return $this->get('EVT_order');
407
-    }
408
-
409
-
410
-    /**
411
-     * @return bool|string
412
-     * @throws EE_Error
413
-     */
414
-    public function default_registration_status()
415
-    {
416
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
418
-            ? $event_default_registration_status
419
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
420
-    }
421
-
422
-
423
-    /**
424
-     * @param int $num_words
425
-     * @param null $more
426
-     * @param bool $not_full_desc
427
-     * @return bool|string
428
-     * @throws EE_Error
429
-     */
430
-    public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
-    {
432
-        $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
434
-            return $short_desc;
435
-        }
436
-        $full_desc = $this->get('EVT_desc');
437
-        return wp_trim_words($full_desc, $num_words, $more);
438
-    }
439
-
440
-
441
-    /**
442
-     * @return bool
443
-     * @throws EE_Error
444
-     */
445
-    public function slug()
446
-    {
447
-        return $this->get('EVT_slug');
448
-    }
449
-
450
-
451
-    /**
452
-     * @return bool
453
-     * @throws EE_Error
454
-     */
455
-    public function timezone_string()
456
-    {
457
-        return $this->get('EVT_timezone_string');
458
-    }
459
-
460
-
461
-    /**
462
-     * @return bool
463
-     * @throws EE_Error
464
-     */
465
-    public function visible_on()
466
-    {
467
-        return $this->get('EVT_visible_on');
468
-    }
469
-
470
-
471
-    /**
472
-     * @return int
473
-     * @throws EE_Error
474
-     */
475
-    public function wp_user()
476
-    {
477
-        return $this->get('EVT_wp_user');
478
-    }
479
-
480
-
481
-    /**
482
-     * @return bool
483
-     * @throws EE_Error
484
-     */
485
-    public function donations()
486
-    {
487
-        return $this->get('EVT_donations');
488
-    }
489
-
490
-
491
-    /**
492
-     * @param $limit
493
-     * @throws EE_Error
494
-     */
495
-    public function set_additional_limit($limit)
496
-    {
497
-        $this->set('EVT_additional_limit', $limit);
498
-    }
499
-
500
-
501
-    /**
502
-     * @param $created
503
-     * @throws EE_Error
504
-     */
505
-    public function set_created($created)
506
-    {
507
-        $this->set('EVT_created', $created);
508
-    }
509
-
510
-
511
-    /**
512
-     * @param $desc
513
-     * @throws EE_Error
514
-     */
515
-    public function set_description($desc)
516
-    {
517
-        $this->set('EVT_desc', $desc);
518
-    }
519
-
520
-
521
-    /**
522
-     * @param $display_desc
523
-     * @throws EE_Error
524
-     */
525
-    public function set_display_description($display_desc)
526
-    {
527
-        $this->set('EVT_display_desc', $display_desc);
528
-    }
529
-
530
-
531
-    /**
532
-     * @param $display_ticket_selector
533
-     * @throws EE_Error
534
-     */
535
-    public function set_display_ticket_selector($display_ticket_selector)
536
-    {
537
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
-    }
539
-
540
-
541
-    /**
542
-     * @param $external_url
543
-     * @throws EE_Error
544
-     */
545
-    public function set_external_url($external_url)
546
-    {
547
-        $this->set('EVT_external_URL', $external_url);
548
-    }
549
-
550
-
551
-    /**
552
-     * @param $member_only
553
-     * @throws EE_Error
554
-     */
555
-    public function set_member_only($member_only)
556
-    {
557
-        $this->set('EVT_member_only', $member_only);
558
-    }
559
-
560
-
561
-    /**
562
-     * @param $event_phone
563
-     * @throws EE_Error
564
-     */
565
-    public function set_event_phone($event_phone)
566
-    {
567
-        $this->set('EVT_phone', $event_phone);
568
-    }
569
-
570
-
571
-    /**
572
-     * @param $modified
573
-     * @throws EE_Error
574
-     */
575
-    public function set_modified($modified)
576
-    {
577
-        $this->set('EVT_modified', $modified);
578
-    }
579
-
580
-
581
-    /**
582
-     * @param $name
583
-     * @throws EE_Error
584
-     */
585
-    public function set_name($name)
586
-    {
587
-        $this->set('EVT_name', $name);
588
-    }
589
-
590
-
591
-    /**
592
-     * @param $order
593
-     * @throws EE_Error
594
-     */
595
-    public function set_order($order)
596
-    {
597
-        $this->set('EVT_order', $order);
598
-    }
599
-
600
-
601
-    /**
602
-     * @param $short_desc
603
-     * @throws EE_Error
604
-     */
605
-    public function set_short_description($short_desc)
606
-    {
607
-        $this->set('EVT_short_desc', $short_desc);
608
-    }
609
-
610
-
611
-    /**
612
-     * @param $slug
613
-     * @throws EE_Error
614
-     */
615
-    public function set_slug($slug)
616
-    {
617
-        $this->set('EVT_slug', $slug);
618
-    }
619
-
620
-
621
-    /**
622
-     * @param $timezone_string
623
-     * @throws EE_Error
624
-     */
625
-    public function set_timezone_string($timezone_string)
626
-    {
627
-        $this->set('EVT_timezone_string', $timezone_string);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $visible_on
633
-     * @throws EE_Error
634
-     */
635
-    public function set_visible_on($visible_on)
636
-    {
637
-        $this->set('EVT_visible_on', $visible_on);
638
-    }
639
-
640
-
641
-    /**
642
-     * @param $wp_user
643
-     * @throws EE_Error
644
-     */
645
-    public function set_wp_user($wp_user)
646
-    {
647
-        $this->set('EVT_wp_user', $wp_user);
648
-    }
649
-
650
-
651
-    /**
652
-     * @param $default_registration_status
653
-     * @throws EE_Error
654
-     */
655
-    public function set_default_registration_status($default_registration_status)
656
-    {
657
-        $this->set('EVT_default_registration_status', $default_registration_status);
658
-    }
659
-
660
-
661
-    /**
662
-     * @param $donations
663
-     * @throws EE_Error
664
-     */
665
-    public function set_donations($donations)
666
-    {
667
-        $this->set('EVT_donations', $donations);
668
-    }
669
-
670
-
671
-    /**
672
-     * Adds a venue to this event
673
-     *
674
-     * @param EE_Venue /int $venue_id_or_obj
675
-     * @return EE_Base_Class|EE_Venue
676
-     * @throws EE_Error
677
-     */
678
-    public function add_venue($venue_id_or_obj)
679
-    {
680
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
-    }
682
-
683
-
684
-    /**
685
-     * Removes a venue from the event
686
-     *
687
-     * @param EE_Venue /int $venue_id_or_obj
688
-     * @return EE_Base_Class|EE_Venue
689
-     * @throws EE_Error
690
-     */
691
-    public function remove_venue($venue_id_or_obj)
692
-    {
693
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
-    }
695
-
696
-
697
-    /**
698
-     * Gets all the venues related ot the event. May provide additional $query_params if desired
699
-     *
700
-     * @param array $query_params like EEM_Base::get_all's $query_params
701
-     * @return EE_Base_Class[]|EE_Venue[]
702
-     * @throws EE_Error
703
-     */
704
-    public function venues($query_params = array())
705
-    {
706
-        return $this->get_many_related('Venue', $query_params);
707
-    }
708
-
709
-
710
-    /**
711
-     * check if event id is present and if event is published
712
-     *
713
-     * @access public
714
-     * @return boolean true yes, false no
715
-     * @throws EE_Error
716
-     */
717
-    private function _has_ID_and_is_published()
718
-    {
719
-        // first check if event id is present and not NULL,
720
-        // then check if this event is published (or any of the equivalent "published" statuses)
721
-        return
722
-            $this->ID() && $this->ID() !== null
723
-            && (
724
-                $this->status() === 'publish'
725
-                || $this->status() === EEM_Event::sold_out
726
-                || $this->status() === EEM_Event::postponed
727
-                || $this->status() === EEM_Event::cancelled
728
-            );
729
-    }
730
-
731
-
732
-    /**
733
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
-     *
735
-     * @access public
736
-     * @return boolean true yes, false no
737
-     * @throws EE_Error
738
-     */
739
-    public function is_upcoming()
740
-    {
741
-        // check if event id is present and if this event is published
742
-        if ($this->is_inactive()) {
743
-            return false;
744
-        }
745
-        // set initial value
746
-        $upcoming = false;
747
-        //next let's get all datetimes and loop through them
748
-        $datetimes = $this->datetimes_in_chronological_order();
749
-        foreach ($datetimes as $datetime) {
750
-            if ($datetime instanceof EE_Datetime) {
751
-                //if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
-                if ($datetime->is_expired()) {
753
-                    continue;
754
-                }
755
-                //if this dtt is active then we return false.
756
-                if ($datetime->is_active()) {
757
-                    return false;
758
-                }
759
-                //otherwise let's check upcoming status
760
-                $upcoming = $datetime->is_upcoming();
761
-            }
762
-        }
763
-        return $upcoming;
764
-    }
765
-
766
-
767
-    /**
768
-     * @return bool
769
-     * @throws EE_Error
770
-     */
771
-    public function is_active()
772
-    {
773
-        // check if event id is present and if this event is published
774
-        if ($this->is_inactive()) {
775
-            return false;
776
-        }
777
-        // set initial value
778
-        $active = false;
779
-        //next let's get all datetimes and loop through them
780
-        $datetimes = $this->datetimes_in_chronological_order();
781
-        foreach ($datetimes as $datetime) {
782
-            if ($datetime instanceof EE_Datetime) {
783
-                //if this dtt is expired then we continue cause one of the other datetimes might be active.
784
-                if ($datetime->is_expired()) {
785
-                    continue;
786
-                }
787
-                //if this dtt is upcoming then we return false.
788
-                if ($datetime->is_upcoming()) {
789
-                    return false;
790
-                }
791
-                //otherwise let's check active status
792
-                $active = $datetime->is_active();
793
-            }
794
-        }
795
-        return $active;
796
-    }
797
-
798
-
799
-    /**
800
-     * @return bool
801
-     * @throws EE_Error
802
-     */
803
-    public function is_expired()
804
-    {
805
-        // check if event id is present and if this event is published
806
-        if ($this->is_inactive()) {
807
-            return false;
808
-        }
809
-        // set initial value
810
-        $expired = false;
811
-        //first let's get all datetimes and loop through them
812
-        $datetimes = $this->datetimes_in_chronological_order();
813
-        foreach ($datetimes as $datetime) {
814
-            if ($datetime instanceof EE_Datetime) {
815
-                //if this dtt is upcoming or active then we return false.
816
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
817
-                    return false;
818
-                }
819
-                //otherwise let's check active status
820
-                $expired = $datetime->is_expired();
821
-            }
822
-        }
823
-        return $expired;
824
-    }
825
-
826
-
827
-    /**
828
-     * @return bool
829
-     * @throws EE_Error
830
-     */
831
-    public function is_inactive()
832
-    {
833
-        // check if event id is present and if this event is published
834
-        if ($this->_has_ID_and_is_published()) {
835
-            return false;
836
-        }
837
-        return true;
838
-    }
839
-
840
-
841
-    /**
842
-     * calculate spaces remaining based on "saleable" tickets
843
-     *
844
-     * @param array $tickets
845
-     * @param bool $filtered
846
-     * @return int|float
847
-     * @throws EE_Error
848
-     * @throws DomainException
849
-     * @throws UnexpectedEntityException
850
-     */
851
-    public function spaces_remaining($tickets = array(), $filtered = true)
852
-    {
853
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
-        return $filtered
856
-            ? apply_filters(
857
-                'FHEE_EE_Event__spaces_remaining',
858
-                $spaces_remaining,
859
-                $this,
860
-                $tickets
861
-            )
862
-            : $spaces_remaining;
863
-    }
864
-
865
-
866
-    /**
867
-     *    perform_sold_out_status_check
868
-     *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
-     *    if NOT, then the event status will get toggled to 'sold_out'
870
-     *
871
-     * @return bool    return the ACTUAL sold out state.
872
-     * @throws EE_Error
873
-     * @throws DomainException
874
-     * @throws UnexpectedEntityException
875
-     */
876
-    public function perform_sold_out_status_check()
877
-    {
878
-        // get all unexpired untrashed tickets
879
-        $tickets = $this->active_tickets();
880
-        // if all the tickets are just expired, then don't update the event status to sold out
881
-        if (empty($tickets)) {
882
-            return true;
883
-        }
884
-        $spaces_remaining = $this->spaces_remaining($tickets);
885
-        if ($spaces_remaining < 1) {
886
-            $this->set_status(EEM_Event::sold_out);
887
-            $this->save();
888
-            $sold_out = true;
889
-        } else {
890
-            $sold_out = false;
891
-            // was event previously marked as sold out ?
892
-            if ($this->status() === EEM_Event::sold_out) {
893
-                // revert status to previous value, if it was set
894
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
-                if ($previous_event_status) {
896
-                    $this->set_status($previous_event_status);
897
-                    $this->save();
898
-                }
899
-            }
900
-        }
901
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
-        return $sold_out;
903
-    }
904
-
905
-
906
-
907
-    /**
908
-     * This returns the total remaining spaces for sale on this event.
909
-     *
910
-     * @uses EE_Event::total_available_spaces()
911
-     * @return float|int
912
-     * @throws EE_Error
913
-     * @throws DomainException
914
-     * @throws UnexpectedEntityException
915
-     */
916
-    public function spaces_remaining_for_sale()
917
-    {
918
-        return $this->total_available_spaces(true);
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * This returns the total spaces available for an event
925
-     * while considering all the qtys on the tickets and the reg limits
926
-     * on the datetimes attached to this event.
927
-     *
928
-     * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
-     *                              If this is false, then we return the most tickets that could ever be sold
930
-     *                              for this event with the datetime and tickets setup on the event under optimal
931
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
933
-     *                              may appear to equal remaining tickets.  However, the more tickets are
934
-     *                              sold out, the more accurate the "live" total is.
935
-     * @return float|int
936
-     * @throws EE_Error
937
-     * @throws DomainException
938
-     * @throws UnexpectedEntityException
939
-     */
940
-    public function total_available_spaces($consider_sold = false)
941
-    {
942
-        $spaces_available = $consider_sold
943
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
-        return apply_filters(
946
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
947
-            $spaces_available,
948
-            $this,
949
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
950
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
951
-        );
952
-    }
953
-
954
-
955
-    /**
956
-     * Checks if the event is set to sold out
957
-     *
958
-     * @param  bool $actual whether or not to perform calculations to not only figure the
959
-     *                      actual status but also to flip the status if necessary to sold
960
-     *                      out If false, we just check the existing status of the event
961
-     * @return boolean
962
-     * @throws EE_Error
963
-     */
964
-    public function is_sold_out($actual = false)
965
-    {
966
-        if (!$actual) {
967
-            return $this->status() === EEM_Event::sold_out;
968
-        }
969
-        return $this->perform_sold_out_status_check();
970
-    }
971
-
972
-
973
-    /**
974
-     * Checks if the event is marked as postponed
975
-     *
976
-     * @return boolean
977
-     */
978
-    public function is_postponed()
979
-    {
980
-        return $this->status() === EEM_Event::postponed;
981
-    }
982
-
983
-
984
-    /**
985
-     * Checks if the event is marked as cancelled
986
-     *
987
-     * @return boolean
988
-     */
989
-    public function is_cancelled()
990
-    {
991
-        return $this->status() === EEM_Event::cancelled;
992
-    }
993
-
994
-
995
-    /**
996
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
-     * the event is considered expired.
1001
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
-     * set on the EVENT when it is not published and thus is done
1003
-     *
1004
-     * @param bool $reset
1005
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
-     * @throws EE_Error
1007
-     */
1008
-    public function get_active_status($reset = false)
1009
-    {
1010
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1012
-            return $this->_active_status;
1013
-        }
1014
-        //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1016
-            return false;
1017
-        }
1018
-        $where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
-        //if event is published:
1020
-        if ($this->status() === 'publish') {
1021
-            //active?
1022
-            if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
-                $this->_active_status = EE_Datetime::active;
1024
-            } else {
1025
-                //upcoming?
1026
-                if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
-                    $this->_active_status = EE_Datetime::upcoming;
1028
-                } else {
1029
-                    //expired?
1030
-                    if (
1031
-                        EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
-                    ) {
1033
-                        $this->_active_status = EE_Datetime::expired;
1034
-                    } else {
1035
-                        //it would be odd if things make it this far because it basically means there are no datetime's
1036
-                        //attached to the event.  So in this case it will just be considered inactive.
1037
-                        $this->_active_status = EE_Datetime::inactive;
1038
-                    }
1039
-                }
1040
-            }
1041
-        } else {
1042
-            //the event is not published, so let's just set it's active status according to its' post status
1043
-            switch ($this->status()) {
1044
-                case EEM_Event::sold_out :
1045
-                    $this->_active_status = EE_Datetime::sold_out;
1046
-                    break;
1047
-                case EEM_Event::cancelled :
1048
-                    $this->_active_status = EE_Datetime::cancelled;
1049
-                    break;
1050
-                case EEM_Event::postponed :
1051
-                    $this->_active_status = EE_Datetime::postponed;
1052
-                    break;
1053
-                default :
1054
-                    $this->_active_status = EE_Datetime::inactive;
1055
-            }
1056
-        }
1057
-        return $this->_active_status;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     *    pretty_active_status
1063
-     *
1064
-     * @access public
1065
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
-     * @return mixed void|string
1067
-     * @throws EE_Error
1068
-     */
1069
-    public function pretty_active_status($echo = true)
1070
-    {
1071
-        $active_status = $this->get_active_status();
1072
-        $status = '<span class="ee-status event-active-status-'
1073
-            . $active_status
1074
-            . '">'
1075
-            . EEH_Template::pretty_status($active_status, false, 'sentence')
1076
-            . '</span>';
1077
-        if ($echo) {
1078
-            echo $status;
1079
-            return '';
1080
-        }
1081
-        return $status;
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * @return bool|int
1087
-     * @throws EE_Error
1088
-     */
1089
-    public function get_number_of_tickets_sold()
1090
-    {
1091
-        $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1093
-            return 0;
1094
-        }
1095
-        $datetimes = $this->datetimes();
1096
-        foreach ($datetimes as $datetime) {
1097
-            if ($datetime instanceof EE_Datetime) {
1098
-                $tkt_sold += $datetime->sold();
1099
-            }
1100
-        }
1101
-        return $tkt_sold;
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * This just returns a count of all the registrations for this event
1107
-     *
1108
-     * @access  public
1109
-     * @return int
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function get_count_of_all_registrations()
1113
-    {
1114
-        return EEM_Event::instance()->count_related($this, 'Registration');
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * This returns the ticket with the earliest start time that is
1120
-     * available for this event (across all datetimes attached to the event)
1121
-     *
1122
-     * @return EE_Base_Class|EE_Ticket|null
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_ticket_with_earliest_start_time()
1126
-    {
1127
-        $where['Datetime.EVT_ID'] = $this->ID();
1128
-        $query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * This returns the ticket with the latest end time that is available
1135
-     * for this event (across all datetimes attached to the event)
1136
-     *
1137
-     * @return EE_Base_Class|EE_Ticket|null
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function get_ticket_with_latest_end_time()
1141
-    {
1142
-        $where['Datetime.EVT_ID'] = $this->ID();
1143
-        $query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This returns whether there are any tickets on sale for this event.
1150
-     *
1151
-     * @return bool true = YES tickets on sale.
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function tickets_on_sale()
1155
-    {
1156
-        $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
-        $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
-            return false;
1160
-        }
1161
-        //check on sale for these two tickets.
1162
-        if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
-            return true;
1164
-        }
1165
-        return false;
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1171
-     * to check for an external URL first
1172
-     *
1173
-     * @return string
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get_permalink()
1177
-    {
1178
-        if ($this->external_url()) {
1179
-            return $this->external_url();
1180
-        }
1181
-        return parent::get_permalink();
1182
-    }
1183
-
1184
-
1185
-    /**
1186
-     * Gets the first term for 'espresso_event_categories' we can find
1187
-     *
1188
-     * @param array $query_params like EEM_Base::get_all
1189
-     * @return EE_Base_Class|EE_Term|null
1190
-     * @throws EE_Error
1191
-     */
1192
-    public function first_event_category($query_params = array())
1193
-    {
1194
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
-        return EEM_Term::instance()->get_one($query_params);
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * Gets all terms for 'espresso_event_categories' we can find
1202
-     *
1203
-     * @param array $query_params
1204
-     * @return EE_Base_Class[]|EE_Term[]
1205
-     * @throws EE_Error
1206
-     */
1207
-    public function get_all_event_categories($query_params = array())
1208
-    {
1209
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
-        return EEM_Term::instance()->get_all($query_params);
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Gets all the question groups, ordering them by QSG_order ascending
1217
-     *
1218
-     * @param array $query_params @see EEM_Base::get_all
1219
-     * @return EE_Base_Class[]|EE_Question_Group[]
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function question_groups($query_params = array())
1223
-    {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
-        return $this->get_many_related('Question_Group', $query_params);
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Implementation for EEI_Has_Icon interface method.
1231
-     *
1232
-     * @see EEI_Visual_Representation for comments
1233
-     * @return string
1234
-     */
1235
-    public function get_icon()
1236
-    {
1237
-        return '<span class="dashicons dashicons-flag"></span>';
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * Implementation for EEI_Admin_Links interface method.
1243
-     *
1244
-     * @see EEI_Admin_Links for comments
1245
-     * @return string
1246
-     * @throws EE_Error
1247
-     */
1248
-    public function get_admin_details_link()
1249
-    {
1250
-        return $this->get_admin_edit_link();
1251
-    }
1252
-
1253
-
1254
-    /**
1255
-     * Implementation for EEI_Admin_Links interface method.
1256
-     *
1257
-     * @see EEI_Admin_Links for comments
1258
-     * @return string
1259
-     * @throws EE_Error
1260
-     */
1261
-    public function get_admin_edit_link()
1262
-    {
1263
-        return EEH_URL::add_query_args_and_nonce(array(
1264
-            'page' => 'espresso_events',
1265
-            'action' => 'edit',
1266
-            'post' => $this->ID(),
1267
-        ),
1268
-            admin_url('admin.php')
1269
-        );
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Implementation for EEI_Admin_Links interface method.
1275
-     *
1276
-     * @see EEI_Admin_Links for comments
1277
-     * @return string
1278
-     */
1279
-    public function get_admin_settings_link()
1280
-    {
1281
-        return EEH_URL::add_query_args_and_nonce(array(
1282
-            'page' => 'espresso_events',
1283
-            'action' => 'default_event_settings',
1284
-        ),
1285
-            admin_url('admin.php')
1286
-        );
1287
-    }
1288
-
1289
-
1290
-    /**
1291
-     * Implementation for EEI_Admin_Links interface method.
1292
-     *
1293
-     * @see EEI_Admin_Links for comments
1294
-     * @return string
1295
-     */
1296
-    public function get_admin_overview_link()
1297
-    {
1298
-        return EEH_URL::add_query_args_and_nonce(array(
1299
-            'page' => 'espresso_events',
1300
-            'action' => 'default',
1301
-        ),
1302
-            admin_url('admin.php')
1303
-        );
1304
-    }
21
+	/**
22
+	 * cached value for the the logical active status for the event
23
+	 *
24
+	 * @see get_active_status()
25
+	 * @var string
26
+	 */
27
+	protected $_active_status = '';
28
+
29
+	/**
30
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
+	 *
32
+	 * @var EE_Datetime
33
+	 */
34
+	protected $_Primary_Datetime;
35
+
36
+	/**
37
+	 * @var EventSpacesCalculator $available_spaces_calculator
38
+	 */
39
+	protected $available_spaces_calculator;
40
+
41
+
42
+	/**
43
+	 * @param array $props_n_values incoming values
44
+	 * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
+	 *                                        used.)
46
+	 * @param array $date_formats incoming date_formats in an array where the first value is the
47
+	 *                                        date_format and the second value is the time format
48
+	 * @return EE_Event
49
+	 * @throws EE_Error
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param array $props_n_values incoming values from the database
60
+	 * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
+	 *                                the website will be used.
62
+	 * @return EE_Event
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * @return EventSpacesCalculator
74
+	 * @throws \EE_Error
75
+	 */
76
+	public function getAvailableSpacesCalculator()
77
+	{
78
+		if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
+	 *
89
+	 * @param string $field_name
90
+	 * @param mixed $field_value
91
+	 * @param bool $use_default
92
+	 * @throws EE_Error
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status' :
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default :
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @access public
113
+	 * @param string $new_status
114
+	 * @param bool $use_default
115
+	 * @return void
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_status($new_status = null, $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($new_status) && !$use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $new_status) {
128
+			// TO sold_out
129
+			if ($new_status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
+				// OR FROM  sold_out
134
+			} else if ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
+			}
138
+			// update status
139
+			parent::set('status', $new_status, $use_default);
140
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
141
+			return;
142
+		}
143
+		// even though the old value matches the new value, it's still good to
144
+		// allow the parent set method to have a say
145
+		parent::set('status', $new_status, $use_default);
146
+	}
147
+
148
+
149
+	/**
150
+	 * Gets all the datetimes for this event
151
+	 *
152
+	 * @param array $query_params like EEM_Base::get_all
153
+	 * @return EE_Base_Class[]|EE_Datetime[]
154
+	 * @throws EE_Error
155
+	 */
156
+	public function datetimes($query_params = array())
157
+	{
158
+		return $this->get_many_related('Datetime', $query_params);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
+	 *
165
+	 * @return EE_Base_Class[]|EE_Datetime[]
166
+	 * @throws EE_Error
167
+	 */
168
+	public function datetimes_in_chronological_order()
169
+	{
170
+		return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
+	}
172
+
173
+
174
+	/**
175
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
+	 * after running our query, so that this timezone isn't set for EVERY query
178
+	 * on EEM_Datetime for the rest of the request, no?
179
+	 *
180
+	 * @param boolean $show_expired whether or not to include expired events
181
+	 * @param boolean $show_deleted whether or not to include deleted events
182
+	 * @param null $limit
183
+	 * @return EE_Datetime[]
184
+	 * @throws EE_Error
185
+	 */
186
+	public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
+	{
188
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
+			$this->ID(),
190
+			$show_expired,
191
+			$show_deleted,
192
+			$limit
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * Returns one related datetime. Mostly only used by some legacy code.
199
+	 *
200
+	 * @return EE_Base_Class|EE_Datetime
201
+	 * @throws EE_Error
202
+	 */
203
+	public function first_datetime()
204
+	{
205
+		return $this->get_first_related('Datetime');
206
+	}
207
+
208
+
209
+	/**
210
+	 * Returns the 'primary' datetime for the event
211
+	 *
212
+	 * @param bool $try_to_exclude_expired
213
+	 * @param bool $try_to_exclude_deleted
214
+	 * @return EE_Datetime
215
+	 * @throws EE_Error
216
+	 */
217
+	public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
+	{
219
+		if (!empty ($this->_Primary_Datetime)) {
220
+			return $this->_Primary_Datetime;
221
+		}
222
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
+			$this->ID(),
224
+			$try_to_exclude_expired,
225
+			$try_to_exclude_deleted
226
+		);
227
+		return $this->_Primary_Datetime;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets all the tickets available for purchase of this event
233
+	 *
234
+	 * @param array $query_params like EEM_Base::get_all
235
+	 * @return EE_Base_Class[]|EE_Ticket[]
236
+	 * @throws EE_Error
237
+	 */
238
+	public function tickets($query_params = array())
239
+	{
240
+		//first get all datetimes
241
+		$datetimes = $this->datetimes_ordered();
242
+		if (!$datetimes) {
243
+			return array();
244
+		}
245
+		$datetime_ids = array();
246
+		foreach ($datetimes as $datetime) {
247
+			$datetime_ids[] = $datetime->ID();
248
+		}
249
+		$where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
+		//if incoming $query_params has where conditions let's merge but not override existing.
251
+		if (is_array($query_params) && isset($query_params[0])) {
252
+			$where_params = array_merge($query_params[0], $where_params);
253
+			unset($query_params[0]);
254
+		}
255
+		//now add $where_params to $query_params
256
+		$query_params[0] = $where_params;
257
+		return EEM_Ticket::instance()->get_all($query_params);
258
+	}
259
+
260
+
261
+	/**
262
+	 * get all unexpired untrashed tickets
263
+	 *
264
+	 * @return EE_Ticket[]
265
+	 * @throws EE_Error
266
+	 */
267
+	public function active_tickets()
268
+	{
269
+		return $this->tickets(array(
270
+			array(
271
+				'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
+				'TKT_deleted' => false,
273
+			),
274
+		));
275
+	}
276
+
277
+
278
+	/**
279
+	 * @return bool
280
+	 * @throws EE_Error
281
+	 */
282
+	public function additional_limit()
283
+	{
284
+		return $this->get('EVT_additional_limit');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return bool
290
+	 * @throws EE_Error
291
+	 */
292
+	public function allow_overflow()
293
+	{
294
+		return $this->get('EVT_allow_overflow');
295
+	}
296
+
297
+
298
+	/**
299
+	 * @return bool
300
+	 * @throws EE_Error
301
+	 */
302
+	public function created()
303
+	{
304
+		return $this->get('EVT_created');
305
+	}
306
+
307
+
308
+	/**
309
+	 * @return bool
310
+	 * @throws EE_Error
311
+	 */
312
+	public function description()
313
+	{
314
+		return $this->get('EVT_desc');
315
+	}
316
+
317
+
318
+	/**
319
+	 * Runs do_shortcode and wpautop on the description
320
+	 *
321
+	 * @return string of html
322
+	 * @throws EE_Error
323
+	 */
324
+	public function description_filtered()
325
+	{
326
+		return $this->get_pretty('EVT_desc');
327
+	}
328
+
329
+
330
+	/**
331
+	 * @return bool
332
+	 * @throws EE_Error
333
+	 */
334
+	public function display_description()
335
+	{
336
+		return $this->get('EVT_display_desc');
337
+	}
338
+
339
+
340
+	/**
341
+	 * @return bool
342
+	 * @throws EE_Error
343
+	 */
344
+	public function display_ticket_selector()
345
+	{
346
+		return (bool)$this->get('EVT_display_ticket_selector');
347
+	}
348
+
349
+
350
+	/**
351
+	 * @return bool
352
+	 * @throws EE_Error
353
+	 */
354
+	public function external_url()
355
+	{
356
+		return $this->get('EVT_external_URL');
357
+	}
358
+
359
+
360
+	/**
361
+	 * @return bool
362
+	 * @throws EE_Error
363
+	 */
364
+	public function member_only()
365
+	{
366
+		return $this->get('EVT_member_only');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return bool
372
+	 * @throws EE_Error
373
+	 */
374
+	public function phone()
375
+	{
376
+		return $this->get('EVT_phone');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 */
384
+	public function modified()
385
+	{
386
+		return $this->get('EVT_modified');
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return bool
392
+	 * @throws EE_Error
393
+	 */
394
+	public function name()
395
+	{
396
+		return $this->get('EVT_name');
397
+	}
398
+
399
+
400
+	/**
401
+	 * @return bool
402
+	 * @throws EE_Error
403
+	 */
404
+	public function order()
405
+	{
406
+		return $this->get('EVT_order');
407
+	}
408
+
409
+
410
+	/**
411
+	 * @return bool|string
412
+	 * @throws EE_Error
413
+	 */
414
+	public function default_registration_status()
415
+	{
416
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
417
+		return !empty($event_default_registration_status)
418
+			? $event_default_registration_status
419
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
420
+	}
421
+
422
+
423
+	/**
424
+	 * @param int $num_words
425
+	 * @param null $more
426
+	 * @param bool $not_full_desc
427
+	 * @return bool|string
428
+	 * @throws EE_Error
429
+	 */
430
+	public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
+	{
432
+		$short_desc = $this->get('EVT_short_desc');
433
+		if (!empty($short_desc) || $not_full_desc) {
434
+			return $short_desc;
435
+		}
436
+		$full_desc = $this->get('EVT_desc');
437
+		return wp_trim_words($full_desc, $num_words, $more);
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return bool
443
+	 * @throws EE_Error
444
+	 */
445
+	public function slug()
446
+	{
447
+		return $this->get('EVT_slug');
448
+	}
449
+
450
+
451
+	/**
452
+	 * @return bool
453
+	 * @throws EE_Error
454
+	 */
455
+	public function timezone_string()
456
+	{
457
+		return $this->get('EVT_timezone_string');
458
+	}
459
+
460
+
461
+	/**
462
+	 * @return bool
463
+	 * @throws EE_Error
464
+	 */
465
+	public function visible_on()
466
+	{
467
+		return $this->get('EVT_visible_on');
468
+	}
469
+
470
+
471
+	/**
472
+	 * @return int
473
+	 * @throws EE_Error
474
+	 */
475
+	public function wp_user()
476
+	{
477
+		return $this->get('EVT_wp_user');
478
+	}
479
+
480
+
481
+	/**
482
+	 * @return bool
483
+	 * @throws EE_Error
484
+	 */
485
+	public function donations()
486
+	{
487
+		return $this->get('EVT_donations');
488
+	}
489
+
490
+
491
+	/**
492
+	 * @param $limit
493
+	 * @throws EE_Error
494
+	 */
495
+	public function set_additional_limit($limit)
496
+	{
497
+		$this->set('EVT_additional_limit', $limit);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @param $created
503
+	 * @throws EE_Error
504
+	 */
505
+	public function set_created($created)
506
+	{
507
+		$this->set('EVT_created', $created);
508
+	}
509
+
510
+
511
+	/**
512
+	 * @param $desc
513
+	 * @throws EE_Error
514
+	 */
515
+	public function set_description($desc)
516
+	{
517
+		$this->set('EVT_desc', $desc);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @param $display_desc
523
+	 * @throws EE_Error
524
+	 */
525
+	public function set_display_description($display_desc)
526
+	{
527
+		$this->set('EVT_display_desc', $display_desc);
528
+	}
529
+
530
+
531
+	/**
532
+	 * @param $display_ticket_selector
533
+	 * @throws EE_Error
534
+	 */
535
+	public function set_display_ticket_selector($display_ticket_selector)
536
+	{
537
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
+	}
539
+
540
+
541
+	/**
542
+	 * @param $external_url
543
+	 * @throws EE_Error
544
+	 */
545
+	public function set_external_url($external_url)
546
+	{
547
+		$this->set('EVT_external_URL', $external_url);
548
+	}
549
+
550
+
551
+	/**
552
+	 * @param $member_only
553
+	 * @throws EE_Error
554
+	 */
555
+	public function set_member_only($member_only)
556
+	{
557
+		$this->set('EVT_member_only', $member_only);
558
+	}
559
+
560
+
561
+	/**
562
+	 * @param $event_phone
563
+	 * @throws EE_Error
564
+	 */
565
+	public function set_event_phone($event_phone)
566
+	{
567
+		$this->set('EVT_phone', $event_phone);
568
+	}
569
+
570
+
571
+	/**
572
+	 * @param $modified
573
+	 * @throws EE_Error
574
+	 */
575
+	public function set_modified($modified)
576
+	{
577
+		$this->set('EVT_modified', $modified);
578
+	}
579
+
580
+
581
+	/**
582
+	 * @param $name
583
+	 * @throws EE_Error
584
+	 */
585
+	public function set_name($name)
586
+	{
587
+		$this->set('EVT_name', $name);
588
+	}
589
+
590
+
591
+	/**
592
+	 * @param $order
593
+	 * @throws EE_Error
594
+	 */
595
+	public function set_order($order)
596
+	{
597
+		$this->set('EVT_order', $order);
598
+	}
599
+
600
+
601
+	/**
602
+	 * @param $short_desc
603
+	 * @throws EE_Error
604
+	 */
605
+	public function set_short_description($short_desc)
606
+	{
607
+		$this->set('EVT_short_desc', $short_desc);
608
+	}
609
+
610
+
611
+	/**
612
+	 * @param $slug
613
+	 * @throws EE_Error
614
+	 */
615
+	public function set_slug($slug)
616
+	{
617
+		$this->set('EVT_slug', $slug);
618
+	}
619
+
620
+
621
+	/**
622
+	 * @param $timezone_string
623
+	 * @throws EE_Error
624
+	 */
625
+	public function set_timezone_string($timezone_string)
626
+	{
627
+		$this->set('EVT_timezone_string', $timezone_string);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $visible_on
633
+	 * @throws EE_Error
634
+	 */
635
+	public function set_visible_on($visible_on)
636
+	{
637
+		$this->set('EVT_visible_on', $visible_on);
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param $wp_user
643
+	 * @throws EE_Error
644
+	 */
645
+	public function set_wp_user($wp_user)
646
+	{
647
+		$this->set('EVT_wp_user', $wp_user);
648
+	}
649
+
650
+
651
+	/**
652
+	 * @param $default_registration_status
653
+	 * @throws EE_Error
654
+	 */
655
+	public function set_default_registration_status($default_registration_status)
656
+	{
657
+		$this->set('EVT_default_registration_status', $default_registration_status);
658
+	}
659
+
660
+
661
+	/**
662
+	 * @param $donations
663
+	 * @throws EE_Error
664
+	 */
665
+	public function set_donations($donations)
666
+	{
667
+		$this->set('EVT_donations', $donations);
668
+	}
669
+
670
+
671
+	/**
672
+	 * Adds a venue to this event
673
+	 *
674
+	 * @param EE_Venue /int $venue_id_or_obj
675
+	 * @return EE_Base_Class|EE_Venue
676
+	 * @throws EE_Error
677
+	 */
678
+	public function add_venue($venue_id_or_obj)
679
+	{
680
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
+	}
682
+
683
+
684
+	/**
685
+	 * Removes a venue from the event
686
+	 *
687
+	 * @param EE_Venue /int $venue_id_or_obj
688
+	 * @return EE_Base_Class|EE_Venue
689
+	 * @throws EE_Error
690
+	 */
691
+	public function remove_venue($venue_id_or_obj)
692
+	{
693
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
+	}
695
+
696
+
697
+	/**
698
+	 * Gets all the venues related ot the event. May provide additional $query_params if desired
699
+	 *
700
+	 * @param array $query_params like EEM_Base::get_all's $query_params
701
+	 * @return EE_Base_Class[]|EE_Venue[]
702
+	 * @throws EE_Error
703
+	 */
704
+	public function venues($query_params = array())
705
+	{
706
+		return $this->get_many_related('Venue', $query_params);
707
+	}
708
+
709
+
710
+	/**
711
+	 * check if event id is present and if event is published
712
+	 *
713
+	 * @access public
714
+	 * @return boolean true yes, false no
715
+	 * @throws EE_Error
716
+	 */
717
+	private function _has_ID_and_is_published()
718
+	{
719
+		// first check if event id is present and not NULL,
720
+		// then check if this event is published (or any of the equivalent "published" statuses)
721
+		return
722
+			$this->ID() && $this->ID() !== null
723
+			&& (
724
+				$this->status() === 'publish'
725
+				|| $this->status() === EEM_Event::sold_out
726
+				|| $this->status() === EEM_Event::postponed
727
+				|| $this->status() === EEM_Event::cancelled
728
+			);
729
+	}
730
+
731
+
732
+	/**
733
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
+	 *
735
+	 * @access public
736
+	 * @return boolean true yes, false no
737
+	 * @throws EE_Error
738
+	 */
739
+	public function is_upcoming()
740
+	{
741
+		// check if event id is present and if this event is published
742
+		if ($this->is_inactive()) {
743
+			return false;
744
+		}
745
+		// set initial value
746
+		$upcoming = false;
747
+		//next let's get all datetimes and loop through them
748
+		$datetimes = $this->datetimes_in_chronological_order();
749
+		foreach ($datetimes as $datetime) {
750
+			if ($datetime instanceof EE_Datetime) {
751
+				//if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
+				if ($datetime->is_expired()) {
753
+					continue;
754
+				}
755
+				//if this dtt is active then we return false.
756
+				if ($datetime->is_active()) {
757
+					return false;
758
+				}
759
+				//otherwise let's check upcoming status
760
+				$upcoming = $datetime->is_upcoming();
761
+			}
762
+		}
763
+		return $upcoming;
764
+	}
765
+
766
+
767
+	/**
768
+	 * @return bool
769
+	 * @throws EE_Error
770
+	 */
771
+	public function is_active()
772
+	{
773
+		// check if event id is present and if this event is published
774
+		if ($this->is_inactive()) {
775
+			return false;
776
+		}
777
+		// set initial value
778
+		$active = false;
779
+		//next let's get all datetimes and loop through them
780
+		$datetimes = $this->datetimes_in_chronological_order();
781
+		foreach ($datetimes as $datetime) {
782
+			if ($datetime instanceof EE_Datetime) {
783
+				//if this dtt is expired then we continue cause one of the other datetimes might be active.
784
+				if ($datetime->is_expired()) {
785
+					continue;
786
+				}
787
+				//if this dtt is upcoming then we return false.
788
+				if ($datetime->is_upcoming()) {
789
+					return false;
790
+				}
791
+				//otherwise let's check active status
792
+				$active = $datetime->is_active();
793
+			}
794
+		}
795
+		return $active;
796
+	}
797
+
798
+
799
+	/**
800
+	 * @return bool
801
+	 * @throws EE_Error
802
+	 */
803
+	public function is_expired()
804
+	{
805
+		// check if event id is present and if this event is published
806
+		if ($this->is_inactive()) {
807
+			return false;
808
+		}
809
+		// set initial value
810
+		$expired = false;
811
+		//first let's get all datetimes and loop through them
812
+		$datetimes = $this->datetimes_in_chronological_order();
813
+		foreach ($datetimes as $datetime) {
814
+			if ($datetime instanceof EE_Datetime) {
815
+				//if this dtt is upcoming or active then we return false.
816
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
817
+					return false;
818
+				}
819
+				//otherwise let's check active status
820
+				$expired = $datetime->is_expired();
821
+			}
822
+		}
823
+		return $expired;
824
+	}
825
+
826
+
827
+	/**
828
+	 * @return bool
829
+	 * @throws EE_Error
830
+	 */
831
+	public function is_inactive()
832
+	{
833
+		// check if event id is present and if this event is published
834
+		if ($this->_has_ID_and_is_published()) {
835
+			return false;
836
+		}
837
+		return true;
838
+	}
839
+
840
+
841
+	/**
842
+	 * calculate spaces remaining based on "saleable" tickets
843
+	 *
844
+	 * @param array $tickets
845
+	 * @param bool $filtered
846
+	 * @return int|float
847
+	 * @throws EE_Error
848
+	 * @throws DomainException
849
+	 * @throws UnexpectedEntityException
850
+	 */
851
+	public function spaces_remaining($tickets = array(), $filtered = true)
852
+	{
853
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
+		return $filtered
856
+			? apply_filters(
857
+				'FHEE_EE_Event__spaces_remaining',
858
+				$spaces_remaining,
859
+				$this,
860
+				$tickets
861
+			)
862
+			: $spaces_remaining;
863
+	}
864
+
865
+
866
+	/**
867
+	 *    perform_sold_out_status_check
868
+	 *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
+	 *    if NOT, then the event status will get toggled to 'sold_out'
870
+	 *
871
+	 * @return bool    return the ACTUAL sold out state.
872
+	 * @throws EE_Error
873
+	 * @throws DomainException
874
+	 * @throws UnexpectedEntityException
875
+	 */
876
+	public function perform_sold_out_status_check()
877
+	{
878
+		// get all unexpired untrashed tickets
879
+		$tickets = $this->active_tickets();
880
+		// if all the tickets are just expired, then don't update the event status to sold out
881
+		if (empty($tickets)) {
882
+			return true;
883
+		}
884
+		$spaces_remaining = $this->spaces_remaining($tickets);
885
+		if ($spaces_remaining < 1) {
886
+			$this->set_status(EEM_Event::sold_out);
887
+			$this->save();
888
+			$sold_out = true;
889
+		} else {
890
+			$sold_out = false;
891
+			// was event previously marked as sold out ?
892
+			if ($this->status() === EEM_Event::sold_out) {
893
+				// revert status to previous value, if it was set
894
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
+				if ($previous_event_status) {
896
+					$this->set_status($previous_event_status);
897
+					$this->save();
898
+				}
899
+			}
900
+		}
901
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
+		return $sold_out;
903
+	}
904
+
905
+
906
+
907
+	/**
908
+	 * This returns the total remaining spaces for sale on this event.
909
+	 *
910
+	 * @uses EE_Event::total_available_spaces()
911
+	 * @return float|int
912
+	 * @throws EE_Error
913
+	 * @throws DomainException
914
+	 * @throws UnexpectedEntityException
915
+	 */
916
+	public function spaces_remaining_for_sale()
917
+	{
918
+		return $this->total_available_spaces(true);
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * This returns the total spaces available for an event
925
+	 * while considering all the qtys on the tickets and the reg limits
926
+	 * on the datetimes attached to this event.
927
+	 *
928
+	 * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
+	 *                              If this is false, then we return the most tickets that could ever be sold
930
+	 *                              for this event with the datetime and tickets setup on the event under optimal
931
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
933
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
934
+	 *                              sold out, the more accurate the "live" total is.
935
+	 * @return float|int
936
+	 * @throws EE_Error
937
+	 * @throws DomainException
938
+	 * @throws UnexpectedEntityException
939
+	 */
940
+	public function total_available_spaces($consider_sold = false)
941
+	{
942
+		$spaces_available = $consider_sold
943
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
+		return apply_filters(
946
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
947
+			$spaces_available,
948
+			$this,
949
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
950
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
951
+		);
952
+	}
953
+
954
+
955
+	/**
956
+	 * Checks if the event is set to sold out
957
+	 *
958
+	 * @param  bool $actual whether or not to perform calculations to not only figure the
959
+	 *                      actual status but also to flip the status if necessary to sold
960
+	 *                      out If false, we just check the existing status of the event
961
+	 * @return boolean
962
+	 * @throws EE_Error
963
+	 */
964
+	public function is_sold_out($actual = false)
965
+	{
966
+		if (!$actual) {
967
+			return $this->status() === EEM_Event::sold_out;
968
+		}
969
+		return $this->perform_sold_out_status_check();
970
+	}
971
+
972
+
973
+	/**
974
+	 * Checks if the event is marked as postponed
975
+	 *
976
+	 * @return boolean
977
+	 */
978
+	public function is_postponed()
979
+	{
980
+		return $this->status() === EEM_Event::postponed;
981
+	}
982
+
983
+
984
+	/**
985
+	 * Checks if the event is marked as cancelled
986
+	 *
987
+	 * @return boolean
988
+	 */
989
+	public function is_cancelled()
990
+	{
991
+		return $this->status() === EEM_Event::cancelled;
992
+	}
993
+
994
+
995
+	/**
996
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
+	 * the event is considered expired.
1001
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
+	 * set on the EVENT when it is not published and thus is done
1003
+	 *
1004
+	 * @param bool $reset
1005
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
+	 * @throws EE_Error
1007
+	 */
1008
+	public function get_active_status($reset = false)
1009
+	{
1010
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1011
+		if (!empty($this->_active_status) && !$reset) {
1012
+			return $this->_active_status;
1013
+		}
1014
+		//first check if event id is present on this object
1015
+		if (!$this->ID()) {
1016
+			return false;
1017
+		}
1018
+		$where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
+		//if event is published:
1020
+		if ($this->status() === 'publish') {
1021
+			//active?
1022
+			if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
+				$this->_active_status = EE_Datetime::active;
1024
+			} else {
1025
+				//upcoming?
1026
+				if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
+					$this->_active_status = EE_Datetime::upcoming;
1028
+				} else {
1029
+					//expired?
1030
+					if (
1031
+						EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
+					) {
1033
+						$this->_active_status = EE_Datetime::expired;
1034
+					} else {
1035
+						//it would be odd if things make it this far because it basically means there are no datetime's
1036
+						//attached to the event.  So in this case it will just be considered inactive.
1037
+						$this->_active_status = EE_Datetime::inactive;
1038
+					}
1039
+				}
1040
+			}
1041
+		} else {
1042
+			//the event is not published, so let's just set it's active status according to its' post status
1043
+			switch ($this->status()) {
1044
+				case EEM_Event::sold_out :
1045
+					$this->_active_status = EE_Datetime::sold_out;
1046
+					break;
1047
+				case EEM_Event::cancelled :
1048
+					$this->_active_status = EE_Datetime::cancelled;
1049
+					break;
1050
+				case EEM_Event::postponed :
1051
+					$this->_active_status = EE_Datetime::postponed;
1052
+					break;
1053
+				default :
1054
+					$this->_active_status = EE_Datetime::inactive;
1055
+			}
1056
+		}
1057
+		return $this->_active_status;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 *    pretty_active_status
1063
+	 *
1064
+	 * @access public
1065
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
+	 * @return mixed void|string
1067
+	 * @throws EE_Error
1068
+	 */
1069
+	public function pretty_active_status($echo = true)
1070
+	{
1071
+		$active_status = $this->get_active_status();
1072
+		$status = '<span class="ee-status event-active-status-'
1073
+			. $active_status
1074
+			. '">'
1075
+			. EEH_Template::pretty_status($active_status, false, 'sentence')
1076
+			. '</span>';
1077
+		if ($echo) {
1078
+			echo $status;
1079
+			return '';
1080
+		}
1081
+		return $status;
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * @return bool|int
1087
+	 * @throws EE_Error
1088
+	 */
1089
+	public function get_number_of_tickets_sold()
1090
+	{
1091
+		$tkt_sold = 0;
1092
+		if (!$this->ID()) {
1093
+			return 0;
1094
+		}
1095
+		$datetimes = $this->datetimes();
1096
+		foreach ($datetimes as $datetime) {
1097
+			if ($datetime instanceof EE_Datetime) {
1098
+				$tkt_sold += $datetime->sold();
1099
+			}
1100
+		}
1101
+		return $tkt_sold;
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * This just returns a count of all the registrations for this event
1107
+	 *
1108
+	 * @access  public
1109
+	 * @return int
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function get_count_of_all_registrations()
1113
+	{
1114
+		return EEM_Event::instance()->count_related($this, 'Registration');
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * This returns the ticket with the earliest start time that is
1120
+	 * available for this event (across all datetimes attached to the event)
1121
+	 *
1122
+	 * @return EE_Base_Class|EE_Ticket|null
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_ticket_with_earliest_start_time()
1126
+	{
1127
+		$where['Datetime.EVT_ID'] = $this->ID();
1128
+		$query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * This returns the ticket with the latest end time that is available
1135
+	 * for this event (across all datetimes attached to the event)
1136
+	 *
1137
+	 * @return EE_Base_Class|EE_Ticket|null
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function get_ticket_with_latest_end_time()
1141
+	{
1142
+		$where['Datetime.EVT_ID'] = $this->ID();
1143
+		$query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This returns whether there are any tickets on sale for this event.
1150
+	 *
1151
+	 * @return bool true = YES tickets on sale.
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function tickets_on_sale()
1155
+	{
1156
+		$earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
+		$latest_ticket = $this->get_ticket_with_latest_end_time();
1158
+		if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
+			return false;
1160
+		}
1161
+		//check on sale for these two tickets.
1162
+		if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
+			return true;
1164
+		}
1165
+		return false;
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1171
+	 * to check for an external URL first
1172
+	 *
1173
+	 * @return string
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get_permalink()
1177
+	{
1178
+		if ($this->external_url()) {
1179
+			return $this->external_url();
1180
+		}
1181
+		return parent::get_permalink();
1182
+	}
1183
+
1184
+
1185
+	/**
1186
+	 * Gets the first term for 'espresso_event_categories' we can find
1187
+	 *
1188
+	 * @param array $query_params like EEM_Base::get_all
1189
+	 * @return EE_Base_Class|EE_Term|null
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public function first_event_category($query_params = array())
1193
+	{
1194
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
+		return EEM_Term::instance()->get_one($query_params);
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * Gets all terms for 'espresso_event_categories' we can find
1202
+	 *
1203
+	 * @param array $query_params
1204
+	 * @return EE_Base_Class[]|EE_Term[]
1205
+	 * @throws EE_Error
1206
+	 */
1207
+	public function get_all_event_categories($query_params = array())
1208
+	{
1209
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
+		return EEM_Term::instance()->get_all($query_params);
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Gets all the question groups, ordering them by QSG_order ascending
1217
+	 *
1218
+	 * @param array $query_params @see EEM_Base::get_all
1219
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function question_groups($query_params = array())
1223
+	{
1224
+		$query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
+		return $this->get_many_related('Question_Group', $query_params);
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Implementation for EEI_Has_Icon interface method.
1231
+	 *
1232
+	 * @see EEI_Visual_Representation for comments
1233
+	 * @return string
1234
+	 */
1235
+	public function get_icon()
1236
+	{
1237
+		return '<span class="dashicons dashicons-flag"></span>';
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * Implementation for EEI_Admin_Links interface method.
1243
+	 *
1244
+	 * @see EEI_Admin_Links for comments
1245
+	 * @return string
1246
+	 * @throws EE_Error
1247
+	 */
1248
+	public function get_admin_details_link()
1249
+	{
1250
+		return $this->get_admin_edit_link();
1251
+	}
1252
+
1253
+
1254
+	/**
1255
+	 * Implementation for EEI_Admin_Links interface method.
1256
+	 *
1257
+	 * @see EEI_Admin_Links for comments
1258
+	 * @return string
1259
+	 * @throws EE_Error
1260
+	 */
1261
+	public function get_admin_edit_link()
1262
+	{
1263
+		return EEH_URL::add_query_args_and_nonce(array(
1264
+			'page' => 'espresso_events',
1265
+			'action' => 'edit',
1266
+			'post' => $this->ID(),
1267
+		),
1268
+			admin_url('admin.php')
1269
+		);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Implementation for EEI_Admin_Links interface method.
1275
+	 *
1276
+	 * @see EEI_Admin_Links for comments
1277
+	 * @return string
1278
+	 */
1279
+	public function get_admin_settings_link()
1280
+	{
1281
+		return EEH_URL::add_query_args_and_nonce(array(
1282
+			'page' => 'espresso_events',
1283
+			'action' => 'default_event_settings',
1284
+		),
1285
+			admin_url('admin.php')
1286
+		);
1287
+	}
1288
+
1289
+
1290
+	/**
1291
+	 * Implementation for EEI_Admin_Links interface method.
1292
+	 *
1293
+	 * @see EEI_Admin_Links for comments
1294
+	 * @return string
1295
+	 */
1296
+	public function get_admin_overview_link()
1297
+	{
1298
+		return EEH_URL::add_query_args_and_nonce(array(
1299
+			'page' => 'espresso_events',
1300
+			'action' => 'default',
1301
+		),
1302
+			admin_url('admin.php')
1303
+		);
1304
+	}
1305 1305
 
1306 1306
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\domain\services\event\EventSpacesCalculator;
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6
-if (!defined('EVENT_ESPRESSO_VERSION')) {
6
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7 7
     exit('No direct script access allowed');
8 8
 }
9 9
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
      */
76 76
     public function getAvailableSpacesCalculator()
77 77
     {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
78
+        if ( ! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79 79
             $this->available_spaces_calculator = new EventSpacesCalculator($this);
80 80
         }
81 81
         return $this->available_spaces_calculator;
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     public function set_status($new_status = null, $use_default = false)
119 119
     {
120 120
         // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
121
+        if (empty($new_status) && ! $use_default) {
122 122
             return;
123 123
         }
124 124
         // get current Event status
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
      */
217 217
     public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218 218
     {
219
-        if (!empty ($this->_Primary_Datetime)) {
219
+        if ( ! empty ($this->_Primary_Datetime)) {
220 220
             return $this->_Primary_Datetime;
221 221
         }
222 222
         $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
     {
240 240
         //first get all datetimes
241 241
         $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
242
+        if ( ! $datetimes) {
243 243
             return array();
244 244
         }
245 245
         $datetime_ids = array();
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
      */
344 344
     public function display_ticket_selector()
345 345
     {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
346
+        return (bool) $this->get('EVT_display_ticket_selector');
347 347
     }
348 348
 
349 349
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
     public function default_registration_status()
415 415
     {
416 416
         $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
417
+        return ! empty($event_default_registration_status)
418 418
             ? $event_default_registration_status
419 419
             : EE_Registry::instance()->CFG->registration->default_STS_ID;
420 420
     }
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
     public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431 431
     {
432 432
         $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
433
+        if ( ! empty($short_desc) || $not_full_desc) {
434 434
             return $short_desc;
435 435
         }
436 436
         $full_desc = $this->get('EVT_desc');
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
      */
964 964
     public function is_sold_out($actual = false)
965 965
     {
966
-        if (!$actual) {
966
+        if ( ! $actual) {
967 967
             return $this->status() === EEM_Event::sold_out;
968 968
         }
969 969
         return $this->perform_sold_out_status_check();
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
     public function get_active_status($reset = false)
1009 1009
     {
1010 1010
         // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1011
+        if ( ! empty($this->_active_status) && ! $reset) {
1012 1012
             return $this->_active_status;
1013 1013
         }
1014 1014
         //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1015
+        if ( ! $this->ID()) {
1016 1016
             return false;
1017 1017
         }
1018 1018
         $where_params_for_event = array(array('EVT_ID' => $this->ID()));
@@ -1089,7 +1089,7 @@  discard block
 block discarded – undo
1089 1089
     public function get_number_of_tickets_sold()
1090 1090
     {
1091 1091
         $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1092
+        if ( ! $this->ID()) {
1093 1093
             return 0;
1094 1094
         }
1095 1095
         $datetimes = $this->datetimes();
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
     {
1156 1156
         $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157 1157
         $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1158
+        if ( ! $latest_ticket instanceof EE_Ticket && ! $earliest_ticket instanceof EE_Ticket) {
1159 1159
             return false;
1160 1160
         }
1161 1161
         //check on sale for these two tickets.
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
      */
1222 1222
     public function question_groups($query_params = array())
1223 1223
     {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1224
+        $query_params = ! empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225 1225
         return $this->get_many_related('Question_Group', $query_params);
1226 1226
     }
1227 1227
 
Please login to merge, or discard this patch.
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 3 patches
Doc Comments   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 
146 146
 
147 147
     /**
148
-     * @return null
148
+     * @return EE_Line_Item_Display
149 149
      */
150 150
     public function line_item_display()
151 151
     {
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 
155 155
 
156 156
     /**
157
-     * @param null $line_item_display
157
+     * @param EE_Line_Item_Display $line_item_display
158 158
      */
159 159
     public function set_line_item_display($line_item_display)
160 160
     {
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
      *    _apply_registration_payments_to_amount_owing
883 883
      *
884 884
      * @access protected
885
-     * @param array $registrations
885
+     * @param EE_Base_Class[] $registrations
886 886
      * @throws EE_Error
887 887
      */
888 888
     protected function _apply_registration_payments_to_amount_owing(array $registrations)
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
      * get_billing_form_html_for_payment_method
1189 1189
      *
1190 1190
      * @access public
1191
-     * @return string
1191
+     * @return boolean
1192 1192
      * @throws EE_Error
1193 1193
      * @throws InvalidArgumentException
1194 1194
      * @throws ReflectionException
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
      *
1256 1256
      * @access private
1257 1257
      * @param EE_Payment_Method $payment_method
1258
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1258
+     * @return EE_Billing_Info_Form
1259 1259
      * @throws EE_Error
1260 1260
      * @throws InvalidArgumentException
1261 1261
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
@@ -1364,7 +1364,7 @@  discard block
 block discarded – undo
1364 1364
      * switch_payment_method
1365 1365
      *
1366 1366
      * @access public
1367
-     * @return string
1367
+     * @return boolean
1368 1368
      * @throws EE_Error
1369 1369
      * @throws InvalidArgumentException
1370 1370
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
     /**
1644 1644
      * process_reg_step
1645 1645
      *
1646
-     * @return bool
1646
+     * @return null|boolean
1647 1647
      * @throws EE_Error
1648 1648
      * @throws InvalidArgumentException
1649 1649
      * @throws ReflectionException
@@ -1774,7 +1774,7 @@  discard block
 block discarded – undo
1774 1774
      *    update_reg_step
1775 1775
      *    this is the final step after a user  revisits the site to retry a payment
1776 1776
      *
1777
-     * @return bool
1777
+     * @return null|boolean
1778 1778
      * @throws EE_Error
1779 1779
      * @throws InvalidArgumentException
1780 1780
      * @throws ReflectionException
@@ -2221,7 +2221,7 @@  discard block
 block discarded – undo
2221 2221
      *
2222 2222
      * @access    private
2223 2223
      * @type    EE_Payment_Method $payment_method
2224
-     * @return mixed EE_Payment | boolean
2224
+     * @return EE_Payment|null EE_Payment | boolean
2225 2225
      * @throws EE_Error
2226 2226
      * @throws InvalidArgumentException
2227 2227
      * @throws ReflectionException
@@ -2546,7 +2546,7 @@  discard block
 block discarded – undo
2546 2546
      *        or present the payment options again
2547 2547
      *
2548 2548
      * @access private
2549
-     * @return EE_Payment|FALSE
2549
+     * @return boolean
2550 2550
      * @throws EE_Error
2551 2551
      * @throws InvalidArgumentException
2552 2552
      * @throws ReflectionException
@@ -2686,8 +2686,8 @@  discard block
 block discarded – undo
2686 2686
      * _redirect_wayward_request
2687 2687
      *
2688 2688
      * @access private
2689
-     * @param \EE_Registration|null $primary_registrant
2690
-     * @return bool
2689
+     * @param EE_Registration $primary_registrant
2690
+     * @return false|null
2691 2691
      * @throws EE_Error
2692 2692
      * @throws InvalidArgumentException
2693 2693
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
     {
133 133
         $this->_slug     = 'payment_options';
134 134
         $this->_name     = esc_html__('Payment Options', 'event_espresso');
135
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
135
+        $this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'payment_options_main.template.php';
136 136
         $this->checkout  = $checkout;
137 137
         $this->_reset_success_message();
138 138
         $this->set_instructions(
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
      */
188 188
     public function translate_js_strings()
189 189
     {
190
-        EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
190
+        EE_Registry::$i18n_js_strings['no_payment_method'] = esc_html__(
191 191
             'Please select a method of payment in order to continue.',
192 192
             'event_espresso'
193 193
         );
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
             'A valid method of payment could not be determined. Please refresh the page and try again.',
196 196
             'event_espresso'
197 197
         );
198
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
198
+        EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = esc_html__(
199 199
             'Forwarding to Secure Payment Provider.',
200 200
             'event_espresso'
201 201
         );
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
     {
216 216
         $transaction = $this->checkout->transaction;
217 217
         //if the transaction isn't set or nothing is owed on it, don't enqueue any JS
218
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
218
+        if ( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
219 219
             return;
220 220
         }
221 221
         foreach (EEM_Payment_Method::instance()->get_all_for_transaction($transaction, EEM_Payment_Method::scope_cart) as $payment_method) {
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
                     $registration->event(),
344 344
                     $this
345 345
                 );
346
-            } elseif (! $this->checkout->revisit
346
+            } elseif ( ! $this->checkout->revisit
347 347
                 && $registration->status_ID() !== EEM_Registration::status_id_not_approved
348 348
                 && $registration->ticket()->is_free()
349 349
             ) {
@@ -352,23 +352,23 @@  discard block
 block discarded – undo
352 352
         }
353 353
         $subsections = array();
354 354
         // now decide which template to load
355
-        if (! empty($sold_out_events)) {
355
+        if ( ! empty($sold_out_events)) {
356 356
             $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
357 357
         }
358
-        if (! empty($insufficient_spaces_available)) {
358
+        if ( ! empty($insufficient_spaces_available)) {
359 359
             $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
360 360
                 $insufficient_spaces_available
361 361
             );
362 362
         }
363
-        if (! empty($registrations_requiring_pre_approval)) {
363
+        if ( ! empty($registrations_requiring_pre_approval)) {
364 364
             $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
365 365
                 $registrations_requiring_pre_approval
366 366
             );
367 367
         }
368
-        if (! empty($registrations_for_free_events)) {
368
+        if ( ! empty($registrations_for_free_events)) {
369 369
             $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
370 370
         }
371
-        if (! empty($registrations_requiring_payment)) {
371
+        if ( ! empty($registrations_requiring_payment)) {
372 372
             if ($this->checkout->amount_owing > 0) {
373 373
                 // autoload Line_Item_Display classes
374 374
                 EEH_Autoloader::register_line_item_filter_autoloaders();
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
                         array('registrations' => $registrations)
390 390
                     )
391 391
                 );
392
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
392
+                $this->checkout->amount_owing = $filtered_line_item_tree->total();
393 393
                 $this->_apply_registration_payments_to_amount_owing($registrations);
394 394
             }
395 395
             $no_payment_required = false;
@@ -433,13 +433,13 @@  discard block
 block discarded – undo
433 433
      */
434 434
     public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
435 435
     {
436
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
436
+        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
437 437
             return $line_item_filter_collection;
438 438
         }
439
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
439
+        if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
440 440
             return $line_item_filter_collection;
441 441
         }
442
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
442
+        if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
443 443
             return $line_item_filter_collection;
444 444
         }
445 445
         $line_item_filter_collection->add(
@@ -530,15 +530,15 @@  discard block
 block discarded – undo
530 530
             }
531 531
             $EVT_ID = $registration->event_ID();
532 532
             $ticket = $registration->ticket();
533
-            if (! isset($tickets_remaining[$ticket->ID()])) {
533
+            if ( ! isset($tickets_remaining[$ticket->ID()])) {
534 534
                 $tickets_remaining[$ticket->ID()] = $ticket->remaining();
535 535
             }
536 536
             if ($tickets_remaining[$ticket->ID()] > 0) {
537
-                if (! isset($event_reg_count[$EVT_ID])) {
537
+                if ( ! isset($event_reg_count[$EVT_ID])) {
538 538
                     $event_reg_count[$EVT_ID] = 0;
539 539
                 }
540 540
                 $event_reg_count[$EVT_ID]++;
541
-                if (! isset($event_spaces_remaining[$EVT_ID])) {
541
+                if ( ! isset($event_spaces_remaining[$EVT_ID])) {
542 542
                     $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
543 543
                 }
544 544
             }
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
         foreach ($sold_out_events_array as $sold_out_event) {
608 608
             $sold_out_events .= EEH_HTML::li(
609 609
                 EEH_HTML::span(
610
-                    '  ' . $sold_out_event->name(),
610
+                    '  '.$sold_out_event->name(),
611 611
                     '',
612 612
                     'dashicons dashicons-marker ee-icon-size-16 pink-text'
613 613
                 )
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
         foreach ($insufficient_spaces_events_array as $event) {
664 664
             if ($event instanceof EE_Event) {
665 665
                 $insufficient_space_events .= EEH_HTML::li(
666
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
666
+                    EEH_HTML::span(' '.$event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
667 667
                 );
668 668
             }
669 669
         }
@@ -853,7 +853,7 @@  discard block
 block discarded – undo
853 853
     {
854 854
         return new EE_Form_Section_Proper(
855 855
             array(
856
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
856
+                'html_id'         => 'ee-'.$this->slug().'-extra-hidden-inputs',
857 857
                 'layout_strategy' => new EE_Div_Per_Section_Layout(),
858 858
                 'subsections'     => array(
859 859
                     'spco_no_payment_required' => new EE_Hidden_Input(
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
                 $payments += $registration->registration_payments();
894 894
             }
895 895
         }
896
-        if (! empty($payments)) {
896
+        if ( ! empty($payments)) {
897 897
             foreach ($payments as $payment) {
898 898
                 if ($payment instanceof EE_Registration_Payment) {
899 899
                     $this->checkout->amount_owing -= $payment->amount();
@@ -979,7 +979,7 @@  discard block
 block discarded – undo
979 979
             );
980 980
         }
981 981
         // switch up header depending on number of available payment methods
982
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
982
+        $payment_method_header = count($this->checkout->available_payment_methods) > 1
983 983
             ? apply_filters(
984 984
                 'FHEE__registration_page_payment_options__method_of_payment_hdr',
985 985
                 esc_html__('Please Select Your Method of Payment', 'event_espresso')
@@ -1009,14 +1009,14 @@  discard block
 block discarded – undo
1009 1009
                 $payment_method_button = EEH_HTML::img(
1010 1010
                     $payment_method->button_url(),
1011 1011
                     $payment_method->name(),
1012
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1012
+                    'spco-payment-method-'.$payment_method->slug().'-btn-img',
1013 1013
                     'spco-payment-method-btn-img'
1014 1014
                 );
1015 1015
                 // check if any payment methods are set as default
1016 1016
                 // if payment method is already selected OR nothing is selected and this payment method should be
1017 1017
                 // open_by_default
1018 1018
                 if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1019
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1019
+                    || ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1020 1020
                 ) {
1021 1021
                     $this->checkout->selected_method_of_payment = $payment_method->slug();
1022 1022
                     $this->_save_selected_method_of_payment();
@@ -1024,7 +1024,7 @@  discard block
 block discarded – undo
1024 1024
                 } else {
1025 1025
                     $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1026 1026
                 }
1027
-                $payment_methods_billing_info[$payment_method->slug() . '-info'] = $this->_payment_method_billing_info(
1027
+                $payment_methods_billing_info[$payment_method->slug().'-info'] = $this->_payment_method_billing_info(
1028 1028
                     $payment_method
1029 1029
                 );
1030 1030
             }
@@ -1036,7 +1036,7 @@  discard block
 block discarded – undo
1036 1036
         $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1037 1037
             $available_payment_method_options
1038 1038
         );
1039
-        $available_payment_methods                              += $payment_methods_billing_info;
1039
+        $available_payment_methods += $payment_methods_billing_info;
1040 1040
         // build the available payment methods form
1041 1041
         return new EE_Form_Section_Proper(
1042 1042
             array(
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
      */
1061 1061
     protected function _get_available_payment_methods()
1062 1062
     {
1063
-        if (! empty($this->checkout->available_payment_methods)) {
1063
+        if ( ! empty($this->checkout->available_payment_methods)) {
1064 1064
             return $this->checkout->available_payment_methods;
1065 1065
         }
1066 1066
         $available_payment_methods = array();
@@ -1170,7 +1170,7 @@  discard block
 block discarded – undo
1170 1170
         );
1171 1171
         return new EE_Form_Section_Proper(
1172 1172
             array(
1173
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1173
+                'html_id'         => 'spco-payment-method-info-'.$payment_method->slug(),
1174 1174
                 'html_class'      => 'spco-payment-method-info-dv',
1175 1175
                 // only display the selected or default PM
1176 1176
                 'html_style'      => $currently_selected ? '' : 'display:none;',
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
         // how have they chosen to pay?
1201 1201
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1202 1202
         $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1203
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1203
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1204 1204
             return false;
1205 1205
         }
1206 1206
         if (apply_filters(
@@ -1372,7 +1372,7 @@  discard block
 block discarded – undo
1372 1372
      */
1373 1373
     public function switch_payment_method()
1374 1374
     {
1375
-        if (! $this->_verify_payment_method_is_set()) {
1375
+        if ( ! $this->_verify_payment_method_is_set()) {
1376 1376
             return false;
1377 1377
         }
1378 1378
         if (apply_filters(
@@ -1501,7 +1501,7 @@  discard block
 block discarded – undo
1501 1501
             }
1502 1502
         }
1503 1503
         // verify payment method
1504
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1504
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1505 1505
             // get payment method for selected method of payment
1506 1506
             $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1507 1507
         }
@@ -1526,7 +1526,7 @@  discard block
 block discarded – undo
1526 1526
      */
1527 1527
     public function save_payer_details_via_ajax()
1528 1528
     {
1529
-        if (! $this->_verify_payment_method_is_set()) {
1529
+        if ( ! $this->_verify_payment_method_is_set()) {
1530 1530
             return;
1531 1531
         }
1532 1532
         // generate billing form for selected method of payment if it hasn't been done already
@@ -1536,7 +1536,7 @@  discard block
 block discarded – undo
1536 1536
             );
1537 1537
         }
1538 1538
         // generate primary attendee from payer info if applicable
1539
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1539
+        if ( ! $this->checkout->transaction_has_primary_registrant()) {
1540 1540
             $attendee = $this->_create_attendee_from_request_data();
1541 1541
             if ($attendee instanceof EE_Attendee) {
1542 1542
                 foreach ($this->checkout->transaction->registrations() as $registration) {
@@ -1567,7 +1567,7 @@  discard block
 block discarded – undo
1567 1567
     {
1568 1568
         // get State ID
1569 1569
         $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1570
-        if (! empty($STA_ID)) {
1570
+        if ( ! empty($STA_ID)) {
1571 1571
             // can we get state object from name ?
1572 1572
             EE_Registry::instance()->load_model('State');
1573 1573
             $state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
@@ -1575,7 +1575,7 @@  discard block
 block discarded – undo
1575 1575
         }
1576 1576
         // get Country ISO
1577 1577
         $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1578
-        if (! empty($CNT_ISO)) {
1578
+        if ( ! empty($CNT_ISO)) {
1579 1579
             // can we get country object from name ?
1580 1580
             EE_Registry::instance()->load_model('Country');
1581 1581
             $country = EEM_Country::instance()->get_col(
@@ -1608,7 +1608,7 @@  discard block
 block discarded – undo
1608 1608
         }
1609 1609
         // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1610 1610
         // AND email address
1611
-        if (! empty($attendee_data['ATT_fname'])
1611
+        if ( ! empty($attendee_data['ATT_fname'])
1612 1612
             && ! empty($attendee_data['ATT_lname'])
1613 1613
             && ! empty($attendee_data['ATT_email'])
1614 1614
         ) {
@@ -1824,7 +1824,7 @@  discard block
 block discarded – undo
1824 1824
     private function _process_payment()
1825 1825
     {
1826 1826
         // basically confirm that the event hasn't sold out since they hit the page
1827
-        if (! $this->_last_second_ticket_verifications()) {
1827
+        if ( ! $this->_last_second_ticket_verifications()) {
1828 1828
             return false;
1829 1829
         }
1830 1830
         // ya gotta make a choice man
@@ -1835,7 +1835,7 @@  discard block
 block discarded – undo
1835 1835
             return false;
1836 1836
         }
1837 1837
         // get EE_Payment_Method object
1838
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1838
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1839 1839
             return false;
1840 1840
         }
1841 1841
         // setup billing form
@@ -1844,12 +1844,12 @@  discard block
 block discarded – undo
1844 1844
                 $this->checkout->payment_method
1845 1845
             );
1846 1846
             // bad billing form ?
1847
-            if (! $this->_billing_form_is_valid()) {
1847
+            if ( ! $this->_billing_form_is_valid()) {
1848 1848
                 return false;
1849 1849
             }
1850 1850
         }
1851 1851
         // ensure primary registrant has been fully processed
1852
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1852
+        if ( ! $this->_setup_primary_registrant_prior_to_payment()) {
1853 1853
             return false;
1854 1854
         }
1855 1855
         // if session is close to expiring (under 10 minutes by default)
@@ -1905,7 +1905,7 @@  discard block
 block discarded – undo
1905 1905
     protected function _last_second_ticket_verifications()
1906 1906
     {
1907 1907
         // don't bother re-validating if not a return visit
1908
-        if (! $this->checkout->revisit) {
1908
+        if ( ! $this->checkout->revisit) {
1909 1909
             return true;
1910 1910
         }
1911 1911
         $registrations = $this->checkout->transaction->registrations();
@@ -1956,7 +1956,7 @@  discard block
 block discarded – undo
1956 1956
             $this->_get_payment_method_for_selected_method_of_payment()
1957 1957
         );
1958 1958
         $html                        = $payment_method_billing_info->get_html();
1959
-        $html                        .= $this->checkout->redirect_form;
1959
+        $html .= $this->checkout->redirect_form;
1960 1960
         EE_Registry::instance()->REQ->add_output($html);
1961 1961
         return true;
1962 1962
     }
@@ -1971,7 +1971,7 @@  discard block
 block discarded – undo
1971 1971
      */
1972 1972
     private function _billing_form_is_valid()
1973 1973
     {
1974
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1974
+        if ( ! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1975 1975
             return true;
1976 1976
         }
1977 1977
         if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
@@ -2088,7 +2088,7 @@  discard block
 block discarded – undo
2088 2088
     {
2089 2089
         // convert billing form data into an attendee
2090 2090
         $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2091
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2091
+        if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2092 2092
             EE_Error::add_error(
2093 2093
                 sprintf(
2094 2094
                     esc_html__(
@@ -2105,7 +2105,7 @@  discard block
 block discarded – undo
2105 2105
             return false;
2106 2106
         }
2107 2107
         $primary_registration = $this->checkout->transaction->primary_registration();
2108
-        if (! $primary_registration instanceof EE_Registration) {
2108
+        if ( ! $primary_registration instanceof EE_Registration) {
2109 2109
             EE_Error::add_error(
2110 2110
                 sprintf(
2111 2111
                     esc_html__(
@@ -2121,7 +2121,7 @@  discard block
 block discarded – undo
2121 2121
             );
2122 2122
             return false;
2123 2123
         }
2124
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2124
+        if ( ! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2125 2125
               instanceof
2126 2126
               EE_Attendee
2127 2127
         ) {
@@ -2177,7 +2177,7 @@  discard block
 block discarded – undo
2177 2177
             $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2178 2178
         }
2179 2179
         // verify $payment_method
2180
-        if (! $payment_method instanceof EE_Payment_Method) {
2180
+        if ( ! $payment_method instanceof EE_Payment_Method) {
2181 2181
             // not a payment
2182 2182
             EE_Error::add_error(
2183 2183
                 sprintf(
@@ -2195,7 +2195,7 @@  discard block
 block discarded – undo
2195 2195
             return null;
2196 2196
         }
2197 2197
         // and verify it has a valid Payment_Method Type object
2198
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2198
+        if ( ! $payment_method->type_obj() instanceof EE_PMT_Base) {
2199 2199
             // not a payment
2200 2200
             EE_Error::add_error(
2201 2201
                 sprintf(
@@ -2233,7 +2233,7 @@  discard block
 block discarded – undo
2233 2233
         $payment = null;
2234 2234
         $this->checkout->transaction->save();
2235 2235
         $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2236
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2236
+        if ( ! $payment_processor instanceof EE_Payment_Processor) {
2237 2237
             return false;
2238 2238
         }
2239 2239
         try {
@@ -2337,7 +2337,7 @@  discard block
 block discarded – undo
2337 2337
             return true;
2338 2338
         }
2339 2339
         // verify payment object
2340
-        if (! $payment instanceof EE_Payment) {
2340
+        if ( ! $payment instanceof EE_Payment) {
2341 2341
             // not a payment
2342 2342
             EE_Error::add_error(
2343 2343
                 sprintf(
@@ -2377,7 +2377,7 @@  discard block
 block discarded – undo
2377 2377
             return true;
2378 2378
             // On-Site payment?
2379 2379
         } else if ($this->checkout->payment_method->is_on_site()) {
2380
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2380
+            if ( ! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2381 2381
                 //$this->_setup_redirect_for_next_step();
2382 2382
                 $this->checkout->continue_reg = false;
2383 2383
             }
@@ -2499,7 +2499,7 @@  discard block
 block discarded – undo
2499 2499
                     break;
2500 2500
                 // bad payment
2501 2501
                 case EEM_Payment::status_id_failed :
2502
-                    if (! empty($msg)) {
2502
+                    if ( ! empty($msg)) {
2503 2503
                         EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2504 2504
                         return false;
2505 2505
                     }
@@ -2560,11 +2560,11 @@  discard block
 block discarded – undo
2560 2560
         // how have they chosen to pay?
2561 2561
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2562 2562
         // get EE_Payment_Method object
2563
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2563
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2564 2564
             $this->checkout->continue_reg = false;
2565 2565
             return false;
2566 2566
         }
2567
-        if (! $this->checkout->payment_method->is_off_site()) {
2567
+        if ( ! $this->checkout->payment_method->is_off_site()) {
2568 2568
             return false;
2569 2569
         }
2570 2570
         $this->_validate_offsite_return();
@@ -2580,7 +2580,7 @@  discard block
 block discarded – undo
2580 2580
         // verify TXN
2581 2581
         if ($this->checkout->transaction instanceof EE_Transaction) {
2582 2582
             $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2583
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2583
+            if ( ! $gateway instanceof EE_Offsite_Gateway) {
2584 2584
                 $this->checkout->continue_reg = false;
2585 2585
                 return false;
2586 2586
             }
@@ -2622,7 +2622,7 @@  discard block
 block discarded – undo
2622 2622
      */
2623 2623
     private function _validate_offsite_return()
2624 2624
     {
2625
-        $TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2625
+        $TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2626 2626
         if ($TXN_ID !== $this->checkout->transaction->ID()) {
2627 2627
             // Houston... we might have a problem
2628 2628
             $invalid_TXN = false;
@@ -2695,13 +2695,13 @@  discard block
 block discarded – undo
2695 2695
      */
2696 2696
     private function _redirect_wayward_request(EE_Registration $primary_registrant)
2697 2697
     {
2698
-        if (! $primary_registrant instanceof EE_Registration) {
2698
+        if ( ! $primary_registrant instanceof EE_Registration) {
2699 2699
             // try redirecting based on the current TXN
2700 2700
             $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2701 2701
                 ? $this->checkout->transaction->primary_registration()
2702 2702
                 : null;
2703 2703
         }
2704
-        if (! $primary_registrant instanceof EE_Registration) {
2704
+        if ( ! $primary_registrant instanceof EE_Registration) {
2705 2705
             EE_Error::add_error(
2706 2706
                 sprintf(
2707 2707
                     esc_html__(
@@ -2771,7 +2771,7 @@  discard block
 block discarded – undo
2771 2771
             $payment = $this->checkout->transaction->last_payment();
2772 2772
             //$payment_source = 'last_payment after Exception';
2773 2773
             // but if we STILL don't have a payment object
2774
-            if (! $payment instanceof EE_Payment) {
2774
+            if ( ! $payment instanceof EE_Payment) {
2775 2775
                 // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2776 2776
                 $this->_handle_payment_processor_exception($e);
2777 2777
             }
Please login to merge, or discard this patch.
Indentation   +2872 added lines, -2872 removed lines patch added patch discarded remove patch
@@ -15,2876 +15,2876 @@
 block discarded – undo
15 15
 class EE_SPCO_Reg_Step_Payment_Options extends EE_SPCO_Reg_Step
16 16
 {
17 17
 
18
-    /**
19
-     * @access protected
20
-     * @var EE_Line_Item_Display $Line_Item_Display
21
-     */
22
-    protected $line_item_display;
23
-
24
-    /**
25
-     * @access protected
26
-     * @var boolean $handle_IPN_in_this_request
27
-     */
28
-    protected $handle_IPN_in_this_request = false;
29
-
30
-
31
-    /**
32
-     *    set_hooks - for hooking into EE Core, other modules, etc
33
-     *
34
-     * @access    public
35
-     * @return    void
36
-     */
37
-    public static function set_hooks()
38
-    {
39
-        add_filter(
40
-            'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
-            array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42
-        );
43
-        add_action(
44
-            'wp_ajax_switch_spco_billing_form',
45
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46
-        );
47
-        add_action(
48
-            'wp_ajax_nopriv_switch_spco_billing_form',
49
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50
-        );
51
-        add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52
-        add_action(
53
-            'wp_ajax_nopriv_save_payer_details',
54
-            array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55
-        );
56
-        add_action(
57
-            'wp_ajax_get_transaction_details_for_gateways',
58
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59
-        );
60
-        add_action(
61
-            'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63
-        );
64
-        add_filter(
65
-            'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
-            array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67
-            10,
68
-            1
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     *    ajax switch_spco_billing_form
75
-     *
76
-     * @throws \EE_Error
77
-     */
78
-    public static function switch_spco_billing_form()
79
-    {
80
-        EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81
-    }
82
-
83
-
84
-    /**
85
-     *    ajax save_payer_details
86
-     *
87
-     * @throws \EE_Error
88
-     */
89
-    public static function save_payer_details()
90
-    {
91
-        EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92
-    }
93
-
94
-
95
-    /**
96
-     *    ajax get_transaction_details
97
-     *
98
-     * @throws \EE_Error
99
-     */
100
-    public static function get_transaction_details()
101
-    {
102
-        EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
-    }
104
-
105
-
106
-    /**
107
-     * bypass_recaptcha_for_load_payment_method
108
-     *
109
-     * @access public
110
-     * @return array
111
-     * @throws InvalidArgumentException
112
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
113
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
114
-     */
115
-    public static function bypass_recaptcha_for_load_payment_method()
116
-    {
117
-        return array(
118
-            'EESID'  => EE_Registry::instance()->SSN->id(),
119
-            'step'   => 'payment_options',
120
-            'action' => 'spco_billing_form',
121
-        );
122
-    }
123
-
124
-
125
-    /**
126
-     *    class constructor
127
-     *
128
-     * @access    public
129
-     * @param    EE_Checkout $checkout
130
-     */
131
-    public function __construct(EE_Checkout $checkout)
132
-    {
133
-        $this->_slug     = 'payment_options';
134
-        $this->_name     = esc_html__('Payment Options', 'event_espresso');
135
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
136
-        $this->checkout  = $checkout;
137
-        $this->_reset_success_message();
138
-        $this->set_instructions(
139
-            esc_html__(
140
-                'Please select a method of payment and provide any necessary billing information before proceeding.',
141
-                'event_espresso'
142
-            )
143
-        );
144
-    }
145
-
146
-
147
-    /**
148
-     * @return null
149
-     */
150
-    public function line_item_display()
151
-    {
152
-        return $this->line_item_display;
153
-    }
154
-
155
-
156
-    /**
157
-     * @param null $line_item_display
158
-     */
159
-    public function set_line_item_display($line_item_display)
160
-    {
161
-        $this->line_item_display = $line_item_display;
162
-    }
163
-
164
-
165
-    /**
166
-     * @return boolean
167
-     */
168
-    public function handle_IPN_in_this_request()
169
-    {
170
-        return $this->handle_IPN_in_this_request;
171
-    }
172
-
173
-
174
-    /**
175
-     * @param boolean $handle_IPN_in_this_request
176
-     */
177
-    public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
178
-    {
179
-        $this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
180
-    }
181
-
182
-
183
-    /**
184
-     * translate_js_strings
185
-     *
186
-     * @return void
187
-     */
188
-    public function translate_js_strings()
189
-    {
190
-        EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
191
-            'Please select a method of payment in order to continue.',
192
-            'event_espresso'
193
-        );
194
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
195
-            'A valid method of payment could not be determined. Please refresh the page and try again.',
196
-            'event_espresso'
197
-        );
198
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
199
-            'Forwarding to Secure Payment Provider.',
200
-            'event_espresso'
201
-        );
202
-    }
203
-
204
-
205
-    /**
206
-     * enqueue_styles_and_scripts
207
-     *
208
-     * @return void
209
-     * @throws EE_Error
210
-     * @throws InvalidArgumentException
211
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
212
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
213
-     */
214
-    public function enqueue_styles_and_scripts()
215
-    {
216
-        $transaction = $this->checkout->transaction;
217
-        //if the transaction isn't set or nothing is owed on it, don't enqueue any JS
218
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
219
-            return;
220
-        }
221
-        foreach (EEM_Payment_Method::instance()->get_all_for_transaction($transaction, EEM_Payment_Method::scope_cart) as $payment_method) {
222
-            $type_obj = $payment_method->type_obj();
223
-            if ($type_obj instanceof EE_PMT_Base) {
224
-                $billing_form = $type_obj->generate_new_billing_form($transaction);
225
-                if ($billing_form instanceof EE_Form_Section_Proper) {
226
-                    $billing_form->enqueue_js();
227
-                }
228
-            }
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     * initialize_reg_step
235
-     *
236
-     * @return bool
237
-     * @throws EE_Error
238
-     * @throws InvalidArgumentException
239
-     * @throws ReflectionException
240
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
241
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
242
-     */
243
-    public function initialize_reg_step()
244
-    {
245
-        // TODO: if /when we implement donations, then this will need overriding
246
-        if (// don't need payment options for:
247
-            // 	registrations made via the admin
248
-            // 	completed transactions
249
-            // 	overpaid transactions
250
-            // 	$ 0.00 transactions (no payment required)
251
-            ! $this->checkout->payment_required()
252
-            // but do NOT remove if current action being called belongs to this reg step
253
-            && ! is_callable(array($this, $this->checkout->action))
254
-            && ! $this->completed()
255
-        ) {
256
-            // and if so, then we no longer need the Payment Options step
257
-            if ($this->is_current_step()) {
258
-                $this->checkout->generate_reg_form = false;
259
-            }
260
-            $this->checkout->remove_reg_step($this->_slug);
261
-            // DEBUG LOG
262
-            //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
263
-            return false;
264
-        }
265
-        // load EEM_Payment_Method
266
-        EE_Registry::instance()->load_model('Payment_Method');
267
-        // get all active payment methods
268
-        $this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
269
-            $this->checkout->transaction,
270
-            EEM_Payment_Method::scope_cart
271
-        );
272
-        return true;
273
-    }
274
-
275
-
276
-    /**
277
-     * @return EE_Form_Section_Proper
278
-     * @throws EE_Error
279
-     * @throws InvalidArgumentException
280
-     * @throws ReflectionException
281
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
282
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
283
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
284
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
285
-     */
286
-    public function generate_reg_form()
287
-    {
288
-        // reset in case someone changes their mind
289
-        $this->_reset_selected_method_of_payment();
290
-        // set some defaults
291
-        $this->checkout->selected_method_of_payment = 'payments_closed';
292
-        $registrations_requiring_payment            = array();
293
-        $registrations_for_free_events              = array();
294
-        $registrations_requiring_pre_approval       = array();
295
-        $sold_out_events                            = array();
296
-        $insufficient_spaces_available              = array();
297
-        $no_payment_required                        = true;
298
-        // loop thru registrations to gather info
299
-        $registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
300
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
301
-            $registrations,
302
-            $this->checkout->revisit
303
-        );
304
-        foreach ($registrations as $REG_ID => $registration) {
305
-            /** @var $registration EE_Registration */
306
-            // has this registration lost it's space ?
307
-            if (isset($ejected_registrations[$REG_ID])) {
308
-                $insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
309
-                continue;
310
-            }
311
-            // event requires admin approval
312
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
313
-                // add event to list of events with pre-approval reg status
314
-                $registrations_requiring_pre_approval[$REG_ID] = $registration;
315
-                do_action(
316
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
317
-                    $registration->event(),
318
-                    $this
319
-                );
320
-                continue;
321
-            }
322
-            if ($this->checkout->revisit
323
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
324
-                && (
325
-                    $registration->event()->is_sold_out()
326
-                    || $registration->event()->is_sold_out(true)
327
-                )
328
-            ) {
329
-                // add event to list of events that are sold out
330
-                $sold_out_events[$registration->event()->ID()] = $registration->event();
331
-                do_action(
332
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
333
-                    $registration->event(),
334
-                    $this
335
-                );
336
-                continue;
337
-            }
338
-            // are they allowed to pay now and is there monies owing?
339
-            if ($registration->owes_monies_and_can_pay()) {
340
-                $registrations_requiring_payment[$REG_ID] = $registration;
341
-                do_action(
342
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
343
-                    $registration->event(),
344
-                    $this
345
-                );
346
-            } elseif (! $this->checkout->revisit
347
-                && $registration->status_ID() !== EEM_Registration::status_id_not_approved
348
-                && $registration->ticket()->is_free()
349
-            ) {
350
-                $registrations_for_free_events[$registration->event()->ID()] = $registration;
351
-            }
352
-        }
353
-        $subsections = array();
354
-        // now decide which template to load
355
-        if (! empty($sold_out_events)) {
356
-            $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
357
-        }
358
-        if (! empty($insufficient_spaces_available)) {
359
-            $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
360
-                $insufficient_spaces_available
361
-            );
362
-        }
363
-        if (! empty($registrations_requiring_pre_approval)) {
364
-            $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
365
-                $registrations_requiring_pre_approval
366
-            );
367
-        }
368
-        if (! empty($registrations_for_free_events)) {
369
-            $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
370
-        }
371
-        if (! empty($registrations_requiring_payment)) {
372
-            if ($this->checkout->amount_owing > 0) {
373
-                // autoload Line_Item_Display classes
374
-                EEH_Autoloader::register_line_item_filter_autoloaders();
375
-                $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
376
-                    apply_filters(
377
-                        'FHEE__SPCO__EE_Line_Item_Filter_Collection',
378
-                        new EE_Line_Item_Filter_Collection()
379
-                    ),
380
-                    $this->checkout->cart->get_grand_total()
381
-                );
382
-                /** @var EE_Line_Item $filtered_line_item_tree */
383
-                $filtered_line_item_tree = $line_item_filter_processor->process();
384
-                EEH_Autoloader::register_line_item_display_autoloaders();
385
-                $this->set_line_item_display(new EE_Line_Item_Display('spco'));
386
-                $subsections['payment_options'] = $this->_display_payment_options(
387
-                    $this->line_item_display->display_line_item(
388
-                        $filtered_line_item_tree,
389
-                        array('registrations' => $registrations)
390
-                    )
391
-                );
392
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
393
-                $this->_apply_registration_payments_to_amount_owing($registrations);
394
-            }
395
-            $no_payment_required = false;
396
-        } else {
397
-            $this->_hide_reg_step_submit_button_if_revisit();
398
-        }
399
-        $this->_save_selected_method_of_payment();
400
-
401
-        $subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
402
-        $subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
403
-
404
-        return new EE_Form_Section_Proper(
405
-            array(
406
-                'name'            => $this->reg_form_name(),
407
-                'html_id'         => $this->reg_form_name(),
408
-                'subsections'     => $subsections,
409
-                'layout_strategy' => new EE_No_Layout(),
410
-            )
411
-        );
412
-    }
413
-
414
-
415
-    /**
416
-     * add line item filters required for this reg step
417
-     * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
418
-     *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
419
-     *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
420
-     *        payment options reg step, can apply these filters via the following: apply_filters(
421
-     *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
422
-     *        filter collection by passing that instead of instantiating a new collection
423
-     *
424
-     * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
425
-     * @return EE_Line_Item_Filter_Collection
426
-     * @throws EE_Error
427
-     * @throws InvalidArgumentException
428
-     * @throws ReflectionException
429
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
430
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
431
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
432
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
433
-     */
434
-    public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
435
-    {
436
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
437
-            return $line_item_filter_collection;
438
-        }
439
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
440
-            return $line_item_filter_collection;
441
-        }
442
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
443
-            return $line_item_filter_collection;
444
-        }
445
-        $line_item_filter_collection->add(
446
-            new EE_Billable_Line_Item_Filter(
447
-                EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
448
-                    EE_Registry::instance()->SSN->checkout()->transaction->registrations(
449
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
450
-                    )
451
-                )
452
-            )
453
-        );
454
-        $line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
455
-        return $line_item_filter_collection;
456
-    }
457
-
458
-
459
-    /**
460
-     * remove_ejected_registrations
461
-     * if a registrant has lost their potential space at an event due to lack of payment,
462
-     * then this method removes them from the list of registrations being paid for during this request
463
-     *
464
-     * @param \EE_Registration[] $registrations
465
-     * @return EE_Registration[]
466
-     * @throws EE_Error
467
-     * @throws InvalidArgumentException
468
-     * @throws ReflectionException
469
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
470
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
471
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
472
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
473
-     */
474
-    public static function remove_ejected_registrations(array $registrations)
475
-    {
476
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
477
-            $registrations,
478
-            EE_Registry::instance()->SSN->checkout()->revisit
479
-        );
480
-        foreach ($registrations as $REG_ID => $registration) {
481
-            // has this registration lost it's space ?
482
-            if (isset($ejected_registrations[$REG_ID])) {
483
-                unset($registrations[$REG_ID]);
484
-                continue;
485
-            }
486
-        }
487
-        return $registrations;
488
-    }
489
-
490
-
491
-    /**
492
-     * find_registrations_that_lost_their_space
493
-     * If a registrant chooses an offline payment method like Invoice,
494
-     * then no space is reserved for them at the event until they fully pay fo that site
495
-     * (unless the event's default reg status is set to APPROVED)
496
-     * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
497
-     * then this method will determine which registrations have lost the ability to complete the reg process.
498
-     *
499
-     * @param \EE_Registration[] $registrations
500
-     * @param bool               $revisit
501
-     * @return array
502
-     * @throws EE_Error
503
-     * @throws InvalidArgumentException
504
-     * @throws ReflectionException
505
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
506
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
507
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
508
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
509
-     */
510
-    public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
511
-    {
512
-        // registrations per event
513
-        $event_reg_count = array();
514
-        // spaces left per event
515
-        $event_spaces_remaining = array();
516
-        // tickets left sorted by ID
517
-        $tickets_remaining = array();
518
-        // registrations that have lost their space
519
-        $ejected_registrations = array();
520
-        foreach ($registrations as $REG_ID => $registration) {
521
-            if ($registration->status_ID() === EEM_Registration::status_id_approved
522
-                || apply_filters(
523
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
524
-                    false,
525
-                    $registration,
526
-                    $revisit
527
-                )
528
-            ) {
529
-                continue;
530
-            }
531
-            $EVT_ID = $registration->event_ID();
532
-            $ticket = $registration->ticket();
533
-            if (! isset($tickets_remaining[$ticket->ID()])) {
534
-                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
535
-            }
536
-            if ($tickets_remaining[$ticket->ID()] > 0) {
537
-                if (! isset($event_reg_count[$EVT_ID])) {
538
-                    $event_reg_count[$EVT_ID] = 0;
539
-                }
540
-                $event_reg_count[$EVT_ID]++;
541
-                if (! isset($event_spaces_remaining[$EVT_ID])) {
542
-                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
543
-                }
544
-            }
545
-            if ($revisit
546
-                && ($tickets_remaining[$ticket->ID()] === 0
547
-                    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
548
-                )
549
-            ) {
550
-                $ejected_registrations[$REG_ID] = $registration->event();
551
-                if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
552
-                    /** @type EE_Registration_Processor $registration_processor */
553
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
554
-                    // at this point, we should have enough details about the registrant to consider the registration
555
-                    // NOT incomplete
556
-                    $registration_processor->manually_update_registration_status(
557
-                        $registration,
558
-                        EEM_Registration::status_id_wait_list
559
-                    );
560
-                }
561
-            }
562
-        }
563
-        return $ejected_registrations;
564
-    }
565
-
566
-
567
-    /**
568
-     * _hide_reg_step_submit_button
569
-     * removes the html for the reg step submit button
570
-     * by replacing it with an empty string via filter callback
571
-     *
572
-     * @return void
573
-     */
574
-    protected function _adjust_registration_status_if_event_old_sold()
575
-    {
576
-    }
577
-
578
-
579
-    /**
580
-     * _hide_reg_step_submit_button
581
-     * removes the html for the reg step submit button
582
-     * by replacing it with an empty string via filter callback
583
-     *
584
-     * @return void
585
-     */
586
-    protected function _hide_reg_step_submit_button_if_revisit()
587
-    {
588
-        if ($this->checkout->revisit) {
589
-            add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
590
-        }
591
-    }
592
-
593
-
594
-    /**
595
-     * sold_out_events
596
-     * displays notices regarding events that have sold out since hte registrant first signed up
597
-     *
598
-     * @param \EE_Event[] $sold_out_events_array
599
-     * @return \EE_Form_Section_Proper
600
-     * @throws \EE_Error
601
-     */
602
-    private function _sold_out_events($sold_out_events_array = array())
603
-    {
604
-        // set some defaults
605
-        $this->checkout->selected_method_of_payment = 'events_sold_out';
606
-        $sold_out_events                            = '';
607
-        foreach ($sold_out_events_array as $sold_out_event) {
608
-            $sold_out_events .= EEH_HTML::li(
609
-                EEH_HTML::span(
610
-                    '  ' . $sold_out_event->name(),
611
-                    '',
612
-                    'dashicons dashicons-marker ee-icon-size-16 pink-text'
613
-                )
614
-            );
615
-        }
616
-        return new EE_Form_Section_Proper(
617
-            array(
618
-                'layout_strategy' => new EE_Template_Layout(
619
-                    array(
620
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
621
-                                                  . $this->_slug
622
-                                                  . DS
623
-                                                  . 'sold_out_events.template.php',
624
-                        'template_args'        => apply_filters(
625
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
626
-                            array(
627
-                                'sold_out_events'     => $sold_out_events,
628
-                                'sold_out_events_msg' => apply_filters(
629
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
630
-                                    sprintf(
631
-                                        esc_html__(
632
-                                            'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
633
-                                            'event_espresso'
634
-                                        ),
635
-                                        '<strong>',
636
-                                        '</strong>',
637
-                                        '<br />'
638
-                                    )
639
-                                ),
640
-                            )
641
-                        ),
642
-                    )
643
-                ),
644
-            )
645
-        );
646
-    }
647
-
648
-
649
-    /**
650
-     * _insufficient_spaces_available
651
-     * displays notices regarding events that do not have enough remaining spaces
652
-     * to satisfy the current number of registrations looking to pay
653
-     *
654
-     * @param \EE_Event[] $insufficient_spaces_events_array
655
-     * @return \EE_Form_Section_Proper
656
-     * @throws \EE_Error
657
-     */
658
-    private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
659
-    {
660
-        // set some defaults
661
-        $this->checkout->selected_method_of_payment = 'invoice';
662
-        $insufficient_space_events                  = '';
663
-        foreach ($insufficient_spaces_events_array as $event) {
664
-            if ($event instanceof EE_Event) {
665
-                $insufficient_space_events .= EEH_HTML::li(
666
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
667
-                );
668
-            }
669
-        }
670
-        return new EE_Form_Section_Proper(
671
-            array(
672
-                'subsections'     => array(
673
-                    'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
674
-                    'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
675
-                ),
676
-                'layout_strategy' => new EE_Template_Layout(
677
-                    array(
678
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
679
-                                                  . $this->_slug
680
-                                                  . DS
681
-                                                  . 'sold_out_events.template.php',
682
-                        'template_args'        => apply_filters(
683
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
684
-                            array(
685
-                                'sold_out_events'     => $insufficient_space_events,
686
-                                'sold_out_events_msg' => apply_filters(
687
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
688
-                                    esc_html__(
689
-                                        'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
690
-                                        'event_espresso'
691
-                                    )
692
-                                ),
693
-                            )
694
-                        ),
695
-                    )
696
-                ),
697
-            )
698
-        );
699
-    }
700
-
701
-
702
-    /**
703
-     * registrations_requiring_pre_approval
704
-     *
705
-     * @param array $registrations_requiring_pre_approval
706
-     * @return EE_Form_Section_Proper
707
-     * @throws EE_Error
708
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
709
-     */
710
-    private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
711
-    {
712
-        $events_requiring_pre_approval = '';
713
-        foreach ($registrations_requiring_pre_approval as $registration) {
714
-            if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
715
-                $events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
716
-                    EEH_HTML::span(
717
-                        '',
718
-                        '',
719
-                        'dashicons dashicons-marker ee-icon-size-16 orange-text'
720
-                    )
721
-                    . EEH_HTML::span($registration->event()->name(), '', 'orange-text')
722
-                );
723
-            }
724
-        }
725
-        return new EE_Form_Section_Proper(
726
-            array(
727
-                'layout_strategy' => new EE_Template_Layout(
728
-                    array(
729
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
730
-                                                  . $this->_slug
731
-                                                  . DS
732
-                                                  . 'events_requiring_pre_approval.template.php', // layout_template
733
-                        'template_args'        => apply_filters(
734
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
735
-                            array(
736
-                                'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
737
-                                'events_requiring_pre_approval_msg' => apply_filters(
738
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
739
-                                    esc_html__(
740
-                                        'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has 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.',
741
-                                        'event_espresso'
742
-                                    )
743
-                                ),
744
-                            )
745
-                        ),
746
-                    )
747
-                ),
748
-            )
749
-        );
750
-    }
751
-
752
-
753
-    /**
754
-     * _no_payment_required
755
-     *
756
-     * @param \EE_Event[] $registrations_for_free_events
757
-     * @return \EE_Form_Section_Proper
758
-     * @throws \EE_Error
759
-     */
760
-    private function _no_payment_required($registrations_for_free_events = array())
761
-    {
762
-        // set some defaults
763
-        $this->checkout->selected_method_of_payment = 'no_payment_required';
764
-        // generate no_payment_required form
765
-        return new EE_Form_Section_Proper(
766
-            array(
767
-                'layout_strategy' => new EE_Template_Layout(
768
-                    array(
769
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
770
-                                                  . $this->_slug
771
-                                                  . DS
772
-                                                  . 'no_payment_required.template.php', // layout_template
773
-                        'template_args'        => apply_filters(
774
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
775
-                            array(
776
-                                'revisit'                       => $this->checkout->revisit,
777
-                                'registrations'                 => array(),
778
-                                'ticket_count'                  => array(),
779
-                                'registrations_for_free_events' => $registrations_for_free_events,
780
-                                'no_payment_required_msg'       => EEH_HTML::p(
781
-                                    esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
782
-                                ),
783
-                            )
784
-                        ),
785
-                    )
786
-                ),
787
-            )
788
-        );
789
-    }
790
-
791
-
792
-    /**
793
-     * _display_payment_options
794
-     *
795
-     * @param string $transaction_details
796
-     * @return EE_Form_Section_Proper
797
-     * @throws EE_Error
798
-     * @throws InvalidArgumentException
799
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
800
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
801
-     */
802
-    private function _display_payment_options($transaction_details = '')
803
-    {
804
-        // has method_of_payment been set by no-js user?
805
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
806
-        // build payment options form
807
-        return apply_filters(
808
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
809
-            new EE_Form_Section_Proper(
810
-                array(
811
-                    'subsections'     => array(
812
-                        'before_payment_options' => apply_filters(
813
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
814
-                            new EE_Form_Section_Proper(
815
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
816
-                            )
817
-                        ),
818
-                        'payment_options'        => $this->_setup_payment_options(),
819
-                        'after_payment_options'  => apply_filters(
820
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
821
-                            new EE_Form_Section_Proper(
822
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
823
-                            )
824
-                        ),
825
-                    ),
826
-                    'layout_strategy' => new EE_Template_Layout(
827
-                        array(
828
-                            'layout_template_file' => $this->_template,
829
-                            'template_args'        => apply_filters(
830
-                                'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
831
-                                array(
832
-                                    'reg_count'                 => $this->line_item_display->total_items(),
833
-                                    'transaction_details'       => $transaction_details,
834
-                                    'available_payment_methods' => array(),
835
-                                )
836
-                            ),
837
-                        )
838
-                    ),
839
-                )
840
-            )
841
-        );
842
-    }
843
-
844
-
845
-    /**
846
-     * _extra_hidden_inputs
847
-     *
848
-     * @param bool $no_payment_required
849
-     * @return \EE_Form_Section_Proper
850
-     * @throws \EE_Error
851
-     */
852
-    private function _extra_hidden_inputs($no_payment_required = true)
853
-    {
854
-        return new EE_Form_Section_Proper(
855
-            array(
856
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
857
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
858
-                'subsections'     => array(
859
-                    'spco_no_payment_required' => new EE_Hidden_Input(
860
-                        array(
861
-                            'normalization_strategy' => new EE_Boolean_Normalization(),
862
-                            'html_name'              => 'spco_no_payment_required',
863
-                            'html_id'                => 'spco-no-payment-required-payment_options',
864
-                            'default'                => $no_payment_required,
865
-                        )
866
-                    ),
867
-                    'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
868
-                        array(
869
-                            'normalization_strategy' => new EE_Int_Normalization(),
870
-                            'html_name'              => 'spco_transaction_id',
871
-                            'html_id'                => 'spco-transaction-id',
872
-                            'default'                => $this->checkout->transaction->ID(),
873
-                        )
874
-                    ),
875
-                ),
876
-            )
877
-        );
878
-    }
879
-
880
-
881
-    /**
882
-     *    _apply_registration_payments_to_amount_owing
883
-     *
884
-     * @access protected
885
-     * @param array $registrations
886
-     * @throws EE_Error
887
-     */
888
-    protected function _apply_registration_payments_to_amount_owing(array $registrations)
889
-    {
890
-        $payments = array();
891
-        foreach ($registrations as $registration) {
892
-            if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
893
-                $payments += $registration->registration_payments();
894
-            }
895
-        }
896
-        if (! empty($payments)) {
897
-            foreach ($payments as $payment) {
898
-                if ($payment instanceof EE_Registration_Payment) {
899
-                    $this->checkout->amount_owing -= $payment->amount();
900
-                }
901
-            }
902
-        }
903
-    }
904
-
905
-
906
-    /**
907
-     *    _reset_selected_method_of_payment
908
-     *
909
-     * @access    private
910
-     * @param    bool $force_reset
911
-     * @return void
912
-     * @throws InvalidArgumentException
913
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
914
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
915
-     */
916
-    private function _reset_selected_method_of_payment($force_reset = false)
917
-    {
918
-        $reset_payment_method = $force_reset
919
-            ? true
920
-            : sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
921
-        if ($reset_payment_method) {
922
-            $this->checkout->selected_method_of_payment = null;
923
-            $this->checkout->payment_method             = null;
924
-            $this->checkout->billing_form               = null;
925
-            $this->_save_selected_method_of_payment();
926
-        }
927
-    }
928
-
929
-
930
-    /**
931
-     * _save_selected_method_of_payment
932
-     * stores the selected_method_of_payment in the session
933
-     * so that it's available for all subsequent requests including AJAX
934
-     *
935
-     * @access        private
936
-     * @param string $selected_method_of_payment
937
-     * @return void
938
-     * @throws InvalidArgumentException
939
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
940
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
941
-     */
942
-    private function _save_selected_method_of_payment($selected_method_of_payment = '')
943
-    {
944
-        $selected_method_of_payment = ! empty($selected_method_of_payment)
945
-            ? $selected_method_of_payment
946
-            : $this->checkout->selected_method_of_payment;
947
-        EE_Registry::instance()->SSN->set_session_data(
948
-            array('selected_method_of_payment' => $selected_method_of_payment)
949
-        );
950
-    }
951
-
952
-
953
-    /**
954
-     * _setup_payment_options
955
-     *
956
-     * @return EE_Form_Section_Proper
957
-     * @throws EE_Error
958
-     * @throws InvalidArgumentException
959
-     * @throws ReflectionException
960
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
961
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
962
-     */
963
-    public function _setup_payment_options()
964
-    {
965
-        // load payment method classes
966
-        $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
967
-        if (empty($this->checkout->available_payment_methods)) {
968
-            EE_Error::add_error(
969
-                apply_filters(
970
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
971
-                    sprintf(
972
-                        esc_html__(
973
-                            'Sorry, you cannot complete your purchase because a payment method is not active.%1$s Please contact %2$s for assistance and provide a description of the problem.',
974
-                            'event_espresso'
975
-                        ),
976
-                        '<br>',
977
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
978
-                    )
979
-                ),
980
-                __FILE__,
981
-                __FUNCTION__,
982
-                __LINE__
983
-            );
984
-        }
985
-        // switch up header depending on number of available payment methods
986
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
987
-            ? apply_filters(
988
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
989
-                esc_html__('Please Select Your Method of Payment', 'event_espresso')
990
-            )
991
-            : apply_filters(
992
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
-                esc_html__('Method of Payment', 'event_espresso')
994
-            );
995
-        $available_payment_methods = array(
996
-            // display the "Payment Method" header
997
-            'payment_method_header' => new EE_Form_Section_HTML(
998
-                EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
999
-            ),
1000
-        );
1001
-        // the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1002
-        $available_payment_method_options = array();
1003
-        $default_payment_method_option    = array();
1004
-        // additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1005
-        $payment_methods_billing_info = array(
1006
-            new EE_Form_Section_HTML(
1007
-                EEH_HTML::div('<br />', '', '', 'clear:both;')
1008
-            ),
1009
-        );
1010
-        // loop through payment methods
1011
-        foreach ($this->checkout->available_payment_methods as $payment_method) {
1012
-            if ($payment_method instanceof EE_Payment_Method) {
1013
-                $payment_method_button = EEH_HTML::img(
1014
-                    $payment_method->button_url(),
1015
-                    $payment_method->name(),
1016
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1017
-                    'spco-payment-method-btn-img'
1018
-                );
1019
-                // check if any payment methods are set as default
1020
-                // if payment method is already selected OR nothing is selected and this payment method should be
1021
-                // open_by_default
1022
-                if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1023
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1024
-                ) {
1025
-                    $this->checkout->selected_method_of_payment = $payment_method->slug();
1026
-                    $this->_save_selected_method_of_payment();
1027
-                    $default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1028
-                } else {
1029
-                    $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1030
-                }
1031
-                $payment_methods_billing_info[$payment_method->slug() . '-info'] = $this->_payment_method_billing_info(
1032
-                    $payment_method
1033
-                );
1034
-            }
1035
-        }
1036
-        // prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1037
-        // of PMs
1038
-        $available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1039
-        // now generate the actual form  inputs
1040
-        $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1041
-            $available_payment_method_options
1042
-        );
1043
-        $available_payment_methods                              += $payment_methods_billing_info;
1044
-        // build the available payment methods form
1045
-        return new EE_Form_Section_Proper(
1046
-            array(
1047
-                'html_id'         => 'spco-available-methods-of-payment-dv',
1048
-                'subsections'     => $available_payment_methods,
1049
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1050
-            )
1051
-        );
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * _get_available_payment_methods
1057
-     *
1058
-     * @return EE_Payment_Method[]
1059
-     * @throws EE_Error
1060
-     * @throws InvalidArgumentException
1061
-     * @throws ReflectionException
1062
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1063
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1064
-     */
1065
-    protected function _get_available_payment_methods()
1066
-    {
1067
-        if (! empty($this->checkout->available_payment_methods)) {
1068
-            return $this->checkout->available_payment_methods;
1069
-        }
1070
-        $available_payment_methods = array();
1071
-        // load EEM_Payment_Method
1072
-        EE_Registry::instance()->load_model('Payment_Method');
1073
-        /** @type EEM_Payment_Method $EEM_Payment_Method */
1074
-        $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1075
-        // get all active payment methods
1076
-        $payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1077
-            $this->checkout->transaction,
1078
-            EEM_Payment_Method::scope_cart
1079
-        );
1080
-        foreach ($payment_methods as $payment_method) {
1081
-            if ($payment_method instanceof EE_Payment_Method) {
1082
-                $available_payment_methods[$payment_method->slug()] = $payment_method;
1083
-            }
1084
-        }
1085
-        return $available_payment_methods;
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     *    _available_payment_method_inputs
1091
-     *
1092
-     * @access    private
1093
-     * @param    array $available_payment_method_options
1094
-     * @return    \EE_Form_Section_Proper
1095
-     */
1096
-    private function _available_payment_method_inputs($available_payment_method_options = array())
1097
-    {
1098
-        // generate inputs
1099
-        return new EE_Form_Section_Proper(
1100
-            array(
1101
-                'html_id'         => 'ee-available-payment-method-inputs',
1102
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1103
-                'subsections'     => array(
1104
-                    '' => new EE_Radio_Button_Input(
1105
-                        $available_payment_method_options,
1106
-                        array(
1107
-                            'html_name'          => 'selected_method_of_payment',
1108
-                            'html_class'         => 'spco-payment-method',
1109
-                            'default'            => $this->checkout->selected_method_of_payment,
1110
-                            'label_size'         => 11,
1111
-                            'enforce_label_size' => true,
1112
-                        )
1113
-                    ),
1114
-                ),
1115
-            )
1116
-        );
1117
-    }
1118
-
1119
-
1120
-    /**
1121
-     *    _payment_method_billing_info
1122
-     *
1123
-     * @access    private
1124
-     * @param    EE_Payment_Method $payment_method
1125
-     * @return EE_Form_Section_Proper
1126
-     * @throws EE_Error
1127
-     * @throws InvalidArgumentException
1128
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1129
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1130
-     */
1131
-    private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1132
-    {
1133
-        $currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1134
-            ? true
1135
-            : false;
1136
-        // generate the billing form for payment method
1137
-        $billing_form                 = $currently_selected
1138
-            ? $this->_get_billing_form_for_payment_method($payment_method)
1139
-            : new EE_Form_Section_HTML();
1140
-        $this->checkout->billing_form = $currently_selected
1141
-            ? $billing_form
1142
-            : $this->checkout->billing_form;
1143
-        // it's all in the details
1144
-        $info_html = EEH_HTML::h3(
1145
-            esc_html__('Important information regarding your payment', 'event_espresso'),
1146
-            '',
1147
-            'spco-payment-method-hdr'
1148
-        );
1149
-        // add some info regarding the step, either from what's saved in the admin,
1150
-        // or a default string depending on whether the PM has a billing form or not
1151
-        if ($payment_method->description()) {
1152
-            $payment_method_info = $payment_method->description();
1153
-        } elseif ($billing_form instanceof EE_Billing_Info_Form) {
1154
-            $payment_method_info = sprintf(
1155
-                esc_html__(
1156
-                    'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1157
-                    'event_espresso'
1158
-                ),
1159
-                $this->submit_button_text()
1160
-            );
1161
-        } else {
1162
-            $payment_method_info = sprintf(
1163
-                esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1164
-                $this->submit_button_text()
1165
-            );
1166
-        }
1167
-        $info_html .= EEH_HTML::p(
1168
-            apply_filters(
1169
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1170
-                $payment_method_info
1171
-            ),
1172
-            '',
1173
-            'spco-payment-method-desc ee-attention'
1174
-        );
1175
-        return new EE_Form_Section_Proper(
1176
-            array(
1177
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1178
-                'html_class'      => 'spco-payment-method-info-dv',
1179
-                // only display the selected or default PM
1180
-                'html_style'      => $currently_selected ? '' : 'display:none;',
1181
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1182
-                'subsections'     => array(
1183
-                    'info'         => new EE_Form_Section_HTML($info_html),
1184
-                    'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1185
-                ),
1186
-            )
1187
-        );
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * get_billing_form_html_for_payment_method
1193
-     *
1194
-     * @access public
1195
-     * @return string
1196
-     * @throws EE_Error
1197
-     * @throws InvalidArgumentException
1198
-     * @throws ReflectionException
1199
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1200
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1201
-     */
1202
-    public function get_billing_form_html_for_payment_method()
1203
-    {
1204
-        // how have they chosen to pay?
1205
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1206
-        $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1207
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1208
-            return false;
1209
-        }
1210
-        if (apply_filters(
1211
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1212
-            false
1213
-        )) {
1214
-            EE_Error::add_success(
1215
-                apply_filters(
1216
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1217
-                    sprintf(
1218
-                        esc_html__(
1219
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1220
-                            'event_espresso'
1221
-                        ),
1222
-                        $this->checkout->payment_method->name()
1223
-                    )
1224
-                )
1225
-            );
1226
-        }
1227
-        // now generate billing form for selected method of payment
1228
-        $payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1229
-        // fill form with attendee info if applicable
1230
-        if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1231
-            && $this->checkout->transaction_has_primary_registrant()
1232
-        ) {
1233
-            $payment_method_billing_form->populate_from_attendee(
1234
-                $this->checkout->transaction->primary_registration()->attendee()
1235
-            );
1236
-        }
1237
-        // and debug content
1238
-        if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1239
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1240
-        ) {
1241
-            $payment_method_billing_form =
1242
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1243
-                    $payment_method_billing_form
1244
-                );
1245
-        }
1246
-        $billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1247
-            ? $payment_method_billing_form->get_html()
1248
-            : '';
1249
-        $this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1250
-        // localize validation rules for main form
1251
-        $this->checkout->current_step->reg_form->localize_validation_rules();
1252
-        $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1253
-        return true;
1254
-    }
1255
-
1256
-
1257
-    /**
1258
-     * _get_billing_form_for_payment_method
1259
-     *
1260
-     * @access private
1261
-     * @param EE_Payment_Method $payment_method
1262
-     * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1263
-     * @throws EE_Error
1264
-     * @throws InvalidArgumentException
1265
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1266
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1267
-     */
1268
-    private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1269
-    {
1270
-        $billing_form = $payment_method->type_obj()->billing_form(
1271
-            $this->checkout->transaction,
1272
-            array('amount_owing' => $this->checkout->amount_owing)
1273
-        );
1274
-        if ($billing_form instanceof EE_Billing_Info_Form) {
1275
-            if (apply_filters(
1276
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1277
-                false
1278
-            )
1279
-                && EE_Registry::instance()->REQ->is_set('payment_method')
1280
-            ) {
1281
-                EE_Error::add_success(
1282
-                    apply_filters(
1283
-                        'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1284
-                        sprintf(
1285
-                            esc_html__(
1286
-                                'You have selected "%s" as your method of payment. Please note the important payment information below.',
1287
-                                'event_espresso'
1288
-                            ),
1289
-                            $payment_method->name()
1290
-                        )
1291
-                    )
1292
-                );
1293
-            }
1294
-            return apply_filters(
1295
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1296
-                $billing_form,
1297
-                $payment_method
1298
-            );
1299
-        }
1300
-        // no actual billing form, so return empty HTML form section
1301
-        return new EE_Form_Section_HTML();
1302
-    }
1303
-
1304
-
1305
-    /**
1306
-     * _get_selected_method_of_payment
1307
-     *
1308
-     * @access private
1309
-     * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1310
-     *                          is not found in the incoming request
1311
-     * @param string  $request_param
1312
-     * @return NULL|string
1313
-     * @throws EE_Error
1314
-     * @throws InvalidArgumentException
1315
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1316
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1317
-     */
1318
-    private function _get_selected_method_of_payment(
1319
-        $required = false,
1320
-        $request_param = 'selected_method_of_payment'
1321
-    ) {
1322
-        // is selected_method_of_payment set in the request ?
1323
-        $selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1324
-        if ($selected_method_of_payment) {
1325
-            // sanitize it
1326
-            $selected_method_of_payment = is_array($selected_method_of_payment)
1327
-                ? array_shift($selected_method_of_payment)
1328
-                : $selected_method_of_payment;
1329
-            $selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1330
-            // store it in the session so that it's available for all subsequent requests including AJAX
1331
-            $this->_save_selected_method_of_payment($selected_method_of_payment);
1332
-        } else {
1333
-            // or is is set in the session ?
1334
-            $selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1335
-                'selected_method_of_payment'
1336
-            );
1337
-        }
1338
-        // do ya really really gotta have it?
1339
-        if (empty($selected_method_of_payment) && $required) {
1340
-            EE_Error::add_error(
1341
-                sprintf(
1342
-                    esc_html__(
1343
-                        'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1344
-                        'event_espresso'
1345
-                    ),
1346
-                    '<br/>',
1347
-                    '<br/>',
1348
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1349
-                ),
1350
-                __FILE__,
1351
-                __FUNCTION__,
1352
-                __LINE__
1353
-            );
1354
-            return null;
1355
-        }
1356
-        return $selected_method_of_payment;
1357
-    }
1358
-
1359
-
1360
-
1361
-
1362
-
1363
-
1364
-    /********************************************************************************************************/
1365
-    /***********************************  SWITCH PAYMENT METHOD  ************************************/
1366
-    /********************************************************************************************************/
1367
-    /**
1368
-     * switch_payment_method
1369
-     *
1370
-     * @access public
1371
-     * @return string
1372
-     * @throws EE_Error
1373
-     * @throws InvalidArgumentException
1374
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1375
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1376
-     */
1377
-    public function switch_payment_method()
1378
-    {
1379
-        if (! $this->_verify_payment_method_is_set()) {
1380
-            return false;
1381
-        }
1382
-        if (apply_filters(
1383
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1384
-            false
1385
-        )) {
1386
-            EE_Error::add_success(
1387
-                apply_filters(
1388
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1389
-                    sprintf(
1390
-                        esc_html__(
1391
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1392
-                            'event_espresso'
1393
-                        ),
1394
-                        $this->checkout->payment_method->name()
1395
-                    )
1396
-                )
1397
-            );
1398
-        }
1399
-        // generate billing form for selected method of payment if it hasn't been done already
1400
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1401
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1402
-                $this->checkout->payment_method
1403
-            );
1404
-        }
1405
-        // fill form with attendee info if applicable
1406
-        if (apply_filters(
1407
-            'FHEE__populate_billing_form_fields_from_attendee',
1408
-            (
1409
-                $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1410
-                && $this->checkout->transaction_has_primary_registrant()
1411
-            ),
1412
-            $this->checkout->billing_form,
1413
-            $this->checkout->transaction
1414
-        )
1415
-        ) {
1416
-            $this->checkout->billing_form->populate_from_attendee(
1417
-                $this->checkout->transaction->primary_registration()->attendee()
1418
-            );
1419
-        }
1420
-        // and debug content
1421
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1422
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1423
-        ) {
1424
-            $this->checkout->billing_form =
1425
-                $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1426
-                    $this->checkout->billing_form
1427
-                );
1428
-        }
1429
-        // get html and validation rules for form
1430
-        if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1431
-            $this->checkout->json_response->set_return_data(
1432
-                array('payment_method_info' => $this->checkout->billing_form->get_html())
1433
-            );
1434
-            // localize validation rules for main form
1435
-            $this->checkout->billing_form->localize_validation_rules(true);
1436
-            $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1437
-        } else {
1438
-            $this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1439
-        }
1440
-        //prevents advancement to next step
1441
-        $this->checkout->continue_reg = false;
1442
-        return true;
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * _verify_payment_method_is_set
1448
-     *
1449
-     * @return bool
1450
-     * @throws EE_Error
1451
-     * @throws InvalidArgumentException
1452
-     * @throws ReflectionException
1453
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1454
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1455
-     */
1456
-    protected function _verify_payment_method_is_set()
1457
-    {
1458
-        // generate billing form for selected method of payment if it hasn't been done already
1459
-        if (empty($this->checkout->selected_method_of_payment)) {
1460
-            // how have they chosen to pay?
1461
-            $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1462
-        } else {
1463
-            // choose your own adventure based on method_of_payment
1464
-            switch ($this->checkout->selected_method_of_payment) {
1465
-                case 'events_sold_out' :
1466
-                    EE_Error::add_attention(
1467
-                        apply_filters(
1468
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1469
-                            esc_html__(
1470
-                                'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1471
-                                'event_espresso'
1472
-                            )
1473
-                        ),
1474
-                        __FILE__, __FUNCTION__, __LINE__
1475
-                    );
1476
-                    return false;
1477
-                    break;
1478
-                case 'payments_closed' :
1479
-                    EE_Error::add_attention(
1480
-                        apply_filters(
1481
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1482
-                            esc_html__(
1483
-                                'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1484
-                                'event_espresso'
1485
-                            )
1486
-                        ),
1487
-                        __FILE__, __FUNCTION__, __LINE__
1488
-                    );
1489
-                    return false;
1490
-                    break;
1491
-                case 'no_payment_required' :
1492
-                    EE_Error::add_attention(
1493
-                        apply_filters(
1494
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1495
-                            esc_html__(
1496
-                                'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1497
-                                'event_espresso'
1498
-                            )
1499
-                        ),
1500
-                        __FILE__, __FUNCTION__, __LINE__
1501
-                    );
1502
-                    return false;
1503
-                    break;
1504
-                default:
1505
-            }
1506
-        }
1507
-        // verify payment method
1508
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1509
-            // get payment method for selected method of payment
1510
-            $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1511
-        }
1512
-        return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1513
-    }
1514
-
1515
-
1516
-
1517
-    /********************************************************************************************************/
1518
-    /***************************************  SAVE PAYER DETAILS  ****************************************/
1519
-    /********************************************************************************************************/
1520
-    /**
1521
-     * save_payer_details_via_ajax
1522
-     *
1523
-     * @return void
1524
-     * @throws EE_Error
1525
-     * @throws InvalidArgumentException
1526
-     * @throws ReflectionException
1527
-     * @throws RuntimeException
1528
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1529
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1530
-     */
1531
-    public function save_payer_details_via_ajax()
1532
-    {
1533
-        if (! $this->_verify_payment_method_is_set()) {
1534
-            return;
1535
-        }
1536
-        // generate billing form for selected method of payment if it hasn't been done already
1537
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1538
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1539
-                $this->checkout->payment_method
1540
-            );
1541
-        }
1542
-        // generate primary attendee from payer info if applicable
1543
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1544
-            $attendee = $this->_create_attendee_from_request_data();
1545
-            if ($attendee instanceof EE_Attendee) {
1546
-                foreach ($this->checkout->transaction->registrations() as $registration) {
1547
-                    if ($registration->is_primary_registrant()) {
1548
-                        $this->checkout->primary_attendee_obj = $attendee;
1549
-                        $registration->_add_relation_to($attendee, 'Attendee');
1550
-                        $registration->set_attendee_id($attendee->ID());
1551
-                        $registration->update_cache_after_object_save('Attendee', $attendee);
1552
-                    }
1553
-                }
1554
-            }
1555
-        }
1556
-    }
1557
-
1558
-
1559
-    /**
1560
-     * create_attendee_from_request_data
1561
-     * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1562
-     *
1563
-     * @return EE_Attendee
1564
-     * @throws EE_Error
1565
-     * @throws InvalidArgumentException
1566
-     * @throws ReflectionException
1567
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1568
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1569
-     */
1570
-    protected function _create_attendee_from_request_data()
1571
-    {
1572
-        // get State ID
1573
-        $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1574
-        if (! empty($STA_ID)) {
1575
-            // can we get state object from name ?
1576
-            EE_Registry::instance()->load_model('State');
1577
-            $state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1578
-            $STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1579
-        }
1580
-        // get Country ISO
1581
-        $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1582
-        if (! empty($CNT_ISO)) {
1583
-            // can we get country object from name ?
1584
-            EE_Registry::instance()->load_model('Country');
1585
-            $country = EEM_Country::instance()->get_col(
1586
-                array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1587
-                'CNT_ISO'
1588
-            );
1589
-            $CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1590
-        }
1591
-        // grab attendee data
1592
-        $attendee_data = array(
1593
-            'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1594
-            'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1595
-            'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1596
-            'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1597
-            'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1598
-            'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1599
-            'STA_ID'       => $STA_ID,
1600
-            'CNT_ISO'      => $CNT_ISO,
1601
-            'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1602
-            'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1603
-        );
1604
-        // validate the email address since it is the most important piece of info
1605
-        if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1606
-            EE_Error::add_error(
1607
-                esc_html__('An invalid email address was submitted.', 'event_espresso'),
1608
-                __FILE__,
1609
-                __FUNCTION__,
1610
-                __LINE__
1611
-            );
1612
-        }
1613
-        // does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1614
-        // AND email address
1615
-        if (! empty($attendee_data['ATT_fname'])
1616
-            && ! empty($attendee_data['ATT_lname'])
1617
-            && ! empty($attendee_data['ATT_email'])
1618
-        ) {
1619
-            $existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1620
-                array(
1621
-                    'ATT_fname' => $attendee_data['ATT_fname'],
1622
-                    'ATT_lname' => $attendee_data['ATT_lname'],
1623
-                    'ATT_email' => $attendee_data['ATT_email'],
1624
-                )
1625
-            );
1626
-            if ($existing_attendee instanceof EE_Attendee) {
1627
-                return $existing_attendee;
1628
-            }
1629
-        }
1630
-        // no existing attendee? kk let's create a new one
1631
-        // kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1632
-        // don't exist
1633
-        $attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1634
-            ? $attendee_data['ATT_fname']
1635
-            : $attendee_data['ATT_email'];
1636
-        $attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1637
-            ? $attendee_data['ATT_lname']
1638
-            : $attendee_data['ATT_email'];
1639
-        return EE_Attendee::new_instance($attendee_data);
1640
-    }
1641
-
1642
-
1643
-
1644
-    /********************************************************************************************************/
1645
-    /****************************************  PROCESS REG STEP  *****************************************/
1646
-    /********************************************************************************************************/
1647
-    /**
1648
-     * process_reg_step
1649
-     *
1650
-     * @return bool
1651
-     * @throws EE_Error
1652
-     * @throws InvalidArgumentException
1653
-     * @throws ReflectionException
1654
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1655
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1656
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1657
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1658
-     */
1659
-    public function process_reg_step()
1660
-    {
1661
-        // how have they chosen to pay?
1662
-        $this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1663
-            ? 'no_payment_required'
1664
-            : $this->_get_selected_method_of_payment(true);
1665
-        // choose your own adventure based on method_of_payment
1666
-        switch ($this->checkout->selected_method_of_payment) {
1667
-
1668
-            case 'events_sold_out' :
1669
-                $this->checkout->redirect     = true;
1670
-                $this->checkout->redirect_url = $this->checkout->cancel_page_url;
1671
-                $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1672
-                // mark this reg step as completed
1673
-                $this->set_completed();
1674
-                return false;
1675
-                break;
1676
-
1677
-            case 'payments_closed' :
1678
-                if (apply_filters(
1679
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1680
-                    false
1681
-                )) {
1682
-                    EE_Error::add_success(
1683
-                        esc_html__('no payment required at this time.', 'event_espresso'),
1684
-                        __FILE__,
1685
-                        __FUNCTION__,
1686
-                        __LINE__
1687
-                    );
1688
-                }
1689
-                // mark this reg step as completed
1690
-                $this->set_completed();
1691
-                return true;
1692
-                break;
1693
-
1694
-            case 'no_payment_required' :
1695
-                if (apply_filters(
1696
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1697
-                    false
1698
-                )) {
1699
-                    EE_Error::add_success(
1700
-                        esc_html__('no payment required.', 'event_espresso'),
1701
-                        __FILE__,
1702
-                        __FUNCTION__,
1703
-                        __LINE__
1704
-                    );
1705
-                }
1706
-                // mark this reg step as completed
1707
-                $this->set_completed();
1708
-                return true;
1709
-                break;
1710
-
1711
-            default:
1712
-                $registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1713
-                    EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1714
-                );
1715
-                $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1716
-                    $registrations,
1717
-                    EE_Registry::instance()->SSN->checkout()->revisit
1718
-                );
1719
-                // calculate difference between the two arrays
1720
-                $registrations = array_diff($registrations, $ejected_registrations);
1721
-                if (empty($registrations)) {
1722
-                    $this->_redirect_because_event_sold_out();
1723
-                    return false;
1724
-                }
1725
-                $payment_successful = $this->_process_payment();
1726
-                if ($payment_successful) {
1727
-                    $this->checkout->continue_reg = true;
1728
-                    $this->_maybe_set_completed($this->checkout->payment_method);
1729
-                } else {
1730
-                    $this->checkout->continue_reg = false;
1731
-                }
1732
-                return $payment_successful;
1733
-        }
1734
-    }
1735
-
1736
-
1737
-    /**
1738
-     * _redirect_because_event_sold_out
1739
-     *
1740
-     * @access protected
1741
-     * @return void
1742
-     */
1743
-    protected function _redirect_because_event_sold_out()
1744
-    {
1745
-        $this->checkout->continue_reg = false;
1746
-        // set redirect URL
1747
-        $this->checkout->redirect_url = add_query_arg(
1748
-            array('e_reg_url_link' => $this->checkout->reg_url_link),
1749
-            $this->checkout->current_step->reg_step_url()
1750
-        );
1751
-        $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1752
-    }
1753
-
1754
-
1755
-    /**
1756
-     * _maybe_set_completed
1757
-     *
1758
-     * @access protected
1759
-     * @param \EE_Payment_Method $payment_method
1760
-     * @return void
1761
-     * @throws \EE_Error
1762
-     */
1763
-    protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1764
-    {
1765
-        switch ($payment_method->type_obj()->payment_occurs()) {
1766
-            case EE_PMT_Base::offsite :
1767
-                break;
1768
-            case EE_PMT_Base::onsite :
1769
-            case EE_PMT_Base::offline :
1770
-                // mark this reg step as completed
1771
-                $this->set_completed();
1772
-                break;
1773
-        }
1774
-    }
1775
-
1776
-
1777
-    /**
1778
-     *    update_reg_step
1779
-     *    this is the final step after a user  revisits the site to retry a payment
1780
-     *
1781
-     * @return bool
1782
-     * @throws EE_Error
1783
-     * @throws InvalidArgumentException
1784
-     * @throws ReflectionException
1785
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1786
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1787
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1788
-     * @throws \EventEspresso\core\exceptions\InvalidStatusException
1789
-     */
1790
-    public function update_reg_step()
1791
-    {
1792
-        $success = true;
1793
-        // if payment required
1794
-        if ($this->checkout->transaction->total() > 0) {
1795
-            do_action(
1796
-                'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1797
-                $this->checkout->transaction
1798
-            );
1799
-            // attempt payment via payment method
1800
-            $success = $this->process_reg_step();
1801
-        }
1802
-        if ($success && ! $this->checkout->redirect) {
1803
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1804
-                $this->checkout->transaction->ID()
1805
-            );
1806
-            // set return URL
1807
-            $this->checkout->redirect_url = add_query_arg(
1808
-                array('e_reg_url_link' => $this->checkout->reg_url_link),
1809
-                $this->checkout->thank_you_page_url
1810
-            );
1811
-        }
1812
-        return $success;
1813
-    }
1814
-
1815
-
1816
-    /**
1817
-     *    _process_payment
1818
-     *
1819
-     * @access private
1820
-     * @return bool
1821
-     * @throws EE_Error
1822
-     * @throws InvalidArgumentException
1823
-     * @throws ReflectionException
1824
-     * @throws RuntimeException
1825
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1826
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1827
-     */
1828
-    private function _process_payment()
1829
-    {
1830
-        // basically confirm that the event hasn't sold out since they hit the page
1831
-        if (! $this->_last_second_ticket_verifications()) {
1832
-            return false;
1833
-        }
1834
-        // ya gotta make a choice man
1835
-        if (empty($this->checkout->selected_method_of_payment)) {
1836
-            $this->checkout->json_response->set_plz_select_method_of_payment(
1837
-                esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1838
-            );
1839
-            return false;
1840
-        }
1841
-        // get EE_Payment_Method object
1842
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1843
-            return false;
1844
-        }
1845
-        // setup billing form
1846
-        if ($this->checkout->payment_method->is_on_site()) {
1847
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1848
-                $this->checkout->payment_method
1849
-            );
1850
-            // bad billing form ?
1851
-            if (! $this->_billing_form_is_valid()) {
1852
-                return false;
1853
-            }
1854
-        }
1855
-        // ensure primary registrant has been fully processed
1856
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1857
-            return false;
1858
-        }
1859
-        // if session is close to expiring (under 10 minutes by default)
1860
-        if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1861
-            // add some time to session expiration so that payment can be completed
1862
-            EE_Registry::instance()->SSN->extend_expiration();
1863
-        }
1864
-        /** @type EE_Transaction_Processor $transaction_processor */
1865
-        //$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1866
-        // in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1867
-        // for events with a default reg status of Approved
1868
-        // $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1869
-        //      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1870
-        // );
1871
-        // attempt payment
1872
-        $payment = $this->_attempt_payment($this->checkout->payment_method);
1873
-        // process results
1874
-        $payment = $this->_validate_payment($payment);
1875
-        $payment = $this->_post_payment_processing($payment);
1876
-        // verify payment
1877
-        if ($payment instanceof EE_Payment) {
1878
-            // store that for later
1879
-            $this->checkout->payment = $payment;
1880
-            // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1881
-            $this->checkout->transaction->toggle_failed_transaction_status();
1882
-            $payment_status = $payment->status();
1883
-            if (
1884
-                $payment_status === EEM_Payment::status_id_approved
1885
-                || $payment_status === EEM_Payment::status_id_pending
1886
-            ) {
1887
-                return true;
1888
-            } else {
1889
-                return false;
1890
-            }
1891
-        } else if ($payment === true) {
1892
-            // please note that offline payment methods will NOT make a payment,
1893
-            // but instead just mark themselves as the PMD_ID on the transaction, and return true
1894
-            $this->checkout->payment = $payment;
1895
-            return true;
1896
-        }
1897
-        // where's my money?
1898
-        return false;
1899
-    }
1900
-
1901
-
1902
-    /**
1903
-     * _last_second_ticket_verifications
1904
-     *
1905
-     * @access public
1906
-     * @return bool
1907
-     * @throws EE_Error
1908
-     */
1909
-    protected function _last_second_ticket_verifications()
1910
-    {
1911
-        // don't bother re-validating if not a return visit
1912
-        if (! $this->checkout->revisit) {
1913
-            return true;
1914
-        }
1915
-        $registrations = $this->checkout->transaction->registrations();
1916
-        if (empty($registrations)) {
1917
-            return false;
1918
-        }
1919
-        foreach ($registrations as $registration) {
1920
-            if ($registration instanceof EE_Registration) {
1921
-                $event = $registration->event_obj();
1922
-                if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1923
-                    EE_Error::add_error(
1924
-                        apply_filters(
1925
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1926
-                            sprintf(
1927
-                                esc_html__(
1928
-                                    'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1929
-                                    'event_espresso'
1930
-                                ),
1931
-                                $event->name()
1932
-                            )
1933
-                        ),
1934
-                        __FILE__,
1935
-                        __FUNCTION__,
1936
-                        __LINE__
1937
-                    );
1938
-                    return false;
1939
-                }
1940
-            }
1941
-        }
1942
-        return true;
1943
-    }
1944
-
1945
-
1946
-    /**
1947
-     * redirect_form
1948
-     *
1949
-     * @access public
1950
-     * @return bool
1951
-     * @throws EE_Error
1952
-     * @throws InvalidArgumentException
1953
-     * @throws ReflectionException
1954
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1955
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1956
-     */
1957
-    public function redirect_form()
1958
-    {
1959
-        $payment_method_billing_info = $this->_payment_method_billing_info(
1960
-            $this->_get_payment_method_for_selected_method_of_payment()
1961
-        );
1962
-        $html                        = $payment_method_billing_info->get_html();
1963
-        $html                        .= $this->checkout->redirect_form;
1964
-        EE_Registry::instance()->REQ->add_output($html);
1965
-        return true;
1966
-    }
1967
-
1968
-
1969
-    /**
1970
-     * _billing_form_is_valid
1971
-     *
1972
-     * @access private
1973
-     * @return bool
1974
-     * @throws \EE_Error
1975
-     */
1976
-    private function _billing_form_is_valid()
1977
-    {
1978
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1979
-            return true;
1980
-        }
1981
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1982
-            if ($this->checkout->billing_form->was_submitted()) {
1983
-                $this->checkout->billing_form->receive_form_submission();
1984
-                if ($this->checkout->billing_form->is_valid()) {
1985
-                    return true;
1986
-                }
1987
-                $validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1988
-                $error_strings     = array();
1989
-                foreach ($validation_errors as $validation_error) {
1990
-                    if ($validation_error instanceof EE_Validation_Error) {
1991
-                        $form_section = $validation_error->get_form_section();
1992
-                        if ($form_section instanceof EE_Form_Input_Base) {
1993
-                            $label = $form_section->html_label_text();
1994
-                        } elseif ($form_section instanceof EE_Form_Section_Base) {
1995
-                            $label = $form_section->name();
1996
-                        } else {
1997
-                            $label = esc_html__('Validation Error', 'event_espresso');
1998
-                        }
1999
-                        $error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2000
-                    }
2001
-                }
2002
-                EE_Error::add_error(
2003
-                    sprintf(
2004
-                        esc_html__(
2005
-                            'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2006
-                            'event_espresso'
2007
-                        ),
2008
-                        '<br/>',
2009
-                        implode('<br/>', $error_strings)
2010
-                    ),
2011
-                    __FILE__,
2012
-                    __FUNCTION__,
2013
-                    __LINE__
2014
-                );
2015
-            } else {
2016
-                EE_Error::add_error(
2017
-                    esc_html__(
2018
-                        'The billing form was not submitted or something prevented it\'s submission.',
2019
-                        'event_espresso'
2020
-                    ),
2021
-                    __FILE__,
2022
-                    __FUNCTION__,
2023
-                    __LINE__
2024
-                );
2025
-            }
2026
-        } else {
2027
-            EE_Error::add_error(
2028
-                esc_html__('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
2029
-                __FILE__,
2030
-                __FUNCTION__,
2031
-                __LINE__
2032
-            );
2033
-        }
2034
-        return false;
2035
-    }
2036
-
2037
-
2038
-    /**
2039
-     * _setup_primary_registrant_prior_to_payment
2040
-     * ensures that the primary registrant has a valid attendee object created with the critical details populated
2041
-     * (first & last name & email) and that both the transaction object and primary registration object have been saved
2042
-     * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2043
-     * yet)
2044
-     *
2045
-     * @access private
2046
-     * @return bool
2047
-     * @throws EE_Error
2048
-     * @throws InvalidArgumentException
2049
-     * @throws ReflectionException
2050
-     * @throws RuntimeException
2051
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2052
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2053
-     */
2054
-    private function _setup_primary_registrant_prior_to_payment()
2055
-    {
2056
-        // check if transaction has a primary registrant and that it has a related Attendee object
2057
-        // if not, then we need to at least gather some primary registrant data before attempting payment
2058
-        if (
2059
-            $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2060
-            && ! $this->checkout->transaction_has_primary_registrant()
2061
-            && ! $this->_capture_primary_registration_data_from_billing_form()
2062
-        ) {
2063
-            return false;
2064
-        }
2065
-        // because saving an object clears it's cache, we need to do the chevy shuffle
2066
-        // grab the primary_registration object
2067
-        $primary_registration = $this->checkout->transaction->primary_registration();
2068
-        // at this point we'll consider a TXN to not have been failed
2069
-        $this->checkout->transaction->toggle_failed_transaction_status();
2070
-        // save the TXN ( which clears cached copy of primary_registration)
2071
-        $this->checkout->transaction->save();
2072
-        // grab TXN ID and save it to the primary_registration
2073
-        $primary_registration->set_transaction_id($this->checkout->transaction->ID());
2074
-        // save what we have so far
2075
-        $primary_registration->save();
2076
-        return true;
2077
-    }
2078
-
2079
-
2080
-    /**
2081
-     * _capture_primary_registration_data_from_billing_form
2082
-     *
2083
-     * @access private
2084
-     * @return bool
2085
-     * @throws EE_Error
2086
-     * @throws InvalidArgumentException
2087
-     * @throws ReflectionException
2088
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2089
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2090
-     */
2091
-    private function _capture_primary_registration_data_from_billing_form()
2092
-    {
2093
-        // convert billing form data into an attendee
2094
-        $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2095
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2096
-            EE_Error::add_error(
2097
-                sprintf(
2098
-                    esc_html__(
2099
-                        'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2100
-                        'event_espresso'
2101
-                    ),
2102
-                    '<br/>',
2103
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2104
-                ),
2105
-                __FILE__,
2106
-                __FUNCTION__,
2107
-                __LINE__
2108
-            );
2109
-            return false;
2110
-        }
2111
-        $primary_registration = $this->checkout->transaction->primary_registration();
2112
-        if (! $primary_registration instanceof EE_Registration) {
2113
-            EE_Error::add_error(
2114
-                sprintf(
2115
-                    esc_html__(
2116
-                        'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2117
-                        'event_espresso'
2118
-                    ),
2119
-                    '<br/>',
2120
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2121
-                ),
2122
-                __FILE__,
2123
-                __FUNCTION__,
2124
-                __LINE__
2125
-            );
2126
-            return false;
2127
-        }
2128
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2129
-              instanceof
2130
-              EE_Attendee
2131
-        ) {
2132
-            EE_Error::add_error(
2133
-                sprintf(
2134
-                    esc_html__(
2135
-                        'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2136
-                        'event_espresso'
2137
-                    ),
2138
-                    '<br/>',
2139
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2140
-                ),
2141
-                __FILE__,
2142
-                __FUNCTION__,
2143
-                __LINE__
2144
-            );
2145
-            return false;
2146
-        }
2147
-        /** @type EE_Registration_Processor $registration_processor */
2148
-        $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2149
-        // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2150
-        $registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2151
-        return true;
2152
-    }
2153
-
2154
-
2155
-    /**
2156
-     * _get_payment_method_for_selected_method_of_payment
2157
-     * retrieves a valid payment method
2158
-     *
2159
-     * @access public
2160
-     * @return EE_Payment_Method
2161
-     * @throws EE_Error
2162
-     * @throws InvalidArgumentException
2163
-     * @throws ReflectionException
2164
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2165
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2166
-     */
2167
-    private function _get_payment_method_for_selected_method_of_payment()
2168
-    {
2169
-        if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2170
-            $this->_redirect_because_event_sold_out();
2171
-            return null;
2172
-        }
2173
-        // get EE_Payment_Method object
2174
-        if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2175
-            $payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2176
-        } else {
2177
-            // load EEM_Payment_Method
2178
-            EE_Registry::instance()->load_model('Payment_Method');
2179
-            /** @type EEM_Payment_Method $EEM_Payment_Method */
2180
-            $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2181
-            $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2182
-        }
2183
-        // verify $payment_method
2184
-        if (! $payment_method instanceof EE_Payment_Method) {
2185
-            // not a payment
2186
-            EE_Error::add_error(
2187
-                sprintf(
2188
-                    esc_html__(
2189
-                        'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2190
-                        'event_espresso'
2191
-                    ),
2192
-                    '<br/>',
2193
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2194
-                ),
2195
-                __FILE__,
2196
-                __FUNCTION__,
2197
-                __LINE__
2198
-            );
2199
-            return null;
2200
-        }
2201
-        // and verify it has a valid Payment_Method Type object
2202
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2203
-            // not a payment
2204
-            EE_Error::add_error(
2205
-                sprintf(
2206
-                    esc_html__(
2207
-                        'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2208
-                        'event_espresso'
2209
-                    ),
2210
-                    '<br/>',
2211
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2212
-                ),
2213
-                __FILE__,
2214
-                __FUNCTION__,
2215
-                __LINE__
2216
-            );
2217
-            return null;
2218
-        }
2219
-        return $payment_method;
2220
-    }
2221
-
2222
-
2223
-    /**
2224
-     *    _attempt_payment
2225
-     *
2226
-     * @access    private
2227
-     * @type    EE_Payment_Method $payment_method
2228
-     * @return mixed EE_Payment | boolean
2229
-     * @throws EE_Error
2230
-     * @throws InvalidArgumentException
2231
-     * @throws ReflectionException
2232
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2233
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2234
-     */
2235
-    private function _attempt_payment(EE_Payment_Method $payment_method)
2236
-    {
2237
-        $payment = null;
2238
-        $this->checkout->transaction->save();
2239
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2240
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2241
-            return false;
2242
-        }
2243
-        try {
2244
-            $payment_processor->set_revisit($this->checkout->revisit);
2245
-            // generate payment object
2246
-            $payment = $payment_processor->process_payment(
2247
-                $payment_method,
2248
-                $this->checkout->transaction,
2249
-                $this->checkout->amount_owing,
2250
-                $this->checkout->billing_form,
2251
-                $this->_get_return_url($payment_method),
2252
-                'CART',
2253
-                $this->checkout->admin_request,
2254
-                true,
2255
-                $this->reg_step_url()
2256
-            );
2257
-        } catch (Exception $e) {
2258
-            $this->_handle_payment_processor_exception($e);
2259
-        }
2260
-        return $payment;
2261
-    }
2262
-
2263
-
2264
-    /**
2265
-     * _handle_payment_processor_exception
2266
-     *
2267
-     * @access protected
2268
-     * @param \Exception $e
2269
-     * @return void
2270
-     * @throws EE_Error
2271
-     * @throws InvalidArgumentException
2272
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2273
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2274
-     */
2275
-    protected function _handle_payment_processor_exception(Exception $e)
2276
-    {
2277
-        EE_Error::add_error(
2278
-            sprintf(
2279
-                esc_html__(
2280
-                    'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2281
-                    'event_espresso'
2282
-                ),
2283
-                '<br/>',
2284
-                EE_Registry::instance()->CFG->organization->get_pretty('email'),
2285
-                $e->getMessage(),
2286
-                $e->getFile(),
2287
-                $e->getLine()
2288
-            ),
2289
-            __FILE__,
2290
-            __FUNCTION__,
2291
-            __LINE__
2292
-        );
2293
-    }
2294
-
2295
-
2296
-    /**
2297
-     * _get_return_url
2298
-     *
2299
-     * @access protected
2300
-     * @param \EE_Payment_Method $payment_method
2301
-     * @return string
2302
-     * @throws \EE_Error
2303
-     */
2304
-    protected function _get_return_url(EE_Payment_Method $payment_method)
2305
-    {
2306
-        $return_url = '';
2307
-        switch ($payment_method->type_obj()->payment_occurs()) {
2308
-            case EE_PMT_Base::offsite :
2309
-                $return_url = add_query_arg(
2310
-                    array(
2311
-                        'action'                     => 'process_gateway_response',
2312
-                        'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2313
-                        'spco_txn'                   => $this->checkout->transaction->ID(),
2314
-                    ),
2315
-                    $this->reg_step_url()
2316
-                );
2317
-                break;
2318
-            case EE_PMT_Base::onsite :
2319
-            case EE_PMT_Base::offline :
2320
-                $return_url = $this->checkout->next_step->reg_step_url();
2321
-                break;
2322
-        }
2323
-        return $return_url;
2324
-    }
2325
-
2326
-
2327
-    /**
2328
-     * _validate_payment
2329
-     *
2330
-     * @access private
2331
-     * @param EE_Payment $payment
2332
-     * @return EE_Payment|FALSE
2333
-     * @throws EE_Error
2334
-     * @throws InvalidArgumentException
2335
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2336
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2337
-     */
2338
-    private function _validate_payment($payment = null)
2339
-    {
2340
-        if ($this->checkout->payment_method->is_off_line()) {
2341
-            return true;
2342
-        }
2343
-        // verify payment object
2344
-        if (! $payment instanceof EE_Payment) {
2345
-            // not a payment
2346
-            EE_Error::add_error(
2347
-                sprintf(
2348
-                    esc_html__(
2349
-                        'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2350
-                        'event_espresso'
2351
-                    ),
2352
-                    '<br/>',
2353
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2354
-                ),
2355
-                __FILE__,
2356
-                __FUNCTION__,
2357
-                __LINE__
2358
-            );
2359
-            return false;
2360
-        }
2361
-        return $payment;
2362
-    }
2363
-
2364
-
2365
-    /**
2366
-     * _post_payment_processing
2367
-     *
2368
-     * @access private
2369
-     * @param EE_Payment|bool $payment
2370
-     * @return bool
2371
-     * @throws EE_Error
2372
-     * @throws InvalidArgumentException
2373
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2374
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2375
-     */
2376
-    private function _post_payment_processing($payment = null)
2377
-    {
2378
-        // Off-Line payment?
2379
-        if ($payment === true) {
2380
-            //$this->_setup_redirect_for_next_step();
2381
-            return true;
2382
-            // On-Site payment?
2383
-        } else if ($this->checkout->payment_method->is_on_site()) {
2384
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2385
-                //$this->_setup_redirect_for_next_step();
2386
-                $this->checkout->continue_reg = false;
2387
-            }
2388
-            // Off-Site payment?
2389
-        } else if ($this->checkout->payment_method->is_off_site()) {
2390
-            // if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2391
-            if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2392
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2393
-                $this->checkout->redirect      = true;
2394
-                $this->checkout->redirect_form = $payment->redirect_form();
2395
-                $this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2396
-                // set JSON response
2397
-                $this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2398
-                // set cron job for finalizing the TXN
2399
-                // in case the user does not return from the off-site gateway
2400
-                EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
2401
-                    EE_Registry::instance()->SSN->expiration() + 1,
2402
-                    $this->checkout->transaction->ID()
2403
-                );
2404
-                // and lastly, let's bump the payment status to pending
2405
-                $payment->set_status(EEM_Payment::status_id_pending);
2406
-                $payment->save();
2407
-            } else {
2408
-                // not a payment
2409
-                $this->checkout->continue_reg = false;
2410
-                EE_Error::add_error(
2411
-                    sprintf(
2412
-                        esc_html__(
2413
-                            'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2414
-                            'event_espresso'
2415
-                        ),
2416
-                        '<br/>',
2417
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
2418
-                    ),
2419
-                    __FILE__,
2420
-                    __FUNCTION__,
2421
-                    __LINE__
2422
-                );
2423
-            }
2424
-        } else {
2425
-            // ummm ya... not Off-Line, not On-Site, not off-Site ????
2426
-            $this->checkout->continue_reg = false;
2427
-            return false;
2428
-        }
2429
-        return $payment;
2430
-    }
2431
-
2432
-
2433
-    /**
2434
-     *    _process_payment_status
2435
-     *
2436
-     * @access private
2437
-     * @type    EE_Payment $payment
2438
-     * @param string       $payment_occurs
2439
-     * @return bool
2440
-     * @throws EE_Error
2441
-     * @throws InvalidArgumentException
2442
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2443
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2444
-     */
2445
-    private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2446
-    {
2447
-        // off-line payment? carry on
2448
-        if ($payment_occurs === EE_PMT_Base::offline) {
2449
-            return true;
2450
-        }
2451
-        // verify payment validity
2452
-        if ($payment instanceof EE_Payment) {
2453
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2454
-            $msg = $payment->gateway_response();
2455
-            // check results
2456
-            switch ($payment->status()) {
2457
-                // good payment
2458
-                case EEM_Payment::status_id_approved :
2459
-                    EE_Error::add_success(
2460
-                        esc_html__('Your payment was processed successfully.', 'event_espresso'),
2461
-                        __FILE__,
2462
-                        __FUNCTION__,
2463
-                        __LINE__
2464
-                    );
2465
-                    return true;
2466
-                    break;
2467
-                // slow payment
2468
-                case EEM_Payment::status_id_pending :
2469
-                    if (empty($msg)) {
2470
-                        $msg = esc_html__(
2471
-                            'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2472
-                            'event_espresso'
2473
-                        );
2474
-                    }
2475
-                    EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2476
-                    return true;
2477
-                    break;
2478
-                // don't wanna payment
2479
-                case EEM_Payment::status_id_cancelled :
2480
-                    if (empty($msg)) {
2481
-                        $msg = _n(
2482
-                            'Payment cancelled. Please try again.',
2483
-                            'Payment cancelled. Please try again or select another method of payment.',
2484
-                            count($this->checkout->available_payment_methods),
2485
-                            'event_espresso'
2486
-                        );
2487
-                    }
2488
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2489
-                    return false;
2490
-                    break;
2491
-                // not enough payment
2492
-                case EEM_Payment::status_id_declined :
2493
-                    if (empty($msg)) {
2494
-                        $msg = _n(
2495
-                            'We\'re sorry but your payment was declined. Please try again.',
2496
-                            'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2497
-                            count($this->checkout->available_payment_methods),
2498
-                            'event_espresso'
2499
-                        );
2500
-                    }
2501
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2502
-                    return false;
2503
-                    break;
2504
-                // bad payment
2505
-                case EEM_Payment::status_id_failed :
2506
-                    if (! empty($msg)) {
2507
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2508
-                        return false;
2509
-                    }
2510
-                    // default to error below
2511
-                    break;
2512
-            }
2513
-        }
2514
-        // off-site payment gateway responses are too unreliable, so let's just assume that
2515
-        // the payment processing is just running slower than the registrant's request
2516
-        if ($payment_occurs === EE_PMT_Base::offsite) {
2517
-            return true;
2518
-        }
2519
-        EE_Error::add_error(
2520
-            sprintf(
2521
-                esc_html__(
2522
-                    'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2523
-                    'event_espresso'
2524
-                ),
2525
-                '<br/>',
2526
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
2527
-            ),
2528
-            __FILE__,
2529
-            __FUNCTION__,
2530
-            __LINE__
2531
-        );
2532
-        return false;
2533
-    }
2534
-
2535
-
2536
-
2537
-
2538
-
2539
-
2540
-    /********************************************************************************************************/
2541
-    /**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2542
-    /********************************************************************************************************/
2543
-    /**
2544
-     * process_gateway_response
2545
-     * this is the return point for Off-Site Payment Methods
2546
-     * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2547
-     * otherwise, it will load up the last payment made for the TXN.
2548
-     * If the payment retrieved looks good, it will then either:
2549
-     *    complete the current step and allow advancement to the next reg step
2550
-     *        or present the payment options again
2551
-     *
2552
-     * @access private
2553
-     * @return EE_Payment|FALSE
2554
-     * @throws EE_Error
2555
-     * @throws InvalidArgumentException
2556
-     * @throws ReflectionException
2557
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2558
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2559
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2560
-     */
2561
-    public function process_gateway_response()
2562
-    {
2563
-        $payment = null;
2564
-        // how have they chosen to pay?
2565
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2566
-        // get EE_Payment_Method object
2567
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2568
-            $this->checkout->continue_reg = false;
2569
-            return false;
2570
-        }
2571
-        if (! $this->checkout->payment_method->is_off_site()) {
2572
-            return false;
2573
-        }
2574
-        $this->_validate_offsite_return();
2575
-        // DEBUG LOG
2576
-        //$this->checkout->log(
2577
-        //	__CLASS__, __FUNCTION__, __LINE__,
2578
-        //	array(
2579
-        //		'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2580
-        //		'payment_method' => $this->checkout->payment_method,
2581
-        //	),
2582
-        //	true
2583
-        //);
2584
-        // verify TXN
2585
-        if ($this->checkout->transaction instanceof EE_Transaction) {
2586
-            $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2587
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2588
-                $this->checkout->continue_reg = false;
2589
-                return false;
2590
-            }
2591
-            $payment = $this->_process_off_site_payment($gateway);
2592
-            $payment = $this->_process_cancelled_payments($payment);
2593
-            $payment = $this->_validate_payment($payment);
2594
-            // if payment was not declined by the payment gateway or cancelled by the registrant
2595
-            if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2596
-                //$this->_setup_redirect_for_next_step();
2597
-                // store that for later
2598
-                $this->checkout->payment = $payment;
2599
-                // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2600
-                // because we will complete this step during the IPN processing then
2601
-                if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2602
-                    $this->set_completed();
2603
-                }
2604
-                return true;
2605
-            }
2606
-        }
2607
-        // DEBUG LOG
2608
-        //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2609
-        //	array( 'payment' => $payment )
2610
-        //);
2611
-        $this->checkout->continue_reg = false;
2612
-        return false;
2613
-    }
2614
-
2615
-
2616
-    /**
2617
-     * _validate_return
2618
-     *
2619
-     * @access private
2620
-     * @return void
2621
-     * @throws EE_Error
2622
-     * @throws InvalidArgumentException
2623
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2624
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2625
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2626
-     */
2627
-    private function _validate_offsite_return()
2628
-    {
2629
-        $TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2630
-        if ($TXN_ID !== $this->checkout->transaction->ID()) {
2631
-            // Houston... we might have a problem
2632
-            $invalid_TXN = false;
2633
-            // first gather some info
2634
-            $valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2635
-            $primary_registrant = $valid_TXN instanceof EE_Transaction
2636
-                ? $valid_TXN->primary_registration()
2637
-                : null;
2638
-            // let's start by retrieving the cart for this TXN
2639
-            $cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2640
-            if ($cart instanceof EE_Cart) {
2641
-                // verify that the current cart has tickets
2642
-                $tickets = $cart->get_tickets();
2643
-                if (empty($tickets)) {
2644
-                    $invalid_TXN = true;
2645
-                }
2646
-            } else {
2647
-                $invalid_TXN = true;
2648
-            }
2649
-            $valid_TXN_SID = $primary_registrant instanceof EE_Registration
2650
-                ? $primary_registrant->session_ID()
2651
-                : null;
2652
-            // validate current Session ID and compare against valid TXN session ID
2653
-            if (
2654
-                $invalid_TXN // if this is already true, then skip other checks
2655
-                || EE_Session::instance()->id() === null
2656
-                || (
2657
-                    // WARNING !!!
2658
-                    // this could be PayPal sending back duplicate requests (ya they do that)
2659
-                    // or it **could** mean someone is simply registering AGAIN after having just done so
2660
-                    // so now we need to determine if this current TXN looks valid or not
2661
-                    // and whether this reg step has even been started ?
2662
-                    EE_Session::instance()->id() === $valid_TXN_SID
2663
-                    // really? you're half way through this reg step, but you never started it ?
2664
-                    && $this->checkout->transaction->reg_step_completed($this->slug()) === false
2665
-                )
2666
-            ) {
2667
-                $invalid_TXN = true;
2668
-            }
2669
-            if ($invalid_TXN) {
2670
-                // is the valid TXN completed ?
2671
-                if ($valid_TXN instanceof EE_Transaction) {
2672
-                    // has this step even been started ?
2673
-                    $reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2674
-                    if ($reg_step_completed !== false && $reg_step_completed !== true) {
2675
-                        // so it **looks** like this is a double request from PayPal
2676
-                        // so let's try to pick up where we left off
2677
-                        $this->checkout->transaction = $valid_TXN;
2678
-                        $this->checkout->refresh_all_entities(true);
2679
-                        return;
2680
-                    }
2681
-                }
2682
-                // you appear to be lost?
2683
-                $this->_redirect_wayward_request($primary_registrant);
2684
-            }
2685
-        }
2686
-    }
2687
-
2688
-
2689
-    /**
2690
-     * _redirect_wayward_request
2691
-     *
2692
-     * @access private
2693
-     * @param \EE_Registration|null $primary_registrant
2694
-     * @return bool
2695
-     * @throws EE_Error
2696
-     * @throws InvalidArgumentException
2697
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2698
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2699
-     */
2700
-    private function _redirect_wayward_request(EE_Registration $primary_registrant)
2701
-    {
2702
-        if (! $primary_registrant instanceof EE_Registration) {
2703
-            // try redirecting based on the current TXN
2704
-            $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2705
-                ? $this->checkout->transaction->primary_registration()
2706
-                : null;
2707
-        }
2708
-        if (! $primary_registrant instanceof EE_Registration) {
2709
-            EE_Error::add_error(
2710
-                sprintf(
2711
-                    esc_html__(
2712
-                        'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2713
-                        'event_espresso'
2714
-                    ),
2715
-                    '<br/>',
2716
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2717
-                ),
2718
-                __FILE__,
2719
-                __FUNCTION__,
2720
-                __LINE__
2721
-            );
2722
-            return false;
2723
-        }
2724
-        // make sure transaction is not locked
2725
-        $this->checkout->transaction->unlock();
2726
-        wp_safe_redirect(
2727
-            add_query_arg(
2728
-                array(
2729
-                    'e_reg_url_link' => $primary_registrant->reg_url_link(),
2730
-                ),
2731
-                $this->checkout->thank_you_page_url
2732
-            )
2733
-        );
2734
-        exit();
2735
-    }
2736
-
2737
-
2738
-    /**
2739
-     * _process_off_site_payment
2740
-     *
2741
-     * @access private
2742
-     * @param \EE_Offsite_Gateway $gateway
2743
-     * @return EE_Payment
2744
-     * @throws EE_Error
2745
-     * @throws InvalidArgumentException
2746
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2747
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2748
-     */
2749
-    private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2750
-    {
2751
-        try {
2752
-            $request_data = \EE_Registry::instance()->REQ->params();
2753
-            // if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2754
-            $this->set_handle_IPN_in_this_request(
2755
-                $gateway->handle_IPN_in_this_request($request_data, false)
2756
-            );
2757
-            if ($this->handle_IPN_in_this_request()) {
2758
-                // get payment details and process results
2759
-                /** @type EE_Payment_Processor $payment_processor */
2760
-                $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2761
-                $payment           = $payment_processor->process_ipn(
2762
-                    $request_data,
2763
-                    $this->checkout->transaction,
2764
-                    $this->checkout->payment_method,
2765
-                    true,
2766
-                    false
2767
-                );
2768
-                //$payment_source = 'process_ipn';
2769
-            } else {
2770
-                $payment = $this->checkout->transaction->last_payment();
2771
-                //$payment_source = 'last_payment';
2772
-            }
2773
-        } catch (Exception $e) {
2774
-            // let's just eat the exception and try to move on using any previously set payment info
2775
-            $payment = $this->checkout->transaction->last_payment();
2776
-            //$payment_source = 'last_payment after Exception';
2777
-            // but if we STILL don't have a payment object
2778
-            if (! $payment instanceof EE_Payment) {
2779
-                // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2780
-                $this->_handle_payment_processor_exception($e);
2781
-            }
2782
-        }
2783
-        // DEBUG LOG
2784
-        //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2785
-        //	array(
2786
-        //		'process_ipn_payment' => $payment,
2787
-        //		'payment_source'      => $payment_source,
2788
-        //	)
2789
-        //);
2790
-        return $payment;
2791
-    }
2792
-
2793
-
2794
-    /**
2795
-     * _process_cancelled_payments
2796
-     * just makes sure that the payment status gets updated correctly
2797
-     * so tha tan error isn't generated during payment validation
2798
-     *
2799
-     * @access private
2800
-     * @param EE_Payment $payment
2801
-     * @return EE_Payment | FALSE
2802
-     * @throws \EE_Error
2803
-     */
2804
-    private function _process_cancelled_payments($payment = null)
2805
-    {
2806
-        if (
2807
-            $payment instanceof EE_Payment
2808
-            && isset($_REQUEST['ee_cancel_payment'])
2809
-            && $payment->status() === EEM_Payment::status_id_failed
2810
-        ) {
2811
-            $payment->set_status(EEM_Payment::status_id_cancelled);
2812
-        }
2813
-        return $payment;
2814
-    }
2815
-
2816
-
2817
-    /**
2818
-     *    get_transaction_details_for_gateways
2819
-     *
2820
-     * @access    public
2821
-     * @return int
2822
-     * @throws EE_Error
2823
-     * @throws InvalidArgumentException
2824
-     * @throws ReflectionException
2825
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2826
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2827
-     */
2828
-    public function get_transaction_details_for_gateways()
2829
-    {
2830
-        $txn_details = array();
2831
-        // ya gotta make a choice man
2832
-        if (empty($this->checkout->selected_method_of_payment)) {
2833
-            $txn_details = array(
2834
-                'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2835
-            );
2836
-        }
2837
-        // get EE_Payment_Method object
2838
-        if (
2839
-            empty($txn_details)
2840
-            &&
2841
-            ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2842
-        ) {
2843
-            $txn_details = array(
2844
-                'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2845
-                'error'                      => esc_html__(
2846
-                    'A valid Payment Method could not be determined.',
2847
-                    'event_espresso'
2848
-                ),
2849
-            );
2850
-        }
2851
-        if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2852
-            $return_url  = $this->_get_return_url($this->checkout->payment_method);
2853
-            $txn_details = array(
2854
-                'TXN_ID'         => $this->checkout->transaction->ID(),
2855
-                'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2856
-                'TXN_total'      => $this->checkout->transaction->total(),
2857
-                'TXN_paid'       => $this->checkout->transaction->paid(),
2858
-                'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2859
-                'STS_ID'         => $this->checkout->transaction->status_ID(),
2860
-                'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2861
-                'payment_amount' => $this->checkout->amount_owing,
2862
-                'return_url'     => $return_url,
2863
-                'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2864
-                'notify_url'     => EE_Config::instance()->core->txn_page_url(
2865
-                    array(
2866
-                        'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2867
-                        'ee_payment_method' => $this->checkout->payment_method->slug(),
2868
-                    )
2869
-                ),
2870
-            );
2871
-        }
2872
-        echo wp_json_encode($txn_details);
2873
-        exit();
2874
-    }
2875
-
2876
-
2877
-    /**
2878
-     *    __sleep
2879
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2880
-     * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2881
-     * reg form, because if needed, it will be regenerated anyways
2882
-     *
2883
-     * @return array
2884
-     */
2885
-    public function __sleep()
2886
-    {
2887
-        // remove the reg form and the checkout
2888
-        return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2889
-    }
18
+	/**
19
+	 * @access protected
20
+	 * @var EE_Line_Item_Display $Line_Item_Display
21
+	 */
22
+	protected $line_item_display;
23
+
24
+	/**
25
+	 * @access protected
26
+	 * @var boolean $handle_IPN_in_this_request
27
+	 */
28
+	protected $handle_IPN_in_this_request = false;
29
+
30
+
31
+	/**
32
+	 *    set_hooks - for hooking into EE Core, other modules, etc
33
+	 *
34
+	 * @access    public
35
+	 * @return    void
36
+	 */
37
+	public static function set_hooks()
38
+	{
39
+		add_filter(
40
+			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
+			array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42
+		);
43
+		add_action(
44
+			'wp_ajax_switch_spco_billing_form',
45
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46
+		);
47
+		add_action(
48
+			'wp_ajax_nopriv_switch_spco_billing_form',
49
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50
+		);
51
+		add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52
+		add_action(
53
+			'wp_ajax_nopriv_save_payer_details',
54
+			array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55
+		);
56
+		add_action(
57
+			'wp_ajax_get_transaction_details_for_gateways',
58
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59
+		);
60
+		add_action(
61
+			'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63
+		);
64
+		add_filter(
65
+			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
+			array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67
+			10,
68
+			1
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 *    ajax switch_spco_billing_form
75
+	 *
76
+	 * @throws \EE_Error
77
+	 */
78
+	public static function switch_spco_billing_form()
79
+	{
80
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81
+	}
82
+
83
+
84
+	/**
85
+	 *    ajax save_payer_details
86
+	 *
87
+	 * @throws \EE_Error
88
+	 */
89
+	public static function save_payer_details()
90
+	{
91
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92
+	}
93
+
94
+
95
+	/**
96
+	 *    ajax get_transaction_details
97
+	 *
98
+	 * @throws \EE_Error
99
+	 */
100
+	public static function get_transaction_details()
101
+	{
102
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
+	}
104
+
105
+
106
+	/**
107
+	 * bypass_recaptcha_for_load_payment_method
108
+	 *
109
+	 * @access public
110
+	 * @return array
111
+	 * @throws InvalidArgumentException
112
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
113
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
114
+	 */
115
+	public static function bypass_recaptcha_for_load_payment_method()
116
+	{
117
+		return array(
118
+			'EESID'  => EE_Registry::instance()->SSN->id(),
119
+			'step'   => 'payment_options',
120
+			'action' => 'spco_billing_form',
121
+		);
122
+	}
123
+
124
+
125
+	/**
126
+	 *    class constructor
127
+	 *
128
+	 * @access    public
129
+	 * @param    EE_Checkout $checkout
130
+	 */
131
+	public function __construct(EE_Checkout $checkout)
132
+	{
133
+		$this->_slug     = 'payment_options';
134
+		$this->_name     = esc_html__('Payment Options', 'event_espresso');
135
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
136
+		$this->checkout  = $checkout;
137
+		$this->_reset_success_message();
138
+		$this->set_instructions(
139
+			esc_html__(
140
+				'Please select a method of payment and provide any necessary billing information before proceeding.',
141
+				'event_espresso'
142
+			)
143
+		);
144
+	}
145
+
146
+
147
+	/**
148
+	 * @return null
149
+	 */
150
+	public function line_item_display()
151
+	{
152
+		return $this->line_item_display;
153
+	}
154
+
155
+
156
+	/**
157
+	 * @param null $line_item_display
158
+	 */
159
+	public function set_line_item_display($line_item_display)
160
+	{
161
+		$this->line_item_display = $line_item_display;
162
+	}
163
+
164
+
165
+	/**
166
+	 * @return boolean
167
+	 */
168
+	public function handle_IPN_in_this_request()
169
+	{
170
+		return $this->handle_IPN_in_this_request;
171
+	}
172
+
173
+
174
+	/**
175
+	 * @param boolean $handle_IPN_in_this_request
176
+	 */
177
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
178
+	{
179
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
180
+	}
181
+
182
+
183
+	/**
184
+	 * translate_js_strings
185
+	 *
186
+	 * @return void
187
+	 */
188
+	public function translate_js_strings()
189
+	{
190
+		EE_Registry::$i18n_js_strings['no_payment_method']      = esc_html__(
191
+			'Please select a method of payment in order to continue.',
192
+			'event_espresso'
193
+		);
194
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = esc_html__(
195
+			'A valid method of payment could not be determined. Please refresh the page and try again.',
196
+			'event_espresso'
197
+		);
198
+		EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = esc_html__(
199
+			'Forwarding to Secure Payment Provider.',
200
+			'event_espresso'
201
+		);
202
+	}
203
+
204
+
205
+	/**
206
+	 * enqueue_styles_and_scripts
207
+	 *
208
+	 * @return void
209
+	 * @throws EE_Error
210
+	 * @throws InvalidArgumentException
211
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
212
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
213
+	 */
214
+	public function enqueue_styles_and_scripts()
215
+	{
216
+		$transaction = $this->checkout->transaction;
217
+		//if the transaction isn't set or nothing is owed on it, don't enqueue any JS
218
+		if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
219
+			return;
220
+		}
221
+		foreach (EEM_Payment_Method::instance()->get_all_for_transaction($transaction, EEM_Payment_Method::scope_cart) as $payment_method) {
222
+			$type_obj = $payment_method->type_obj();
223
+			if ($type_obj instanceof EE_PMT_Base) {
224
+				$billing_form = $type_obj->generate_new_billing_form($transaction);
225
+				if ($billing_form instanceof EE_Form_Section_Proper) {
226
+					$billing_form->enqueue_js();
227
+				}
228
+			}
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 * initialize_reg_step
235
+	 *
236
+	 * @return bool
237
+	 * @throws EE_Error
238
+	 * @throws InvalidArgumentException
239
+	 * @throws ReflectionException
240
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
241
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
242
+	 */
243
+	public function initialize_reg_step()
244
+	{
245
+		// TODO: if /when we implement donations, then this will need overriding
246
+		if (// don't need payment options for:
247
+			// 	registrations made via the admin
248
+			// 	completed transactions
249
+			// 	overpaid transactions
250
+			// 	$ 0.00 transactions (no payment required)
251
+			! $this->checkout->payment_required()
252
+			// but do NOT remove if current action being called belongs to this reg step
253
+			&& ! is_callable(array($this, $this->checkout->action))
254
+			&& ! $this->completed()
255
+		) {
256
+			// and if so, then we no longer need the Payment Options step
257
+			if ($this->is_current_step()) {
258
+				$this->checkout->generate_reg_form = false;
259
+			}
260
+			$this->checkout->remove_reg_step($this->_slug);
261
+			// DEBUG LOG
262
+			//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
263
+			return false;
264
+		}
265
+		// load EEM_Payment_Method
266
+		EE_Registry::instance()->load_model('Payment_Method');
267
+		// get all active payment methods
268
+		$this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
269
+			$this->checkout->transaction,
270
+			EEM_Payment_Method::scope_cart
271
+		);
272
+		return true;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @return EE_Form_Section_Proper
278
+	 * @throws EE_Error
279
+	 * @throws InvalidArgumentException
280
+	 * @throws ReflectionException
281
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
282
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
283
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
284
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
285
+	 */
286
+	public function generate_reg_form()
287
+	{
288
+		// reset in case someone changes their mind
289
+		$this->_reset_selected_method_of_payment();
290
+		// set some defaults
291
+		$this->checkout->selected_method_of_payment = 'payments_closed';
292
+		$registrations_requiring_payment            = array();
293
+		$registrations_for_free_events              = array();
294
+		$registrations_requiring_pre_approval       = array();
295
+		$sold_out_events                            = array();
296
+		$insufficient_spaces_available              = array();
297
+		$no_payment_required                        = true;
298
+		// loop thru registrations to gather info
299
+		$registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
300
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
301
+			$registrations,
302
+			$this->checkout->revisit
303
+		);
304
+		foreach ($registrations as $REG_ID => $registration) {
305
+			/** @var $registration EE_Registration */
306
+			// has this registration lost it's space ?
307
+			if (isset($ejected_registrations[$REG_ID])) {
308
+				$insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
309
+				continue;
310
+			}
311
+			// event requires admin approval
312
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
313
+				// add event to list of events with pre-approval reg status
314
+				$registrations_requiring_pre_approval[$REG_ID] = $registration;
315
+				do_action(
316
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
317
+					$registration->event(),
318
+					$this
319
+				);
320
+				continue;
321
+			}
322
+			if ($this->checkout->revisit
323
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
324
+				&& (
325
+					$registration->event()->is_sold_out()
326
+					|| $registration->event()->is_sold_out(true)
327
+				)
328
+			) {
329
+				// add event to list of events that are sold out
330
+				$sold_out_events[$registration->event()->ID()] = $registration->event();
331
+				do_action(
332
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
333
+					$registration->event(),
334
+					$this
335
+				);
336
+				continue;
337
+			}
338
+			// are they allowed to pay now and is there monies owing?
339
+			if ($registration->owes_monies_and_can_pay()) {
340
+				$registrations_requiring_payment[$REG_ID] = $registration;
341
+				do_action(
342
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
343
+					$registration->event(),
344
+					$this
345
+				);
346
+			} elseif (! $this->checkout->revisit
347
+				&& $registration->status_ID() !== EEM_Registration::status_id_not_approved
348
+				&& $registration->ticket()->is_free()
349
+			) {
350
+				$registrations_for_free_events[$registration->event()->ID()] = $registration;
351
+			}
352
+		}
353
+		$subsections = array();
354
+		// now decide which template to load
355
+		if (! empty($sold_out_events)) {
356
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
357
+		}
358
+		if (! empty($insufficient_spaces_available)) {
359
+			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
360
+				$insufficient_spaces_available
361
+			);
362
+		}
363
+		if (! empty($registrations_requiring_pre_approval)) {
364
+			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
365
+				$registrations_requiring_pre_approval
366
+			);
367
+		}
368
+		if (! empty($registrations_for_free_events)) {
369
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
370
+		}
371
+		if (! empty($registrations_requiring_payment)) {
372
+			if ($this->checkout->amount_owing > 0) {
373
+				// autoload Line_Item_Display classes
374
+				EEH_Autoloader::register_line_item_filter_autoloaders();
375
+				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
376
+					apply_filters(
377
+						'FHEE__SPCO__EE_Line_Item_Filter_Collection',
378
+						new EE_Line_Item_Filter_Collection()
379
+					),
380
+					$this->checkout->cart->get_grand_total()
381
+				);
382
+				/** @var EE_Line_Item $filtered_line_item_tree */
383
+				$filtered_line_item_tree = $line_item_filter_processor->process();
384
+				EEH_Autoloader::register_line_item_display_autoloaders();
385
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
386
+				$subsections['payment_options'] = $this->_display_payment_options(
387
+					$this->line_item_display->display_line_item(
388
+						$filtered_line_item_tree,
389
+						array('registrations' => $registrations)
390
+					)
391
+				);
392
+				$this->checkout->amount_owing   = $filtered_line_item_tree->total();
393
+				$this->_apply_registration_payments_to_amount_owing($registrations);
394
+			}
395
+			$no_payment_required = false;
396
+		} else {
397
+			$this->_hide_reg_step_submit_button_if_revisit();
398
+		}
399
+		$this->_save_selected_method_of_payment();
400
+
401
+		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
402
+		$subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
403
+
404
+		return new EE_Form_Section_Proper(
405
+			array(
406
+				'name'            => $this->reg_form_name(),
407
+				'html_id'         => $this->reg_form_name(),
408
+				'subsections'     => $subsections,
409
+				'layout_strategy' => new EE_No_Layout(),
410
+			)
411
+		);
412
+	}
413
+
414
+
415
+	/**
416
+	 * add line item filters required for this reg step
417
+	 * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
418
+	 *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
419
+	 *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
420
+	 *        payment options reg step, can apply these filters via the following: apply_filters(
421
+	 *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
422
+	 *        filter collection by passing that instead of instantiating a new collection
423
+	 *
424
+	 * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
425
+	 * @return EE_Line_Item_Filter_Collection
426
+	 * @throws EE_Error
427
+	 * @throws InvalidArgumentException
428
+	 * @throws ReflectionException
429
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
430
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
431
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
432
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
433
+	 */
434
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
435
+	{
436
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
437
+			return $line_item_filter_collection;
438
+		}
439
+		if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
440
+			return $line_item_filter_collection;
441
+		}
442
+		if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
443
+			return $line_item_filter_collection;
444
+		}
445
+		$line_item_filter_collection->add(
446
+			new EE_Billable_Line_Item_Filter(
447
+				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
448
+					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
449
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
450
+					)
451
+				)
452
+			)
453
+		);
454
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
455
+		return $line_item_filter_collection;
456
+	}
457
+
458
+
459
+	/**
460
+	 * remove_ejected_registrations
461
+	 * if a registrant has lost their potential space at an event due to lack of payment,
462
+	 * then this method removes them from the list of registrations being paid for during this request
463
+	 *
464
+	 * @param \EE_Registration[] $registrations
465
+	 * @return EE_Registration[]
466
+	 * @throws EE_Error
467
+	 * @throws InvalidArgumentException
468
+	 * @throws ReflectionException
469
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
470
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
471
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
472
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
473
+	 */
474
+	public static function remove_ejected_registrations(array $registrations)
475
+	{
476
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
477
+			$registrations,
478
+			EE_Registry::instance()->SSN->checkout()->revisit
479
+		);
480
+		foreach ($registrations as $REG_ID => $registration) {
481
+			// has this registration lost it's space ?
482
+			if (isset($ejected_registrations[$REG_ID])) {
483
+				unset($registrations[$REG_ID]);
484
+				continue;
485
+			}
486
+		}
487
+		return $registrations;
488
+	}
489
+
490
+
491
+	/**
492
+	 * find_registrations_that_lost_their_space
493
+	 * If a registrant chooses an offline payment method like Invoice,
494
+	 * then no space is reserved for them at the event until they fully pay fo that site
495
+	 * (unless the event's default reg status is set to APPROVED)
496
+	 * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
497
+	 * then this method will determine which registrations have lost the ability to complete the reg process.
498
+	 *
499
+	 * @param \EE_Registration[] $registrations
500
+	 * @param bool               $revisit
501
+	 * @return array
502
+	 * @throws EE_Error
503
+	 * @throws InvalidArgumentException
504
+	 * @throws ReflectionException
505
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
506
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
507
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
508
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
509
+	 */
510
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
511
+	{
512
+		// registrations per event
513
+		$event_reg_count = array();
514
+		// spaces left per event
515
+		$event_spaces_remaining = array();
516
+		// tickets left sorted by ID
517
+		$tickets_remaining = array();
518
+		// registrations that have lost their space
519
+		$ejected_registrations = array();
520
+		foreach ($registrations as $REG_ID => $registration) {
521
+			if ($registration->status_ID() === EEM_Registration::status_id_approved
522
+				|| apply_filters(
523
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
524
+					false,
525
+					$registration,
526
+					$revisit
527
+				)
528
+			) {
529
+				continue;
530
+			}
531
+			$EVT_ID = $registration->event_ID();
532
+			$ticket = $registration->ticket();
533
+			if (! isset($tickets_remaining[$ticket->ID()])) {
534
+				$tickets_remaining[$ticket->ID()] = $ticket->remaining();
535
+			}
536
+			if ($tickets_remaining[$ticket->ID()] > 0) {
537
+				if (! isset($event_reg_count[$EVT_ID])) {
538
+					$event_reg_count[$EVT_ID] = 0;
539
+				}
540
+				$event_reg_count[$EVT_ID]++;
541
+				if (! isset($event_spaces_remaining[$EVT_ID])) {
542
+					$event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
543
+				}
544
+			}
545
+			if ($revisit
546
+				&& ($tickets_remaining[$ticket->ID()] === 0
547
+					|| $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
548
+				)
549
+			) {
550
+				$ejected_registrations[$REG_ID] = $registration->event();
551
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
552
+					/** @type EE_Registration_Processor $registration_processor */
553
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
554
+					// at this point, we should have enough details about the registrant to consider the registration
555
+					// NOT incomplete
556
+					$registration_processor->manually_update_registration_status(
557
+						$registration,
558
+						EEM_Registration::status_id_wait_list
559
+					);
560
+				}
561
+			}
562
+		}
563
+		return $ejected_registrations;
564
+	}
565
+
566
+
567
+	/**
568
+	 * _hide_reg_step_submit_button
569
+	 * removes the html for the reg step submit button
570
+	 * by replacing it with an empty string via filter callback
571
+	 *
572
+	 * @return void
573
+	 */
574
+	protected function _adjust_registration_status_if_event_old_sold()
575
+	{
576
+	}
577
+
578
+
579
+	/**
580
+	 * _hide_reg_step_submit_button
581
+	 * removes the html for the reg step submit button
582
+	 * by replacing it with an empty string via filter callback
583
+	 *
584
+	 * @return void
585
+	 */
586
+	protected function _hide_reg_step_submit_button_if_revisit()
587
+	{
588
+		if ($this->checkout->revisit) {
589
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
590
+		}
591
+	}
592
+
593
+
594
+	/**
595
+	 * sold_out_events
596
+	 * displays notices regarding events that have sold out since hte registrant first signed up
597
+	 *
598
+	 * @param \EE_Event[] $sold_out_events_array
599
+	 * @return \EE_Form_Section_Proper
600
+	 * @throws \EE_Error
601
+	 */
602
+	private function _sold_out_events($sold_out_events_array = array())
603
+	{
604
+		// set some defaults
605
+		$this->checkout->selected_method_of_payment = 'events_sold_out';
606
+		$sold_out_events                            = '';
607
+		foreach ($sold_out_events_array as $sold_out_event) {
608
+			$sold_out_events .= EEH_HTML::li(
609
+				EEH_HTML::span(
610
+					'  ' . $sold_out_event->name(),
611
+					'',
612
+					'dashicons dashicons-marker ee-icon-size-16 pink-text'
613
+				)
614
+			);
615
+		}
616
+		return new EE_Form_Section_Proper(
617
+			array(
618
+				'layout_strategy' => new EE_Template_Layout(
619
+					array(
620
+						'layout_template_file' => SPCO_REG_STEPS_PATH
621
+												  . $this->_slug
622
+												  . DS
623
+												  . 'sold_out_events.template.php',
624
+						'template_args'        => apply_filters(
625
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
626
+							array(
627
+								'sold_out_events'     => $sold_out_events,
628
+								'sold_out_events_msg' => apply_filters(
629
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
630
+									sprintf(
631
+										esc_html__(
632
+											'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
633
+											'event_espresso'
634
+										),
635
+										'<strong>',
636
+										'</strong>',
637
+										'<br />'
638
+									)
639
+								),
640
+							)
641
+						),
642
+					)
643
+				),
644
+			)
645
+		);
646
+	}
647
+
648
+
649
+	/**
650
+	 * _insufficient_spaces_available
651
+	 * displays notices regarding events that do not have enough remaining spaces
652
+	 * to satisfy the current number of registrations looking to pay
653
+	 *
654
+	 * @param \EE_Event[] $insufficient_spaces_events_array
655
+	 * @return \EE_Form_Section_Proper
656
+	 * @throws \EE_Error
657
+	 */
658
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
659
+	{
660
+		// set some defaults
661
+		$this->checkout->selected_method_of_payment = 'invoice';
662
+		$insufficient_space_events                  = '';
663
+		foreach ($insufficient_spaces_events_array as $event) {
664
+			if ($event instanceof EE_Event) {
665
+				$insufficient_space_events .= EEH_HTML::li(
666
+					EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
667
+				);
668
+			}
669
+		}
670
+		return new EE_Form_Section_Proper(
671
+			array(
672
+				'subsections'     => array(
673
+					'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
674
+					'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
675
+				),
676
+				'layout_strategy' => new EE_Template_Layout(
677
+					array(
678
+						'layout_template_file' => SPCO_REG_STEPS_PATH
679
+												  . $this->_slug
680
+												  . DS
681
+												  . 'sold_out_events.template.php',
682
+						'template_args'        => apply_filters(
683
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
684
+							array(
685
+								'sold_out_events'     => $insufficient_space_events,
686
+								'sold_out_events_msg' => apply_filters(
687
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
688
+									esc_html__(
689
+										'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
690
+										'event_espresso'
691
+									)
692
+								),
693
+							)
694
+						),
695
+					)
696
+				),
697
+			)
698
+		);
699
+	}
700
+
701
+
702
+	/**
703
+	 * registrations_requiring_pre_approval
704
+	 *
705
+	 * @param array $registrations_requiring_pre_approval
706
+	 * @return EE_Form_Section_Proper
707
+	 * @throws EE_Error
708
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
709
+	 */
710
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
711
+	{
712
+		$events_requiring_pre_approval = '';
713
+		foreach ($registrations_requiring_pre_approval as $registration) {
714
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
715
+				$events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
716
+					EEH_HTML::span(
717
+						'',
718
+						'',
719
+						'dashicons dashicons-marker ee-icon-size-16 orange-text'
720
+					)
721
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
722
+				);
723
+			}
724
+		}
725
+		return new EE_Form_Section_Proper(
726
+			array(
727
+				'layout_strategy' => new EE_Template_Layout(
728
+					array(
729
+						'layout_template_file' => SPCO_REG_STEPS_PATH
730
+												  . $this->_slug
731
+												  . DS
732
+												  . 'events_requiring_pre_approval.template.php', // layout_template
733
+						'template_args'        => apply_filters(
734
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
735
+							array(
736
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
737
+								'events_requiring_pre_approval_msg' => apply_filters(
738
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
739
+									esc_html__(
740
+										'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has 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.',
741
+										'event_espresso'
742
+									)
743
+								),
744
+							)
745
+						),
746
+					)
747
+				),
748
+			)
749
+		);
750
+	}
751
+
752
+
753
+	/**
754
+	 * _no_payment_required
755
+	 *
756
+	 * @param \EE_Event[] $registrations_for_free_events
757
+	 * @return \EE_Form_Section_Proper
758
+	 * @throws \EE_Error
759
+	 */
760
+	private function _no_payment_required($registrations_for_free_events = array())
761
+	{
762
+		// set some defaults
763
+		$this->checkout->selected_method_of_payment = 'no_payment_required';
764
+		// generate no_payment_required form
765
+		return new EE_Form_Section_Proper(
766
+			array(
767
+				'layout_strategy' => new EE_Template_Layout(
768
+					array(
769
+						'layout_template_file' => SPCO_REG_STEPS_PATH
770
+												  . $this->_slug
771
+												  . DS
772
+												  . 'no_payment_required.template.php', // layout_template
773
+						'template_args'        => apply_filters(
774
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
775
+							array(
776
+								'revisit'                       => $this->checkout->revisit,
777
+								'registrations'                 => array(),
778
+								'ticket_count'                  => array(),
779
+								'registrations_for_free_events' => $registrations_for_free_events,
780
+								'no_payment_required_msg'       => EEH_HTML::p(
781
+									esc_html__('This is a free event, so no billing will occur.', 'event_espresso')
782
+								),
783
+							)
784
+						),
785
+					)
786
+				),
787
+			)
788
+		);
789
+	}
790
+
791
+
792
+	/**
793
+	 * _display_payment_options
794
+	 *
795
+	 * @param string $transaction_details
796
+	 * @return EE_Form_Section_Proper
797
+	 * @throws EE_Error
798
+	 * @throws InvalidArgumentException
799
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
800
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
801
+	 */
802
+	private function _display_payment_options($transaction_details = '')
803
+	{
804
+		// has method_of_payment been set by no-js user?
805
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
806
+		// build payment options form
807
+		return apply_filters(
808
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
809
+			new EE_Form_Section_Proper(
810
+				array(
811
+					'subsections'     => array(
812
+						'before_payment_options' => apply_filters(
813
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
814
+							new EE_Form_Section_Proper(
815
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
816
+							)
817
+						),
818
+						'payment_options'        => $this->_setup_payment_options(),
819
+						'after_payment_options'  => apply_filters(
820
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
821
+							new EE_Form_Section_Proper(
822
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
823
+							)
824
+						),
825
+					),
826
+					'layout_strategy' => new EE_Template_Layout(
827
+						array(
828
+							'layout_template_file' => $this->_template,
829
+							'template_args'        => apply_filters(
830
+								'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
831
+								array(
832
+									'reg_count'                 => $this->line_item_display->total_items(),
833
+									'transaction_details'       => $transaction_details,
834
+									'available_payment_methods' => array(),
835
+								)
836
+							),
837
+						)
838
+					),
839
+				)
840
+			)
841
+		);
842
+	}
843
+
844
+
845
+	/**
846
+	 * _extra_hidden_inputs
847
+	 *
848
+	 * @param bool $no_payment_required
849
+	 * @return \EE_Form_Section_Proper
850
+	 * @throws \EE_Error
851
+	 */
852
+	private function _extra_hidden_inputs($no_payment_required = true)
853
+	{
854
+		return new EE_Form_Section_Proper(
855
+			array(
856
+				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
857
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
858
+				'subsections'     => array(
859
+					'spco_no_payment_required' => new EE_Hidden_Input(
860
+						array(
861
+							'normalization_strategy' => new EE_Boolean_Normalization(),
862
+							'html_name'              => 'spco_no_payment_required',
863
+							'html_id'                => 'spco-no-payment-required-payment_options',
864
+							'default'                => $no_payment_required,
865
+						)
866
+					),
867
+					'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
868
+						array(
869
+							'normalization_strategy' => new EE_Int_Normalization(),
870
+							'html_name'              => 'spco_transaction_id',
871
+							'html_id'                => 'spco-transaction-id',
872
+							'default'                => $this->checkout->transaction->ID(),
873
+						)
874
+					),
875
+				),
876
+			)
877
+		);
878
+	}
879
+
880
+
881
+	/**
882
+	 *    _apply_registration_payments_to_amount_owing
883
+	 *
884
+	 * @access protected
885
+	 * @param array $registrations
886
+	 * @throws EE_Error
887
+	 */
888
+	protected function _apply_registration_payments_to_amount_owing(array $registrations)
889
+	{
890
+		$payments = array();
891
+		foreach ($registrations as $registration) {
892
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
893
+				$payments += $registration->registration_payments();
894
+			}
895
+		}
896
+		if (! empty($payments)) {
897
+			foreach ($payments as $payment) {
898
+				if ($payment instanceof EE_Registration_Payment) {
899
+					$this->checkout->amount_owing -= $payment->amount();
900
+				}
901
+			}
902
+		}
903
+	}
904
+
905
+
906
+	/**
907
+	 *    _reset_selected_method_of_payment
908
+	 *
909
+	 * @access    private
910
+	 * @param    bool $force_reset
911
+	 * @return void
912
+	 * @throws InvalidArgumentException
913
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
914
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
915
+	 */
916
+	private function _reset_selected_method_of_payment($force_reset = false)
917
+	{
918
+		$reset_payment_method = $force_reset
919
+			? true
920
+			: sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
921
+		if ($reset_payment_method) {
922
+			$this->checkout->selected_method_of_payment = null;
923
+			$this->checkout->payment_method             = null;
924
+			$this->checkout->billing_form               = null;
925
+			$this->_save_selected_method_of_payment();
926
+		}
927
+	}
928
+
929
+
930
+	/**
931
+	 * _save_selected_method_of_payment
932
+	 * stores the selected_method_of_payment in the session
933
+	 * so that it's available for all subsequent requests including AJAX
934
+	 *
935
+	 * @access        private
936
+	 * @param string $selected_method_of_payment
937
+	 * @return void
938
+	 * @throws InvalidArgumentException
939
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
940
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
941
+	 */
942
+	private function _save_selected_method_of_payment($selected_method_of_payment = '')
943
+	{
944
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
945
+			? $selected_method_of_payment
946
+			: $this->checkout->selected_method_of_payment;
947
+		EE_Registry::instance()->SSN->set_session_data(
948
+			array('selected_method_of_payment' => $selected_method_of_payment)
949
+		);
950
+	}
951
+
952
+
953
+	/**
954
+	 * _setup_payment_options
955
+	 *
956
+	 * @return EE_Form_Section_Proper
957
+	 * @throws EE_Error
958
+	 * @throws InvalidArgumentException
959
+	 * @throws ReflectionException
960
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
961
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
962
+	 */
963
+	public function _setup_payment_options()
964
+	{
965
+		// load payment method classes
966
+		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
967
+		if (empty($this->checkout->available_payment_methods)) {
968
+			EE_Error::add_error(
969
+				apply_filters(
970
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options___setup_payment_options__error_message_no_payment_methods',
971
+					sprintf(
972
+						esc_html__(
973
+							'Sorry, you cannot complete your purchase because a payment method is not active.%1$s Please contact %2$s for assistance and provide a description of the problem.',
974
+							'event_espresso'
975
+						),
976
+						'<br>',
977
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
978
+					)
979
+				),
980
+				__FILE__,
981
+				__FUNCTION__,
982
+				__LINE__
983
+			);
984
+		}
985
+		// switch up header depending on number of available payment methods
986
+		$payment_method_header     = count($this->checkout->available_payment_methods) > 1
987
+			? apply_filters(
988
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
989
+				esc_html__('Please Select Your Method of Payment', 'event_espresso')
990
+			)
991
+			: apply_filters(
992
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
993
+				esc_html__('Method of Payment', 'event_espresso')
994
+			);
995
+		$available_payment_methods = array(
996
+			// display the "Payment Method" header
997
+			'payment_method_header' => new EE_Form_Section_HTML(
998
+				EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
999
+			),
1000
+		);
1001
+		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
1002
+		$available_payment_method_options = array();
1003
+		$default_payment_method_option    = array();
1004
+		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
1005
+		$payment_methods_billing_info = array(
1006
+			new EE_Form_Section_HTML(
1007
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
1008
+			),
1009
+		);
1010
+		// loop through payment methods
1011
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
1012
+			if ($payment_method instanceof EE_Payment_Method) {
1013
+				$payment_method_button = EEH_HTML::img(
1014
+					$payment_method->button_url(),
1015
+					$payment_method->name(),
1016
+					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
1017
+					'spco-payment-method-btn-img'
1018
+				);
1019
+				// check if any payment methods are set as default
1020
+				// if payment method is already selected OR nothing is selected and this payment method should be
1021
+				// open_by_default
1022
+				if (($this->checkout->selected_method_of_payment === $payment_method->slug())
1023
+					|| (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
1024
+				) {
1025
+					$this->checkout->selected_method_of_payment = $payment_method->slug();
1026
+					$this->_save_selected_method_of_payment();
1027
+					$default_payment_method_option[$payment_method->slug()] = $payment_method_button;
1028
+				} else {
1029
+					$available_payment_method_options[$payment_method->slug()] = $payment_method_button;
1030
+				}
1031
+				$payment_methods_billing_info[$payment_method->slug() . '-info'] = $this->_payment_method_billing_info(
1032
+					$payment_method
1033
+				);
1034
+			}
1035
+		}
1036
+		// prepend available_payment_method_options with default_payment_method_option so that it appears first in list
1037
+		// of PMs
1038
+		$available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
1039
+		// now generate the actual form  inputs
1040
+		$available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
1041
+			$available_payment_method_options
1042
+		);
1043
+		$available_payment_methods                              += $payment_methods_billing_info;
1044
+		// build the available payment methods form
1045
+		return new EE_Form_Section_Proper(
1046
+			array(
1047
+				'html_id'         => 'spco-available-methods-of-payment-dv',
1048
+				'subsections'     => $available_payment_methods,
1049
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1050
+			)
1051
+		);
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * _get_available_payment_methods
1057
+	 *
1058
+	 * @return EE_Payment_Method[]
1059
+	 * @throws EE_Error
1060
+	 * @throws InvalidArgumentException
1061
+	 * @throws ReflectionException
1062
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1063
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1064
+	 */
1065
+	protected function _get_available_payment_methods()
1066
+	{
1067
+		if (! empty($this->checkout->available_payment_methods)) {
1068
+			return $this->checkout->available_payment_methods;
1069
+		}
1070
+		$available_payment_methods = array();
1071
+		// load EEM_Payment_Method
1072
+		EE_Registry::instance()->load_model('Payment_Method');
1073
+		/** @type EEM_Payment_Method $EEM_Payment_Method */
1074
+		$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1075
+		// get all active payment methods
1076
+		$payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1077
+			$this->checkout->transaction,
1078
+			EEM_Payment_Method::scope_cart
1079
+		);
1080
+		foreach ($payment_methods as $payment_method) {
1081
+			if ($payment_method instanceof EE_Payment_Method) {
1082
+				$available_payment_methods[$payment_method->slug()] = $payment_method;
1083
+			}
1084
+		}
1085
+		return $available_payment_methods;
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 *    _available_payment_method_inputs
1091
+	 *
1092
+	 * @access    private
1093
+	 * @param    array $available_payment_method_options
1094
+	 * @return    \EE_Form_Section_Proper
1095
+	 */
1096
+	private function _available_payment_method_inputs($available_payment_method_options = array())
1097
+	{
1098
+		// generate inputs
1099
+		return new EE_Form_Section_Proper(
1100
+			array(
1101
+				'html_id'         => 'ee-available-payment-method-inputs',
1102
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1103
+				'subsections'     => array(
1104
+					'' => new EE_Radio_Button_Input(
1105
+						$available_payment_method_options,
1106
+						array(
1107
+							'html_name'          => 'selected_method_of_payment',
1108
+							'html_class'         => 'spco-payment-method',
1109
+							'default'            => $this->checkout->selected_method_of_payment,
1110
+							'label_size'         => 11,
1111
+							'enforce_label_size' => true,
1112
+						)
1113
+					),
1114
+				),
1115
+			)
1116
+		);
1117
+	}
1118
+
1119
+
1120
+	/**
1121
+	 *    _payment_method_billing_info
1122
+	 *
1123
+	 * @access    private
1124
+	 * @param    EE_Payment_Method $payment_method
1125
+	 * @return EE_Form_Section_Proper
1126
+	 * @throws EE_Error
1127
+	 * @throws InvalidArgumentException
1128
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1129
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1130
+	 */
1131
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1132
+	{
1133
+		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1134
+			? true
1135
+			: false;
1136
+		// generate the billing form for payment method
1137
+		$billing_form                 = $currently_selected
1138
+			? $this->_get_billing_form_for_payment_method($payment_method)
1139
+			: new EE_Form_Section_HTML();
1140
+		$this->checkout->billing_form = $currently_selected
1141
+			? $billing_form
1142
+			: $this->checkout->billing_form;
1143
+		// it's all in the details
1144
+		$info_html = EEH_HTML::h3(
1145
+			esc_html__('Important information regarding your payment', 'event_espresso'),
1146
+			'',
1147
+			'spco-payment-method-hdr'
1148
+		);
1149
+		// add some info regarding the step, either from what's saved in the admin,
1150
+		// or a default string depending on whether the PM has a billing form or not
1151
+		if ($payment_method->description()) {
1152
+			$payment_method_info = $payment_method->description();
1153
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1154
+			$payment_method_info = sprintf(
1155
+				esc_html__(
1156
+					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1157
+					'event_espresso'
1158
+				),
1159
+				$this->submit_button_text()
1160
+			);
1161
+		} else {
1162
+			$payment_method_info = sprintf(
1163
+				esc_html__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1164
+				$this->submit_button_text()
1165
+			);
1166
+		}
1167
+		$info_html .= EEH_HTML::p(
1168
+			apply_filters(
1169
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1170
+				$payment_method_info
1171
+			),
1172
+			'',
1173
+			'spco-payment-method-desc ee-attention'
1174
+		);
1175
+		return new EE_Form_Section_Proper(
1176
+			array(
1177
+				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1178
+				'html_class'      => 'spco-payment-method-info-dv',
1179
+				// only display the selected or default PM
1180
+				'html_style'      => $currently_selected ? '' : 'display:none;',
1181
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1182
+				'subsections'     => array(
1183
+					'info'         => new EE_Form_Section_HTML($info_html),
1184
+					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1185
+				),
1186
+			)
1187
+		);
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * get_billing_form_html_for_payment_method
1193
+	 *
1194
+	 * @access public
1195
+	 * @return string
1196
+	 * @throws EE_Error
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws ReflectionException
1199
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1200
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1201
+	 */
1202
+	public function get_billing_form_html_for_payment_method()
1203
+	{
1204
+		// how have they chosen to pay?
1205
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1206
+		$this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1207
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1208
+			return false;
1209
+		}
1210
+		if (apply_filters(
1211
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1212
+			false
1213
+		)) {
1214
+			EE_Error::add_success(
1215
+				apply_filters(
1216
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1217
+					sprintf(
1218
+						esc_html__(
1219
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1220
+							'event_espresso'
1221
+						),
1222
+						$this->checkout->payment_method->name()
1223
+					)
1224
+				)
1225
+			);
1226
+		}
1227
+		// now generate billing form for selected method of payment
1228
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1229
+		// fill form with attendee info if applicable
1230
+		if ($payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1231
+			&& $this->checkout->transaction_has_primary_registrant()
1232
+		) {
1233
+			$payment_method_billing_form->populate_from_attendee(
1234
+				$this->checkout->transaction->primary_registration()->attendee()
1235
+			);
1236
+		}
1237
+		// and debug content
1238
+		if ($payment_method_billing_form instanceof EE_Billing_Info_Form
1239
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1240
+		) {
1241
+			$payment_method_billing_form =
1242
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1243
+					$payment_method_billing_form
1244
+				);
1245
+		}
1246
+		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1247
+			? $payment_method_billing_form->get_html()
1248
+			: '';
1249
+		$this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1250
+		// localize validation rules for main form
1251
+		$this->checkout->current_step->reg_form->localize_validation_rules();
1252
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1253
+		return true;
1254
+	}
1255
+
1256
+
1257
+	/**
1258
+	 * _get_billing_form_for_payment_method
1259
+	 *
1260
+	 * @access private
1261
+	 * @param EE_Payment_Method $payment_method
1262
+	 * @return EE_Billing_Info_Form|EE_Form_Section_HTML
1263
+	 * @throws EE_Error
1264
+	 * @throws InvalidArgumentException
1265
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1266
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1267
+	 */
1268
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1269
+	{
1270
+		$billing_form = $payment_method->type_obj()->billing_form(
1271
+			$this->checkout->transaction,
1272
+			array('amount_owing' => $this->checkout->amount_owing)
1273
+		);
1274
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1275
+			if (apply_filters(
1276
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1277
+				false
1278
+			)
1279
+				&& EE_Registry::instance()->REQ->is_set('payment_method')
1280
+			) {
1281
+				EE_Error::add_success(
1282
+					apply_filters(
1283
+						'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1284
+						sprintf(
1285
+							esc_html__(
1286
+								'You have selected "%s" as your method of payment. Please note the important payment information below.',
1287
+								'event_espresso'
1288
+							),
1289
+							$payment_method->name()
1290
+						)
1291
+					)
1292
+				);
1293
+			}
1294
+			return apply_filters(
1295
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1296
+				$billing_form,
1297
+				$payment_method
1298
+			);
1299
+		}
1300
+		// no actual billing form, so return empty HTML form section
1301
+		return new EE_Form_Section_HTML();
1302
+	}
1303
+
1304
+
1305
+	/**
1306
+	 * _get_selected_method_of_payment
1307
+	 *
1308
+	 * @access private
1309
+	 * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1310
+	 *                          is not found in the incoming request
1311
+	 * @param string  $request_param
1312
+	 * @return NULL|string
1313
+	 * @throws EE_Error
1314
+	 * @throws InvalidArgumentException
1315
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1316
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1317
+	 */
1318
+	private function _get_selected_method_of_payment(
1319
+		$required = false,
1320
+		$request_param = 'selected_method_of_payment'
1321
+	) {
1322
+		// is selected_method_of_payment set in the request ?
1323
+		$selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1324
+		if ($selected_method_of_payment) {
1325
+			// sanitize it
1326
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1327
+				? array_shift($selected_method_of_payment)
1328
+				: $selected_method_of_payment;
1329
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1330
+			// store it in the session so that it's available for all subsequent requests including AJAX
1331
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1332
+		} else {
1333
+			// or is is set in the session ?
1334
+			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1335
+				'selected_method_of_payment'
1336
+			);
1337
+		}
1338
+		// do ya really really gotta have it?
1339
+		if (empty($selected_method_of_payment) && $required) {
1340
+			EE_Error::add_error(
1341
+				sprintf(
1342
+					esc_html__(
1343
+						'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1344
+						'event_espresso'
1345
+					),
1346
+					'<br/>',
1347
+					'<br/>',
1348
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1349
+				),
1350
+				__FILE__,
1351
+				__FUNCTION__,
1352
+				__LINE__
1353
+			);
1354
+			return null;
1355
+		}
1356
+		return $selected_method_of_payment;
1357
+	}
1358
+
1359
+
1360
+
1361
+
1362
+
1363
+
1364
+	/********************************************************************************************************/
1365
+	/***********************************  SWITCH PAYMENT METHOD  ************************************/
1366
+	/********************************************************************************************************/
1367
+	/**
1368
+	 * switch_payment_method
1369
+	 *
1370
+	 * @access public
1371
+	 * @return string
1372
+	 * @throws EE_Error
1373
+	 * @throws InvalidArgumentException
1374
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1375
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1376
+	 */
1377
+	public function switch_payment_method()
1378
+	{
1379
+		if (! $this->_verify_payment_method_is_set()) {
1380
+			return false;
1381
+		}
1382
+		if (apply_filters(
1383
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1384
+			false
1385
+		)) {
1386
+			EE_Error::add_success(
1387
+				apply_filters(
1388
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1389
+					sprintf(
1390
+						esc_html__(
1391
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1392
+							'event_espresso'
1393
+						),
1394
+						$this->checkout->payment_method->name()
1395
+					)
1396
+				)
1397
+			);
1398
+		}
1399
+		// generate billing form for selected method of payment if it hasn't been done already
1400
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1401
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1402
+				$this->checkout->payment_method
1403
+			);
1404
+		}
1405
+		// fill form with attendee info if applicable
1406
+		if (apply_filters(
1407
+			'FHEE__populate_billing_form_fields_from_attendee',
1408
+			(
1409
+				$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1410
+				&& $this->checkout->transaction_has_primary_registrant()
1411
+			),
1412
+			$this->checkout->billing_form,
1413
+			$this->checkout->transaction
1414
+		)
1415
+		) {
1416
+			$this->checkout->billing_form->populate_from_attendee(
1417
+				$this->checkout->transaction->primary_registration()->attendee()
1418
+			);
1419
+		}
1420
+		// and debug content
1421
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1422
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1423
+		) {
1424
+			$this->checkout->billing_form =
1425
+				$this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1426
+					$this->checkout->billing_form
1427
+				);
1428
+		}
1429
+		// get html and validation rules for form
1430
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1431
+			$this->checkout->json_response->set_return_data(
1432
+				array('payment_method_info' => $this->checkout->billing_form->get_html())
1433
+			);
1434
+			// localize validation rules for main form
1435
+			$this->checkout->billing_form->localize_validation_rules(true);
1436
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1437
+		} else {
1438
+			$this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1439
+		}
1440
+		//prevents advancement to next step
1441
+		$this->checkout->continue_reg = false;
1442
+		return true;
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * _verify_payment_method_is_set
1448
+	 *
1449
+	 * @return bool
1450
+	 * @throws EE_Error
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws ReflectionException
1453
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1454
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1455
+	 */
1456
+	protected function _verify_payment_method_is_set()
1457
+	{
1458
+		// generate billing form for selected method of payment if it hasn't been done already
1459
+		if (empty($this->checkout->selected_method_of_payment)) {
1460
+			// how have they chosen to pay?
1461
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1462
+		} else {
1463
+			// choose your own adventure based on method_of_payment
1464
+			switch ($this->checkout->selected_method_of_payment) {
1465
+				case 'events_sold_out' :
1466
+					EE_Error::add_attention(
1467
+						apply_filters(
1468
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1469
+							esc_html__(
1470
+								'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1471
+								'event_espresso'
1472
+							)
1473
+						),
1474
+						__FILE__, __FUNCTION__, __LINE__
1475
+					);
1476
+					return false;
1477
+					break;
1478
+				case 'payments_closed' :
1479
+					EE_Error::add_attention(
1480
+						apply_filters(
1481
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1482
+							esc_html__(
1483
+								'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1484
+								'event_espresso'
1485
+							)
1486
+						),
1487
+						__FILE__, __FUNCTION__, __LINE__
1488
+					);
1489
+					return false;
1490
+					break;
1491
+				case 'no_payment_required' :
1492
+					EE_Error::add_attention(
1493
+						apply_filters(
1494
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1495
+							esc_html__(
1496
+								'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1497
+								'event_espresso'
1498
+							)
1499
+						),
1500
+						__FILE__, __FUNCTION__, __LINE__
1501
+					);
1502
+					return false;
1503
+					break;
1504
+				default:
1505
+			}
1506
+		}
1507
+		// verify payment method
1508
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1509
+			// get payment method for selected method of payment
1510
+			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1511
+		}
1512
+		return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1513
+	}
1514
+
1515
+
1516
+
1517
+	/********************************************************************************************************/
1518
+	/***************************************  SAVE PAYER DETAILS  ****************************************/
1519
+	/********************************************************************************************************/
1520
+	/**
1521
+	 * save_payer_details_via_ajax
1522
+	 *
1523
+	 * @return void
1524
+	 * @throws EE_Error
1525
+	 * @throws InvalidArgumentException
1526
+	 * @throws ReflectionException
1527
+	 * @throws RuntimeException
1528
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1529
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1530
+	 */
1531
+	public function save_payer_details_via_ajax()
1532
+	{
1533
+		if (! $this->_verify_payment_method_is_set()) {
1534
+			return;
1535
+		}
1536
+		// generate billing form for selected method of payment if it hasn't been done already
1537
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1538
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1539
+				$this->checkout->payment_method
1540
+			);
1541
+		}
1542
+		// generate primary attendee from payer info if applicable
1543
+		if (! $this->checkout->transaction_has_primary_registrant()) {
1544
+			$attendee = $this->_create_attendee_from_request_data();
1545
+			if ($attendee instanceof EE_Attendee) {
1546
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1547
+					if ($registration->is_primary_registrant()) {
1548
+						$this->checkout->primary_attendee_obj = $attendee;
1549
+						$registration->_add_relation_to($attendee, 'Attendee');
1550
+						$registration->set_attendee_id($attendee->ID());
1551
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1552
+					}
1553
+				}
1554
+			}
1555
+		}
1556
+	}
1557
+
1558
+
1559
+	/**
1560
+	 * create_attendee_from_request_data
1561
+	 * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1562
+	 *
1563
+	 * @return EE_Attendee
1564
+	 * @throws EE_Error
1565
+	 * @throws InvalidArgumentException
1566
+	 * @throws ReflectionException
1567
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1568
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1569
+	 */
1570
+	protected function _create_attendee_from_request_data()
1571
+	{
1572
+		// get State ID
1573
+		$STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1574
+		if (! empty($STA_ID)) {
1575
+			// can we get state object from name ?
1576
+			EE_Registry::instance()->load_model('State');
1577
+			$state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1578
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1579
+		}
1580
+		// get Country ISO
1581
+		$CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1582
+		if (! empty($CNT_ISO)) {
1583
+			// can we get country object from name ?
1584
+			EE_Registry::instance()->load_model('Country');
1585
+			$country = EEM_Country::instance()->get_col(
1586
+				array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1587
+				'CNT_ISO'
1588
+			);
1589
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1590
+		}
1591
+		// grab attendee data
1592
+		$attendee_data = array(
1593
+			'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1594
+			'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1595
+			'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1596
+			'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1597
+			'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1598
+			'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1599
+			'STA_ID'       => $STA_ID,
1600
+			'CNT_ISO'      => $CNT_ISO,
1601
+			'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1602
+			'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1603
+		);
1604
+		// validate the email address since it is the most important piece of info
1605
+		if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1606
+			EE_Error::add_error(
1607
+				esc_html__('An invalid email address was submitted.', 'event_espresso'),
1608
+				__FILE__,
1609
+				__FUNCTION__,
1610
+				__LINE__
1611
+			);
1612
+		}
1613
+		// does this attendee already exist in the db ? we're searching using a combination of first name, last name,
1614
+		// AND email address
1615
+		if (! empty($attendee_data['ATT_fname'])
1616
+			&& ! empty($attendee_data['ATT_lname'])
1617
+			&& ! empty($attendee_data['ATT_email'])
1618
+		) {
1619
+			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1620
+				array(
1621
+					'ATT_fname' => $attendee_data['ATT_fname'],
1622
+					'ATT_lname' => $attendee_data['ATT_lname'],
1623
+					'ATT_email' => $attendee_data['ATT_email'],
1624
+				)
1625
+			);
1626
+			if ($existing_attendee instanceof EE_Attendee) {
1627
+				return $existing_attendee;
1628
+			}
1629
+		}
1630
+		// no existing attendee? kk let's create a new one
1631
+		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those
1632
+		// don't exist
1633
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1634
+			? $attendee_data['ATT_fname']
1635
+			: $attendee_data['ATT_email'];
1636
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1637
+			? $attendee_data['ATT_lname']
1638
+			: $attendee_data['ATT_email'];
1639
+		return EE_Attendee::new_instance($attendee_data);
1640
+	}
1641
+
1642
+
1643
+
1644
+	/********************************************************************************************************/
1645
+	/****************************************  PROCESS REG STEP  *****************************************/
1646
+	/********************************************************************************************************/
1647
+	/**
1648
+	 * process_reg_step
1649
+	 *
1650
+	 * @return bool
1651
+	 * @throws EE_Error
1652
+	 * @throws InvalidArgumentException
1653
+	 * @throws ReflectionException
1654
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1655
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1656
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1657
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1658
+	 */
1659
+	public function process_reg_step()
1660
+	{
1661
+		// how have they chosen to pay?
1662
+		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1663
+			? 'no_payment_required'
1664
+			: $this->_get_selected_method_of_payment(true);
1665
+		// choose your own adventure based on method_of_payment
1666
+		switch ($this->checkout->selected_method_of_payment) {
1667
+
1668
+			case 'events_sold_out' :
1669
+				$this->checkout->redirect     = true;
1670
+				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1671
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1672
+				// mark this reg step as completed
1673
+				$this->set_completed();
1674
+				return false;
1675
+				break;
1676
+
1677
+			case 'payments_closed' :
1678
+				if (apply_filters(
1679
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1680
+					false
1681
+				)) {
1682
+					EE_Error::add_success(
1683
+						esc_html__('no payment required at this time.', 'event_espresso'),
1684
+						__FILE__,
1685
+						__FUNCTION__,
1686
+						__LINE__
1687
+					);
1688
+				}
1689
+				// mark this reg step as completed
1690
+				$this->set_completed();
1691
+				return true;
1692
+				break;
1693
+
1694
+			case 'no_payment_required' :
1695
+				if (apply_filters(
1696
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1697
+					false
1698
+				)) {
1699
+					EE_Error::add_success(
1700
+						esc_html__('no payment required.', 'event_espresso'),
1701
+						__FILE__,
1702
+						__FUNCTION__,
1703
+						__LINE__
1704
+					);
1705
+				}
1706
+				// mark this reg step as completed
1707
+				$this->set_completed();
1708
+				return true;
1709
+				break;
1710
+
1711
+			default:
1712
+				$registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1713
+					EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1714
+				);
1715
+				$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1716
+					$registrations,
1717
+					EE_Registry::instance()->SSN->checkout()->revisit
1718
+				);
1719
+				// calculate difference between the two arrays
1720
+				$registrations = array_diff($registrations, $ejected_registrations);
1721
+				if (empty($registrations)) {
1722
+					$this->_redirect_because_event_sold_out();
1723
+					return false;
1724
+				}
1725
+				$payment_successful = $this->_process_payment();
1726
+				if ($payment_successful) {
1727
+					$this->checkout->continue_reg = true;
1728
+					$this->_maybe_set_completed($this->checkout->payment_method);
1729
+				} else {
1730
+					$this->checkout->continue_reg = false;
1731
+				}
1732
+				return $payment_successful;
1733
+		}
1734
+	}
1735
+
1736
+
1737
+	/**
1738
+	 * _redirect_because_event_sold_out
1739
+	 *
1740
+	 * @access protected
1741
+	 * @return void
1742
+	 */
1743
+	protected function _redirect_because_event_sold_out()
1744
+	{
1745
+		$this->checkout->continue_reg = false;
1746
+		// set redirect URL
1747
+		$this->checkout->redirect_url = add_query_arg(
1748
+			array('e_reg_url_link' => $this->checkout->reg_url_link),
1749
+			$this->checkout->current_step->reg_step_url()
1750
+		);
1751
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1752
+	}
1753
+
1754
+
1755
+	/**
1756
+	 * _maybe_set_completed
1757
+	 *
1758
+	 * @access protected
1759
+	 * @param \EE_Payment_Method $payment_method
1760
+	 * @return void
1761
+	 * @throws \EE_Error
1762
+	 */
1763
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1764
+	{
1765
+		switch ($payment_method->type_obj()->payment_occurs()) {
1766
+			case EE_PMT_Base::offsite :
1767
+				break;
1768
+			case EE_PMT_Base::onsite :
1769
+			case EE_PMT_Base::offline :
1770
+				// mark this reg step as completed
1771
+				$this->set_completed();
1772
+				break;
1773
+		}
1774
+	}
1775
+
1776
+
1777
+	/**
1778
+	 *    update_reg_step
1779
+	 *    this is the final step after a user  revisits the site to retry a payment
1780
+	 *
1781
+	 * @return bool
1782
+	 * @throws EE_Error
1783
+	 * @throws InvalidArgumentException
1784
+	 * @throws ReflectionException
1785
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1786
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1787
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1788
+	 * @throws \EventEspresso\core\exceptions\InvalidStatusException
1789
+	 */
1790
+	public function update_reg_step()
1791
+	{
1792
+		$success = true;
1793
+		// if payment required
1794
+		if ($this->checkout->transaction->total() > 0) {
1795
+			do_action(
1796
+				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1797
+				$this->checkout->transaction
1798
+			);
1799
+			// attempt payment via payment method
1800
+			$success = $this->process_reg_step();
1801
+		}
1802
+		if ($success && ! $this->checkout->redirect) {
1803
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1804
+				$this->checkout->transaction->ID()
1805
+			);
1806
+			// set return URL
1807
+			$this->checkout->redirect_url = add_query_arg(
1808
+				array('e_reg_url_link' => $this->checkout->reg_url_link),
1809
+				$this->checkout->thank_you_page_url
1810
+			);
1811
+		}
1812
+		return $success;
1813
+	}
1814
+
1815
+
1816
+	/**
1817
+	 *    _process_payment
1818
+	 *
1819
+	 * @access private
1820
+	 * @return bool
1821
+	 * @throws EE_Error
1822
+	 * @throws InvalidArgumentException
1823
+	 * @throws ReflectionException
1824
+	 * @throws RuntimeException
1825
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1826
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1827
+	 */
1828
+	private function _process_payment()
1829
+	{
1830
+		// basically confirm that the event hasn't sold out since they hit the page
1831
+		if (! $this->_last_second_ticket_verifications()) {
1832
+			return false;
1833
+		}
1834
+		// ya gotta make a choice man
1835
+		if (empty($this->checkout->selected_method_of_payment)) {
1836
+			$this->checkout->json_response->set_plz_select_method_of_payment(
1837
+				esc_html__('Please select a method of payment before proceeding.', 'event_espresso')
1838
+			);
1839
+			return false;
1840
+		}
1841
+		// get EE_Payment_Method object
1842
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1843
+			return false;
1844
+		}
1845
+		// setup billing form
1846
+		if ($this->checkout->payment_method->is_on_site()) {
1847
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1848
+				$this->checkout->payment_method
1849
+			);
1850
+			// bad billing form ?
1851
+			if (! $this->_billing_form_is_valid()) {
1852
+				return false;
1853
+			}
1854
+		}
1855
+		// ensure primary registrant has been fully processed
1856
+		if (! $this->_setup_primary_registrant_prior_to_payment()) {
1857
+			return false;
1858
+		}
1859
+		// if session is close to expiring (under 10 minutes by default)
1860
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1861
+			// add some time to session expiration so that payment can be completed
1862
+			EE_Registry::instance()->SSN->extend_expiration();
1863
+		}
1864
+		/** @type EE_Transaction_Processor $transaction_processor */
1865
+		//$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1866
+		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations
1867
+		// for events with a default reg status of Approved
1868
+		// $transaction_processor->toggle_registration_statuses_for_default_approved_events(
1869
+		//      $this->checkout->transaction, $this->checkout->reg_cache_where_params
1870
+		// );
1871
+		// attempt payment
1872
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1873
+		// process results
1874
+		$payment = $this->_validate_payment($payment);
1875
+		$payment = $this->_post_payment_processing($payment);
1876
+		// verify payment
1877
+		if ($payment instanceof EE_Payment) {
1878
+			// store that for later
1879
+			$this->checkout->payment = $payment;
1880
+			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1881
+			$this->checkout->transaction->toggle_failed_transaction_status();
1882
+			$payment_status = $payment->status();
1883
+			if (
1884
+				$payment_status === EEM_Payment::status_id_approved
1885
+				|| $payment_status === EEM_Payment::status_id_pending
1886
+			) {
1887
+				return true;
1888
+			} else {
1889
+				return false;
1890
+			}
1891
+		} else if ($payment === true) {
1892
+			// please note that offline payment methods will NOT make a payment,
1893
+			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1894
+			$this->checkout->payment = $payment;
1895
+			return true;
1896
+		}
1897
+		// where's my money?
1898
+		return false;
1899
+	}
1900
+
1901
+
1902
+	/**
1903
+	 * _last_second_ticket_verifications
1904
+	 *
1905
+	 * @access public
1906
+	 * @return bool
1907
+	 * @throws EE_Error
1908
+	 */
1909
+	protected function _last_second_ticket_verifications()
1910
+	{
1911
+		// don't bother re-validating if not a return visit
1912
+		if (! $this->checkout->revisit) {
1913
+			return true;
1914
+		}
1915
+		$registrations = $this->checkout->transaction->registrations();
1916
+		if (empty($registrations)) {
1917
+			return false;
1918
+		}
1919
+		foreach ($registrations as $registration) {
1920
+			if ($registration instanceof EE_Registration) {
1921
+				$event = $registration->event_obj();
1922
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1923
+					EE_Error::add_error(
1924
+						apply_filters(
1925
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1926
+							sprintf(
1927
+								esc_html__(
1928
+									'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1929
+									'event_espresso'
1930
+								),
1931
+								$event->name()
1932
+							)
1933
+						),
1934
+						__FILE__,
1935
+						__FUNCTION__,
1936
+						__LINE__
1937
+					);
1938
+					return false;
1939
+				}
1940
+			}
1941
+		}
1942
+		return true;
1943
+	}
1944
+
1945
+
1946
+	/**
1947
+	 * redirect_form
1948
+	 *
1949
+	 * @access public
1950
+	 * @return bool
1951
+	 * @throws EE_Error
1952
+	 * @throws InvalidArgumentException
1953
+	 * @throws ReflectionException
1954
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
1955
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
1956
+	 */
1957
+	public function redirect_form()
1958
+	{
1959
+		$payment_method_billing_info = $this->_payment_method_billing_info(
1960
+			$this->_get_payment_method_for_selected_method_of_payment()
1961
+		);
1962
+		$html                        = $payment_method_billing_info->get_html();
1963
+		$html                        .= $this->checkout->redirect_form;
1964
+		EE_Registry::instance()->REQ->add_output($html);
1965
+		return true;
1966
+	}
1967
+
1968
+
1969
+	/**
1970
+	 * _billing_form_is_valid
1971
+	 *
1972
+	 * @access private
1973
+	 * @return bool
1974
+	 * @throws \EE_Error
1975
+	 */
1976
+	private function _billing_form_is_valid()
1977
+	{
1978
+		if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1979
+			return true;
1980
+		}
1981
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1982
+			if ($this->checkout->billing_form->was_submitted()) {
1983
+				$this->checkout->billing_form->receive_form_submission();
1984
+				if ($this->checkout->billing_form->is_valid()) {
1985
+					return true;
1986
+				}
1987
+				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1988
+				$error_strings     = array();
1989
+				foreach ($validation_errors as $validation_error) {
1990
+					if ($validation_error instanceof EE_Validation_Error) {
1991
+						$form_section = $validation_error->get_form_section();
1992
+						if ($form_section instanceof EE_Form_Input_Base) {
1993
+							$label = $form_section->html_label_text();
1994
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
1995
+							$label = $form_section->name();
1996
+						} else {
1997
+							$label = esc_html__('Validation Error', 'event_espresso');
1998
+						}
1999
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
2000
+					}
2001
+				}
2002
+				EE_Error::add_error(
2003
+					sprintf(
2004
+						esc_html__(
2005
+							'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
2006
+							'event_espresso'
2007
+						),
2008
+						'<br/>',
2009
+						implode('<br/>', $error_strings)
2010
+					),
2011
+					__FILE__,
2012
+					__FUNCTION__,
2013
+					__LINE__
2014
+				);
2015
+			} else {
2016
+				EE_Error::add_error(
2017
+					esc_html__(
2018
+						'The billing form was not submitted or something prevented it\'s submission.',
2019
+						'event_espresso'
2020
+					),
2021
+					__FILE__,
2022
+					__FUNCTION__,
2023
+					__LINE__
2024
+				);
2025
+			}
2026
+		} else {
2027
+			EE_Error::add_error(
2028
+				esc_html__('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
2029
+				__FILE__,
2030
+				__FUNCTION__,
2031
+				__LINE__
2032
+			);
2033
+		}
2034
+		return false;
2035
+	}
2036
+
2037
+
2038
+	/**
2039
+	 * _setup_primary_registrant_prior_to_payment
2040
+	 * ensures that the primary registrant has a valid attendee object created with the critical details populated
2041
+	 * (first & last name & email) and that both the transaction object and primary registration object have been saved
2042
+	 * plz note that any other registrations will NOT be saved at this point (because they may not have any details
2043
+	 * yet)
2044
+	 *
2045
+	 * @access private
2046
+	 * @return bool
2047
+	 * @throws EE_Error
2048
+	 * @throws InvalidArgumentException
2049
+	 * @throws ReflectionException
2050
+	 * @throws RuntimeException
2051
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2052
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2053
+	 */
2054
+	private function _setup_primary_registrant_prior_to_payment()
2055
+	{
2056
+		// check if transaction has a primary registrant and that it has a related Attendee object
2057
+		// if not, then we need to at least gather some primary registrant data before attempting payment
2058
+		if (
2059
+			$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
2060
+			&& ! $this->checkout->transaction_has_primary_registrant()
2061
+			&& ! $this->_capture_primary_registration_data_from_billing_form()
2062
+		) {
2063
+			return false;
2064
+		}
2065
+		// because saving an object clears it's cache, we need to do the chevy shuffle
2066
+		// grab the primary_registration object
2067
+		$primary_registration = $this->checkout->transaction->primary_registration();
2068
+		// at this point we'll consider a TXN to not have been failed
2069
+		$this->checkout->transaction->toggle_failed_transaction_status();
2070
+		// save the TXN ( which clears cached copy of primary_registration)
2071
+		$this->checkout->transaction->save();
2072
+		// grab TXN ID and save it to the primary_registration
2073
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
2074
+		// save what we have so far
2075
+		$primary_registration->save();
2076
+		return true;
2077
+	}
2078
+
2079
+
2080
+	/**
2081
+	 * _capture_primary_registration_data_from_billing_form
2082
+	 *
2083
+	 * @access private
2084
+	 * @return bool
2085
+	 * @throws EE_Error
2086
+	 * @throws InvalidArgumentException
2087
+	 * @throws ReflectionException
2088
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2089
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2090
+	 */
2091
+	private function _capture_primary_registration_data_from_billing_form()
2092
+	{
2093
+		// convert billing form data into an attendee
2094
+		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
2095
+		if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
2096
+			EE_Error::add_error(
2097
+				sprintf(
2098
+					esc_html__(
2099
+						'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
2100
+						'event_espresso'
2101
+					),
2102
+					'<br/>',
2103
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2104
+				),
2105
+				__FILE__,
2106
+				__FUNCTION__,
2107
+				__LINE__
2108
+			);
2109
+			return false;
2110
+		}
2111
+		$primary_registration = $this->checkout->transaction->primary_registration();
2112
+		if (! $primary_registration instanceof EE_Registration) {
2113
+			EE_Error::add_error(
2114
+				sprintf(
2115
+					esc_html__(
2116
+						'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2117
+						'event_espresso'
2118
+					),
2119
+					'<br/>',
2120
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2121
+				),
2122
+				__FILE__,
2123
+				__FUNCTION__,
2124
+				__LINE__
2125
+			);
2126
+			return false;
2127
+		}
2128
+		if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
2129
+			  instanceof
2130
+			  EE_Attendee
2131
+		) {
2132
+			EE_Error::add_error(
2133
+				sprintf(
2134
+					esc_html__(
2135
+						'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
2136
+						'event_espresso'
2137
+					),
2138
+					'<br/>',
2139
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2140
+				),
2141
+				__FILE__,
2142
+				__FUNCTION__,
2143
+				__LINE__
2144
+			);
2145
+			return false;
2146
+		}
2147
+		/** @type EE_Registration_Processor $registration_processor */
2148
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2149
+		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2150
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2151
+		return true;
2152
+	}
2153
+
2154
+
2155
+	/**
2156
+	 * _get_payment_method_for_selected_method_of_payment
2157
+	 * retrieves a valid payment method
2158
+	 *
2159
+	 * @access public
2160
+	 * @return EE_Payment_Method
2161
+	 * @throws EE_Error
2162
+	 * @throws InvalidArgumentException
2163
+	 * @throws ReflectionException
2164
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2165
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2166
+	 */
2167
+	private function _get_payment_method_for_selected_method_of_payment()
2168
+	{
2169
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2170
+			$this->_redirect_because_event_sold_out();
2171
+			return null;
2172
+		}
2173
+		// get EE_Payment_Method object
2174
+		if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2175
+			$payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2176
+		} else {
2177
+			// load EEM_Payment_Method
2178
+			EE_Registry::instance()->load_model('Payment_Method');
2179
+			/** @type EEM_Payment_Method $EEM_Payment_Method */
2180
+			$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2181
+			$payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2182
+		}
2183
+		// verify $payment_method
2184
+		if (! $payment_method instanceof EE_Payment_Method) {
2185
+			// not a payment
2186
+			EE_Error::add_error(
2187
+				sprintf(
2188
+					esc_html__(
2189
+						'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2190
+						'event_espresso'
2191
+					),
2192
+					'<br/>',
2193
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2194
+				),
2195
+				__FILE__,
2196
+				__FUNCTION__,
2197
+				__LINE__
2198
+			);
2199
+			return null;
2200
+		}
2201
+		// and verify it has a valid Payment_Method Type object
2202
+		if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2203
+			// not a payment
2204
+			EE_Error::add_error(
2205
+				sprintf(
2206
+					esc_html__(
2207
+						'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2208
+						'event_espresso'
2209
+					),
2210
+					'<br/>',
2211
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2212
+				),
2213
+				__FILE__,
2214
+				__FUNCTION__,
2215
+				__LINE__
2216
+			);
2217
+			return null;
2218
+		}
2219
+		return $payment_method;
2220
+	}
2221
+
2222
+
2223
+	/**
2224
+	 *    _attempt_payment
2225
+	 *
2226
+	 * @access    private
2227
+	 * @type    EE_Payment_Method $payment_method
2228
+	 * @return mixed EE_Payment | boolean
2229
+	 * @throws EE_Error
2230
+	 * @throws InvalidArgumentException
2231
+	 * @throws ReflectionException
2232
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2233
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2234
+	 */
2235
+	private function _attempt_payment(EE_Payment_Method $payment_method)
2236
+	{
2237
+		$payment = null;
2238
+		$this->checkout->transaction->save();
2239
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2240
+		if (! $payment_processor instanceof EE_Payment_Processor) {
2241
+			return false;
2242
+		}
2243
+		try {
2244
+			$payment_processor->set_revisit($this->checkout->revisit);
2245
+			// generate payment object
2246
+			$payment = $payment_processor->process_payment(
2247
+				$payment_method,
2248
+				$this->checkout->transaction,
2249
+				$this->checkout->amount_owing,
2250
+				$this->checkout->billing_form,
2251
+				$this->_get_return_url($payment_method),
2252
+				'CART',
2253
+				$this->checkout->admin_request,
2254
+				true,
2255
+				$this->reg_step_url()
2256
+			);
2257
+		} catch (Exception $e) {
2258
+			$this->_handle_payment_processor_exception($e);
2259
+		}
2260
+		return $payment;
2261
+	}
2262
+
2263
+
2264
+	/**
2265
+	 * _handle_payment_processor_exception
2266
+	 *
2267
+	 * @access protected
2268
+	 * @param \Exception $e
2269
+	 * @return void
2270
+	 * @throws EE_Error
2271
+	 * @throws InvalidArgumentException
2272
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2273
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2274
+	 */
2275
+	protected function _handle_payment_processor_exception(Exception $e)
2276
+	{
2277
+		EE_Error::add_error(
2278
+			sprintf(
2279
+				esc_html__(
2280
+					'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2281
+					'event_espresso'
2282
+				),
2283
+				'<br/>',
2284
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2285
+				$e->getMessage(),
2286
+				$e->getFile(),
2287
+				$e->getLine()
2288
+			),
2289
+			__FILE__,
2290
+			__FUNCTION__,
2291
+			__LINE__
2292
+		);
2293
+	}
2294
+
2295
+
2296
+	/**
2297
+	 * _get_return_url
2298
+	 *
2299
+	 * @access protected
2300
+	 * @param \EE_Payment_Method $payment_method
2301
+	 * @return string
2302
+	 * @throws \EE_Error
2303
+	 */
2304
+	protected function _get_return_url(EE_Payment_Method $payment_method)
2305
+	{
2306
+		$return_url = '';
2307
+		switch ($payment_method->type_obj()->payment_occurs()) {
2308
+			case EE_PMT_Base::offsite :
2309
+				$return_url = add_query_arg(
2310
+					array(
2311
+						'action'                     => 'process_gateway_response',
2312
+						'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2313
+						'spco_txn'                   => $this->checkout->transaction->ID(),
2314
+					),
2315
+					$this->reg_step_url()
2316
+				);
2317
+				break;
2318
+			case EE_PMT_Base::onsite :
2319
+			case EE_PMT_Base::offline :
2320
+				$return_url = $this->checkout->next_step->reg_step_url();
2321
+				break;
2322
+		}
2323
+		return $return_url;
2324
+	}
2325
+
2326
+
2327
+	/**
2328
+	 * _validate_payment
2329
+	 *
2330
+	 * @access private
2331
+	 * @param EE_Payment $payment
2332
+	 * @return EE_Payment|FALSE
2333
+	 * @throws EE_Error
2334
+	 * @throws InvalidArgumentException
2335
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2336
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2337
+	 */
2338
+	private function _validate_payment($payment = null)
2339
+	{
2340
+		if ($this->checkout->payment_method->is_off_line()) {
2341
+			return true;
2342
+		}
2343
+		// verify payment object
2344
+		if (! $payment instanceof EE_Payment) {
2345
+			// not a payment
2346
+			EE_Error::add_error(
2347
+				sprintf(
2348
+					esc_html__(
2349
+						'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2350
+						'event_espresso'
2351
+					),
2352
+					'<br/>',
2353
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2354
+				),
2355
+				__FILE__,
2356
+				__FUNCTION__,
2357
+				__LINE__
2358
+			);
2359
+			return false;
2360
+		}
2361
+		return $payment;
2362
+	}
2363
+
2364
+
2365
+	/**
2366
+	 * _post_payment_processing
2367
+	 *
2368
+	 * @access private
2369
+	 * @param EE_Payment|bool $payment
2370
+	 * @return bool
2371
+	 * @throws EE_Error
2372
+	 * @throws InvalidArgumentException
2373
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2374
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2375
+	 */
2376
+	private function _post_payment_processing($payment = null)
2377
+	{
2378
+		// Off-Line payment?
2379
+		if ($payment === true) {
2380
+			//$this->_setup_redirect_for_next_step();
2381
+			return true;
2382
+			// On-Site payment?
2383
+		} else if ($this->checkout->payment_method->is_on_site()) {
2384
+			if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2385
+				//$this->_setup_redirect_for_next_step();
2386
+				$this->checkout->continue_reg = false;
2387
+			}
2388
+			// Off-Site payment?
2389
+		} else if ($this->checkout->payment_method->is_off_site()) {
2390
+			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2391
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2392
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2393
+				$this->checkout->redirect      = true;
2394
+				$this->checkout->redirect_form = $payment->redirect_form();
2395
+				$this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2396
+				// set JSON response
2397
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2398
+				// set cron job for finalizing the TXN
2399
+				// in case the user does not return from the off-site gateway
2400
+				EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
2401
+					EE_Registry::instance()->SSN->expiration() + 1,
2402
+					$this->checkout->transaction->ID()
2403
+				);
2404
+				// and lastly, let's bump the payment status to pending
2405
+				$payment->set_status(EEM_Payment::status_id_pending);
2406
+				$payment->save();
2407
+			} else {
2408
+				// not a payment
2409
+				$this->checkout->continue_reg = false;
2410
+				EE_Error::add_error(
2411
+					sprintf(
2412
+						esc_html__(
2413
+							'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2414
+							'event_espresso'
2415
+						),
2416
+						'<br/>',
2417
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
2418
+					),
2419
+					__FILE__,
2420
+					__FUNCTION__,
2421
+					__LINE__
2422
+				);
2423
+			}
2424
+		} else {
2425
+			// ummm ya... not Off-Line, not On-Site, not off-Site ????
2426
+			$this->checkout->continue_reg = false;
2427
+			return false;
2428
+		}
2429
+		return $payment;
2430
+	}
2431
+
2432
+
2433
+	/**
2434
+	 *    _process_payment_status
2435
+	 *
2436
+	 * @access private
2437
+	 * @type    EE_Payment $payment
2438
+	 * @param string       $payment_occurs
2439
+	 * @return bool
2440
+	 * @throws EE_Error
2441
+	 * @throws InvalidArgumentException
2442
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2443
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2444
+	 */
2445
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2446
+	{
2447
+		// off-line payment? carry on
2448
+		if ($payment_occurs === EE_PMT_Base::offline) {
2449
+			return true;
2450
+		}
2451
+		// verify payment validity
2452
+		if ($payment instanceof EE_Payment) {
2453
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2454
+			$msg = $payment->gateway_response();
2455
+			// check results
2456
+			switch ($payment->status()) {
2457
+				// good payment
2458
+				case EEM_Payment::status_id_approved :
2459
+					EE_Error::add_success(
2460
+						esc_html__('Your payment was processed successfully.', 'event_espresso'),
2461
+						__FILE__,
2462
+						__FUNCTION__,
2463
+						__LINE__
2464
+					);
2465
+					return true;
2466
+					break;
2467
+				// slow payment
2468
+				case EEM_Payment::status_id_pending :
2469
+					if (empty($msg)) {
2470
+						$msg = esc_html__(
2471
+							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2472
+							'event_espresso'
2473
+						);
2474
+					}
2475
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2476
+					return true;
2477
+					break;
2478
+				// don't wanna payment
2479
+				case EEM_Payment::status_id_cancelled :
2480
+					if (empty($msg)) {
2481
+						$msg = _n(
2482
+							'Payment cancelled. Please try again.',
2483
+							'Payment cancelled. Please try again or select another method of payment.',
2484
+							count($this->checkout->available_payment_methods),
2485
+							'event_espresso'
2486
+						);
2487
+					}
2488
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2489
+					return false;
2490
+					break;
2491
+				// not enough payment
2492
+				case EEM_Payment::status_id_declined :
2493
+					if (empty($msg)) {
2494
+						$msg = _n(
2495
+							'We\'re sorry but your payment was declined. Please try again.',
2496
+							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2497
+							count($this->checkout->available_payment_methods),
2498
+							'event_espresso'
2499
+						);
2500
+					}
2501
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2502
+					return false;
2503
+					break;
2504
+				// bad payment
2505
+				case EEM_Payment::status_id_failed :
2506
+					if (! empty($msg)) {
2507
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2508
+						return false;
2509
+					}
2510
+					// default to error below
2511
+					break;
2512
+			}
2513
+		}
2514
+		// off-site payment gateway responses are too unreliable, so let's just assume that
2515
+		// the payment processing is just running slower than the registrant's request
2516
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2517
+			return true;
2518
+		}
2519
+		EE_Error::add_error(
2520
+			sprintf(
2521
+				esc_html__(
2522
+					'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2523
+					'event_espresso'
2524
+				),
2525
+				'<br/>',
2526
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2527
+			),
2528
+			__FILE__,
2529
+			__FUNCTION__,
2530
+			__LINE__
2531
+		);
2532
+		return false;
2533
+	}
2534
+
2535
+
2536
+
2537
+
2538
+
2539
+
2540
+	/********************************************************************************************************/
2541
+	/**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2542
+	/********************************************************************************************************/
2543
+	/**
2544
+	 * process_gateway_response
2545
+	 * this is the return point for Off-Site Payment Methods
2546
+	 * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2547
+	 * otherwise, it will load up the last payment made for the TXN.
2548
+	 * If the payment retrieved looks good, it will then either:
2549
+	 *    complete the current step and allow advancement to the next reg step
2550
+	 *        or present the payment options again
2551
+	 *
2552
+	 * @access private
2553
+	 * @return EE_Payment|FALSE
2554
+	 * @throws EE_Error
2555
+	 * @throws InvalidArgumentException
2556
+	 * @throws ReflectionException
2557
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2558
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2559
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2560
+	 */
2561
+	public function process_gateway_response()
2562
+	{
2563
+		$payment = null;
2564
+		// how have they chosen to pay?
2565
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2566
+		// get EE_Payment_Method object
2567
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2568
+			$this->checkout->continue_reg = false;
2569
+			return false;
2570
+		}
2571
+		if (! $this->checkout->payment_method->is_off_site()) {
2572
+			return false;
2573
+		}
2574
+		$this->_validate_offsite_return();
2575
+		// DEBUG LOG
2576
+		//$this->checkout->log(
2577
+		//	__CLASS__, __FUNCTION__, __LINE__,
2578
+		//	array(
2579
+		//		'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2580
+		//		'payment_method' => $this->checkout->payment_method,
2581
+		//	),
2582
+		//	true
2583
+		//);
2584
+		// verify TXN
2585
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2586
+			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2587
+			if (! $gateway instanceof EE_Offsite_Gateway) {
2588
+				$this->checkout->continue_reg = false;
2589
+				return false;
2590
+			}
2591
+			$payment = $this->_process_off_site_payment($gateway);
2592
+			$payment = $this->_process_cancelled_payments($payment);
2593
+			$payment = $this->_validate_payment($payment);
2594
+			// if payment was not declined by the payment gateway or cancelled by the registrant
2595
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2596
+				//$this->_setup_redirect_for_next_step();
2597
+				// store that for later
2598
+				$this->checkout->payment = $payment;
2599
+				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2600
+				// because we will complete this step during the IPN processing then
2601
+				if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2602
+					$this->set_completed();
2603
+				}
2604
+				return true;
2605
+			}
2606
+		}
2607
+		// DEBUG LOG
2608
+		//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2609
+		//	array( 'payment' => $payment )
2610
+		//);
2611
+		$this->checkout->continue_reg = false;
2612
+		return false;
2613
+	}
2614
+
2615
+
2616
+	/**
2617
+	 * _validate_return
2618
+	 *
2619
+	 * @access private
2620
+	 * @return void
2621
+	 * @throws EE_Error
2622
+	 * @throws InvalidArgumentException
2623
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2624
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2625
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2626
+	 */
2627
+	private function _validate_offsite_return()
2628
+	{
2629
+		$TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2630
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2631
+			// Houston... we might have a problem
2632
+			$invalid_TXN = false;
2633
+			// first gather some info
2634
+			$valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2635
+			$primary_registrant = $valid_TXN instanceof EE_Transaction
2636
+				? $valid_TXN->primary_registration()
2637
+				: null;
2638
+			// let's start by retrieving the cart for this TXN
2639
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2640
+			if ($cart instanceof EE_Cart) {
2641
+				// verify that the current cart has tickets
2642
+				$tickets = $cart->get_tickets();
2643
+				if (empty($tickets)) {
2644
+					$invalid_TXN = true;
2645
+				}
2646
+			} else {
2647
+				$invalid_TXN = true;
2648
+			}
2649
+			$valid_TXN_SID = $primary_registrant instanceof EE_Registration
2650
+				? $primary_registrant->session_ID()
2651
+				: null;
2652
+			// validate current Session ID and compare against valid TXN session ID
2653
+			if (
2654
+				$invalid_TXN // if this is already true, then skip other checks
2655
+				|| EE_Session::instance()->id() === null
2656
+				|| (
2657
+					// WARNING !!!
2658
+					// this could be PayPal sending back duplicate requests (ya they do that)
2659
+					// or it **could** mean someone is simply registering AGAIN after having just done so
2660
+					// so now we need to determine if this current TXN looks valid or not
2661
+					// and whether this reg step has even been started ?
2662
+					EE_Session::instance()->id() === $valid_TXN_SID
2663
+					// really? you're half way through this reg step, but you never started it ?
2664
+					&& $this->checkout->transaction->reg_step_completed($this->slug()) === false
2665
+				)
2666
+			) {
2667
+				$invalid_TXN = true;
2668
+			}
2669
+			if ($invalid_TXN) {
2670
+				// is the valid TXN completed ?
2671
+				if ($valid_TXN instanceof EE_Transaction) {
2672
+					// has this step even been started ?
2673
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2674
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2675
+						// so it **looks** like this is a double request from PayPal
2676
+						// so let's try to pick up where we left off
2677
+						$this->checkout->transaction = $valid_TXN;
2678
+						$this->checkout->refresh_all_entities(true);
2679
+						return;
2680
+					}
2681
+				}
2682
+				// you appear to be lost?
2683
+				$this->_redirect_wayward_request($primary_registrant);
2684
+			}
2685
+		}
2686
+	}
2687
+
2688
+
2689
+	/**
2690
+	 * _redirect_wayward_request
2691
+	 *
2692
+	 * @access private
2693
+	 * @param \EE_Registration|null $primary_registrant
2694
+	 * @return bool
2695
+	 * @throws EE_Error
2696
+	 * @throws InvalidArgumentException
2697
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2698
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2699
+	 */
2700
+	private function _redirect_wayward_request(EE_Registration $primary_registrant)
2701
+	{
2702
+		if (! $primary_registrant instanceof EE_Registration) {
2703
+			// try redirecting based on the current TXN
2704
+			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2705
+				? $this->checkout->transaction->primary_registration()
2706
+				: null;
2707
+		}
2708
+		if (! $primary_registrant instanceof EE_Registration) {
2709
+			EE_Error::add_error(
2710
+				sprintf(
2711
+					esc_html__(
2712
+						'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2713
+						'event_espresso'
2714
+					),
2715
+					'<br/>',
2716
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2717
+				),
2718
+				__FILE__,
2719
+				__FUNCTION__,
2720
+				__LINE__
2721
+			);
2722
+			return false;
2723
+		}
2724
+		// make sure transaction is not locked
2725
+		$this->checkout->transaction->unlock();
2726
+		wp_safe_redirect(
2727
+			add_query_arg(
2728
+				array(
2729
+					'e_reg_url_link' => $primary_registrant->reg_url_link(),
2730
+				),
2731
+				$this->checkout->thank_you_page_url
2732
+			)
2733
+		);
2734
+		exit();
2735
+	}
2736
+
2737
+
2738
+	/**
2739
+	 * _process_off_site_payment
2740
+	 *
2741
+	 * @access private
2742
+	 * @param \EE_Offsite_Gateway $gateway
2743
+	 * @return EE_Payment
2744
+	 * @throws EE_Error
2745
+	 * @throws InvalidArgumentException
2746
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2747
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2748
+	 */
2749
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2750
+	{
2751
+		try {
2752
+			$request_data = \EE_Registry::instance()->REQ->params();
2753
+			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2754
+			$this->set_handle_IPN_in_this_request(
2755
+				$gateway->handle_IPN_in_this_request($request_data, false)
2756
+			);
2757
+			if ($this->handle_IPN_in_this_request()) {
2758
+				// get payment details and process results
2759
+				/** @type EE_Payment_Processor $payment_processor */
2760
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2761
+				$payment           = $payment_processor->process_ipn(
2762
+					$request_data,
2763
+					$this->checkout->transaction,
2764
+					$this->checkout->payment_method,
2765
+					true,
2766
+					false
2767
+				);
2768
+				//$payment_source = 'process_ipn';
2769
+			} else {
2770
+				$payment = $this->checkout->transaction->last_payment();
2771
+				//$payment_source = 'last_payment';
2772
+			}
2773
+		} catch (Exception $e) {
2774
+			// let's just eat the exception and try to move on using any previously set payment info
2775
+			$payment = $this->checkout->transaction->last_payment();
2776
+			//$payment_source = 'last_payment after Exception';
2777
+			// but if we STILL don't have a payment object
2778
+			if (! $payment instanceof EE_Payment) {
2779
+				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2780
+				$this->_handle_payment_processor_exception($e);
2781
+			}
2782
+		}
2783
+		// DEBUG LOG
2784
+		//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2785
+		//	array(
2786
+		//		'process_ipn_payment' => $payment,
2787
+		//		'payment_source'      => $payment_source,
2788
+		//	)
2789
+		//);
2790
+		return $payment;
2791
+	}
2792
+
2793
+
2794
+	/**
2795
+	 * _process_cancelled_payments
2796
+	 * just makes sure that the payment status gets updated correctly
2797
+	 * so tha tan error isn't generated during payment validation
2798
+	 *
2799
+	 * @access private
2800
+	 * @param EE_Payment $payment
2801
+	 * @return EE_Payment | FALSE
2802
+	 * @throws \EE_Error
2803
+	 */
2804
+	private function _process_cancelled_payments($payment = null)
2805
+	{
2806
+		if (
2807
+			$payment instanceof EE_Payment
2808
+			&& isset($_REQUEST['ee_cancel_payment'])
2809
+			&& $payment->status() === EEM_Payment::status_id_failed
2810
+		) {
2811
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2812
+		}
2813
+		return $payment;
2814
+	}
2815
+
2816
+
2817
+	/**
2818
+	 *    get_transaction_details_for_gateways
2819
+	 *
2820
+	 * @access    public
2821
+	 * @return int
2822
+	 * @throws EE_Error
2823
+	 * @throws InvalidArgumentException
2824
+	 * @throws ReflectionException
2825
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2826
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2827
+	 */
2828
+	public function get_transaction_details_for_gateways()
2829
+	{
2830
+		$txn_details = array();
2831
+		// ya gotta make a choice man
2832
+		if (empty($this->checkout->selected_method_of_payment)) {
2833
+			$txn_details = array(
2834
+				'error' => esc_html__('Please select a method of payment before proceeding.', 'event_espresso'),
2835
+			);
2836
+		}
2837
+		// get EE_Payment_Method object
2838
+		if (
2839
+			empty($txn_details)
2840
+			&&
2841
+			! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2842
+		) {
2843
+			$txn_details = array(
2844
+				'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2845
+				'error'                      => esc_html__(
2846
+					'A valid Payment Method could not be determined.',
2847
+					'event_espresso'
2848
+				),
2849
+			);
2850
+		}
2851
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2852
+			$return_url  = $this->_get_return_url($this->checkout->payment_method);
2853
+			$txn_details = array(
2854
+				'TXN_ID'         => $this->checkout->transaction->ID(),
2855
+				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2856
+				'TXN_total'      => $this->checkout->transaction->total(),
2857
+				'TXN_paid'       => $this->checkout->transaction->paid(),
2858
+				'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2859
+				'STS_ID'         => $this->checkout->transaction->status_ID(),
2860
+				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2861
+				'payment_amount' => $this->checkout->amount_owing,
2862
+				'return_url'     => $return_url,
2863
+				'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2864
+				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2865
+					array(
2866
+						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2867
+						'ee_payment_method' => $this->checkout->payment_method->slug(),
2868
+					)
2869
+				),
2870
+			);
2871
+		}
2872
+		echo wp_json_encode($txn_details);
2873
+		exit();
2874
+	}
2875
+
2876
+
2877
+	/**
2878
+	 *    __sleep
2879
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2880
+	 * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2881
+	 * reg form, because if needed, it will be regenerated anyways
2882
+	 *
2883
+	 * @return array
2884
+	 */
2885
+	public function __sleep()
2886
+	{
2887
+		// remove the reg form and the checkout
2888
+		return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2889
+	}
2890 2890
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Message_Template_Group.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -211,7 +211,7 @@
 block discarded – undo
211 211
      * appropriately.
212 212
      *
213 213
      * @throws EE_Error
214
-     * @return EE_message_type|false if exception thrown.
214
+     * @return null|EE_message_type if exception thrown.
215 215
      */
216 216
     public function message_type_obj()
217 217
     {
Please login to merge, or discard this patch.
Indentation   +396 added lines, -396 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -13,400 +13,400 @@  discard block
 block discarded – undo
13 13
 class EE_Message_Template_Group extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * @param array  $props_n_values
18
-     * @param string $timezone
19
-     * @return EE_Message_Template_Group|mixed
20
-     */
21
-    public static function new_instance($props_n_values = array(), $timezone = '')
22
-    {
23
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
24
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone);
25
-    }
26
-
27
-
28
-    /**
29
-     * @param array  $props_n_values
30
-     * @param string $timezone
31
-     * @return EE_Message_Template_Group
32
-     */
33
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
34
-    {
35
-        return new self($props_n_values, true, $timezone);
36
-    }
37
-
38
-
39
-    /**
40
-     * @param bool $message_type
41
-     * @throws EE_Error
42
-     */
43
-    public function set_message_type($message_type = false)
44
-    {
45
-        if (! $message_type) {
46
-            throw new EE_Error(__('Missing required value for the message_type parameter', 'event_espresso'));
47
-        }
48
-        $this->set('MTP_message_type', $message_type);
49
-    }
50
-
51
-
52
-    /**
53
-     * @param bool $messenger
54
-     * @throws EE_Error
55
-     */
56
-    public function set_messenger($messenger = false)
57
-    {
58
-        if (! $messenger) {
59
-            throw new EE_Error(__('Missing required value for the messenger parameter', 'event_espresso'));
60
-        }
61
-        $this->set('MTP_messenger', $messenger);
62
-    }
63
-
64
-
65
-    /**
66
-     * @param bool $GRP_ID
67
-     * @throws EE_Error
68
-     */
69
-    public function set_group_template_id($GRP_ID = false)
70
-    {
71
-        if (! $GRP_ID) {
72
-            throw new EE_Error(__('Missing required value for the message template group id', 'event_espresso'));
73
-        }
74
-        $this->set('GRP_ID', $GRP_ID);
75
-    }
76
-
77
-
78
-    /**
79
-     * get Group ID
80
-     *
81
-     * @access public
82
-     * @return int
83
-     */
84
-    public function GRP_ID()
85
-    {
86
-        return $this->get('GRP_ID');
87
-    }
88
-
89
-
90
-    /**
91
-     * get User ID
92
-     *
93
-     * @access public
94
-     * @return int
95
-     */
96
-    public function user()
97
-    {
98
-        $user_id = $this->get('MTP_user_id');
99
-        return empty($user_id) ? get_current_user_id() : $user_id;
100
-    }
101
-
102
-
103
-    /**
104
-     * Wrapper for the user function() (preserve backward compat)
105
-     *
106
-     * @since  4.5.0
107
-     * @return int
108
-     */
109
-    public function wp_user()
110
-    {
111
-        return $this->user();
112
-    }
113
-
114
-
115
-    /**
116
-     * This simply returns a count of all related events to this message template group
117
-     *
118
-     * @return int
119
-     */
120
-    public function count_events()
121
-    {
122
-        return $this->count_related('Event');
123
-    }
124
-
125
-
126
-    /**
127
-     * returns the name saved in the db for this template
128
-     *
129
-     * @return string
130
-     */
131
-    public function name()
132
-    {
133
-        return $this->get('MTP_name');
134
-    }
135
-
136
-
137
-    /**
138
-     * Returns the description saved in the db for this template group
139
-     *
140
-     * @return string
141
-     */
142
-    public function description()
143
-    {
144
-        return $this->get('MTP_description');
145
-    }
146
-
147
-
148
-    /**
149
-     * returns all related EE_Message_Template objects
150
-     *
151
-     * @param  array $query_params like EEM_Base::get_all()
152
-     * @return EE_Message_Template[]
153
-     */
154
-    public function message_templates($query_params = array())
155
-    {
156
-        return $this->get_many_related('Message_Template', $query_params);
157
-    }
158
-
159
-
160
-    /**
161
-     * get Message Messenger
162
-     *
163
-     * @access public
164
-     * @return string
165
-     */
166
-    public function messenger()
167
-    {
168
-        return $this->get('MTP_messenger');
169
-    }
170
-
171
-
172
-    /**
173
-     * get Message Messenger OBJECT
174
-     * If an attempt to get the corresponding messenger object fails, then we set this message
175
-     * template group to inactive, and save to db.  Then return null so client code can handle
176
-     * appropriately.
177
-     *
178
-     * @return EE_messenger
179
-     */
180
-    public function messenger_obj()
181
-    {
182
-        $messenger = $this->messenger();
183
-        try {
184
-            $messenger = EEH_MSG_Template::messenger_obj($messenger);
185
-        } catch (EE_Error $e) {
186
-            //if an exception was thrown then let's deactivate this message template group because it means there is no class for this messenger in this group.
187
-            $this->set('MTP_is_active', false);
188
-            $this->save();
189
-            return null;
190
-        }
191
-        return $messenger;
192
-    }
193
-
194
-
195
-    /**
196
-     * get Message Type
197
-     *
198
-     * @access public
199
-     * @return string
200
-     */
201
-    public function message_type()
202
-    {
203
-        return $this->get('MTP_message_type');
204
-    }
205
-
206
-
207
-    /**
208
-     * get Message type OBJECT
209
-     * If an attempt to get the corresponding message type object fails, then we set this message
210
-     * template group to inactive, and save to db.  Then return null so client code can handle
211
-     * appropriately.
212
-     *
213
-     * @throws EE_Error
214
-     * @return EE_message_type|false if exception thrown.
215
-     */
216
-    public function message_type_obj()
217
-    {
218
-        $message_type = $this->message_type();
219
-        try {
220
-            $message_type = EEH_MSG_Template::message_type_obj($message_type);
221
-        } catch (EE_Error $e) {
222
-            //if an exception was thrown then let's deactivate this message template group because it means there is no class for the message type in this group.
223
-            $this->set('MTP_is_active', false);
224
-            $this->save();
225
-            return null;
226
-        }
227
-        return $message_type;
228
-    }
229
-
230
-
231
-    /**
232
-     * @return array
233
-     */
234
-    public function contexts_config()
235
-    {
236
-        return $this->message_type_obj()->get_contexts();
237
-    }
238
-
239
-
240
-    /**
241
-     * This returns the context_label for contexts as set in the message type object
242
-     * Note this is an array with singular and plural keys
243
-     *
244
-     * @access public
245
-     * @return array labels for "context"
246
-     */
247
-    public function context_label()
248
-    {
249
-        $obj = $this->message_type_obj();
250
-        return $obj->get_context_label();
251
-    }
252
-
253
-
254
-    /**
255
-     * This returns an array of EE_Message_Template objects indexed by context and field.
256
-     *
257
-     * @return array()
258
-     */
259
-    public function context_templates()
260
-    {
261
-        $mtps_arr = array();
262
-        $mtps     = $this->get_many_related('Message_Template');
263
-        if (empty($mtps)) {
264
-            return array();
265
-        }
266
-        //note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
267
-        foreach ($mtps as $mtp) {
268
-            $mtps_arr[$mtp->get('MTP_context')][$mtp->get('MTP_template_field')] = $mtp;
269
-        }
270
-        return $mtps_arr;
271
-    }
272
-
273
-
274
-    /**
275
-     * this returns if the template group this template belongs to is global
276
-     *
277
-     * @return boolean true if it is, false if it isn't
278
-     */
279
-    public function is_global()
280
-    {
281
-        return $this->get('MTP_is_global');
282
-    }
283
-
284
-
285
-    /**
286
-     * this returns if the template group this template belongs to is active (i.e. turned "on" or not)
287
-     *
288
-     * @return boolean true if it is, false if it isn't
289
-     */
290
-    public function is_active()
291
-    {
292
-        return $this->get('MTP_is_active');
293
-    }
294
-
295
-
296
-    /**
297
-     * This will return an array of shortcodes => labels from the messenger and message_type objects associated with
298
-     * this template.
299
-     *
300
-     * @since 4.3.0
301
-     * @uses  EEH_MSG_Template::get_shortcodes()
302
-     * @param string $context what context we're going to return shortcodes for
303
-     * @param array  $fields  what fields we're returning valid shortcodes for.  If empty then we assume all fields are
304
-     *                        to be returned.
305
-     * @param bool   $merged  If TRUE then we don't return shortcodes indexed by field but instead an array of the
306
-     *                        unique shortcodes for all the given (or all) fields.
307
-     * @return mixed (array|bool) an array of shortcodes in the format array( '[shortcode] => 'label') OR FALSE if no
308
-     *               shortcodes found.
309
-     */
310
-    public function get_shortcodes($context, $fields = array(), $merged = false)
311
-    {
312
-        $messenger    = $this->messenger();
313
-        $message_type = $this->message_type();
314
-        return EEH_MSG_Template::get_shortcodes($message_type, $messenger, $fields, $context, $merged);
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * this just returns and array of instantiated shortcode objects given an array of object refs
321
-     *
322
-     * @access private
323
-     * @param $sc_refs
324
-     * @throws EE_Error
325
-     * @return array    an array of EE_Shortcode objects
326
-     */
327
-    //private function _get_shortcode_objects( $sc_refs ) {
328
-    //	$sc_objs = array();
329
-    //	EED_Messages::set_autoloaders();
330
-    //	foreach ( $sc_refs as $shortcode_ref ) {
331
-    //		$ref = ucwords( str_replace( '_', ' ', $shortcode_ref ) );
332
-    //		$ref = str_replace( ' ', '_', $ref );
333
-    //		$classname = 'EE_' . $ref . '_Shortcodes';
334
-    //		if ( ! class_exists( $classname ) ) {
335
-    //			$msg[ ] = __( 'Shortcode library loading fail.', 'event_espresso' );
336
-    //			$msg[ ] = sprintf( __( 'The class name checked was "%s". Please check the spelling and case of this reference and make sure it matches the appropriate shortcode library file name (minus the extension) in the "/library/shortcodes/" directory', 'event_espresso' ), $classname );
337
-    //			throw new EE_Error( implode( '||', $msg ) );
338
-    //		}
339
-    //		$a = new ReflectionClass( $classname );
340
-    //		$sc_objs[ ] = $a->newInstance();
341
-    //	}
342
-    //	return $sc_objs;
343
-    //}
344
-
345
-
346
-    /**
347
-     * This just gets the template pack name assigned to this message template group.  If it's not set, then we just
348
-     * use the default template pack.
349
-     *
350
-     * @since 4.5.0
351
-     * @return string
352
-     */
353
-    public function get_template_pack_name()
354
-    {
355
-        return $this->get_extra_meta('MTP_template_pack', true, 'default');
356
-    }
357
-
358
-
359
-    /**
360
-     * This returns the specific template pack object referenced by the template pack name attached to this message
361
-     * template group.  If no template pack is assigned then the default template pack is retrieved.
362
-     *
363
-     * @since 4.5.0
364
-     * @return EE_Messages_Template_Pack
365
-     */
366
-    public function get_template_pack()
367
-    {
368
-        $pack_name = $this->get_template_pack_name();
369
-        EE_Registry::instance()->load_helper('MSG_Template');
370
-        return EEH_MSG_Template::get_template_pack($pack_name);
371
-    }
372
-
373
-
374
-    /**
375
-     * This retrieves the template variation assigned to this message template group.  If it's not set, then we just
376
-     * use the default template variation.
377
-     *
378
-     * @since 4.5.0
379
-     * @return string
380
-     */
381
-    public function get_template_pack_variation()
382
-    {
383
-        return $this->get_extra_meta('MTP_variation', true, 'default');
384
-    }
385
-
386
-
387
-    /**
388
-     * This just sets the template pack name attached to this message template group.
389
-     *
390
-     * @since 4.5.0
391
-     * @param string $template_pack_name What message template pack is assigned.
392
-     * @return int
393
-     */
394
-    public function set_template_pack_name($template_pack_name)
395
-    {
396
-        return $this->update_extra_meta('MTP_template_pack', $template_pack_name);
397
-    }
398
-
399
-
400
-    /**
401
-     * This just sets the template pack variation attached to this message template group.
402
-     *
403
-     * @since 4.5.0
404
-     * @param string $variation What variation is being set on the message template group.
405
-     * @return int
406
-     */
407
-    public function set_template_pack_variation($variation)
408
-    {
409
-        return $this->update_extra_meta('MTP_variation', $variation);
410
-    }
16
+	/**
17
+	 * @param array  $props_n_values
18
+	 * @param string $timezone
19
+	 * @return EE_Message_Template_Group|mixed
20
+	 */
21
+	public static function new_instance($props_n_values = array(), $timezone = '')
22
+	{
23
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
24
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone);
25
+	}
26
+
27
+
28
+	/**
29
+	 * @param array  $props_n_values
30
+	 * @param string $timezone
31
+	 * @return EE_Message_Template_Group
32
+	 */
33
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
34
+	{
35
+		return new self($props_n_values, true, $timezone);
36
+	}
37
+
38
+
39
+	/**
40
+	 * @param bool $message_type
41
+	 * @throws EE_Error
42
+	 */
43
+	public function set_message_type($message_type = false)
44
+	{
45
+		if (! $message_type) {
46
+			throw new EE_Error(__('Missing required value for the message_type parameter', 'event_espresso'));
47
+		}
48
+		$this->set('MTP_message_type', $message_type);
49
+	}
50
+
51
+
52
+	/**
53
+	 * @param bool $messenger
54
+	 * @throws EE_Error
55
+	 */
56
+	public function set_messenger($messenger = false)
57
+	{
58
+		if (! $messenger) {
59
+			throw new EE_Error(__('Missing required value for the messenger parameter', 'event_espresso'));
60
+		}
61
+		$this->set('MTP_messenger', $messenger);
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param bool $GRP_ID
67
+	 * @throws EE_Error
68
+	 */
69
+	public function set_group_template_id($GRP_ID = false)
70
+	{
71
+		if (! $GRP_ID) {
72
+			throw new EE_Error(__('Missing required value for the message template group id', 'event_espresso'));
73
+		}
74
+		$this->set('GRP_ID', $GRP_ID);
75
+	}
76
+
77
+
78
+	/**
79
+	 * get Group ID
80
+	 *
81
+	 * @access public
82
+	 * @return int
83
+	 */
84
+	public function GRP_ID()
85
+	{
86
+		return $this->get('GRP_ID');
87
+	}
88
+
89
+
90
+	/**
91
+	 * get User ID
92
+	 *
93
+	 * @access public
94
+	 * @return int
95
+	 */
96
+	public function user()
97
+	{
98
+		$user_id = $this->get('MTP_user_id');
99
+		return empty($user_id) ? get_current_user_id() : $user_id;
100
+	}
101
+
102
+
103
+	/**
104
+	 * Wrapper for the user function() (preserve backward compat)
105
+	 *
106
+	 * @since  4.5.0
107
+	 * @return int
108
+	 */
109
+	public function wp_user()
110
+	{
111
+		return $this->user();
112
+	}
113
+
114
+
115
+	/**
116
+	 * This simply returns a count of all related events to this message template group
117
+	 *
118
+	 * @return int
119
+	 */
120
+	public function count_events()
121
+	{
122
+		return $this->count_related('Event');
123
+	}
124
+
125
+
126
+	/**
127
+	 * returns the name saved in the db for this template
128
+	 *
129
+	 * @return string
130
+	 */
131
+	public function name()
132
+	{
133
+		return $this->get('MTP_name');
134
+	}
135
+
136
+
137
+	/**
138
+	 * Returns the description saved in the db for this template group
139
+	 *
140
+	 * @return string
141
+	 */
142
+	public function description()
143
+	{
144
+		return $this->get('MTP_description');
145
+	}
146
+
147
+
148
+	/**
149
+	 * returns all related EE_Message_Template objects
150
+	 *
151
+	 * @param  array $query_params like EEM_Base::get_all()
152
+	 * @return EE_Message_Template[]
153
+	 */
154
+	public function message_templates($query_params = array())
155
+	{
156
+		return $this->get_many_related('Message_Template', $query_params);
157
+	}
158
+
159
+
160
+	/**
161
+	 * get Message Messenger
162
+	 *
163
+	 * @access public
164
+	 * @return string
165
+	 */
166
+	public function messenger()
167
+	{
168
+		return $this->get('MTP_messenger');
169
+	}
170
+
171
+
172
+	/**
173
+	 * get Message Messenger OBJECT
174
+	 * If an attempt to get the corresponding messenger object fails, then we set this message
175
+	 * template group to inactive, and save to db.  Then return null so client code can handle
176
+	 * appropriately.
177
+	 *
178
+	 * @return EE_messenger
179
+	 */
180
+	public function messenger_obj()
181
+	{
182
+		$messenger = $this->messenger();
183
+		try {
184
+			$messenger = EEH_MSG_Template::messenger_obj($messenger);
185
+		} catch (EE_Error $e) {
186
+			//if an exception was thrown then let's deactivate this message template group because it means there is no class for this messenger in this group.
187
+			$this->set('MTP_is_active', false);
188
+			$this->save();
189
+			return null;
190
+		}
191
+		return $messenger;
192
+	}
193
+
194
+
195
+	/**
196
+	 * get Message Type
197
+	 *
198
+	 * @access public
199
+	 * @return string
200
+	 */
201
+	public function message_type()
202
+	{
203
+		return $this->get('MTP_message_type');
204
+	}
205
+
206
+
207
+	/**
208
+	 * get Message type OBJECT
209
+	 * If an attempt to get the corresponding message type object fails, then we set this message
210
+	 * template group to inactive, and save to db.  Then return null so client code can handle
211
+	 * appropriately.
212
+	 *
213
+	 * @throws EE_Error
214
+	 * @return EE_message_type|false if exception thrown.
215
+	 */
216
+	public function message_type_obj()
217
+	{
218
+		$message_type = $this->message_type();
219
+		try {
220
+			$message_type = EEH_MSG_Template::message_type_obj($message_type);
221
+		} catch (EE_Error $e) {
222
+			//if an exception was thrown then let's deactivate this message template group because it means there is no class for the message type in this group.
223
+			$this->set('MTP_is_active', false);
224
+			$this->save();
225
+			return null;
226
+		}
227
+		return $message_type;
228
+	}
229
+
230
+
231
+	/**
232
+	 * @return array
233
+	 */
234
+	public function contexts_config()
235
+	{
236
+		return $this->message_type_obj()->get_contexts();
237
+	}
238
+
239
+
240
+	/**
241
+	 * This returns the context_label for contexts as set in the message type object
242
+	 * Note this is an array with singular and plural keys
243
+	 *
244
+	 * @access public
245
+	 * @return array labels for "context"
246
+	 */
247
+	public function context_label()
248
+	{
249
+		$obj = $this->message_type_obj();
250
+		return $obj->get_context_label();
251
+	}
252
+
253
+
254
+	/**
255
+	 * This returns an array of EE_Message_Template objects indexed by context and field.
256
+	 *
257
+	 * @return array()
258
+	 */
259
+	public function context_templates()
260
+	{
261
+		$mtps_arr = array();
262
+		$mtps     = $this->get_many_related('Message_Template');
263
+		if (empty($mtps)) {
264
+			return array();
265
+		}
266
+		//note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
267
+		foreach ($mtps as $mtp) {
268
+			$mtps_arr[$mtp->get('MTP_context')][$mtp->get('MTP_template_field')] = $mtp;
269
+		}
270
+		return $mtps_arr;
271
+	}
272
+
273
+
274
+	/**
275
+	 * this returns if the template group this template belongs to is global
276
+	 *
277
+	 * @return boolean true if it is, false if it isn't
278
+	 */
279
+	public function is_global()
280
+	{
281
+		return $this->get('MTP_is_global');
282
+	}
283
+
284
+
285
+	/**
286
+	 * this returns if the template group this template belongs to is active (i.e. turned "on" or not)
287
+	 *
288
+	 * @return boolean true if it is, false if it isn't
289
+	 */
290
+	public function is_active()
291
+	{
292
+		return $this->get('MTP_is_active');
293
+	}
294
+
295
+
296
+	/**
297
+	 * This will return an array of shortcodes => labels from the messenger and message_type objects associated with
298
+	 * this template.
299
+	 *
300
+	 * @since 4.3.0
301
+	 * @uses  EEH_MSG_Template::get_shortcodes()
302
+	 * @param string $context what context we're going to return shortcodes for
303
+	 * @param array  $fields  what fields we're returning valid shortcodes for.  If empty then we assume all fields are
304
+	 *                        to be returned.
305
+	 * @param bool   $merged  If TRUE then we don't return shortcodes indexed by field but instead an array of the
306
+	 *                        unique shortcodes for all the given (or all) fields.
307
+	 * @return mixed (array|bool) an array of shortcodes in the format array( '[shortcode] => 'label') OR FALSE if no
308
+	 *               shortcodes found.
309
+	 */
310
+	public function get_shortcodes($context, $fields = array(), $merged = false)
311
+	{
312
+		$messenger    = $this->messenger();
313
+		$message_type = $this->message_type();
314
+		return EEH_MSG_Template::get_shortcodes($message_type, $messenger, $fields, $context, $merged);
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * this just returns and array of instantiated shortcode objects given an array of object refs
321
+	 *
322
+	 * @access private
323
+	 * @param $sc_refs
324
+	 * @throws EE_Error
325
+	 * @return array    an array of EE_Shortcode objects
326
+	 */
327
+	//private function _get_shortcode_objects( $sc_refs ) {
328
+	//	$sc_objs = array();
329
+	//	EED_Messages::set_autoloaders();
330
+	//	foreach ( $sc_refs as $shortcode_ref ) {
331
+	//		$ref = ucwords( str_replace( '_', ' ', $shortcode_ref ) );
332
+	//		$ref = str_replace( ' ', '_', $ref );
333
+	//		$classname = 'EE_' . $ref . '_Shortcodes';
334
+	//		if ( ! class_exists( $classname ) ) {
335
+	//			$msg[ ] = __( 'Shortcode library loading fail.', 'event_espresso' );
336
+	//			$msg[ ] = sprintf( __( 'The class name checked was "%s". Please check the spelling and case of this reference and make sure it matches the appropriate shortcode library file name (minus the extension) in the "/library/shortcodes/" directory', 'event_espresso' ), $classname );
337
+	//			throw new EE_Error( implode( '||', $msg ) );
338
+	//		}
339
+	//		$a = new ReflectionClass( $classname );
340
+	//		$sc_objs[ ] = $a->newInstance();
341
+	//	}
342
+	//	return $sc_objs;
343
+	//}
344
+
345
+
346
+	/**
347
+	 * This just gets the template pack name assigned to this message template group.  If it's not set, then we just
348
+	 * use the default template pack.
349
+	 *
350
+	 * @since 4.5.0
351
+	 * @return string
352
+	 */
353
+	public function get_template_pack_name()
354
+	{
355
+		return $this->get_extra_meta('MTP_template_pack', true, 'default');
356
+	}
357
+
358
+
359
+	/**
360
+	 * This returns the specific template pack object referenced by the template pack name attached to this message
361
+	 * template group.  If no template pack is assigned then the default template pack is retrieved.
362
+	 *
363
+	 * @since 4.5.0
364
+	 * @return EE_Messages_Template_Pack
365
+	 */
366
+	public function get_template_pack()
367
+	{
368
+		$pack_name = $this->get_template_pack_name();
369
+		EE_Registry::instance()->load_helper('MSG_Template');
370
+		return EEH_MSG_Template::get_template_pack($pack_name);
371
+	}
372
+
373
+
374
+	/**
375
+	 * This retrieves the template variation assigned to this message template group.  If it's not set, then we just
376
+	 * use the default template variation.
377
+	 *
378
+	 * @since 4.5.0
379
+	 * @return string
380
+	 */
381
+	public function get_template_pack_variation()
382
+	{
383
+		return $this->get_extra_meta('MTP_variation', true, 'default');
384
+	}
385
+
386
+
387
+	/**
388
+	 * This just sets the template pack name attached to this message template group.
389
+	 *
390
+	 * @since 4.5.0
391
+	 * @param string $template_pack_name What message template pack is assigned.
392
+	 * @return int
393
+	 */
394
+	public function set_template_pack_name($template_pack_name)
395
+	{
396
+		return $this->update_extra_meta('MTP_template_pack', $template_pack_name);
397
+	}
398
+
399
+
400
+	/**
401
+	 * This just sets the template pack variation attached to this message template group.
402
+	 *
403
+	 * @since 4.5.0
404
+	 * @param string $variation What variation is being set on the message template group.
405
+	 * @return int
406
+	 */
407
+	public function set_template_pack_variation($variation)
408
+	{
409
+		return $this->update_extra_meta('MTP_variation', $variation);
410
+	}
411 411
 }
412 412
 //end EE_Message_Template_Group class
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
      */
43 43
     public function set_message_type($message_type = false)
44 44
     {
45
-        if (! $message_type) {
45
+        if ( ! $message_type) {
46 46
             throw new EE_Error(__('Missing required value for the message_type parameter', 'event_espresso'));
47 47
         }
48 48
         $this->set('MTP_message_type', $message_type);
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
      */
56 56
     public function set_messenger($messenger = false)
57 57
     {
58
-        if (! $messenger) {
58
+        if ( ! $messenger) {
59 59
             throw new EE_Error(__('Missing required value for the messenger parameter', 'event_espresso'));
60 60
         }
61 61
         $this->set('MTP_messenger', $messenger);
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
      */
69 69
     public function set_group_template_id($GRP_ID = false)
70 70
     {
71
-        if (! $GRP_ID) {
71
+        if ( ! $GRP_ID) {
72 72
             throw new EE_Error(__('Missing required value for the message template group id', 'event_espresso'));
73 73
         }
74 74
         $this->set('GRP_ID', $GRP_ID);
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -38,217 +38,217 @@
 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
 
64 64
 } else {
65
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
-        /**
68
-         * espresso_minimum_php_version_error
69
-         *
70
-         * @return void
71
-         */
72
-        function espresso_minimum_php_version_error()
73
-        {
74
-            ?>
65
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
+		/**
68
+		 * espresso_minimum_php_version_error
69
+		 *
70
+		 * @return void
71
+		 */
72
+		function espresso_minimum_php_version_error()
73
+		{
74
+			?>
75 75
             <div class="error">
76 76
                 <p>
77 77
                     <?php
78
-                    printf(
79
-                        esc_html__(
80
-                            '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.',
81
-                            'event_espresso'
82
-                        ),
83
-                        EE_MIN_PHP_VER_REQUIRED,
84
-                        PHP_VERSION,
85
-                        '<br/>',
86
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
87
-                    );
88
-                    ?>
78
+					printf(
79
+						esc_html__(
80
+							'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.',
81
+							'event_espresso'
82
+						),
83
+						EE_MIN_PHP_VER_REQUIRED,
84
+						PHP_VERSION,
85
+						'<br/>',
86
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
87
+					);
88
+					?>
89 89
                 </p>
90 90
             </div>
91 91
             <?php
92
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
93
-        }
92
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
93
+		}
94 94
 
95
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
96
-    } else {
97
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
98
-        /**
99
-         * espresso_version
100
-         * Returns the plugin version
101
-         *
102
-         * @return string
103
-         */
104
-        function espresso_version()
105
-        {
106
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.066');
107
-        }
95
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
96
+	} else {
97
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
98
+		/**
99
+		 * espresso_version
100
+		 * Returns the plugin version
101
+		 *
102
+		 * @return string
103
+		 */
104
+		function espresso_version()
105
+		{
106
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.066');
107
+		}
108 108
 
109
-        /**
110
-         * espresso_plugin_activation
111
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
112
-         */
113
-        function espresso_plugin_activation()
114
-        {
115
-            update_option('ee_espresso_activation', true);
116
-        }
109
+		/**
110
+		 * espresso_plugin_activation
111
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
112
+		 */
113
+		function espresso_plugin_activation()
114
+		{
115
+			update_option('ee_espresso_activation', true);
116
+		}
117 117
 
118
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
119
-        /**
120
-         *    espresso_load_error_handling
121
-         *    this function loads EE's class for handling exceptions and errors
122
-         */
123
-        function espresso_load_error_handling()
124
-        {
125
-            static $error_handling_loaded = false;
126
-            if ($error_handling_loaded) {
127
-                return;
128
-            }
129
-            // load debugging tools
130
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
131
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
132
-                \EEH_Debug_Tools::instance();
133
-            }
134
-            // load error handling
135
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
136
-                require_once(EE_CORE . 'EE_Error.core.php');
137
-            } else {
138
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
139
-            }
140
-            $error_handling_loaded = true;
141
-        }
118
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
119
+		/**
120
+		 *    espresso_load_error_handling
121
+		 *    this function loads EE's class for handling exceptions and errors
122
+		 */
123
+		function espresso_load_error_handling()
124
+		{
125
+			static $error_handling_loaded = false;
126
+			if ($error_handling_loaded) {
127
+				return;
128
+			}
129
+			// load debugging tools
130
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
131
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
132
+				\EEH_Debug_Tools::instance();
133
+			}
134
+			// load error handling
135
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
136
+				require_once(EE_CORE . 'EE_Error.core.php');
137
+			} else {
138
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
139
+			}
140
+			$error_handling_loaded = true;
141
+		}
142 142
 
143
-        /**
144
-         *    espresso_load_required
145
-         *    given a class name and path, this function will load that file or throw an exception
146
-         *
147
-         * @param    string $classname
148
-         * @param    string $full_path_to_file
149
-         * @throws    EE_Error
150
-         */
151
-        function espresso_load_required($classname, $full_path_to_file)
152
-        {
153
-            if (is_readable($full_path_to_file)) {
154
-                require_once($full_path_to_file);
155
-            } else {
156
-                throw new \EE_Error (
157
-                    sprintf(
158
-                        esc_html__(
159
-                            'The %s class file could not be located or is not readable due to file permissions.',
160
-                            'event_espresso'
161
-                        ),
162
-                        $classname
163
-                    )
164
-                );
165
-            }
166
-        }
143
+		/**
144
+		 *    espresso_load_required
145
+		 *    given a class name and path, this function will load that file or throw an exception
146
+		 *
147
+		 * @param    string $classname
148
+		 * @param    string $full_path_to_file
149
+		 * @throws    EE_Error
150
+		 */
151
+		function espresso_load_required($classname, $full_path_to_file)
152
+		{
153
+			if (is_readable($full_path_to_file)) {
154
+				require_once($full_path_to_file);
155
+			} else {
156
+				throw new \EE_Error (
157
+					sprintf(
158
+						esc_html__(
159
+							'The %s class file could not be located or is not readable due to file permissions.',
160
+							'event_espresso'
161
+						),
162
+						$classname
163
+					)
164
+				);
165
+			}
166
+		}
167 167
 
168
-        /**
169
-         * @since 4.9.27
170
-         * @throws \EE_Error
171
-         * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
172
-         * @throws \EventEspresso\core\exceptions\InvalidEntityException
173
-         * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
174
-         * @throws \EventEspresso\core\exceptions\InvalidClassException
175
-         * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
176
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
177
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
178
-         * @throws \OutOfBoundsException
179
-         */
180
-        function bootstrap_espresso()
181
-        {
182
-            require_once(plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE) . 'core/espresso_definitions.php');
183
-            try {
184
-                espresso_load_error_handling();
185
-                espresso_load_required(
186
-                    'EEH_Base',
187
-                    EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
188
-                );
189
-                espresso_load_required(
190
-                    'EEH_File',
191
-                    EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
192
-                );
193
-                espresso_load_required(
194
-                    'EEH_File',
195
-                    EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
196
-                );
197
-                espresso_load_required(
198
-                    'EEH_Array',
199
-                    EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
200
-                );
201
-                // instantiate and configure PSR4 autoloader
202
-                espresso_load_required(
203
-                    'Psr4Autoloader',
204
-                    EE_CORE . 'Psr4Autoloader.php'
205
-                );
206
-                espresso_load_required(
207
-                    'EE_Psr4AutoloaderInit',
208
-                    EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
209
-                );
210
-                $AutoloaderInit = new EE_Psr4AutoloaderInit();
211
-                $AutoloaderInit->initializeAutoloader();
212
-                espresso_load_required(
213
-                    'EE_Request',
214
-                    EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
215
-                );
216
-                espresso_load_required(
217
-                    'EE_Response',
218
-                    EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
219
-                );
220
-                espresso_load_required(
221
-                    'EE_Bootstrap',
222
-                    EE_CORE . 'EE_Bootstrap.core.php'
223
-                );
224
-                // bootstrap EE and the request stack
225
-                new EE_Bootstrap(
226
-                    new EE_Request($_GET, $_POST, $_COOKIE),
227
-                    new EE_Response()
228
-                );
229
-            } catch (Exception $e) {
230
-                require_once EE_CORE . 'exceptions.' . DS . 'ExceptionStackTraceDisplay.php';
231
-                new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
232
-            }
233
-        }
234
-        bootstrap_espresso();
235
-    }
168
+		/**
169
+		 * @since 4.9.27
170
+		 * @throws \EE_Error
171
+		 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
172
+		 * @throws \EventEspresso\core\exceptions\InvalidEntityException
173
+		 * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
174
+		 * @throws \EventEspresso\core\exceptions\InvalidClassException
175
+		 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
176
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
177
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
178
+		 * @throws \OutOfBoundsException
179
+		 */
180
+		function bootstrap_espresso()
181
+		{
182
+			require_once(plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE) . 'core/espresso_definitions.php');
183
+			try {
184
+				espresso_load_error_handling();
185
+				espresso_load_required(
186
+					'EEH_Base',
187
+					EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
188
+				);
189
+				espresso_load_required(
190
+					'EEH_File',
191
+					EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
192
+				);
193
+				espresso_load_required(
194
+					'EEH_File',
195
+					EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
196
+				);
197
+				espresso_load_required(
198
+					'EEH_Array',
199
+					EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
200
+				);
201
+				// instantiate and configure PSR4 autoloader
202
+				espresso_load_required(
203
+					'Psr4Autoloader',
204
+					EE_CORE . 'Psr4Autoloader.php'
205
+				);
206
+				espresso_load_required(
207
+					'EE_Psr4AutoloaderInit',
208
+					EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
209
+				);
210
+				$AutoloaderInit = new EE_Psr4AutoloaderInit();
211
+				$AutoloaderInit->initializeAutoloader();
212
+				espresso_load_required(
213
+					'EE_Request',
214
+					EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
215
+				);
216
+				espresso_load_required(
217
+					'EE_Response',
218
+					EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
219
+				);
220
+				espresso_load_required(
221
+					'EE_Bootstrap',
222
+					EE_CORE . 'EE_Bootstrap.core.php'
223
+				);
224
+				// bootstrap EE and the request stack
225
+				new EE_Bootstrap(
226
+					new EE_Request($_GET, $_POST, $_COOKIE),
227
+					new EE_Response()
228
+				);
229
+			} catch (Exception $e) {
230
+				require_once EE_CORE . 'exceptions.' . DS . 'ExceptionStackTraceDisplay.php';
231
+				new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
232
+			}
233
+		}
234
+		bootstrap_espresso();
235
+	}
236 236
 }
237 237
 if (! function_exists('espresso_deactivate_plugin')) {
238
-    /**
239
-     *    deactivate_plugin
240
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
241
-     *
242
-     * @access public
243
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
244
-     * @return    void
245
-     */
246
-    function espresso_deactivate_plugin($plugin_basename = '')
247
-    {
248
-        if (! function_exists('deactivate_plugins')) {
249
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
250
-        }
251
-        unset($_GET['activate'], $_REQUEST['activate']);
252
-        deactivate_plugins($plugin_basename);
253
-    }
238
+	/**
239
+	 *    deactivate_plugin
240
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
241
+	 *
242
+	 * @access public
243
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
244
+	 * @return    void
245
+	 */
246
+	function espresso_deactivate_plugin($plugin_basename = '')
247
+	{
248
+		if (! function_exists('deactivate_plugins')) {
249
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
250
+		}
251
+		unset($_GET['activate'], $_REQUEST['activate']);
252
+		deactivate_plugins($plugin_basename);
253
+	}
254 254
 }
Please login to merge, or discard this patch.