Completed
Branch FET-Wait-List (92c8c5)
by
unknown
134:10 queued 122:28
created

EE_Registration::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
use EventEspresso\core\domain\entities\Context;
4
use EventEspresso\core\exceptions\EntityNotFoundException;
5
use EventEspresso\core\exceptions\InvalidDataTypeException;
6
use EventEspresso\core\exceptions\InvalidInterfaceException;
7
8
defined('EVENT_ESPRESSO_VERSION') || exit('No direct access allowed');
9
10
/**
11
 * EE_Registration class
12
 *
13
 * @package               Event Espresso
14
 * @subpackage            includes/classes/EE_Registration.class.php
15
 * @author                Mike Nelson, Brent Christensen
16
 */
17
class EE_Registration extends EE_Soft_Delete_Base_Class implements EEI_Registration, EEI_Admin_Links
18
{
19
20
21
    /**
22
     * Used to reference when a registration has never been checked in.
23
     *
24
     * @deprecated use \EE_Checkin::status_checked_never instead
25
     * @type int
26
     */
27
    const checkin_status_never = 2;
28
29
    /**
30
     * Used to reference when a registration has been checked in.
31
     *
32
     * @deprecated use \EE_Checkin::status_checked_in instead
33
     * @type int
34
     */
35
    const checkin_status_in = 1;
36
37
38
    /**
39
     * Used to reference when a registration has been checked out.
40
     *
41
     * @deprecated use \EE_Checkin::status_checked_out instead
42
     * @type int
43
     */
44
    const checkin_status_out = 0;
45
46
47
    /**
48
     * extra meta key for tracking reg status os trashed registrations
49
     *
50
     * @type string
51
     */
52
    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
53
54
55
    /**
56
     * extra meta key for tracking if registration has reserved ticket
57
     *
58
     * @type string
59
     */
60
    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
61
62
63
    /**
64
     * @param array  $props_n_values          incoming values
65
     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
66
     *                                        used.)
67
     * @param array  $date_formats            incoming date_formats in an array where the first value is the
68
     *                                        date_format and the second value is the time format
69
     * @return EE_Registration
70
     * @throws EE_Error
71
     */
72
    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
73
    {
74
        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
75
        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
76
    }
77
78
79
    /**
80
     * @param array  $props_n_values  incoming values from the database
81
     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
     *                                the website will be used.
83
     * @return EE_Registration
84
     */
85
    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
86
    {
87
        return new self($props_n_values, true, $timezone);
88
    }
89
90
91
    /**
92
     *        Set Event ID
93
     *
94
     * @param        int $EVT_ID Event ID
95
     * @throws EE_Error
96
     * @throws RuntimeException
97
     */
98
    public function set_event($EVT_ID = 0)
99
    {
100
        $this->set('EVT_ID', $EVT_ID);
101
    }
102
103
104
    /**
105
     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
106
     * be routed to internal methods
107
     *
108
     * @param string $field_name
109
     * @param mixed  $field_value
110
     * @param bool   $use_default
111
     * @throws EE_Error
112
     * @throws EntityNotFoundException
113
     * @throws InvalidArgumentException
114
     * @throws InvalidDataTypeException
115
     * @throws InvalidInterfaceException
116
     * @throws ReflectionException
117
     * @throws RuntimeException
118
     */
119
    public function set($field_name, $field_value, $use_default = false)
120
    {
121
        switch ($field_name) {
122
            case 'REG_code':
123
                if (! empty($field_value) && $this->reg_code() === null) {
124
                    $this->set_reg_code($field_value, $use_default);
125
                }
126
                break;
127
            case 'STS_ID':
128
                $this->set_status($field_value, $use_default);
129
                break;
130
            default:
131
                parent::set($field_name, $field_value, $use_default);
132
        }
133
    }
134
135
136
    /**
137
     * Set Status ID
138
     * updates the registration status and ALSO...
139
     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
140
     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
141
     *
142
     * @param string       $new_STS_ID
143
     * @param boolean      $use_default
144
     * @param Context|null $context
145
     * @return bool
146
     * @throws EE_Error
147
     * @throws EntityNotFoundException
148
     * @throws InvalidArgumentException
149
     * @throws ReflectionException
150
     * @throws RuntimeException
151
     * @throws InvalidDataTypeException
152
     * @throws InvalidInterfaceException
153
     */
154
    public function set_status($new_STS_ID = null, $use_default = false, Context $context = null)
155
    {
156
        // get current REG_Status
157
        $old_STS_ID = $this->status_ID();
158
        // if status has changed
159
        if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
160
            && ! empty($old_STS_ID) // and that old status is actually set
161
            && ! empty($new_STS_ID) // as well as the new status
162
            && $this->ID() // ensure registration is in the db
163
        ) {
164
            // TO approved
165
            if ($new_STS_ID === EEM_Registration::status_id_approved) {
166
                // reserve a space by incrementing ticket and datetime sold values
167
                $this->_reserve_registration_space();
168
                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
169
                // OR FROM  approved
170
            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
171
                // release a space by decrementing ticket and datetime sold values
172
                $this->_release_registration_space();
173
                do_action(
174
                    'AHEE__EE_Registration__set_status__from_approved',
175
                    $this,
176
                    $old_STS_ID,
177
                    $new_STS_ID,
178
                    $context
179
                );
180
            }
181
            // update status
182
            parent::set('STS_ID', $new_STS_ID, $use_default);
183
            $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
184
            if($this->statusChangeUpdatesTransaction($context)) {
185
                $this->updateTransactionAfterStatusChange();
186
            }
187
            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
188
            return true;
189
        }
190
        //even though the old value matches the new value, it's still good to
191
        //allow the parent set method to have a say
192
        parent::set('STS_ID', $new_STS_ID, $use_default);
193
        return true;
194
    }
195
196
197
    /**
198
     * update REGs and TXN when cancelled or declined registrations involved
199
     *
200
     * @param string       $new_STS_ID
201
     * @param string       $old_STS_ID
202
     * @param Context|null $context
203
     * @throws EE_Error
204
     * @throws InvalidArgumentException
205
     * @throws InvalidDataTypeException
206
     * @throws InvalidInterfaceException
207
     * @throws ReflectionException
208
     */
209
    private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, Context $context = null)
210
    {
211
        // these reg statuses should not be considered in any calculations involving monies owing
212
        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
213
        // true if registration has been cancelled or declined
214
        $this->updateIfCanceled(
215
            $closed_reg_statuses,
216
            $new_STS_ID,
217
            $old_STS_ID,
218
            $context
219
        );
220
        $this->updateIfDeclined(
221
            $closed_reg_statuses,
222
            $new_STS_ID,
223
            $old_STS_ID,
224
            $context
225
        );
226
    }
227
228
229
    /**
230
     * update REGs and TXN when cancelled or declined registrations involved
231
     *
232
     * @param array        $closed_reg_statuses
233
     * @param string       $new_STS_ID
234
     * @param string       $old_STS_ID
235
     * @param Context|null $context
236
     * @throws EE_Error
237
     * @throws InvalidArgumentException
238
     * @throws InvalidDataTypeException
239
     * @throws InvalidInterfaceException
240
     * @throws ReflectionException
241
     */
242 View Code Duplication
    private function updateIfCanceled(array $closed_reg_statuses, $new_STS_ID, $old_STS_ID, Context $context = null)
243
    {
244
        // true if registration has been cancelled or declined
245
        if (in_array($new_STS_ID, $closed_reg_statuses, true)
246
            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
247
        ) {
248
            /** @type EE_Registration_Processor $registration_processor */
249
            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
250
            /** @type EE_Transaction_Processor $transaction_processor */
251
            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
252
            // cancelled or declined registration
253
            $registration_processor->update_registration_after_being_canceled_or_declined(
254
                $this,
255
                $closed_reg_statuses
256
            );
257
            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
258
                $this,
259
                $closed_reg_statuses,
260
                false
261
            );
262
            do_action(
263
                'AHEE__EE_Registration__set_status__canceled_or_declined',
264
                $this,
265
                $old_STS_ID,
266
                $new_STS_ID,
267
                $context
268
            );
269
            return;
270
        }
271
    }
272
273
274
    /**
275
     * update REGs and TXN when cancelled or declined registrations involved
276
     *
277
     * @param array        $closed_reg_statuses
278
     * @param string       $new_STS_ID
279
     * @param string       $old_STS_ID
280
     * @param Context|null $context
281
     * @throws EE_Error
282
     * @throws InvalidArgumentException
283
     * @throws InvalidDataTypeException
284
     * @throws InvalidInterfaceException
285
     * @throws ReflectionException
286
     */
287 View Code Duplication
    private function updateIfDeclined(array $closed_reg_statuses, $new_STS_ID, $old_STS_ID, Context $context = null)
288
    {
289
        // true if reinstating cancelled or declined registration
290
        if (in_array($old_STS_ID, $closed_reg_statuses, true)
291
            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
292
        ) {
293
            /** @type EE_Registration_Processor $registration_processor */
294
            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
295
            /** @type EE_Transaction_Processor $transaction_processor */
296
            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
297
            // reinstating cancelled or declined registration
298
            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
299
                $this,
300
                $closed_reg_statuses
301
            );
302
            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
303
                $this,
304
                $closed_reg_statuses,
305
                false
306
            );
307
            do_action(
308
                'AHEE__EE_Registration__set_status__after_reinstated',
309
                $this,
310
                $old_STS_ID,
311
                $new_STS_ID,
312
                $context
313
            );
314
        }
315
    }
316
317
318
    /**
319
     * @param Context|null $context
320
     * @return bool
321
     */
322
    private function statusChangeUpdatesTransaction(Context $context = null)
323
    {
324
        $contexts_that_do_not_update_transaction = (array) apply_filters(
325
            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
326
            array('spco_reg_step_attendee_information_process_registrations'),
327
            $context,
328
            $this
329
        );
330
        return ! (
331
            $context instanceof Context
332
            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
333
        );
334
    }
335
336
337
    /**
338
     * @throws EE_Error
339
     * @throws EntityNotFoundException
340
     * @throws InvalidArgumentException
341
     * @throws InvalidDataTypeException
342
     * @throws InvalidInterfaceException
343
     * @throws ReflectionException
344
     * @throws RuntimeException
345
     */
346
    private function updateTransactionAfterStatusChange()
347
    {
348
        /** @type EE_Transaction_Payments $transaction_payments */
349
        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
350
        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
351
        $this->transaction()->update_status_based_on_total_paid(true);
352
    }
353
354
355
    /**
356
     *        get Status ID
357
     */
358
    public function status_ID()
359
    {
360
        return $this->get('STS_ID');
361
    }
362
363
364
    /**
365
     * increments this registration's related ticket sold and corresponding datetime sold values
366
     *
367
     * @return void
368
     * @throws EE_Error
369
     * @throws EntityNotFoundException
370
     */
371
    private function _reserve_registration_space()
372
    {
373
        // reserved ticket and datetime counts will be decremented as sold counts are incremented
374
        // so stop tracking that this reg has a ticket reserved
375
        $this->release_reserved_ticket();
376
        $ticket = $this->ticket();
377
        $ticket->increase_sold();
378
        $ticket->save();
379
        // possibly set event status to sold out
380
        $this->event()->perform_sold_out_status_check();
381
    }
382
383
384
    /**
385
     * Gets the ticket this registration is for
386
     *
387
     * @param boolean $include_archived whether to include archived tickets or not.
388
     * @return EE_Ticket|EE_Base_Class
389
     * @throws \EE_Error
390
     */
391
    public function ticket($include_archived = true)
392
    {
393
        $query_params = array();
394
        if ($include_archived) {
395
            $query_params['default_where_conditions'] = 'none';
396
        }
397
        return $this->get_first_related('Ticket', $query_params);
398
    }
399
400
401
    /**
402
     * Gets the event this registration is for
403
     *
404
     * @return EE_Event
405
     * @throws EE_Error
406
     * @throws EntityNotFoundException
407
     */
408
    public function event()
409
    {
410
        $event = $this->get_first_related('Event');
411
        if (! $event instanceof \EE_Event) {
412
            throw new EntityNotFoundException('Event ID', $this->event_ID());
413
        }
414
        return $event;
415
    }
416
417
418
    /**
419
     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
420
     * with the author of the event this registration is for.
421
     *
422
     * @since 4.5.0
423
     * @return int
424
     * @throws EE_Error
425
     * @throws EntityNotFoundException
426
     */
427
    public function wp_user()
428
    {
429
        $event = $this->event();
430
        if ($event instanceof EE_Event) {
431
            return $event->wp_user();
432
        }
433
        return 0;
434
    }
435
436
437
    /**
438
     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
439
     *
440
     * @return void
441
     * @throws \EE_Error
442
     */
443
    private function _release_registration_space()
444
    {
445
        $ticket = $this->ticket();
446
        $ticket->decrease_sold();
447
        $ticket->save();
448
    }
449
450
451
    /**
452
     * tracks this registration's ticket reservation in extra meta
453
     * and can increment related ticket reserved and corresponding datetime reserved values
454
     *
455
     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
456
     * @return void
457
     * @throws \EE_Error
458
     */
459
    public function reserve_ticket($update_ticket = false)
460
    {
461
        if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) === false) {
462
            // PLZ NOTE: although checking $update_ticket first would be more efficient,
463
            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
464
            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) && $update_ticket) {
465
                $ticket = $this->ticket();
466
                $ticket->increase_reserved();
467
                $ticket->save();
468
            }
469
        }
470
    }
471
472
473
    /**
474
     * stops tracking this registration's ticket reservation in extra meta
475
     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
476
     *
477
     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
478
     * @return void
479
     * @throws \EE_Error
480
     */
481
    public function release_reserved_ticket($update_ticket = false)
482
    {
483
        if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) !== false) {
484
            // PLZ NOTE: although checking $update_ticket first would be more efficient,
485
            // we NEED to ALWAYS call delete_extra_meta(), which is why that is done first
486
            if ($this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY) && $update_ticket) {
487
                $ticket = $this->ticket();
488
                $ticket->decrease_reserved();
489
                $ticket->save();
490
            }
491
        }
492
    }
493
494
495
    /**
496
     * Set Attendee ID
497
     *
498
     * @param        int $ATT_ID Attendee ID
499
     * @throws EE_Error
500
     * @throws RuntimeException
501
     */
502
    public function set_attendee_id($ATT_ID = 0)
503
    {
504
        $this->set('ATT_ID', $ATT_ID);
505
    }
506
507
508
    /**
509
     *        Set Transaction ID
510
     *
511
     * @param        int $TXN_ID Transaction ID
512
     * @throws EE_Error
513
     * @throws RuntimeException
514
     */
515
    public function set_transaction_id($TXN_ID = 0)
516
    {
517
        $this->set('TXN_ID', $TXN_ID);
518
    }
519
520
521
    /**
522
     *        Set Session
523
     *
524
     * @param    string $REG_session PHP Session ID
525
     * @throws EE_Error
526
     * @throws RuntimeException
527
     */
528
    public function set_session($REG_session = '')
529
    {
530
        $this->set('REG_session', $REG_session);
531
    }
532
533
534
    /**
535
     *        Set Registration URL Link
536
     *
537
     * @param    string $REG_url_link Registration URL Link
538
     * @throws EE_Error
539
     * @throws RuntimeException
540
     */
541
    public function set_reg_url_link($REG_url_link = '')
542
    {
543
        $this->set('REG_url_link', $REG_url_link);
544
    }
545
546
547
    /**
548
     *        Set Attendee Counter
549
     *
550
     * @param        int $REG_count Primary Attendee
551
     * @throws EE_Error
552
     * @throws RuntimeException
553
     */
554
    public function set_count($REG_count = 1)
555
    {
556
        $this->set('REG_count', $REG_count);
557
    }
558
559
560
    /**
561
     *        Set Group Size
562
     *
563
     * @param        boolean $REG_group_size Group Registration
564
     * @throws EE_Error
565
     * @throws RuntimeException
566
     */
567
    public function set_group_size($REG_group_size = false)
568
    {
569
        $this->set('REG_group_size', $REG_group_size);
570
    }
571
572
573
    /**
574
     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
575
     *    EEM_Registration::status_id_not_approved
576
     *
577
     * @return        boolean
578
     */
579
    public function is_not_approved()
580
    {
581
        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
582
    }
583
584
585
    /**
586
     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
587
     *    EEM_Registration::status_id_pending_payment
588
     *
589
     * @return        boolean
590
     */
591
    public function is_pending_payment()
592
    {
593
        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
594
    }
595
596
597
    /**
598
     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
599
     *
600
     * @return        boolean
601
     */
602
    public function is_approved()
603
    {
604
        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
605
    }
606
607
608
    /**
609
     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
610
     *
611
     * @return        boolean
612
     */
613
    public function is_cancelled()
614
    {
615
        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
616
    }
617
618
619
    /**
620
     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
621
     *
622
     * @return        boolean
623
     */
624
    public function is_declined()
625
    {
626
        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
627
    }
628
629
630
    /**
631
     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
632
     *    EEM_Registration::status_id_incomplete
633
     *
634
     * @return        boolean
635
     */
636
    public function is_incomplete()
637
    {
638
        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
639
    }
640
641
642
    /**
643
     *        Set Registration Date
644
     *
645
     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
646
     *                                                 Date
647
     * @throws EE_Error
648
     * @throws RuntimeException
649
     */
650
    public function set_reg_date($REG_date = false)
651
    {
652
        $this->set('REG_date', $REG_date);
653
    }
654
655
656
    /**
657
     *    Set final price owing for this registration after all ticket/price modifications
658
     *
659
     * @access    public
660
     * @param    float $REG_final_price
661
     * @throws EE_Error
662
     * @throws RuntimeException
663
     */
664
    public function set_final_price($REG_final_price = 0.00)
665
    {
666
        $this->set('REG_final_price', $REG_final_price);
667
    }
668
669
670
    /**
671
     *    Set amount paid towards this registration's final price
672
     *
673
     * @access    public
674
     * @param    float $REG_paid
675
     * @throws EE_Error
676
     * @throws RuntimeException
677
     */
678
    public function set_paid($REG_paid = 0.00)
679
    {
680
        $this->set('REG_paid', $REG_paid);
681
    }
682
683
684
    /**
685
     *        Attendee Is Going
686
     *
687
     * @param        boolean $REG_att_is_going Attendee Is Going
688
     * @throws EE_Error
689
     * @throws RuntimeException
690
     */
691
    public function set_att_is_going($REG_att_is_going = false)
692
    {
693
        $this->set('REG_att_is_going', $REG_att_is_going);
694
    }
695
696
697
    /**
698
     * Gets the related attendee
699
     *
700
     * @return EE_Attendee
701
     * @throws EE_Error
702
     */
703
    public function attendee()
704
    {
705
        return $this->get_first_related('Attendee');
706
    }
707
708
709
    /**
710
     *        get Event ID
711
     */
712
    public function event_ID()
713
    {
714
        return $this->get('EVT_ID');
715
    }
716
717
718
    /**
719
     *        get Event ID
720
     */
721
    public function event_name()
722
    {
723
        $event = $this->event_obj();
724
        if ($event) {
725
            return $event->name();
726
        } else {
727
            return null;
728
        }
729
    }
730
731
732
    /**
733
     * Fetches the event this registration is for
734
     *
735
     * @return EE_Event
736
     * @throws EE_Error
737
     */
738
    public function event_obj()
739
    {
740
        return $this->get_first_related('Event');
741
    }
742
743
744
    /**
745
     *        get Attendee ID
746
     */
747
    public function attendee_ID()
748
    {
749
        return $this->get('ATT_ID');
750
    }
751
752
753
    /**
754
     *        get PHP Session ID
755
     */
756
    public function session_ID()
757
    {
758
        return $this->get('REG_session');
759
    }
760
761
762
    /**
763
     * Gets the string which represents the URL trigger for the receipt template in the message template system.
764
     *
765
     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
766
     * @return string
767
     */
768
    public function receipt_url($messenger = 'html')
769
    {
770
771
        /**
772
         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
773
         * already in use on old system.  If there is then we just return the standard url for it.
774
         *
775
         * @since 4.5.0
776
         */
777
        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
778
        $has_custom             = EEH_Template::locate_template(
779
            $template_relative_path,
780
            array(),
781
            true,
782
            true,
783
            true
784
        );
785
786
        if ($has_custom) {
787
            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
788
        }
789
        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
790
    }
791
792
793
    /**
794
     * Gets the string which represents the URL trigger for the invoice template in the message template system.
795
     *
796
     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
797
     * @return string
798
     * @throws EE_Error
799
     */
800
    public function invoice_url($messenger = 'html')
801
    {
802
        /**
803
         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
804
         * already in use on old system.  If there is then we just return the standard url for it.
805
         *
806
         * @since 4.5.0
807
         */
808
        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
809
        $has_custom             = EEH_Template::locate_template(
810
            $template_relative_path,
811
            array(),
812
            true,
813
            true,
814
            true
815
        );
816
817
        if ($has_custom) {
818
            if ($messenger == 'html') {
819
                return $this->invoice_url('launch');
820
            }
821
            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
822
823
            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
824
            if ($messenger == 'html') {
825
                $query_args['html'] = true;
826
            }
827
            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
828
        }
829
        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
830
    }
831
832
833
    /**
834
     * get Registration URL Link
835
     *
836
     * @access public
837
     * @return string
838
     * @throws \EE_Error
839
     */
840
    public function reg_url_link()
841
    {
842
        return (string) $this->get('REG_url_link');
843
    }
844
845
846
    /**
847
     * Echoes out invoice_url()
848
     *
849
     * @param string $type 'download','launch', or 'html' (default is 'launch')
850
     * @return void
851
     * @throws EE_Error
852
     */
853
    public function e_invoice_url($type = 'launch')
854
    {
855
        echo $this->invoice_url($type);
856
    }
857
858
859
    /**
860
     * Echoes out payment_overview_url
861
     */
862
    public function e_payment_overview_url()
863
    {
864
        echo $this->payment_overview_url();
865
    }
866
867
868
    /**
869
     * Gets the URL of the thank you page with this registration REG_url_link added as
870
     * a query parameter
871
     *
872
     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
873
     *                            payment overview url.
874
     * @return string
875
     * @throws EE_Error
876
     */
877 View Code Duplication
    public function payment_overview_url($clear_session = false)
878
    {
879
        return add_query_arg(array(
880
            'e_reg_url_link' => $this->reg_url_link(),
881
            'step'           => 'payment_options',
882
            'revisit'        => true,
883
            'clear_session' => (bool) $clear_session
884
        ), EE_Registry::instance()->CFG->core->reg_page_url());
885
    }
886
887
888
    /**
889
     * Gets the URL of the thank you page with this registration REG_url_link added as
890
     * a query parameter
891
     *
892
     * @return string
893
     * @throws EE_Error
894
     */
895 View Code Duplication
    public function edit_attendee_information_url()
896
    {
897
        return add_query_arg(array(
898
            'e_reg_url_link' => $this->reg_url_link(),
899
            'step'           => 'attendee_information',
900
            'revisit'        => true,
901
        ), EE_Registry::instance()->CFG->core->reg_page_url());
902
    }
903
904
905
    /**
906
     * Simply generates and returns the appropriate admin_url link to edit this registration
907
     *
908
     * @return string
909
     * @throws EE_Error
910
     */
911
    public function get_admin_edit_url()
912
    {
913
        return EEH_URL::add_query_args_and_nonce(array(
914
            'page'    => 'espresso_registrations',
915
            'action'  => 'view_registration',
916
            '_REG_ID' => $this->ID(),
917
        ), admin_url('admin.php'));
918
    }
919
920
921
    /**
922
     *    is_primary_registrant?
923
     */
924
    public function is_primary_registrant()
925
    {
926
        return $this->get('REG_count') == 1 ? true : false;
927
    }
928
929
930
    /**
931
     * This returns the primary registration object for this registration group (which may be this object).
932
     *
933
     * @return EE_Registration
934
     * @throws EE_Error
935
     */
936
    public function get_primary_registration()
937
    {
938
        if ($this->is_primary_registrant()) {
939
            return $this;
940
        }
941
942
        //k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
943
        /** @var EE_Registration $primary_registrant */
944
        $primary_registrant = EEM_Registration::instance()->get_one(array(
945
            array(
946
                'TXN_ID'    => $this->transaction_ID(),
947
                'REG_count' => 1,
948
            ),
949
        ));
950
        return $primary_registrant;
951
    }
952
953
954
    /**
955
     *        get  Attendee Number
956
     *
957
     * @access        public
958
     */
959
    public function count()
960
    {
961
        return $this->get('REG_count');
962
    }
963
964
965
    /**
966
     *        get Group Size
967
     */
968
    public function group_size()
969
    {
970
        return $this->get('REG_group_size');
971
    }
972
973
974
    /**
975
     *        get Registration Date
976
     */
977
    public function date()
978
    {
979
        return $this->get('REG_date');
980
    }
981
982
983
    /**
984
     * gets a pretty date
985
     *
986
     * @param string $date_format
987
     * @param string $time_format
988
     * @return string
989
     * @throws EE_Error
990
     */
991
    public function pretty_date($date_format = null, $time_format = null)
992
    {
993
        return $this->get_datetime('REG_date', $date_format, $time_format);
994
    }
995
996
997
    /**
998
     * final_price
999
     * the registration's share of the transaction total, so that the
1000
     * sum of all the transaction's REG_final_prices equal the transaction's total
1001
     *
1002
     * @return float
1003
     * @throws EE_Error
1004
     */
1005
    public function final_price()
1006
    {
1007
        return $this->get('REG_final_price');
1008
    }
1009
1010
1011
    /**
1012
     * pretty_final_price
1013
     *  final price as formatted string, with correct decimal places and currency symbol
1014
     *
1015
     * @return string
1016
     * @throws EE_Error
1017
     */
1018
    public function pretty_final_price()
1019
    {
1020
        return $this->get_pretty('REG_final_price');
1021
    }
1022
1023
1024
    /**
1025
     * get paid (yeah)
1026
     *
1027
     * @return float
1028
     * @throws EE_Error
1029
     */
1030
    public function paid()
1031
    {
1032
        return $this->get('REG_paid');
1033
    }
1034
1035
1036
    /**
1037
     * pretty_paid
1038
     *
1039
     * @return float
1040
     * @throws EE_Error
1041
     */
1042
    public function pretty_paid()
1043
    {
1044
        return $this->get_pretty('REG_paid');
1045
    }
1046
1047
1048
    /**
1049
     * owes_monies_and_can_pay
1050
     * whether or not this registration has monies owing and it's' status allows payment
1051
     *
1052
     * @param array $requires_payment
1053
     * @return bool
1054
     * @throws EE_Error
1055
     */
1056
    public function owes_monies_and_can_pay($requires_payment = array())
1057
    {
1058
        // these reg statuses require payment (if event is not free)
1059
        $requires_payment = ! empty($requires_payment)
1060
            ? $requires_payment
1061
            : EEM_Registration::reg_statuses_that_allow_payment();
1062
        if (in_array($this->status_ID(), $requires_payment) &&
1063
            $this->final_price() != 0 &&
1064
            $this->final_price() != $this->paid()
1065
        ) {
1066
            return true;
1067
        } else {
1068
            return false;
1069
        }
1070
    }
1071
1072
1073
    /**
1074
     * Prints out the return value of $this->pretty_status()
1075
     *
1076
     * @param bool $show_icons
1077
     * @return void
1078
     * @throws EE_Error
1079
     */
1080
    public function e_pretty_status($show_icons = false)
1081
    {
1082
        echo $this->pretty_status($show_icons);
1083
    }
1084
1085
1086
    /**
1087
     * Returns a nice version of the status for displaying to customers
1088
     *
1089
     * @param bool $show_icons
1090
     * @return string
1091
     * @throws EE_Error
1092
     */
1093
    public function pretty_status($show_icons = false)
1094
    {
1095
        $status = EEM_Status::instance()->localized_status(
1096
            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1097
            false,
1098
            'sentence'
1099
        );
1100
        $icon   = '';
1101
        switch ($this->status_ID()) {
1102
            case EEM_Registration::status_id_approved:
1103
                $icon = $show_icons
1104
                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1105
                    : '';
1106
                break;
1107
            case EEM_Registration::status_id_pending_payment:
1108
                $icon = $show_icons
1109
                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1110
                    : '';
1111
                break;
1112
            case EEM_Registration::status_id_not_approved:
1113
                $icon = $show_icons
1114
                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1115
                    : '';
1116
                break;
1117
            case EEM_Registration::status_id_cancelled:
1118
                $icon = $show_icons
1119
                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1120
                    : '';
1121
                break;
1122
            case EEM_Registration::status_id_incomplete:
1123
                $icon = $show_icons
1124
                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1125
                    : '';
1126
                break;
1127
            case EEM_Registration::status_id_declined:
1128
                $icon = $show_icons
1129
                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1130
                    : '';
1131
                break;
1132
            case EEM_Registration::status_id_wait_list:
1133
                $icon = $show_icons
1134
                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1135
                    : '';
1136
                break;
1137
        }
1138
        return $icon . $status[$this->status_ID()];
1139
    }
1140
1141
1142
    /**
1143
     *        get Attendee Is Going
1144
     */
1145
    public function att_is_going()
1146
    {
1147
        return $this->get('REG_att_is_going');
1148
    }
1149
1150
1151
    /**
1152
     * Gets related answers
1153
     *
1154
     * @param array $query_params like EEM_Base::get_all
1155
     * @return EE_Answer[]
1156
     * @throws EE_Error
1157
     */
1158
    public function answers($query_params = null)
1159
    {
1160
        return $this->get_many_related('Answer', $query_params);
1161
    }
1162
1163
1164
    /**
1165
     * Gets the registration's answer value to the specified question
1166
     * (either the question's ID or a question object)
1167
     *
1168
     * @param EE_Question|int $question
1169
     * @param bool            $pretty_value
1170
     * @return array|string if pretty_value= true, the result will always be a string
1171
     * (because the answer might be an array of answer values, so passing pretty_value=true
1172
     * will convert it into some kind of string)
1173
     * @throws EE_Error
1174
     */
1175
    public function answer_value_to_question($question, $pretty_value = true)
1176
    {
1177
        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1178
        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1179
    }
1180
1181
1182
    /**
1183
     * question_groups
1184
     * returns an array of EE_Question_Group objects for this registration
1185
     *
1186
     * @return EE_Question_Group[]
1187
     * @throws EE_Error
1188
     * @throws EntityNotFoundException
1189
     */
1190
    public function question_groups()
1191
    {
1192
        $question_groups = array();
1193
        if ($this->event() instanceof EE_Event) {
1194
            $question_groups = $this->event()->question_groups(
1195
                array(
1196
                    array(
1197
                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1198
                    ),
1199
                    'order_by' => array('QSG_order' => 'ASC'),
1200
                )
1201
            );
1202
        }
1203
        return $question_groups;
1204
    }
1205
1206
1207
    /**
1208
     * count_question_groups
1209
     * returns a count of the number of EE_Question_Group objects for this registration
1210
     *
1211
     * @return int
1212
     * @throws EE_Error
1213
     * @throws EntityNotFoundException
1214
     */
1215
    public function count_question_groups()
1216
    {
1217
        $qg_count = 0;
1218
        if ($this->event() instanceof EE_Event) {
1219
            $qg_count = $this->event()->count_related(
1220
                'Question_Group',
1221
                array(
1222
                    array(
1223
                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1224
                    ),
1225
                )
1226
            );
1227
        }
1228
        return $qg_count;
1229
    }
1230
1231
1232
    /**
1233
     * Returns the registration date in the 'standard' string format
1234
     * (function may be improved in the future to allow for different formats and timezones)
1235
     *
1236
     * @return string
1237
     * @throws EE_Error
1238
     */
1239
    public function reg_date()
1240
    {
1241
        return $this->get_datetime('REG_date');
1242
    }
1243
1244
1245
    /**
1246
     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1247
     * the ticket this registration purchased, or the datetime they have registered
1248
     * to attend)
1249
     *
1250
     * @return EE_Datetime_Ticket
1251
     * @throws EE_Error
1252
     */
1253
    public function datetime_ticket()
1254
    {
1255
        return $this->get_first_related('Datetime_Ticket');
1256
    }
1257
1258
1259
    /**
1260
     * Sets the registration's datetime_ticket.
1261
     *
1262
     * @param EE_Datetime_Ticket $datetime_ticket
1263
     * @return EE_Datetime_Ticket
1264
     * @throws EE_Error
1265
     */
1266
    public function set_datetime_ticket($datetime_ticket)
1267
    {
1268
        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1269
    }
1270
1271
    /**
1272
     * Gets deleted
1273
     *
1274
     * @return bool
1275
     * @throws EE_Error
1276
     */
1277
    public function deleted()
1278
    {
1279
        return $this->get('REG_deleted');
1280
    }
1281
1282
    /**
1283
     * Sets deleted
1284
     *
1285
     * @param boolean $deleted
1286
     * @return bool
1287
     * @throws EE_Error
1288
     * @throws RuntimeException
1289
     */
1290
    public function set_deleted($deleted)
1291
    {
1292
        if ($deleted) {
1293
            $this->delete();
1294
        } else {
1295
            $this->restore();
1296
        }
1297
    }
1298
1299
1300
    /**
1301
     * Get the status object of this object
1302
     *
1303
     * @return EE_Status
1304
     * @throws EE_Error
1305
     */
1306
    public function status_obj()
1307
    {
1308
        return $this->get_first_related('Status');
1309
    }
1310
1311
1312
    /**
1313
     * Returns the number of times this registration has checked into any of the datetimes
1314
     * its available for
1315
     *
1316
     * @return int
1317
     * @throws EE_Error
1318
     */
1319
    public function count_checkins()
1320
    {
1321
        return $this->get_model()->count_related($this, 'Checkin');
1322
    }
1323
1324
1325
    /**
1326
     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1327
     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1328
     *
1329
     * @return int
1330
     * @throws EE_Error
1331
     */
1332
    public function count_checkins_not_checkedout()
1333
    {
1334
        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1335
    }
1336
1337
1338
    /**
1339
     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1340
     *
1341
     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1342
     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1343
     *                                          consider registration status as well as datetime access.
1344
     * @return bool
1345
     * @throws EE_Error
1346
     */
1347
    public function can_checkin($DTT_OR_ID, $check_approved = true)
1348
    {
1349
        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1350
1351
        //first check registration status
1352
        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1353
            return false;
1354
        }
1355
        //is there a datetime ticket that matches this dtt_ID?
1356
        if (! (EEM_Datetime_Ticket::instance()->exists(array(
1357
            array(
1358
                'TKT_ID' => $this->get('TKT_ID'),
1359
                'DTT_ID' => $DTT_ID,
1360
            ),
1361
        )))
1362
        ) {
1363
            return false;
1364
        }
1365
1366
        //final check is against TKT_uses
1367
        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1368
    }
1369
1370
1371
    /**
1372
     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1373
     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1374
     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1375
     * then return false.  Otherwise return true.
1376
     *
1377
     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1378
     * @return bool true means can checkin.  false means cannot checkin.
1379
     * @throws EE_Error
1380
     */
1381
    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1382
    {
1383
        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1384
1385
        if (! $DTT_ID) {
1386
            return false;
1387
        }
1388
1389
        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1390
1391
        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1392
        // check-in or not.
1393
        if (! $max_uses || $max_uses === EE_INF) {
1394
            return true;
1395
        }
1396
1397
        //does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1398
        //go ahead and toggle.
1399
        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1400
            return true;
1401
        }
1402
1403
        //made it here so the last check is whether the number of checkins per unique datetime on this registration
1404
        //disallows further check-ins.
1405
        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1406
            array(
1407
                'REG_ID' => $this->ID(),
1408
                'CHK_in' => true,
1409
            ),
1410
        ), 'DTT_ID', true);
1411
        // checkins have already reached their max number of uses
1412
        // so registrant can NOT checkin
1413
        if ($count_unique_dtt_checkins >= $max_uses) {
1414
            EE_Error::add_error(
1415
                esc_html__(
1416
                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1417
                    'event_espresso'
1418
                ),
1419
                __FILE__,
1420
                __FUNCTION__,
1421
                __LINE__
1422
            );
1423
            return false;
1424
        }
1425
        return true;
1426
    }
1427
1428
1429
    /**
1430
     * toggle Check-in status for this registration
1431
     * Check-ins are toggled in the following order:
1432
     * never checked in -> checked in
1433
     * checked in -> checked out
1434
     * checked out -> checked in
1435
     *
1436
     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1437
     *                      If not included or null, then it is assumed latest datetime is being toggled.
1438
     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1439
     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1440
     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1441
     * @throws EE_Error
1442
     */
1443
    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1444
    {
1445
        if (empty($DTT_ID)) {
1446
            $datetime = $this->get_latest_related_datetime();
1447
            $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1448
            // verify the registration can checkin for the given DTT_ID
1449
        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1450
            EE_Error::add_error(
1451
                sprintf(
1452
                    esc_html__(
1453
                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1454
                        'event_espresso'
1455
                    ),
1456
                    $this->ID(),
1457
                    $DTT_ID
1458
                ),
1459
                __FILE__,
1460
                __FUNCTION__,
1461
                __LINE__
1462
            );
1463
            return false;
1464
        }
1465
        $status_paths = array(
1466
            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1467
            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1468
            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1469
        );
1470
        //start by getting the current status so we know what status we'll be changing to.
1471
        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1472
        $status_to  = $status_paths[$cur_status];
1473
        // database only records true for checked IN or false for checked OUT
1474
        // no record ( null ) means checked in NEVER, but we obviously don't save that
1475
        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1476
        // add relation - note Check-ins are always creating new rows
1477
        // because we are keeping track of Check-ins over time.
1478
        // Eventually we'll probably want to show a list table
1479
        // for the individual Check-ins so that they can be managed.
1480
        $checkin = EE_Checkin::new_instance(array(
1481
            'REG_ID' => $this->ID(),
1482
            'DTT_ID' => $DTT_ID,
1483
            'CHK_in' => $new_status,
1484
        ));
1485
        // if the record could not be saved then return false
1486
        if ($checkin->save() === 0) {
1487
            if (WP_DEBUG) {
1488
                global $wpdb;
1489
                $error = sprintf(
1490
                    esc_html__(
1491
                        'Registration check in update failed because of the following database error: %1$s%2$s',
1492
                        'event_espresso'
1493
                    ),
1494
                    '<br />',
1495
                    $wpdb->last_error
1496
                );
1497
            } else {
1498
                $error = esc_html__(
1499
                    'Registration check in update failed because of an unknown database error',
1500
                    'event_espresso'
1501
                );
1502
            }
1503
            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1504
            return false;
1505
        }
1506
        return $status_to;
1507
    }
1508
1509
1510
    /**
1511
     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1512
     * "Latest" is defined by the `DTT_EVT_start` column.
1513
     *
1514
     * @return EE_Datetime|null
1515
     * @throws \EE_Error
1516
     */
1517 View Code Duplication
    public function get_latest_related_datetime()
1518
    {
1519
        return EEM_Datetime::instance()->get_one(
1520
            array(
1521
                array(
1522
                    'Ticket.Registration.REG_ID' => $this->ID(),
1523
                ),
1524
                'order_by' => array('DTT_EVT_start' => 'DESC'),
1525
            )
1526
        );
1527
    }
1528
1529
1530
    /**
1531
     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1532
     * "Earliest" is defined by the `DTT_EVT_start` column.
1533
     *
1534
     * @throws \EE_Error
1535
     */
1536 View Code Duplication
    public function get_earliest_related_datetime()
1537
    {
1538
        return EEM_Datetime::instance()->get_one(
1539
            array(
1540
                array(
1541
                    'Ticket.Registration.REG_ID' => $this->ID(),
1542
                ),
1543
                'order_by' => array('DTT_EVT_start' => 'ASC'),
1544
            )
1545
        );
1546
    }
1547
1548
1549
    /**
1550
     * This method simply returns the check-in status for this registration and the given datetime.
1551
     * If neither the datetime nor the checkin values are provided as arguments,
1552
     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1553
     *
1554
     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1555
     *                            (if empty we'll get the primary datetime for
1556
     *                            this registration (via event) and use it's ID);
1557
     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1558
     * @return int                Integer representing Check-in status.
1559
     * @throws \EE_Error
1560
     */
1561
    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1562
    {
1563
        $checkin_query_params = array(
1564
            'order_by' => array('CHK_timestamp' => 'DESC'),
1565
        );
1566
1567
        if ($DTT_ID > 0) {
1568
            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1569
        }
1570
1571
        //get checkin object (if exists)
1572
        $checkin = $checkin instanceof EE_Checkin
1573
            ? $checkin
1574
            : $this->get_first_related('Checkin', $checkin_query_params);
1575
        if ($checkin instanceof EE_Checkin) {
1576
            if ($checkin->get('CHK_in')) {
1577
                return EE_Checkin::status_checked_in; //checked in
1578
            }
1579
            return EE_Checkin::status_checked_out; //had checked in but is now checked out.
1580
        }
1581
        return EE_Checkin::status_checked_never; //never been checked in
1582
    }
1583
1584
1585
    /**
1586
     * This method returns a localized message for the toggled Check-in message.
1587
     *
1588
     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1589
     *                     then it is assumed Check-in for primary datetime was toggled.
1590
     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1591
     *                     message can be customized with the attendee name.
1592
     * @return string internationalized message
1593
     * @throws EE_Error
1594
     */
1595
    public function get_checkin_msg($DTT_ID, $error = false)
1596
    {
1597
        //let's get the attendee first so we can include the name of the attendee
1598
        $attendee = $this->get_first_related('Attendee');
1599
        if ($attendee instanceof EE_Attendee) {
1600
            if ($error) {
1601
                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1602
            }
1603
            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1604
            //what is the status message going to be?
1605
            switch ($cur_status) {
1606
                case EE_Checkin::status_checked_never:
1607
                    return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1608
                        $attendee->full_name());
1609
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1610
                case EE_Checkin::status_checked_in:
1611
                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1612
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1613
                case EE_Checkin::status_checked_out:
1614
                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1615
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1616
            }
1617
        }
1618
        return esc_html__("The check-in status could not be determined.", "event_espresso");
1619
    }
1620
1621
1622
    /**
1623
     * Returns the related EE_Transaction to this registration
1624
     *
1625
     * @return EE_Transaction
1626
     * @throws EE_Error
1627
     * @throws EntityNotFoundException
1628
     */
1629
    public function transaction()
1630
    {
1631
        $transaction = $this->get_first_related('Transaction');
1632
        if (! $transaction instanceof \EE_Transaction) {
1633
            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1634
        }
1635
        return $transaction;
1636
    }
1637
1638
1639
    /**
1640
     *        get Registration Code
1641
     */
1642
    public function reg_code()
1643
    {
1644
        return $this->get('REG_code');
1645
    }
1646
1647
1648
    /**
1649
     *        get Transaction ID
1650
     */
1651
    public function transaction_ID()
1652
    {
1653
        return $this->get('TXN_ID');
1654
    }
1655
1656
1657
    /**
1658
     * @return int
1659
     * @throws EE_Error
1660
     */
1661
    public function ticket_ID()
1662
    {
1663
        return $this->get('TKT_ID');
1664
    }
1665
1666
1667
    /**
1668
     *        Set Registration Code
1669
     *
1670
     * @access    public
1671
     * @param    string  $REG_code Registration Code
1672
     * @param    boolean $use_default
1673
     * @throws EE_Error
1674
     */
1675
    public function set_reg_code($REG_code, $use_default = false)
1676
    {
1677
        if (empty($REG_code)) {
1678
            EE_Error::add_error(
1679
                esc_html__('REG_code can not be empty.', 'event_espresso'),
1680
                __FILE__,
1681
                __FUNCTION__,
1682
                __LINE__
1683
            );
1684
            return;
1685
        }
1686
        if (! $this->reg_code()) {
1687
            parent::set('REG_code', $REG_code, $use_default);
1688
        } else {
1689
            EE_Error::doing_it_wrong(
1690
                __CLASS__ . '::' . __FUNCTION__,
1691
                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1692
                '4.6.0'
1693
            );
1694
        }
1695
    }
1696
1697
1698
    /**
1699
     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1700
     * Note, if you want to just get all registrations in the same transaction (group), use:
1701
     *    $registration->transaction()->registrations();
1702
     *
1703
     * @since 4.5.0
1704
     * @return EE_Registration[] or empty array if this isn't a group registration.
1705
     * @throws EE_Error
1706
     */
1707
    public function get_all_other_registrations_in_group()
1708
    {
1709
        if ($this->group_size() < 2) {
1710
            return array();
1711
        }
1712
1713
        $query[0] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$query was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
1714
            'TXN_ID' => $this->transaction_ID(),
1715
            'REG_ID' => array('!=', $this->ID()),
1716
            'TKT_ID' => $this->ticket_ID(),
1717
        );
1718
        /** @var EE_Registration[] $registrations */
1719
        $registrations = $this->get_model()->get_all($query);
1720
        return $registrations;
1721
    }
1722
1723
    /**
1724
     * Return the link to the admin details for the object.
1725
     *
1726
     * @return string
1727
     * @throws EE_Error
1728
     */
1729 View Code Duplication
    public function get_admin_details_link()
1730
    {
1731
        EE_Registry::instance()->load_helper('URL');
1732
        return EEH_URL::add_query_args_and_nonce(
1733
            array(
1734
                'page'    => 'espresso_registrations',
1735
                'action'  => 'view_registration',
1736
                '_REG_ID' => $this->ID(),
1737
            ),
1738
            admin_url('admin.php')
1739
        );
1740
    }
1741
1742
    /**
1743
     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1744
     *
1745
     * @return string
1746
     * @throws EE_Error
1747
     */
1748
    public function get_admin_edit_link()
1749
    {
1750
        return $this->get_admin_details_link();
1751
    }
1752
1753
    /**
1754
     * Returns the link to a settings page for the object.
1755
     *
1756
     * @return string
1757
     * @throws EE_Error
1758
     */
1759
    public function get_admin_settings_link()
1760
    {
1761
        return $this->get_admin_details_link();
1762
    }
1763
1764
    /**
1765
     * Returns the link to the "overview" for the object (typically the "list table" view).
1766
     *
1767
     * @return string
1768
     */
1769
    public function get_admin_overview_link()
1770
    {
1771
        EE_Registry::instance()->load_helper('URL');
1772
        return EEH_URL::add_query_args_and_nonce(
1773
            array(
1774
                'page' => 'espresso_registrations',
1775
            ),
1776
            admin_url('admin.php')
1777
        );
1778
    }
1779
1780
1781
    /**
1782
     * @param array $query_params
1783
     * @return \EE_Registration[]
1784
     * @throws \EE_Error
1785
     */
1786
    public function payments($query_params = array())
1787
    {
1788
        return $this->get_many_related('Payment', $query_params);
1789
    }
1790
1791
1792
    /**
1793
     * @param array $query_params
1794
     * @return \EE_Registration_Payment[]
1795
     * @throws \EE_Error
1796
     */
1797
    public function registration_payments($query_params = array())
1798
    {
1799
        return $this->get_many_related('Registration_Payment', $query_params);
1800
    }
1801
1802
1803
    /**
1804
     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1805
     * Note: if there are no payments on the registration there will be no payment method returned.
1806
     *
1807
     * @return EE_Payment_Method|null
1808
     */
1809
    public function payment_method()
1810
    {
1811
        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1812
    }
1813
1814
1815
    /**
1816
     * @return \EE_Line_Item
1817
     * @throws EntityNotFoundException
1818
     * @throws \EE_Error
1819
     */
1820
    public function ticket_line_item()
1821
    {
1822
        $ticket            = $this->ticket();
1823
        $transaction       = $this->transaction();
1824
        $line_item         = null;
1825
        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1826
            $transaction->total_line_item(),
1827
            'Ticket',
1828
            array($ticket->ID())
1829
        );
1830 View Code Duplication
        foreach ($ticket_line_items as $ticket_line_item) {
1831
            if (
1832
                $ticket_line_item instanceof \EE_Line_Item
1833
                && $ticket_line_item->OBJ_type() === 'Ticket'
1834
                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1835
            ) {
1836
                $line_item = $ticket_line_item;
1837
                break;
1838
            }
1839
        }
1840 View Code Duplication
        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1841
            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1842
        }
1843
        return $line_item;
1844
    }
1845
1846
1847
    /**
1848
     * Soft Deletes this model object.
1849
     *
1850
     * @return boolean | int
1851
     * @throws \RuntimeException
1852
     * @throws \EE_Error
1853
     */
1854
    public function delete()
1855
    {
1856
        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1857
            $this->set_status(EEM_Registration::status_id_cancelled);
1858
        }
1859
        return parent::delete();
1860
    }
1861
1862
1863
    /**
1864
     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1865
     *
1866
     * @throws \EE_Error
1867
     * @throws \RuntimeException
1868
     */
1869
    public function restore()
1870
    {
1871
        $previous_status = $this->get_extra_meta(
1872
            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1873
            true,
1874
            EEM_Registration::status_id_cancelled
1875
        );
1876
        if ($previous_status) {
1877
            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1878
            $this->set_status($previous_status);
1879
        }
1880
        return parent::restore();
1881
    }
1882
1883
1884
1885
    /*************************** DEPRECATED ***************************/
1886
1887
1888
    /**
1889
     * @deprecated
1890
     * @since     4.7.0
1891
     * @access    public
1892
     */
1893
    public function price_paid()
1894
    {
1895
        EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1896
            esc_html__('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1897
            '4.7.0');
1898
        return $this->final_price();
1899
    }
1900
1901
1902
    /**
1903
     * @deprecated
1904
     * @since     4.7.0
1905
     * @access    public
1906
     * @param    float $REG_final_price
1907
     * @throws EE_Error
1908
     * @throws RuntimeException
1909
     */
1910
    public function set_price_paid($REG_final_price = 0.00)
1911
    {
1912
        EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
1913
            esc_html__('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
1914
            '4.7.0');
1915
        $this->set_final_price($REG_final_price);
1916
    }
1917
1918
1919
    /**
1920
     * @deprecated
1921
     * @since 4.7.0
1922
     * @return string
1923
     * @throws EE_Error
1924
     */
1925
    public function pretty_price_paid()
1926
    {
1927
        EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
1928
            esc_html__('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
1929
                'event_espresso'), '4.7.0');
1930
        return $this->pretty_final_price();
1931
    }
1932
1933
1934
    /**
1935
     * Gets the primary datetime related to this registration via the related Event to this registration
1936
     *
1937
     * @deprecated 4.9.17
1938
     * @return EE_Datetime
1939
     * @throws EE_Error
1940
     * @throws EntityNotFoundException
1941
     */
1942
    public function get_related_primary_datetime()
1943
    {
1944
        EE_Error::doing_it_wrong(
1945
            __METHOD__,
1946
            esc_html__(
1947
                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
1948
                'event_espresso'
1949
            ),
1950
            '4.9.17',
1951
            '5.0.0'
1952
        );
1953
        return $this->event()->primary_datetime();
1954
    }
1955
1956
1957
}
1958