Completed
Branch models-cleanup/model-relations (db5ca7)
by
unknown
13:03 queued 08:35
created
core/db_classes/EE_Term_Relationship.class.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -10,23 +10,23 @@
 block discarded – undo
10 10
 class EE_Term_Relationship extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Term_Relationship
16
-     */
17
-    public static function new_instance($props_n_values = array())
18
-    {
19
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
-        return $has_object ? $has_object : new self($props_n_values);
21
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Term_Relationship
16
+	 */
17
+	public static function new_instance($props_n_values = array())
18
+	{
19
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
+		return $has_object ? $has_object : new self($props_n_values);
21
+	}
22 22
 
23 23
 
24
-    /**
25
-     * @param array $props_n_values
26
-     * @return EE_Term_Relationship
27
-     */
28
-    public static function new_instance_from_db($props_n_values = array())
29
-    {
30
-        return new self($props_n_values, true);
31
-    }
24
+	/**
25
+	 * @param array $props_n_values
26
+	 * @return EE_Term_Relationship
27
+	 */
28
+	public static function new_instance_from_db($props_n_values = array())
29
+	{
30
+		return new self($props_n_values, true);
31
+	}
32 32
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Export.class.php 2 patches
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
     {
45 45
         $this->_req_data = $request_data;
46 46
         $this->today = date("Y-m-d", time());
47
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
47
+        require_once(EE_CLASSES.'EE_CSV.class.php');
48 48
         $this->EE_CSV = EE_CSV::instance();
49 49
     }
50 50
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
                 $value_to_equal = $EVT_ID;
168 168
                 $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
169 169
 
170
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
170
+                $filename = 'event-'.($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
171 171
             }
172 172
             $event_query_params[0]['EVT_ID'] = $value_to_equal;
173 173
             $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 
217 217
         $filename = $this->generate_filename($filename);
218 218
 
219
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
219
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220 220
             EE_Error::add_error(
221 221
                 __(
222 222
                     "'An error occurred and the Event details could not be exported from the database.'",
@@ -243,16 +243,16 @@  discard block
 block discarded – undo
243 243
             foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
244 244
                 if ($field_name == 'STA_ID') {
245 245
                     $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
246
-                    $csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
247
-                    ) ];
246
+                    $csv_row[__('State', 'event_espresso')] = $attendee_row[$state_name_field->get_qualified_column(
247
+                    )];
248 248
                 } elseif ($field_name == 'CNT_ISO') {
249 249
                     $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
250
-                    $csv_row[ __(
250
+                    $csv_row[__(
251 251
                         'Country',
252 252
                         'event_espresso'
253
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
253
+                    )] = $attendee_row[$country_name_field->get_qualified_column()];
254 254
                 } else {
255
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
255
+                    $csv_row[$field_obj->get_nicename()] = $attendee_row[$field_obj->get_qualified_column()];
256 256
                 }
257 257
             }
258 258
             $csv_data[] = $csv_row;
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         $model_data = $this->_get_export_data_for_models($models_to_export);
292 292
         $filename = $this->generate_filename('all-attendees');
293 293
 
294
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
294
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295 295
             EE_Error::add_error(
296 296
                 __(
297 297
                     'An error occurred and the Attendee data could not be exported from the database.',
@@ -409,9 +409,9 @@  discard block
 block discarded – undo
409 409
         foreach ($registration_rows as $reg_row) {
410 410
             if (is_array($reg_row)) {
411 411
                 $reg_csv_array = array();
412
-                if (! $event_id) {
412
+                if ( ! $event_id) {
413 413
                     // get the event's name and Id
414
-                    $reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
414
+                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(
415 415
                         __('%1$s (%2$s)', 'event_espresso'),
416 416
                         $this->_prepare_value_from_db_for_display(
417 417
                             EEM_Event::instance(),
@@ -457,13 +457,13 @@  discard block
 block discarded – undo
457 457
                         $value = $this->_prepare_value_from_db_for_display(
458 458
                             $reg_model,
459 459
                             $field_name,
460
-                            $reg_row[ $field->get_qualified_column() ]
460
+                            $reg_row[$field->get_qualified_column()]
461 461
                         );
462 462
                     }
463
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
463
+                    $reg_csv_array[$this->_get_column_name_for_field($field)] = $value;
464 464
                     if ($field_name == 'REG_final_price') {
465 465
                         // add a column named Currency after the final price
466
-                        $reg_csv_array[ __("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
466
+                        $reg_csv_array[__("Currency", "event_espresso")] = EE_Config::instance()->currency->code;
467 467
                     }
468 468
                 }
469 469
                 // get pretty status
@@ -475,23 +475,23 @@  discard block
 block discarded – undo
475 475
                     false,
476 476
                     'sentence'
477 477
                 );
478
-                $reg_csv_array[ __(
478
+                $reg_csv_array[__(
479 479
                     "Registration Status",
480 480
                     'event_espresso'
481
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
481
+                )] = $stati[$reg_row['Registration.STS_ID']];
482 482
                 // get pretty trnasaction status
483
-                $reg_csv_array[ __(
483
+                $reg_csv_array[__(
484 484
                     "Transaction Status",
485 485
                     'event_espresso'
486
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
487
-                $reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
486
+                )] = $stati[$reg_row['TransactionTable.STS_ID']];
487
+                $reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
488 488
                     ? $this->_prepare_value_from_db_for_display(
489 489
                         EEM_Transaction::instance(),
490 490
                         'TXN_total',
491 491
                         $reg_row['TransactionTable.TXN_total'],
492 492
                         'localized_float'
493 493
                     ) : '0.00';
494
-                $reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
494
+                $reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
495 495
                     ? $this->_prepare_value_from_db_for_display(
496 496
                         EEM_Transaction::instance(),
497 497
                         'TXN_paid',
@@ -523,15 +523,15 @@  discard block
 block discarded – undo
523 523
                             ? $payment_method_and_gateway_txn_id['payment_time'] : '';
524 524
                     }
525 525
                 }
526
-                $reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
527
-                $reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
528
-                $reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
526
+                $reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
527
+                $reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
528
+                $reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(
529 529
                     ',',
530 530
                     $gateway_txn_ids_etc
531 531
                 );
532 532
 
533 533
                 // get whether or not the user has checked in
534
-                $reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
534
+                $reg_csv_array[__("Check-Ins", "event_espresso")] = $reg_model->count_related(
535 535
                     $reg_row['Registration.REG_ID'],
536 536
                     'Checkin'
537 537
                 );
@@ -561,8 +561,8 @@  discard block
 block discarded – undo
561 561
                     $ticket_name = __('Unknown', 'event_espresso');
562 562
                     $datetimes_strings = array(__('Unknown', 'event_espresso'));
563 563
                 }
564
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
565
-                $reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
564
+                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
565
+                $reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
566 566
                 // get datetime(s) of registration
567 567
 
568 568
                 // add attendee columns
@@ -583,20 +583,20 @@  discard block
 block discarded – undo
583 583
                             $value = $this->_prepare_value_from_db_for_display(
584 584
                                 EEM_Attendee::instance(),
585 585
                                 $att_field_name,
586
-                                $reg_row[ $field_obj->get_qualified_column() ]
586
+                                $reg_row[$field_obj->get_qualified_column()]
587 587
                             );
588 588
                         }
589 589
                     } else {
590 590
                         $value = '';
591 591
                     }
592 592
 
593
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
593
+                    $reg_csv_array[$this->_get_column_name_for_field($field_obj)] = $value;
594 594
                 }
595 595
 
596 596
                 // make sure each registration has the same questions in the same order
597 597
                 foreach ($questions_for_these_regs_rows as $question_row) {
598
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
599
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
598
+                    if ( ! isset($reg_csv_array[$question_row['Question.QST_admin_label']])) {
599
+                        $reg_csv_array[$question_row['Question.QST_admin_label']] = null;
600 600
                     }
601 601
                 }
602 602
                 // now fill out the questions THEY answered
@@ -614,11 +614,11 @@  discard block
 block discarded – undo
614 614
                         $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615 615
                     }
616 616
                     if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
617
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
617
+                        $reg_csv_array[$question_label] = EEM_State::instance()->get_state_name_by_ID(
618 618
                             $answer_row['Answer.ANS_value']
619 619
                         );
620 620
                     } else {
621
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
621
+                        $reg_csv_array[$question_label] = $this->_prepare_value_from_db_for_display(
622 622
                             EEM_Answer::instance(),
623 623
                             'ANS_value',
624 624
                             $answer_row['Answer.ANS_value']
@@ -644,16 +644,16 @@  discard block
 block discarded – undo
644 644
                 $model = EE_Registry::instance()->load_model($model_name);
645 645
                 foreach ($field_list as $field_name) {
646 646
                     $field = $model->field_settings_for($field_name);
647
-                    $reg_csv_array[ $this->_get_column_name_for_field(
647
+                    $reg_csv_array[$this->_get_column_name_for_field(
648 648
                         $field
649
-                    ) ] = null;// $registration->get($field->get_name());
649
+                    )] = null; // $registration->get($field->get_name());
650 650
                 }
651 651
             }
652 652
             $registrations_csv_ready_array [] = $reg_csv_array;
653 653
         }
654 654
         if ($event_id) {
655 655
             $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
-            if (! $event_slug) {
656
+            if ( ! $event_slug) {
657 657
                 $event_slug = __('unknown', 'event_espresso');
658 658
             }
659 659
         } else {
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
      */
675 675
     protected function _get_column_name_for_field(EE_Model_Field_Base $field)
676 676
     {
677
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
677
+        return $field->get_nicename()."[".$field->get_name()."]";
678 678
     }
679 679
 
680 680
 
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
             } else {
698 698
                 // generate regular where = clause
699 699
                 $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
-                $filename = 'event-category#' . $EVT_CAT_ID;
700
+                $filename = 'event-category#'.$EVT_CAT_ID;
701 701
                 $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702 702
             }
703 703
         } else {
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
         $table_data = $this->_get_export_data_for_models($tables_to_export);
713 713
         $filename = $this->generate_filename($filename);
714 714
 
715
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
715
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716 716
             EE_Error::add_error(
717 717
                 __(
718 718
                     'An error occurred and the Category details could not be exported from the database.',
@@ -735,8 +735,8 @@  discard block
 block discarded – undo
735 735
     private function generate_filename($export_name = '')
736 736
     {
737 737
         if ($export_name != '') {
738
-            $filename = get_bloginfo('name') . '-' . $export_name;
739
-            $filename = sanitize_key($filename) . '-' . $this->today;
738
+            $filename = get_bloginfo('name').'-'.$export_name;
739
+            $filename = sanitize_key($filename).'-'.$this->today;
740 740
             return $filename;
741 741
         } else {
742 742
             EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
@@ -765,25 +765,25 @@  discard block
 block discarded – undo
765 765
                 $model = EE_Registry::instance()->load_model($model_name);
766 766
                 $model_objects = $model->get_all($query_params);
767 767
 
768
-                $table_data[ $model_name ] = array();
768
+                $table_data[$model_name] = array();
769 769
                 foreach ($model_objects as $model_object) {
770 770
                     $model_data_array = array();
771 771
                     $fields = $model->field_settings();
772 772
                     foreach ($fields as $field) {
773
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
773
+                        $column_name = $field->get_nicename()."[".$field->get_name()."]";
774 774
                         if ($field instanceof EE_Datetime_Field) {
775 775
                             // $field->set_date_format('Y-m-d');
776 776
                             // $field->set_time_format('H:i:s');
777
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
777
+                            $model_data_array[$column_name] = $model_object->get_datetime(
778 778
                                 $field->get_name(),
779 779
                                 'Y-m-d',
780 780
                                 'H:i:s'
781 781
                             );
782 782
                         } else {
783
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
783
+                            $model_data_array[$column_name] = $model_object->get($field->get_name());
784 784
                         }
785 785
                     }
786
-                    $table_data[ $model_name ][] = $model_data_array;
786
+                    $table_data[$model_name][] = $model_data_array;
787 787
                 }
788 788
             }
789 789
         }
Please login to merge, or discard this patch.
Indentation   +777 added lines, -777 removed lines patch added patch discarded remove patch
@@ -16,781 +16,781 @@
 block discarded – undo
16 16
 class EE_Export
17 17
 {
18 18
 
19
-    const option_prefix = 'ee_report_job_';
20
-
21
-
22
-    // instance of the EE_Export object
23
-    private static $_instance;
24
-
25
-    // instance of the EE_CSV object
26
-    /**
27
-     *
28
-     * @var EE_CSV
29
-     */
30
-    public $EE_CSV = null;
31
-
32
-
33
-    private $_req_data = array();
34
-
35
-
36
-    /**
37
-     *        private constructor to prevent direct creation
38
-     *
39
-     * @Constructor
40
-     * @access private
41
-     * @param array $request_data
42
-     */
43
-    private function __construct($request_data = array())
44
-    {
45
-        $this->_req_data = $request_data;
46
-        $this->today = date("Y-m-d", time());
47
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
48
-        $this->EE_CSV = EE_CSV::instance();
49
-    }
50
-
51
-
52
-    /**
53
-     *        @ singleton method used to instantiate class object
54
-     *        @ access public
55
-     *
56
-     * @param array $request_data
57
-     * @return \EE_Export
58
-     */
59
-    public static function instance($request_data = array())
60
-    {
61
-        // check if class object is instantiated
62
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
63
-            self::$_instance = new self($request_data);
64
-        }
65
-        return self::$_instance;
66
-    }
67
-
68
-
69
-    /**
70
-     * @Export Event Espresso data - routes export requests
71
-     * @access public
72
-     * @return void | bool
73
-     */
74
-    public function export()
75
-    {
76
-        // in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
77
-        if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
78
-            // check if action2 has export action
79
-            if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
80
-                // whoop! there it is!
81
-                $this->_req_data['action'] = $this->_req_data['action2'];
82
-            }
83
-        }
84
-
85
-        $this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
86
-
87
-        switch ($this->_req_data['export']) {
88
-            case 'report':
89
-                switch ($this->_req_data['action']) {
90
-                    case "event":
91
-                    case "export_events":
92
-                    case 'all_event_data':
93
-                        $this->export_all_event_data();
94
-                        break;
95
-
96
-                    case 'registrations_report_for_event':
97
-                        $this->report_registrations_for_event($this->_req_data['EVT_ID']);
98
-                        break;
99
-
100
-                    case 'attendees':
101
-                        $this->export_attendees();
102
-                        break;
103
-
104
-                    case 'categories':
105
-                        $this->export_categories();
106
-                        break;
107
-
108
-                    default:
109
-                        EE_Error::add_error(
110
-                            __('An error occurred! The requested export report could not be found.', 'event_espresso'),
111
-                            __FILE__,
112
-                            __FUNCTION__,
113
-                            __LINE__
114
-                        );
115
-                        return false;
116
-                        break;
117
-                }
118
-                break; // end of switch export : report
119
-            default:
120
-                break;
121
-        } // end of switch export
122
-
123
-        exit;
124
-    }
125
-
126
-    /**
127
-     * Downloads a CSV file with all the columns, but no data. This should be used for importing
128
-     *
129
-     * @return null kills execution
130
-     */
131
-    public function export_sample()
132
-    {
133
-        $event = EEM_Event::instance()->get_one();
134
-        $this->_req_data['EVT_ID'] = $event->ID();
135
-        $this->export_all_event_data();
136
-    }
137
-
138
-
139
-    /**
140
-     * @Export data for ALL events
141
-     * @access public
142
-     * @return void
143
-     */
144
-    public function export_all_event_data()
145
-    {
146
-        // are any Event IDs set?
147
-        $event_query_params = array();
148
-        $related_models_query_params = array();
149
-        $related_through_reg_query_params = array();
150
-        $datetime_ticket_query_params = array();
151
-        $price_query_params = array();
152
-        $price_type_query_params = array();
153
-        $term_query_params = array();
154
-        $state_country_query_params = array();
155
-        $question_group_query_params = array();
156
-        $question_query_params = array();
157
-        if (isset($this->_req_data['EVT_ID'])) {
158
-            // do we have an array of IDs ?
159
-
160
-            if (is_array($this->_req_data['EVT_ID'])) {
161
-                $EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
162
-                $value_to_equal = array('IN', $EVT_IDs);
163
-                $filename = 'events';
164
-            } else {
165
-                // generate regular where = clause
166
-                $EVT_ID = absint($this->_req_data['EVT_ID']);
167
-                $value_to_equal = $EVT_ID;
168
-                $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
169
-
170
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
171
-            }
172
-            $event_query_params[0]['EVT_ID'] = $value_to_equal;
173
-            $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
174
-            $related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
175
-            $datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
176
-            $price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
177
-            $price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
178
-            $term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
179
-            $state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
180
-            $question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
181
-            $question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
182
-        } else {
183
-            $filename = 'all-events';
184
-        }
185
-
186
-
187
-        // array in the format:  table name =>  query where clause
188
-        $models_to_export = array(
189
-            'Event'                   => $event_query_params,
190
-            'Datetime'                => $related_models_query_params,
191
-            'Ticket_Template'         => $price_query_params,
192
-            'Ticket'                  => $datetime_ticket_query_params,
193
-            'Datetime_Ticket'         => $datetime_ticket_query_params,
194
-            'Price_Type'              => $price_type_query_params,
195
-            'Price'                   => $price_query_params,
196
-            'Ticket_Price'            => $price_query_params,
197
-            'Term'                    => $term_query_params,
198
-            'Term_Taxonomy'           => $related_models_query_params,
199
-            'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
200
-            'Country'                 => $state_country_query_params,
201
-            'State'                   => $state_country_query_params,
202
-            'Venue'                   => $related_models_query_params,
203
-            'Event_Venue'             => $related_models_query_params,
204
-            'Question_Group'          => $question_group_query_params,
205
-            'Event_Question_Group'    => $question_group_query_params,
206
-            'Question'                => $question_query_params,
207
-            'Question_Group_Question' => $question_query_params,
208
-            // 'Transaction'=>$related_through_reg_query_params,
209
-            // 'Registration'=>$related_models_query_params,
210
-            // 'Attendee'=>$related_through_reg_query_params,
211
-            // 'Line_Item'=>
212
-
213
-        );
214
-
215
-        $model_data = $this->_get_export_data_for_models($models_to_export);
216
-
217
-        $filename = $this->generate_filename($filename);
218
-
219
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220
-            EE_Error::add_error(
221
-                __(
222
-                    "'An error occurred and the Event details could not be exported from the database.'",
223
-                    "event_espresso"
224
-                ),
225
-                __FILE__,
226
-                __FUNCTION__,
227
-                __LINE__
228
-            );
229
-        }
230
-    }
231
-
232
-    public function report_attendees()
233
-    {
234
-        $attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
235
-            array(
236
-                'force_join' => array('State', 'Country'),
237
-                'caps'       => EEM_Base::caps_read_admin,
238
-            )
239
-        );
240
-        $csv_data = array();
241
-        foreach ($attendee_rows as $attendee_row) {
242
-            $csv_row = array();
243
-            foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
244
-                if ($field_name == 'STA_ID') {
245
-                    $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
246
-                    $csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
247
-                    ) ];
248
-                } elseif ($field_name == 'CNT_ISO') {
249
-                    $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
250
-                    $csv_row[ __(
251
-                        'Country',
252
-                        'event_espresso'
253
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
254
-                } else {
255
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
256
-                }
257
-            }
258
-            $csv_data[] = $csv_row;
259
-        }
260
-
261
-        $filename = $this->generate_filename('contact-list-report');
262
-
263
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
264
-        $this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
265
-        $this->EE_CSV->end_sending_csv($handle);
266
-    }
267
-
268
-
269
-    /**
270
-     * @Export data for ALL attendees
271
-     * @access public
272
-     * @return void
273
-     */
274
-    public function export_attendees()
275
-    {
276
-
277
-        $states_that_have_an_attendee = EEM_State::instance()->get_all(
278
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
279
-        );
280
-        $countries_that_have_an_attendee = EEM_Country::instance()->get_all(
281
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
282
-        );
283
-        // $states_to_export_query_params
284
-        $models_to_export = array(
285
-            'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
286
-            'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
287
-            'Attendee' => array(),
288
-        );
289
-
290
-
291
-        $model_data = $this->_get_export_data_for_models($models_to_export);
292
-        $filename = $this->generate_filename('all-attendees');
293
-
294
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295
-            EE_Error::add_error(
296
-                __(
297
-                    'An error occurred and the Attendee data could not be exported from the database.',
298
-                    'event_espresso'
299
-                ),
300
-                __FILE__,
301
-                __FUNCTION__,
302
-                __LINE__
303
-            );
304
-        }
305
-    }
306
-
307
-    /**
308
-     * Shortcut for preparing a database result for display
309
-     *
310
-     * @param EEM_Base       $model
311
-     * @param string         $field_name
312
-     * @param string         $raw_db_value
313
-     * @param boolean|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
314
-     *                                      NOT display pretty
315
-     * @return string
316
-     */
317
-    protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
318
-    {
319
-        $field_obj = $model->field_settings_for($field_name);
320
-        $value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
321
-        if ($field_obj instanceof EE_Datetime_Field) {
322
-            $field_obj->set_date_format(
323
-                EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
324
-                $pretty_schema
325
-            );
326
-            $field_obj->set_time_format(
327
-                EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
328
-                $pretty_schema
329
-            );
330
-        }
331
-        if ($pretty_schema === true) {
332
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
333
-        } elseif (is_string($pretty_schema)) {
334
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
335
-        } else {
336
-            return $field_obj->prepare_for_get($value_on_model_obj);
337
-        }
338
-    }
339
-
340
-    /**
341
-     * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
342
-     * name, and the questions associated with the registrations
343
-     *
344
-     * @param int $event_id
345
-     */
346
-    public function report_registrations_for_event($event_id = null)
347
-    {
348
-        $reg_fields_to_include = array(
349
-            'TXN_ID',
350
-            'ATT_ID',
351
-            'REG_ID',
352
-            'REG_date',
353
-            'REG_code',
354
-            'REG_count',
355
-            'REG_final_price',
356
-
357
-        );
358
-        $att_fields_to_include = array(
359
-            'ATT_fname',
360
-            'ATT_lname',
361
-            'ATT_email',
362
-            'ATT_address',
363
-            'ATT_address2',
364
-            'ATT_city',
365
-            'STA_ID',
366
-            'CNT_ISO',
367
-            'ATT_zip',
368
-            'ATT_phone',
369
-        );
370
-
371
-        $registrations_csv_ready_array = array();
372
-        $reg_model = EE_Registry::instance()->load_model('Registration');
373
-        $query_params = apply_filters(
374
-            'FHEE__EE_Export__report_registration_for_event',
375
-            array(
376
-                array(
377
-                    'OR'                 => array(
378
-                        // don't include registrations from failed or abandoned transactions...
379
-                        'Transaction.STS_ID' => array(
380
-                            'NOT IN',
381
-                            array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
382
-                        ),
383
-                        // unless the registration is approved, in which case include it regardless of transaction status
384
-                        'STS_ID'             => EEM_Registration::status_id_approved,
385
-                    ),
386
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
387
-                ),
388
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
389
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
390
-                'caps'       => EEM_Base::caps_read_admin,
391
-            ),
392
-            $event_id
393
-        );
394
-        if ($event_id) {
395
-            $query_params[0]['EVT_ID'] = $event_id;
396
-        } else {
397
-            $query_params['force_join'][] = 'Event';
398
-        }
399
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
400
-        // get all questions which relate to someone in this group
401
-        $registration_ids = array();
402
-        foreach ($registration_rows as $reg_row) {
403
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
404
-        }
405
-        // EEM_Question::instance()->show_next_x_db_queries();
406
-        $questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
407
-            array(array('Answer.REG_ID' => array('IN', $registration_ids)))
408
-        );
409
-        foreach ($registration_rows as $reg_row) {
410
-            if (is_array($reg_row)) {
411
-                $reg_csv_array = array();
412
-                if (! $event_id) {
413
-                    // get the event's name and Id
414
-                    $reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
415
-                        __('%1$s (%2$s)', 'event_espresso'),
416
-                        $this->_prepare_value_from_db_for_display(
417
-                            EEM_Event::instance(),
418
-                            'EVT_name',
419
-                            $reg_row['Event_CPT.post_title']
420
-                        ),
421
-                        $reg_row['Event_CPT.ID']
422
-                    );
423
-                }
424
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
425
-                /*@var $reg_row EE_Registration */
426
-                foreach ($reg_fields_to_include as $field_name) {
427
-                    $field = $reg_model->field_settings_for($field_name);
428
-                    if ($field_name == 'REG_final_price') {
429
-                        $value = $this->_prepare_value_from_db_for_display(
430
-                            $reg_model,
431
-                            $field_name,
432
-                            $reg_row['Registration.REG_final_price'],
433
-                            'localized_float'
434
-                        );
435
-                    } elseif ($field_name == 'REG_count') {
436
-                        $value = sprintf(
437
-                            __('%s of %s', 'event_espresso'),
438
-                            $this->_prepare_value_from_db_for_display(
439
-                                $reg_model,
440
-                                'REG_count',
441
-                                $reg_row['Registration.REG_count']
442
-                            ),
443
-                            $this->_prepare_value_from_db_for_display(
444
-                                $reg_model,
445
-                                'REG_group_size',
446
-                                $reg_row['Registration.REG_group_size']
447
-                            )
448
-                        );
449
-                    } elseif ($field_name == 'REG_date') {
450
-                        $value = $this->_prepare_value_from_db_for_display(
451
-                            $reg_model,
452
-                            $field_name,
453
-                            $reg_row['Registration.REG_date'],
454
-                            'no_html'
455
-                        );
456
-                    } else {
457
-                        $value = $this->_prepare_value_from_db_for_display(
458
-                            $reg_model,
459
-                            $field_name,
460
-                            $reg_row[ $field->get_qualified_column() ]
461
-                        );
462
-                    }
463
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
464
-                    if ($field_name == 'REG_final_price') {
465
-                        // add a column named Currency after the final price
466
-                        $reg_csv_array[ __("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
467
-                    }
468
-                }
469
-                // get pretty status
470
-                $stati = EEM_Status::instance()->localized_status(
471
-                    array(
472
-                        $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
473
-                        $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
474
-                    ),
475
-                    false,
476
-                    'sentence'
477
-                );
478
-                $reg_csv_array[ __(
479
-                    "Registration Status",
480
-                    'event_espresso'
481
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
482
-                // get pretty trnasaction status
483
-                $reg_csv_array[ __(
484
-                    "Transaction Status",
485
-                    'event_espresso'
486
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
487
-                $reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
488
-                    ? $this->_prepare_value_from_db_for_display(
489
-                        EEM_Transaction::instance(),
490
-                        'TXN_total',
491
-                        $reg_row['TransactionTable.TXN_total'],
492
-                        'localized_float'
493
-                    ) : '0.00';
494
-                $reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
495
-                    ? $this->_prepare_value_from_db_for_display(
496
-                        EEM_Transaction::instance(),
497
-                        'TXN_paid',
498
-                        $reg_row['TransactionTable.TXN_paid'],
499
-                        'localized_float'
500
-                    ) : '0.00';
501
-                $payment_methods = array();
502
-                $gateway_txn_ids_etc = array();
503
-                $payment_times = array();
504
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
505
-                    $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
506
-                        array(
507
-                            array(
508
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
509
-                                'STS_ID' => EEM_Payment::status_id_approved,
510
-                            ),
511
-                            'force_join' => array('Payment_Method'),
512
-                        ),
513
-                        ARRAY_A,
514
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
515
-                    );
516
-
517
-                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
518
-                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
519
-                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
520
-                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
521
-                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
522
-                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
523
-                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
524
-                    }
525
-                }
526
-                $reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
527
-                $reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
528
-                $reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
529
-                    ',',
530
-                    $gateway_txn_ids_etc
531
-                );
532
-
533
-                // get whether or not the user has checked in
534
-                $reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
535
-                    $reg_row['Registration.REG_ID'],
536
-                    'Checkin'
537
-                );
538
-                // get ticket of registration and its price
539
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
540
-                if ($reg_row['Ticket.TKT_ID']) {
541
-                    $ticket_name = $this->_prepare_value_from_db_for_display(
542
-                        $ticket_model,
543
-                        'TKT_name',
544
-                        $reg_row['Ticket.TKT_name']
545
-                    );
546
-                    $datetimes_strings = array();
547
-                    foreach (
548
-                        EEM_Datetime::instance()->get_all_wpdb_results(
549
-                            array(
550
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
551
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
552
-                            'default_where_conditions' => 'none',
553
-                            )
554
-                        ) as $datetime
555
-                    ) {
556
-                        $datetimes_strings[] = $this->_prepare_value_from_db_for_display(
557
-                            EEM_Datetime::instance(),
558
-                            'DTT_EVT_start',
559
-                            $datetime['Datetime.DTT_EVT_start']
560
-                        );
561
-                    }
562
-                } else {
563
-                    $ticket_name = __('Unknown', 'event_espresso');
564
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
565
-                }
566
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
567
-                $reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
568
-                // get datetime(s) of registration
569
-
570
-                // add attendee columns
571
-                foreach ($att_fields_to_include as $att_field_name) {
572
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
573
-                    if ($reg_row['Attendee_CPT.ID']) {
574
-                        if ($att_field_name == 'STA_ID') {
575
-                            $value = EEM_State::instance()->get_var(
576
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
577
-                                'STA_name'
578
-                            );
579
-                        } elseif ($att_field_name == 'CNT_ISO') {
580
-                            $value = EEM_Country::instance()->get_var(
581
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
582
-                                'CNT_name'
583
-                            );
584
-                        } else {
585
-                            $value = $this->_prepare_value_from_db_for_display(
586
-                                EEM_Attendee::instance(),
587
-                                $att_field_name,
588
-                                $reg_row[ $field_obj->get_qualified_column() ]
589
-                            );
590
-                        }
591
-                    } else {
592
-                        $value = '';
593
-                    }
594
-
595
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
596
-                }
597
-
598
-                // make sure each registration has the same questions in the same order
599
-                foreach ($questions_for_these_regs_rows as $question_row) {
600
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
601
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
602
-                    }
603
-                }
604
-                // now fill out the questions THEY answered
605
-                foreach (
606
-                    EEM_Answer::instance()->get_all_wpdb_results(
607
-                        array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
608
-                    ) as $answer_row
609
-                ) {
610
-                    /* @var $answer EE_Answer */
611
-                    if ($answer_row['Question.QST_ID']) {
612
-                        $question_label = $this->_prepare_value_from_db_for_display(
613
-                            EEM_Question::instance(),
614
-                            'QST_admin_label',
615
-                            $answer_row['Question.QST_admin_label']
616
-                        );
617
-                    } else {
618
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
619
-                    }
620
-                    if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
621
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
622
-                            $answer_row['Answer.ANS_value']
623
-                        );
624
-                    } else {
625
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
626
-                            EEM_Answer::instance(),
627
-                            'ANS_value',
628
-                            $answer_row['Answer.ANS_value']
629
-                        );
630
-                    }
631
-                }
632
-                $registrations_csv_ready_array[] = apply_filters(
633
-                    'FHEE__EE_Export__report_registrations__reg_csv_array',
634
-                    $reg_csv_array,
635
-                    $reg_row
636
-                );
637
-            }
638
-        }
639
-
640
-        // if we couldn't export anything, we want to at least show the column headers
641
-        if (empty($registrations_csv_ready_array)) {
642
-            $reg_csv_array = array();
643
-            $model_and_fields_to_include = array(
644
-                'Registration' => $reg_fields_to_include,
645
-                'Attendee'     => $att_fields_to_include,
646
-            );
647
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
648
-                $model = EE_Registry::instance()->load_model($model_name);
649
-                foreach ($field_list as $field_name) {
650
-                    $field = $model->field_settings_for($field_name);
651
-                    $reg_csv_array[ $this->_get_column_name_for_field(
652
-                        $field
653
-                    ) ] = null;// $registration->get($field->get_name());
654
-                }
655
-            }
656
-            $registrations_csv_ready_array [] = $reg_csv_array;
657
-        }
658
-        if ($event_id) {
659
-            $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
660
-            if (! $event_slug) {
661
-                $event_slug = __('unknown', 'event_espresso');
662
-            }
663
-        } else {
664
-            $event_slug = __('all', 'event_espresso');
665
-        }
666
-        $filename = sprintf("registrations-for-%s", $event_slug);
667
-
668
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
669
-        $this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
670
-        $this->EE_CSV->end_sending_csv($handle);
671
-    }
672
-
673
-    /**
674
-     * Gets the 'normal' column named for fields
675
-     *
676
-     * @param EE_Model_Field_Base $field
677
-     * @return string
678
-     */
679
-    protected function _get_column_name_for_field(EE_Model_Field_Base $field)
680
-    {
681
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
682
-    }
683
-
684
-
685
-    /**
686
-     * @Export data for ALL events
687
-     * @access public
688
-     * @return void
689
-     */
690
-    public function export_categories()
691
-    {
692
-        // are any Event IDs set?
693
-        $query_params = array();
694
-        if (isset($this->_req_data['EVT_CAT_ID'])) {
695
-            // do we have an array of IDs ?
696
-            if (is_array($this->_req_data['EVT_CAT_ID'])) {
697
-                // generate an "IN (CSV)" where clause
698
-                $EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
699
-                $filename = 'event-categories';
700
-                $query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
701
-            } else {
702
-                // generate regular where = clause
703
-                $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
704
-                $filename = 'event-category#' . $EVT_CAT_ID;
705
-                $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
706
-            }
707
-        } else {
708
-            // no IDs means we will d/l the entire table
709
-            $filename = 'all-categories';
710
-        }
711
-
712
-        $tables_to_export = array(
713
-            'Term_Taxonomy' => $query_params,
714
-        );
715
-
716
-        $table_data = $this->_get_export_data_for_models($tables_to_export);
717
-        $filename = $this->generate_filename($filename);
718
-
719
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
720
-            EE_Error::add_error(
721
-                __(
722
-                    'An error occurred and the Category details could not be exported from the database.',
723
-                    'event_espresso'
724
-                ),
725
-                __FILE__,
726
-                __FUNCTION__,
727
-                __LINE__
728
-            );
729
-        }
730
-    }
731
-
732
-
733
-    /**
734
-     * @process export name to create a suitable filename
735
-     * @access  private
736
-     * @param string - export_name
737
-     * @return string on success, FALSE on fail
738
-     */
739
-    private function generate_filename($export_name = '')
740
-    {
741
-        if ($export_name != '') {
742
-            $filename = get_bloginfo('name') . '-' . $export_name;
743
-            $filename = sanitize_key($filename) . '-' . $this->today;
744
-            return $filename;
745
-        } else {
746
-            EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
747
-        }
748
-        return false;
749
-    }
750
-
751
-
752
-    /**
753
-     * @recursive function for exporting table data and merging the results with the next results
754
-     * @access    private
755
-     * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
756
-     *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
757
-     * @return array on success, FALSE on fail
758
-     */
759
-    private function _get_export_data_for_models($models_to_export = array())
760
-    {
761
-        $table_data = false;
762
-        if (is_array($models_to_export)) {
763
-            foreach ($models_to_export as $model_name => $query_params) {
764
-                // check for a numerically-indexed array. in that case, $model_name is the value!!
765
-                if (is_int($model_name)) {
766
-                    $model_name = $query_params;
767
-                    $query_params = array();
768
-                }
769
-                $model = EE_Registry::instance()->load_model($model_name);
770
-                $model_objects = $model->get_all($query_params);
771
-
772
-                $table_data[ $model_name ] = array();
773
-                foreach ($model_objects as $model_object) {
774
-                    $model_data_array = array();
775
-                    $fields = $model->field_settings();
776
-                    foreach ($fields as $field) {
777
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
778
-                        if ($field instanceof EE_Datetime_Field) {
779
-                            // $field->set_date_format('Y-m-d');
780
-                            // $field->set_time_format('H:i:s');
781
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
782
-                                $field->get_name(),
783
-                                'Y-m-d',
784
-                                'H:i:s'
785
-                            );
786
-                        } else {
787
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
788
-                        }
789
-                    }
790
-                    $table_data[ $model_name ][] = $model_data_array;
791
-                }
792
-            }
793
-        }
794
-        return $table_data;
795
-    }
19
+	const option_prefix = 'ee_report_job_';
20
+
21
+
22
+	// instance of the EE_Export object
23
+	private static $_instance;
24
+
25
+	// instance of the EE_CSV object
26
+	/**
27
+	 *
28
+	 * @var EE_CSV
29
+	 */
30
+	public $EE_CSV = null;
31
+
32
+
33
+	private $_req_data = array();
34
+
35
+
36
+	/**
37
+	 *        private constructor to prevent direct creation
38
+	 *
39
+	 * @Constructor
40
+	 * @access private
41
+	 * @param array $request_data
42
+	 */
43
+	private function __construct($request_data = array())
44
+	{
45
+		$this->_req_data = $request_data;
46
+		$this->today = date("Y-m-d", time());
47
+		require_once(EE_CLASSES . 'EE_CSV.class.php');
48
+		$this->EE_CSV = EE_CSV::instance();
49
+	}
50
+
51
+
52
+	/**
53
+	 *        @ singleton method used to instantiate class object
54
+	 *        @ access public
55
+	 *
56
+	 * @param array $request_data
57
+	 * @return \EE_Export
58
+	 */
59
+	public static function instance($request_data = array())
60
+	{
61
+		// check if class object is instantiated
62
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
63
+			self::$_instance = new self($request_data);
64
+		}
65
+		return self::$_instance;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @Export Event Espresso data - routes export requests
71
+	 * @access public
72
+	 * @return void | bool
73
+	 */
74
+	public function export()
75
+	{
76
+		// in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
77
+		if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
78
+			// check if action2 has export action
79
+			if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
80
+				// whoop! there it is!
81
+				$this->_req_data['action'] = $this->_req_data['action2'];
82
+			}
83
+		}
84
+
85
+		$this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
86
+
87
+		switch ($this->_req_data['export']) {
88
+			case 'report':
89
+				switch ($this->_req_data['action']) {
90
+					case "event":
91
+					case "export_events":
92
+					case 'all_event_data':
93
+						$this->export_all_event_data();
94
+						break;
95
+
96
+					case 'registrations_report_for_event':
97
+						$this->report_registrations_for_event($this->_req_data['EVT_ID']);
98
+						break;
99
+
100
+					case 'attendees':
101
+						$this->export_attendees();
102
+						break;
103
+
104
+					case 'categories':
105
+						$this->export_categories();
106
+						break;
107
+
108
+					default:
109
+						EE_Error::add_error(
110
+							__('An error occurred! The requested export report could not be found.', 'event_espresso'),
111
+							__FILE__,
112
+							__FUNCTION__,
113
+							__LINE__
114
+						);
115
+						return false;
116
+						break;
117
+				}
118
+				break; // end of switch export : report
119
+			default:
120
+				break;
121
+		} // end of switch export
122
+
123
+		exit;
124
+	}
125
+
126
+	/**
127
+	 * Downloads a CSV file with all the columns, but no data. This should be used for importing
128
+	 *
129
+	 * @return null kills execution
130
+	 */
131
+	public function export_sample()
132
+	{
133
+		$event = EEM_Event::instance()->get_one();
134
+		$this->_req_data['EVT_ID'] = $event->ID();
135
+		$this->export_all_event_data();
136
+	}
137
+
138
+
139
+	/**
140
+	 * @Export data for ALL events
141
+	 * @access public
142
+	 * @return void
143
+	 */
144
+	public function export_all_event_data()
145
+	{
146
+		// are any Event IDs set?
147
+		$event_query_params = array();
148
+		$related_models_query_params = array();
149
+		$related_through_reg_query_params = array();
150
+		$datetime_ticket_query_params = array();
151
+		$price_query_params = array();
152
+		$price_type_query_params = array();
153
+		$term_query_params = array();
154
+		$state_country_query_params = array();
155
+		$question_group_query_params = array();
156
+		$question_query_params = array();
157
+		if (isset($this->_req_data['EVT_ID'])) {
158
+			// do we have an array of IDs ?
159
+
160
+			if (is_array($this->_req_data['EVT_ID'])) {
161
+				$EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
162
+				$value_to_equal = array('IN', $EVT_IDs);
163
+				$filename = 'events';
164
+			} else {
165
+				// generate regular where = clause
166
+				$EVT_ID = absint($this->_req_data['EVT_ID']);
167
+				$value_to_equal = $EVT_ID;
168
+				$event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
169
+
170
+				$filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
171
+			}
172
+			$event_query_params[0]['EVT_ID'] = $value_to_equal;
173
+			$related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
174
+			$related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
175
+			$datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
176
+			$price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
177
+			$price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
178
+			$term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
179
+			$state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
180
+			$question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
181
+			$question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
182
+		} else {
183
+			$filename = 'all-events';
184
+		}
185
+
186
+
187
+		// array in the format:  table name =>  query where clause
188
+		$models_to_export = array(
189
+			'Event'                   => $event_query_params,
190
+			'Datetime'                => $related_models_query_params,
191
+			'Ticket_Template'         => $price_query_params,
192
+			'Ticket'                  => $datetime_ticket_query_params,
193
+			'Datetime_Ticket'         => $datetime_ticket_query_params,
194
+			'Price_Type'              => $price_type_query_params,
195
+			'Price'                   => $price_query_params,
196
+			'Ticket_Price'            => $price_query_params,
197
+			'Term'                    => $term_query_params,
198
+			'Term_Taxonomy'           => $related_models_query_params,
199
+			'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
200
+			'Country'                 => $state_country_query_params,
201
+			'State'                   => $state_country_query_params,
202
+			'Venue'                   => $related_models_query_params,
203
+			'Event_Venue'             => $related_models_query_params,
204
+			'Question_Group'          => $question_group_query_params,
205
+			'Event_Question_Group'    => $question_group_query_params,
206
+			'Question'                => $question_query_params,
207
+			'Question_Group_Question' => $question_query_params,
208
+			// 'Transaction'=>$related_through_reg_query_params,
209
+			// 'Registration'=>$related_models_query_params,
210
+			// 'Attendee'=>$related_through_reg_query_params,
211
+			// 'Line_Item'=>
212
+
213
+		);
214
+
215
+		$model_data = $this->_get_export_data_for_models($models_to_export);
216
+
217
+		$filename = $this->generate_filename($filename);
218
+
219
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220
+			EE_Error::add_error(
221
+				__(
222
+					"'An error occurred and the Event details could not be exported from the database.'",
223
+					"event_espresso"
224
+				),
225
+				__FILE__,
226
+				__FUNCTION__,
227
+				__LINE__
228
+			);
229
+		}
230
+	}
231
+
232
+	public function report_attendees()
233
+	{
234
+		$attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
235
+			array(
236
+				'force_join' => array('State', 'Country'),
237
+				'caps'       => EEM_Base::caps_read_admin,
238
+			)
239
+		);
240
+		$csv_data = array();
241
+		foreach ($attendee_rows as $attendee_row) {
242
+			$csv_row = array();
243
+			foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
244
+				if ($field_name == 'STA_ID') {
245
+					$state_name_field = EEM_State::instance()->field_settings_for('STA_name');
246
+					$csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
247
+					) ];
248
+				} elseif ($field_name == 'CNT_ISO') {
249
+					$country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
250
+					$csv_row[ __(
251
+						'Country',
252
+						'event_espresso'
253
+					) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
254
+				} else {
255
+					$csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
256
+				}
257
+			}
258
+			$csv_data[] = $csv_row;
259
+		}
260
+
261
+		$filename = $this->generate_filename('contact-list-report');
262
+
263
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
264
+		$this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
265
+		$this->EE_CSV->end_sending_csv($handle);
266
+	}
267
+
268
+
269
+	/**
270
+	 * @Export data for ALL attendees
271
+	 * @access public
272
+	 * @return void
273
+	 */
274
+	public function export_attendees()
275
+	{
276
+
277
+		$states_that_have_an_attendee = EEM_State::instance()->get_all(
278
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
279
+		);
280
+		$countries_that_have_an_attendee = EEM_Country::instance()->get_all(
281
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
282
+		);
283
+		// $states_to_export_query_params
284
+		$models_to_export = array(
285
+			'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
286
+			'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
287
+			'Attendee' => array(),
288
+		);
289
+
290
+
291
+		$model_data = $this->_get_export_data_for_models($models_to_export);
292
+		$filename = $this->generate_filename('all-attendees');
293
+
294
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295
+			EE_Error::add_error(
296
+				__(
297
+					'An error occurred and the Attendee data could not be exported from the database.',
298
+					'event_espresso'
299
+				),
300
+				__FILE__,
301
+				__FUNCTION__,
302
+				__LINE__
303
+			);
304
+		}
305
+	}
306
+
307
+	/**
308
+	 * Shortcut for preparing a database result for display
309
+	 *
310
+	 * @param EEM_Base       $model
311
+	 * @param string         $field_name
312
+	 * @param string         $raw_db_value
313
+	 * @param boolean|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
314
+	 *                                      NOT display pretty
315
+	 * @return string
316
+	 */
317
+	protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
318
+	{
319
+		$field_obj = $model->field_settings_for($field_name);
320
+		$value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
321
+		if ($field_obj instanceof EE_Datetime_Field) {
322
+			$field_obj->set_date_format(
323
+				EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
324
+				$pretty_schema
325
+			);
326
+			$field_obj->set_time_format(
327
+				EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
328
+				$pretty_schema
329
+			);
330
+		}
331
+		if ($pretty_schema === true) {
332
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
333
+		} elseif (is_string($pretty_schema)) {
334
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
335
+		} else {
336
+			return $field_obj->prepare_for_get($value_on_model_obj);
337
+		}
338
+	}
339
+
340
+	/**
341
+	 * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
342
+	 * name, and the questions associated with the registrations
343
+	 *
344
+	 * @param int $event_id
345
+	 */
346
+	public function report_registrations_for_event($event_id = null)
347
+	{
348
+		$reg_fields_to_include = array(
349
+			'TXN_ID',
350
+			'ATT_ID',
351
+			'REG_ID',
352
+			'REG_date',
353
+			'REG_code',
354
+			'REG_count',
355
+			'REG_final_price',
356
+
357
+		);
358
+		$att_fields_to_include = array(
359
+			'ATT_fname',
360
+			'ATT_lname',
361
+			'ATT_email',
362
+			'ATT_address',
363
+			'ATT_address2',
364
+			'ATT_city',
365
+			'STA_ID',
366
+			'CNT_ISO',
367
+			'ATT_zip',
368
+			'ATT_phone',
369
+		);
370
+
371
+		$registrations_csv_ready_array = array();
372
+		$reg_model = EE_Registry::instance()->load_model('Registration');
373
+		$query_params = apply_filters(
374
+			'FHEE__EE_Export__report_registration_for_event',
375
+			array(
376
+				array(
377
+					'OR'                 => array(
378
+						// don't include registrations from failed or abandoned transactions...
379
+						'Transaction.STS_ID' => array(
380
+							'NOT IN',
381
+							array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
382
+						),
383
+						// unless the registration is approved, in which case include it regardless of transaction status
384
+						'STS_ID'             => EEM_Registration::status_id_approved,
385
+					),
386
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
387
+				),
388
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
389
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
390
+				'caps'       => EEM_Base::caps_read_admin,
391
+			),
392
+			$event_id
393
+		);
394
+		if ($event_id) {
395
+			$query_params[0]['EVT_ID'] = $event_id;
396
+		} else {
397
+			$query_params['force_join'][] = 'Event';
398
+		}
399
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
400
+		// get all questions which relate to someone in this group
401
+		$registration_ids = array();
402
+		foreach ($registration_rows as $reg_row) {
403
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
404
+		}
405
+		// EEM_Question::instance()->show_next_x_db_queries();
406
+		$questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
407
+			array(array('Answer.REG_ID' => array('IN', $registration_ids)))
408
+		);
409
+		foreach ($registration_rows as $reg_row) {
410
+			if (is_array($reg_row)) {
411
+				$reg_csv_array = array();
412
+				if (! $event_id) {
413
+					// get the event's name and Id
414
+					$reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
415
+						__('%1$s (%2$s)', 'event_espresso'),
416
+						$this->_prepare_value_from_db_for_display(
417
+							EEM_Event::instance(),
418
+							'EVT_name',
419
+							$reg_row['Event_CPT.post_title']
420
+						),
421
+						$reg_row['Event_CPT.ID']
422
+					);
423
+				}
424
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
425
+				/*@var $reg_row EE_Registration */
426
+				foreach ($reg_fields_to_include as $field_name) {
427
+					$field = $reg_model->field_settings_for($field_name);
428
+					if ($field_name == 'REG_final_price') {
429
+						$value = $this->_prepare_value_from_db_for_display(
430
+							$reg_model,
431
+							$field_name,
432
+							$reg_row['Registration.REG_final_price'],
433
+							'localized_float'
434
+						);
435
+					} elseif ($field_name == 'REG_count') {
436
+						$value = sprintf(
437
+							__('%s of %s', 'event_espresso'),
438
+							$this->_prepare_value_from_db_for_display(
439
+								$reg_model,
440
+								'REG_count',
441
+								$reg_row['Registration.REG_count']
442
+							),
443
+							$this->_prepare_value_from_db_for_display(
444
+								$reg_model,
445
+								'REG_group_size',
446
+								$reg_row['Registration.REG_group_size']
447
+							)
448
+						);
449
+					} elseif ($field_name == 'REG_date') {
450
+						$value = $this->_prepare_value_from_db_for_display(
451
+							$reg_model,
452
+							$field_name,
453
+							$reg_row['Registration.REG_date'],
454
+							'no_html'
455
+						);
456
+					} else {
457
+						$value = $this->_prepare_value_from_db_for_display(
458
+							$reg_model,
459
+							$field_name,
460
+							$reg_row[ $field->get_qualified_column() ]
461
+						);
462
+					}
463
+					$reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
464
+					if ($field_name == 'REG_final_price') {
465
+						// add a column named Currency after the final price
466
+						$reg_csv_array[ __("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
467
+					}
468
+				}
469
+				// get pretty status
470
+				$stati = EEM_Status::instance()->localized_status(
471
+					array(
472
+						$reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
473
+						$reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
474
+					),
475
+					false,
476
+					'sentence'
477
+				);
478
+				$reg_csv_array[ __(
479
+					"Registration Status",
480
+					'event_espresso'
481
+				) ] = $stati[ $reg_row['Registration.STS_ID'] ];
482
+				// get pretty trnasaction status
483
+				$reg_csv_array[ __(
484
+					"Transaction Status",
485
+					'event_espresso'
486
+				) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
487
+				$reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
488
+					? $this->_prepare_value_from_db_for_display(
489
+						EEM_Transaction::instance(),
490
+						'TXN_total',
491
+						$reg_row['TransactionTable.TXN_total'],
492
+						'localized_float'
493
+					) : '0.00';
494
+				$reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
495
+					? $this->_prepare_value_from_db_for_display(
496
+						EEM_Transaction::instance(),
497
+						'TXN_paid',
498
+						$reg_row['TransactionTable.TXN_paid'],
499
+						'localized_float'
500
+					) : '0.00';
501
+				$payment_methods = array();
502
+				$gateway_txn_ids_etc = array();
503
+				$payment_times = array();
504
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
505
+					$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
506
+						array(
507
+							array(
508
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
509
+								'STS_ID' => EEM_Payment::status_id_approved,
510
+							),
511
+							'force_join' => array('Payment_Method'),
512
+						),
513
+						ARRAY_A,
514
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
515
+					);
516
+
517
+					foreach ($payments_info as $payment_method_and_gateway_txn_id) {
518
+						$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
519
+							? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
520
+						$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
521
+							? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
522
+						$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
523
+							? $payment_method_and_gateway_txn_id['payment_time'] : '';
524
+					}
525
+				}
526
+				$reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
527
+				$reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
528
+				$reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
529
+					',',
530
+					$gateway_txn_ids_etc
531
+				);
532
+
533
+				// get whether or not the user has checked in
534
+				$reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
535
+					$reg_row['Registration.REG_ID'],
536
+					'Checkin'
537
+				);
538
+				// get ticket of registration and its price
539
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
540
+				if ($reg_row['Ticket.TKT_ID']) {
541
+					$ticket_name = $this->_prepare_value_from_db_for_display(
542
+						$ticket_model,
543
+						'TKT_name',
544
+						$reg_row['Ticket.TKT_name']
545
+					);
546
+					$datetimes_strings = array();
547
+					foreach (
548
+						EEM_Datetime::instance()->get_all_wpdb_results(
549
+							array(
550
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
551
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
552
+							'default_where_conditions' => 'none',
553
+							)
554
+						) as $datetime
555
+					) {
556
+						$datetimes_strings[] = $this->_prepare_value_from_db_for_display(
557
+							EEM_Datetime::instance(),
558
+							'DTT_EVT_start',
559
+							$datetime['Datetime.DTT_EVT_start']
560
+						);
561
+					}
562
+				} else {
563
+					$ticket_name = __('Unknown', 'event_espresso');
564
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
565
+				}
566
+				$reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
567
+				$reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
568
+				// get datetime(s) of registration
569
+
570
+				// add attendee columns
571
+				foreach ($att_fields_to_include as $att_field_name) {
572
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
573
+					if ($reg_row['Attendee_CPT.ID']) {
574
+						if ($att_field_name == 'STA_ID') {
575
+							$value = EEM_State::instance()->get_var(
576
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
577
+								'STA_name'
578
+							);
579
+						} elseif ($att_field_name == 'CNT_ISO') {
580
+							$value = EEM_Country::instance()->get_var(
581
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
582
+								'CNT_name'
583
+							);
584
+						} else {
585
+							$value = $this->_prepare_value_from_db_for_display(
586
+								EEM_Attendee::instance(),
587
+								$att_field_name,
588
+								$reg_row[ $field_obj->get_qualified_column() ]
589
+							);
590
+						}
591
+					} else {
592
+						$value = '';
593
+					}
594
+
595
+					$reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
596
+				}
597
+
598
+				// make sure each registration has the same questions in the same order
599
+				foreach ($questions_for_these_regs_rows as $question_row) {
600
+					if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
601
+						$reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
602
+					}
603
+				}
604
+				// now fill out the questions THEY answered
605
+				foreach (
606
+					EEM_Answer::instance()->get_all_wpdb_results(
607
+						array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
608
+					) as $answer_row
609
+				) {
610
+					/* @var $answer EE_Answer */
611
+					if ($answer_row['Question.QST_ID']) {
612
+						$question_label = $this->_prepare_value_from_db_for_display(
613
+							EEM_Question::instance(),
614
+							'QST_admin_label',
615
+							$answer_row['Question.QST_admin_label']
616
+						);
617
+					} else {
618
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
619
+					}
620
+					if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
621
+						$reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
622
+							$answer_row['Answer.ANS_value']
623
+						);
624
+					} else {
625
+						$reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
626
+							EEM_Answer::instance(),
627
+							'ANS_value',
628
+							$answer_row['Answer.ANS_value']
629
+						);
630
+					}
631
+				}
632
+				$registrations_csv_ready_array[] = apply_filters(
633
+					'FHEE__EE_Export__report_registrations__reg_csv_array',
634
+					$reg_csv_array,
635
+					$reg_row
636
+				);
637
+			}
638
+		}
639
+
640
+		// if we couldn't export anything, we want to at least show the column headers
641
+		if (empty($registrations_csv_ready_array)) {
642
+			$reg_csv_array = array();
643
+			$model_and_fields_to_include = array(
644
+				'Registration' => $reg_fields_to_include,
645
+				'Attendee'     => $att_fields_to_include,
646
+			);
647
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
648
+				$model = EE_Registry::instance()->load_model($model_name);
649
+				foreach ($field_list as $field_name) {
650
+					$field = $model->field_settings_for($field_name);
651
+					$reg_csv_array[ $this->_get_column_name_for_field(
652
+						$field
653
+					) ] = null;// $registration->get($field->get_name());
654
+				}
655
+			}
656
+			$registrations_csv_ready_array [] = $reg_csv_array;
657
+		}
658
+		if ($event_id) {
659
+			$event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
660
+			if (! $event_slug) {
661
+				$event_slug = __('unknown', 'event_espresso');
662
+			}
663
+		} else {
664
+			$event_slug = __('all', 'event_espresso');
665
+		}
666
+		$filename = sprintf("registrations-for-%s", $event_slug);
667
+
668
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
669
+		$this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
670
+		$this->EE_CSV->end_sending_csv($handle);
671
+	}
672
+
673
+	/**
674
+	 * Gets the 'normal' column named for fields
675
+	 *
676
+	 * @param EE_Model_Field_Base $field
677
+	 * @return string
678
+	 */
679
+	protected function _get_column_name_for_field(EE_Model_Field_Base $field)
680
+	{
681
+		return $field->get_nicename() . "[" . $field->get_name() . "]";
682
+	}
683
+
684
+
685
+	/**
686
+	 * @Export data for ALL events
687
+	 * @access public
688
+	 * @return void
689
+	 */
690
+	public function export_categories()
691
+	{
692
+		// are any Event IDs set?
693
+		$query_params = array();
694
+		if (isset($this->_req_data['EVT_CAT_ID'])) {
695
+			// do we have an array of IDs ?
696
+			if (is_array($this->_req_data['EVT_CAT_ID'])) {
697
+				// generate an "IN (CSV)" where clause
698
+				$EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
699
+				$filename = 'event-categories';
700
+				$query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
701
+			} else {
702
+				// generate regular where = clause
703
+				$EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
704
+				$filename = 'event-category#' . $EVT_CAT_ID;
705
+				$query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
706
+			}
707
+		} else {
708
+			// no IDs means we will d/l the entire table
709
+			$filename = 'all-categories';
710
+		}
711
+
712
+		$tables_to_export = array(
713
+			'Term_Taxonomy' => $query_params,
714
+		);
715
+
716
+		$table_data = $this->_get_export_data_for_models($tables_to_export);
717
+		$filename = $this->generate_filename($filename);
718
+
719
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
720
+			EE_Error::add_error(
721
+				__(
722
+					'An error occurred and the Category details could not be exported from the database.',
723
+					'event_espresso'
724
+				),
725
+				__FILE__,
726
+				__FUNCTION__,
727
+				__LINE__
728
+			);
729
+		}
730
+	}
731
+
732
+
733
+	/**
734
+	 * @process export name to create a suitable filename
735
+	 * @access  private
736
+	 * @param string - export_name
737
+	 * @return string on success, FALSE on fail
738
+	 */
739
+	private function generate_filename($export_name = '')
740
+	{
741
+		if ($export_name != '') {
742
+			$filename = get_bloginfo('name') . '-' . $export_name;
743
+			$filename = sanitize_key($filename) . '-' . $this->today;
744
+			return $filename;
745
+		} else {
746
+			EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
747
+		}
748
+		return false;
749
+	}
750
+
751
+
752
+	/**
753
+	 * @recursive function for exporting table data and merging the results with the next results
754
+	 * @access    private
755
+	 * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
756
+	 *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
757
+	 * @return array on success, FALSE on fail
758
+	 */
759
+	private function _get_export_data_for_models($models_to_export = array())
760
+	{
761
+		$table_data = false;
762
+		if (is_array($models_to_export)) {
763
+			foreach ($models_to_export as $model_name => $query_params) {
764
+				// check for a numerically-indexed array. in that case, $model_name is the value!!
765
+				if (is_int($model_name)) {
766
+					$model_name = $query_params;
767
+					$query_params = array();
768
+				}
769
+				$model = EE_Registry::instance()->load_model($model_name);
770
+				$model_objects = $model->get_all($query_params);
771
+
772
+				$table_data[ $model_name ] = array();
773
+				foreach ($model_objects as $model_object) {
774
+					$model_data_array = array();
775
+					$fields = $model->field_settings();
776
+					foreach ($fields as $field) {
777
+						$column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
778
+						if ($field instanceof EE_Datetime_Field) {
779
+							// $field->set_date_format('Y-m-d');
780
+							// $field->set_time_format('H:i:s');
781
+							$model_data_array[ $column_name ] = $model_object->get_datetime(
782
+								$field->get_name(),
783
+								'Y-m-d',
784
+								'H:i:s'
785
+							);
786
+						} else {
787
+							$model_data_array[ $column_name ] = $model_object->get($field->get_name());
788
+						}
789
+					}
790
+					$table_data[ $model_name ][] = $model_data_array;
791
+				}
792
+			}
793
+		}
794
+		return $table_data;
795
+	}
796 796
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Message.class.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
     {
52 52
         $has_object = parent::_check_for_object($props_n_values, __CLASS__);
53 53
         // if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
-        if (! $has_object) {
54
+        if ( ! $has_object) {
55 55
             EE_Registry::instance()->load_helper('URL');
56 56
             $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57 57
         }
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     {
220 220
         $label_type = $plural ? 'plural' : 'singular';
221 221
         $messenger = $this->messenger_object();
222
-        return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
222
+        return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
223 223
     }
224 224
 
225 225
 
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
                 $this->messenger(),
337 337
                 $this->message_type()
338 338
             );
339
-            if (! $valid && $throw_exceptions) {
339
+            if ( ! $valid && $throw_exceptions) {
340 340
                 throw new EE_Error(
341 341
                     sprintf(
342 342
                         __(
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
         $label_type = $plural ? 'plural' : 'singular';
367 367
         $message_type = $this->message_type_object();
368 368
         return $message_type instanceof EE_message_type
369
-            ? $message_type->label[ $label_type ]
369
+            ? $message_type->label[$label_type]
370 370
             : str_replace(
371 371
                 '_',
372 372
                 ' ',
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
         /** @type EE_Message_Resource_Manager $message_resource_manager */
398 398
         $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399 399
         $contexts = $message_resource_manager->get_all_contexts();
400
-        return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
400
+        return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
401 401
     }
402 402
 
403 403
 
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
      */
453 453
     public function recipient_object()
454 454
     {
455
-        if (! $this->recipient_type() || ! $this->recipient_ID()) {
455
+        if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
456 456
             return null;
457 457
         }
458 458
 
@@ -736,13 +736,13 @@  discard block
 block discarded – undo
736 736
         /**
737 737
          * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738 738
          */
739
-        if (! empty($this->template_pack)) {
739
+        if ( ! empty($this->template_pack)) {
740 740
             return $this->template_pack;
741 741
         }
742 742
         /** @type EE_Message_Template_Group $grp */
743 743
         $grp = $this->get_first_related('Message_Template_Group');
744 744
         // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
-        if (! $grp instanceof EE_Message_Template_Group) {
745
+        if ( ! $grp instanceof EE_Message_Template_Group) {
746 746
             $grp = EEM_Message_Template_Group::instance()->get_one(
747 747
                 array(
748 748
                     array(
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
         /**
769 769
          * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770 770
          */
771
-        if (! empty($this->template_variation)) {
771
+        if ( ! empty($this->template_variation)) {
772 772
             return $this->template_variation;
773 773
         }
774 774
 
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
         $grp = $this->get_first_related('Message_Template_Group');
777 777
 
778 778
         // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
-        if (! $grp instanceof EE_Message_Template_Group) {
779
+        if ( ! $grp instanceof EE_Message_Template_Group) {
780 780
             $grp = EEM_Message_Template_Group::instance()->get_one(
781 781
                 array(
782 782
                     array(
Please login to merge, or discard this patch.
Indentation   +867 added lines, -867 removed lines patch added patch discarded remove patch
@@ -10,875 +10,875 @@
 block discarded – undo
10 10
 class EE_Message extends EE_Base_Class implements EEI_Admin_Links
11 11
 {
12 12
 
13
-    /**
14
-     * @deprecated 4.9.0  Added for backward compat with add-on's
15
-     * @type null
16
-     */
17
-    public $template_pack;
18
-
19
-    /**
20
-     * @deprecated 4.9.0 Added for backward compat with add-on's
21
-     * @type null
22
-     */
23
-    public $template_variation;
24
-
25
-    /**
26
-     * @deprecated 4.9.0 Added for backward compat with add-on's
27
-     * @type string
28
-     */
29
-    public $content = '';
30
-
31
-
32
-    /**
33
-     * @type EE_messenger $_messenger
34
-     */
35
-    protected $_messenger = null;
36
-
37
-    /**
38
-     * @type EE_message_type $_message_type
39
-     */
40
-    protected $_message_type = null;
41
-
42
-
43
-    /**
44
-     * @param array  $props_n_values
45
-     * @param string $timezone
46
-     * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
47
-     *                             format.
48
-     * @return EE_Message
49
-     */
50
-    public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
53
-        // if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
-        if (! $has_object) {
55
-            EE_Registry::instance()->load_helper('URL');
56
-            $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57
-        }
58
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
59
-    }
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values
64
-     * @param string $timezone
65
-     * @return EE_Message
66
-     */
67
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
68
-    {
69
-        return new self($props_n_values, true, $timezone);
70
-    }
71
-
72
-
73
-    /**
74
-     * Gets MSG_token
75
-     *
76
-     * @return int
77
-     */
78
-    public function MSG_token()
79
-    {
80
-        return $this->get('MSG_token');
81
-    }
82
-
83
-
84
-    /**
85
-     * Sets MSG_token
86
-     *
87
-     * @param int $MSG_token
88
-     */
89
-    public function set_MSG_token($MSG_token)
90
-    {
91
-        $this->set('MSG_token', $MSG_token);
92
-    }
93
-
94
-
95
-    /**
96
-     * Gets GRP_ID
97
-     *
98
-     * @return int
99
-     */
100
-    public function GRP_ID()
101
-    {
102
-        return $this->get('GRP_ID');
103
-    }
104
-
105
-
106
-    /**
107
-     * Sets GRP_ID
108
-     *
109
-     * @param int $GRP_ID
110
-     */
111
-    public function set_GRP_ID($GRP_ID)
112
-    {
113
-        $this->set('GRP_ID', $GRP_ID);
114
-    }
115
-
116
-
117
-    /**
118
-     * Gets TXN_ID
119
-     *
120
-     * @return int
121
-     */
122
-    public function TXN_ID()
123
-    {
124
-        return $this->get('TXN_ID');
125
-    }
126
-
127
-
128
-    /**
129
-     * Sets TXN_ID
130
-     *
131
-     * @param int $TXN_ID
132
-     */
133
-    public function set_TXN_ID($TXN_ID)
134
-    {
135
-        $this->set('TXN_ID', $TXN_ID);
136
-    }
137
-
138
-
139
-    /**
140
-     * Gets messenger
141
-     *
142
-     * @return string
143
-     */
144
-    public function messenger()
145
-    {
146
-        return $this->get('MSG_messenger');
147
-    }
148
-
149
-
150
-    /**
151
-     * Sets messenger
152
-     *
153
-     * @param string $messenger
154
-     */
155
-    public function set_messenger($messenger)
156
-    {
157
-        $this->set('MSG_messenger', $messenger);
158
-    }
159
-
160
-
161
-    /**
162
-     * Returns corresponding messenger object for the set messenger on this message
163
-     *
164
-     * @return EE_messenger | null
165
-     */
166
-    public function messenger_object()
167
-    {
168
-        return $this->_messenger;
169
-    }
170
-
171
-
172
-    /**
173
-     * Sets messenger
174
-     *
175
-     * @param EE_messenger $messenger
176
-     */
177
-    public function set_messenger_object(EE_messenger $messenger)
178
-    {
179
-        $this->_messenger = $messenger;
180
-    }
181
-
182
-
183
-    /**
184
-     * validates messenger
185
-     *
186
-     * @param bool $throw_exceptions
187
-     * @return bool
188
-     * @throws \EE_Error
189
-     */
190
-    public function valid_messenger($throw_exceptions = false)
191
-    {
192
-        if ($this->_messenger instanceof EE_messenger) {
193
-            return true;
194
-        }
195
-        if ($throw_exceptions) {
196
-            throw new EE_Error(
197
-                sprintf(
198
-                    __(
199
-                        'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
200
-                        'event_espresso'
201
-                    ),
202
-                    $this->messenger()
203
-                )
204
-            );
205
-        }
206
-        return false;
207
-    }
208
-
209
-
210
-    /**
211
-     * This returns the set localized label for the messenger on this message.
212
-     * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
213
-     * with this message.
214
-     *
215
-     * @param   bool $plural whether to return the plural label or not.
216
-     * @return string
217
-     */
218
-    public function messenger_label($plural = false)
219
-    {
220
-        $label_type = $plural ? 'plural' : 'singular';
221
-        $messenger = $this->messenger_object();
222
-        return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
223
-    }
224
-
225
-
226
-    /**
227
-     * Gets message_type
228
-     *
229
-     * @return string
230
-     */
231
-    public function message_type()
232
-    {
233
-        return $this->get('MSG_message_type');
234
-    }
235
-
236
-
237
-    /**
238
-     * Sets message_type
239
-     *
240
-     * @param string $message_type
241
-     */
242
-    public function set_message_type($message_type)
243
-    {
244
-        $this->set('MSG_message_type', $message_type);
245
-    }
246
-
247
-
248
-    /**
249
-     * Returns the message type object for the set message type on this message
250
-     *
251
-     * @return EE_message_type | null
252
-     */
253
-    public function message_type_object()
254
-    {
255
-        return $this->_message_type;
256
-    }
257
-
258
-
259
-    /**
260
-     * Sets message_type
261
-     *
262
-     * @param EE_message_type $message_type
263
-     * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
264
-     *                                        the message type or not.
265
-     */
266
-    public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
267
-    {
268
-        $this->_message_type = $message_type;
269
-        if ($set_priority) {
270
-            $this->set_priority($this->_message_type->get_priority());
271
-        }
272
-    }
273
-
274
-
275
-    /**
276
-     * validates message_type
277
-     *
278
-     * @param bool $throw_exceptions
279
-     * @return bool
280
-     * @throws \EE_Error
281
-     */
282
-    public function valid_message_type($throw_exceptions = false)
283
-    {
284
-        if ($this->_message_type instanceof EE_message_type) {
285
-            return true;
286
-        }
287
-        if ($throw_exceptions) {
288
-            throw new EE_Error(
289
-                sprintf(
290
-                    __(
291
-                        'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
292
-                        'event_espresso'
293
-                    ),
294
-                    $this->message_type()
295
-                )
296
-            );
297
-        }
298
-        return false;
299
-    }
300
-
301
-
302
-    /**
303
-     * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
304
-     *
305
-     * @param bool $throw_exceptions
306
-     * @return bool
307
-     * @throws \EE_Error
308
-     */
309
-    public function is_valid($throw_exceptions = false)
310
-    {
311
-        if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
312
-            return true;
313
-        }
314
-        return false;
315
-    }
316
-
317
-
318
-    /**
319
-     * This validates whether the internal messenger and message type objects are valid for sending.
320
-     * Three checks are done:
321
-     * 1. There is a valid messenger object.
322
-     * 2. There is a valid message type object.
323
-     * 3. The message type object is active for the messenger.
324
-     *
325
-     * @throws EE_Error  But only if $throw_exceptions is set to true.
326
-     * @param bool $throw_exceptions
327
-     * @return bool
328
-     */
329
-    public function is_valid_for_sending_or_generation($throw_exceptions = false)
330
-    {
331
-        $valid = false;
332
-        if ($this->is_valid($throw_exceptions)) {
333
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
334
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
335
-            $valid = $message_resource_manager->is_message_type_active_for_messenger(
336
-                $this->messenger(),
337
-                $this->message_type()
338
-            );
339
-            if (! $valid && $throw_exceptions) {
340
-                throw new EE_Error(
341
-                    sprintf(
342
-                        __(
343
-                            'The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
344
-                            'event_espresso'
345
-                        ),
346
-                        $this->message_type(),
347
-                        $this->messenger()
348
-                    )
349
-                );
350
-            }
351
-        }
352
-        return $valid;
353
-    }
354
-
355
-
356
-    /**
357
-     * This returns the set localized label for the message type on this message.
358
-     * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
359
-     * with this message.
360
-     *
361
-     * @param   bool $plural whether to return the plural label or not.
362
-     * @return string
363
-     */
364
-    public function message_type_label($plural = false)
365
-    {
366
-        $label_type = $plural ? 'plural' : 'singular';
367
-        $message_type = $this->message_type_object();
368
-        return $message_type instanceof EE_message_type
369
-            ? $message_type->label[ $label_type ]
370
-            : str_replace(
371
-                '_',
372
-                ' ',
373
-                $this->message_type()
374
-            );
375
-    }
376
-
377
-
378
-    /**
379
-     * Gets context
380
-     *
381
-     * @return string
382
-     */
383
-    public function context()
384
-    {
385
-        return $this->get('MSG_context');
386
-    }
387
-
388
-
389
-    /**
390
-     * This returns the corresponding localized label for the given context slug, if possible from installed message
391
-     * types. Otherwise, this will just return the set context slug on this object.
392
-     *
393
-     * @return string
394
-     */
395
-    public function context_label()
396
-    {
397
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
398
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399
-        $contexts = $message_resource_manager->get_all_contexts();
400
-        return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
401
-    }
402
-
403
-
404
-    /**
405
-     * Sets context
406
-     *
407
-     * @param string $context
408
-     */
409
-    public function set_context($context)
410
-    {
411
-        $this->set('MSG_context', $context);
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets recipient_ID
417
-     *
418
-     * @return int
419
-     */
420
-    public function recipient_ID()
421
-    {
422
-        return $this->get('MSG_recipient_ID');
423
-    }
424
-
425
-
426
-    /**
427
-     * Sets recipient_ID
428
-     *
429
-     * @param string $recipient_ID
430
-     */
431
-    public function set_recipient_ID($recipient_ID)
432
-    {
433
-        $this->set('MSG_recipient_ID', $recipient_ID);
434
-    }
435
-
436
-
437
-    /**
438
-     * Gets recipient_type
439
-     *
440
-     * @return string
441
-     */
442
-    public function recipient_type()
443
-    {
444
-        return $this->get('MSG_recipient_type');
445
-    }
446
-
447
-
448
-    /**
449
-     * Return the related object matching the recipient type and ID.
450
-     *
451
-     * @return EE_Base_Class | null
452
-     */
453
-    public function recipient_object()
454
-    {
455
-        if (! $this->recipient_type() || ! $this->recipient_ID()) {
456
-            return null;
457
-        }
458
-
459
-        return $this->get_first_related($this->recipient_type());
460
-    }
461
-
462
-
463
-    /**
464
-     * Sets recipient_type
465
-     *
466
-     * @param string $recipient_type
467
-     */
468
-    public function set_recipient_type($recipient_type)
469
-    {
470
-        $this->set('MSG_recipient_type', $recipient_type);
471
-    }
472
-
473
-
474
-    /**
475
-     * Gets content
476
-     *
477
-     * @return string
478
-     */
479
-    public function content()
480
-    {
481
-        return $this->get('MSG_content');
482
-    }
483
-
484
-
485
-    /**
486
-     * Sets content
487
-     *
488
-     * @param string $content
489
-     */
490
-    public function set_content($content)
491
-    {
492
-        $this->set('MSG_content', $content);
493
-    }
494
-
495
-
496
-    /**
497
-     * Gets subject
498
-     *
499
-     * @return string
500
-     */
501
-    public function subject()
502
-    {
503
-        return $this->get('MSG_subject');
504
-    }
505
-
506
-
507
-    /**
508
-     * Sets subject
509
-     *
510
-     * @param string $subject
511
-     */
512
-    public function set_subject($subject)
513
-    {
514
-        $this->set('MSG_subject', $subject);
515
-    }
516
-
517
-
518
-    /**
519
-     * Gets to
520
-     *
521
-     * @return string
522
-     */
523
-    public function to()
524
-    {
525
-        $to = $this->get('MSG_to');
526
-        return empty($to) ? __('No recipient', 'event_espresso') : $to;
527
-    }
528
-
529
-
530
-    /**
531
-     * Sets to
532
-     *
533
-     * @param string $to
534
-     */
535
-    public function set_to($to)
536
-    {
537
-        $this->set('MSG_to', $to);
538
-    }
539
-
540
-
541
-    /**
542
-     * Gets from
543
-     *
544
-     * @return string
545
-     */
546
-    public function from()
547
-    {
548
-        return $this->get('MSG_from');
549
-    }
550
-
551
-
552
-    /**
553
-     * Sets from
554
-     *
555
-     * @param string $from
556
-     */
557
-    public function set_from($from)
558
-    {
559
-        $this->set('MSG_from', $from);
560
-    }
561
-
562
-
563
-    /**
564
-     * Gets priority
565
-     *
566
-     * @return int
567
-     */
568
-    public function priority()
569
-    {
570
-        return $this->get('MSG_priority');
571
-    }
572
-
573
-
574
-    /**
575
-     * Sets priority
576
-     * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
577
-     * this method calls the send_now method to verify that.
578
-     *
579
-     * @param int $priority
580
-     */
581
-    public function set_priority($priority)
582
-    {
583
-        $priority = $this->send_now() ? EEM_Message::priority_high : $priority;
584
-        parent::set('MSG_priority', $priority);
585
-    }
586
-
587
-
588
-    /**
589
-     * Overrides parent::set method so we can capture any sets for priority.
590
-     *
591
-     * @param string $field_name
592
-     * @param mixed  $field_value
593
-     * @param bool   $use_default
594
-     * @throws EE_Error
595
-     * @see parent::set() for phpdocs
596
-     */
597
-    public function set($field_name, $field_value, bool $use_default = false)
598
-    {
599
-        if ($field_name === 'MSG_priority') {
600
-            $this->set_priority($field_value);
601
-        }
602
-        parent::set($field_name, $field_value, $use_default);
603
-    }
604
-
605
-
606
-    /**
607
-     * @return bool
608
-     * @throws \EE_Error
609
-     */
610
-    public function send_now()
611
-    {
612
-        $send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high
613
-            : $this->priority();
614
-        return $send_now === EEM_Message::priority_high ? true : false;
615
-    }
616
-
617
-
618
-    /**
619
-     * Gets STS_ID
620
-     *
621
-     * @return string
622
-     */
623
-    public function STS_ID()
624
-    {
625
-        return $this->get('STS_ID');
626
-    }
627
-
628
-
629
-    /**
630
-     * Sets STS_ID
631
-     *
632
-     * @param string $STS_ID
633
-     */
634
-    public function set_STS_ID($STS_ID)
635
-    {
636
-        $this->set('STS_ID', $STS_ID);
637
-    }
638
-
639
-
640
-    /**
641
-     * Gets created
642
-     *
643
-     * @return string
644
-     */
645
-    public function created()
646
-    {
647
-        return $this->get('MSG_created');
648
-    }
649
-
650
-
651
-    /**
652
-     * Sets created
653
-     *
654
-     * @param string $created
655
-     */
656
-    public function set_created($created)
657
-    {
658
-        $this->set('MSG_created', $created);
659
-    }
660
-
661
-
662
-    /**
663
-     * Gets modified
664
-     *
665
-     * @return string
666
-     */
667
-    public function modified()
668
-    {
669
-        return $this->get('MSG_modified');
670
-    }
671
-
672
-
673
-    /**
674
-     * Sets modified
675
-     *
676
-     * @param string $modified
677
-     */
678
-    public function set_modified($modified)
679
-    {
680
-        $this->set('MSG_modified', $modified);
681
-    }
682
-
683
-
684
-    /**
685
-     * Sets generation data for this message.
686
-     *
687
-     * @param mixed $data
688
-     */
689
-    public function set_generation_data($data)
690
-    {
691
-        $this->set_field_or_extra_meta('MSG_generation_data', $data);
692
-    }
693
-
694
-
695
-    /**
696
-     * Returns any set generation data for this message.
697
-     *
698
-     * @return mixed|null
699
-     */
700
-    public function get_generation_data()
701
-    {
702
-        return $this->get_field_or_extra_meta('MSG_generation_data');
703
-    }
704
-
705
-
706
-    /**
707
-     * Gets any error message.
708
-     *
709
-     * @return mixed|null
710
-     */
711
-    public function error_message()
712
-    {
713
-        return $this->get_field_or_extra_meta('MSG_error');
714
-    }
715
-
716
-
717
-    /**
718
-     * Sets an error message.
719
-     *
720
-     * @param $message
721
-     * @return bool|int
722
-     */
723
-    public function set_error_message($message)
724
-    {
725
-        return $this->set_field_or_extra_meta('MSG_error', $message);
726
-    }
727
-
728
-
729
-    /**
730
-     * This retrieves the associated template pack with this message.
731
-     *
732
-     * @return EE_Messages_Template_Pack | null
733
-     */
734
-    public function get_template_pack()
735
-    {
736
-        /**
737
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738
-         */
739
-        if (! empty($this->template_pack)) {
740
-            return $this->template_pack;
741
-        }
742
-        /** @type EE_Message_Template_Group $grp */
743
-        $grp = $this->get_first_related('Message_Template_Group');
744
-        // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
-        if (! $grp instanceof EE_Message_Template_Group) {
746
-            $grp = EEM_Message_Template_Group::instance()->get_one(
747
-                array(
748
-                    array(
749
-                        'MTP_messenger'    => $this->messenger(),
750
-                        'MTP_message_type' => $this->message_type(),
751
-                        'MTP_is_global'    => true,
752
-                    ),
753
-                )
754
-            );
755
-        }
756
-
757
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
758
-    }
759
-
760
-
761
-    /**
762
-     * Retrieves the variation used for generating this message.
763
-     *
764
-     * @return string
765
-     */
766
-    public function get_template_pack_variation()
767
-    {
768
-        /**
769
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770
-         */
771
-        if (! empty($this->template_variation)) {
772
-            return $this->template_variation;
773
-        }
774
-
775
-        /** @type EE_Message_Template_Group $grp */
776
-        $grp = $this->get_first_related('Message_Template_Group');
777
-
778
-        // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
-        if (! $grp instanceof EE_Message_Template_Group) {
780
-            $grp = EEM_Message_Template_Group::instance()->get_one(
781
-                array(
782
-                    array(
783
-                        'MTP_messenger'    => $this->messenger(),
784
-                        'MTP_message_type' => $this->message_type(),
785
-                        'MTP_is_global'    => true,
786
-                    ),
787
-                )
788
-            );
789
-        }
790
-
791
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
792
-    }
793
-
794
-    /**
795
-     * Return the link to the admin details for the object.
796
-     *
797
-     * @return string
798
-     */
799
-    public function get_admin_details_link()
800
-    {
801
-        EE_Registry::instance()->load_helper('URL');
802
-        EE_Registry::instance()->load_helper('MSG_Template');
803
-        switch ($this->STS_ID()) {
804
-            case EEM_Message::status_failed:
805
-            case EEM_Message::status_debug_only:
806
-                return EEH_MSG_Template::generate_error_display_trigger($this);
807
-                break;
808
-
809
-            case EEM_Message::status_sent:
810
-                return EEH_MSG_Template::generate_browser_trigger($this);
811
-                break;
812
-
813
-            default:
814
-                return '';
815
-        }
816
-    }
817
-
818
-    /**
819
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
820
-     *
821
-     * @return string
822
-     */
823
-    public function get_admin_edit_link()
824
-    {
825
-        return $this->get_admin_details_link();
826
-    }
827
-
828
-    /**
829
-     * Returns the link to a settings page for the object.
830
-     *
831
-     * @return string
832
-     */
833
-    public function get_admin_settings_link()
834
-    {
835
-        EE_Registry::instance()->load_helper('URL');
836
-        return EEH_URL::add_query_args_and_nonce(
837
-            array(
838
-                'page'   => 'espresso_messages',
839
-                'action' => 'settings',
840
-            ),
841
-            admin_url('admin.php')
842
-        );
843
-    }
844
-
845
-    /**
846
-     * Returns the link to the "overview" for the object (typically the "list table" view).
847
-     *
848
-     * @return string
849
-     */
850
-    public function get_admin_overview_link()
851
-    {
852
-        EE_Registry::instance()->load_helper('URL');
853
-        return EEH_URL::add_query_args_and_nonce(
854
-            array(
855
-                'page'   => 'espresso_messages',
856
-                'action' => 'default',
857
-            ),
858
-            admin_url('admin.php')
859
-        );
860
-    }
861
-
862
-
863
-    /**
864
-     * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
865
-     * it.
866
-     * Note this also SAVES the current message object to the db because it adds an error message to accompany the
867
-     * status.
868
-     *
869
-     */
870
-    public function set_messenger_is_executing()
871
-    {
872
-        $this->set_STS_ID(EEM_Message::status_messenger_executing);
873
-        $this->set_error_message(
874
-            esc_html__(
875
-                'A message with this status indicates that there was a problem that occurred while the message was being
13
+	/**
14
+	 * @deprecated 4.9.0  Added for backward compat with add-on's
15
+	 * @type null
16
+	 */
17
+	public $template_pack;
18
+
19
+	/**
20
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
21
+	 * @type null
22
+	 */
23
+	public $template_variation;
24
+
25
+	/**
26
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
27
+	 * @type string
28
+	 */
29
+	public $content = '';
30
+
31
+
32
+	/**
33
+	 * @type EE_messenger $_messenger
34
+	 */
35
+	protected $_messenger = null;
36
+
37
+	/**
38
+	 * @type EE_message_type $_message_type
39
+	 */
40
+	protected $_message_type = null;
41
+
42
+
43
+	/**
44
+	 * @param array  $props_n_values
45
+	 * @param string $timezone
46
+	 * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
47
+	 *                             format.
48
+	 * @return EE_Message
49
+	 */
50
+	public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
53
+		// if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
+		if (! $has_object) {
55
+			EE_Registry::instance()->load_helper('URL');
56
+			$props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57
+		}
58
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
59
+	}
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values
64
+	 * @param string $timezone
65
+	 * @return EE_Message
66
+	 */
67
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
68
+	{
69
+		return new self($props_n_values, true, $timezone);
70
+	}
71
+
72
+
73
+	/**
74
+	 * Gets MSG_token
75
+	 *
76
+	 * @return int
77
+	 */
78
+	public function MSG_token()
79
+	{
80
+		return $this->get('MSG_token');
81
+	}
82
+
83
+
84
+	/**
85
+	 * Sets MSG_token
86
+	 *
87
+	 * @param int $MSG_token
88
+	 */
89
+	public function set_MSG_token($MSG_token)
90
+	{
91
+		$this->set('MSG_token', $MSG_token);
92
+	}
93
+
94
+
95
+	/**
96
+	 * Gets GRP_ID
97
+	 *
98
+	 * @return int
99
+	 */
100
+	public function GRP_ID()
101
+	{
102
+		return $this->get('GRP_ID');
103
+	}
104
+
105
+
106
+	/**
107
+	 * Sets GRP_ID
108
+	 *
109
+	 * @param int $GRP_ID
110
+	 */
111
+	public function set_GRP_ID($GRP_ID)
112
+	{
113
+		$this->set('GRP_ID', $GRP_ID);
114
+	}
115
+
116
+
117
+	/**
118
+	 * Gets TXN_ID
119
+	 *
120
+	 * @return int
121
+	 */
122
+	public function TXN_ID()
123
+	{
124
+		return $this->get('TXN_ID');
125
+	}
126
+
127
+
128
+	/**
129
+	 * Sets TXN_ID
130
+	 *
131
+	 * @param int $TXN_ID
132
+	 */
133
+	public function set_TXN_ID($TXN_ID)
134
+	{
135
+		$this->set('TXN_ID', $TXN_ID);
136
+	}
137
+
138
+
139
+	/**
140
+	 * Gets messenger
141
+	 *
142
+	 * @return string
143
+	 */
144
+	public function messenger()
145
+	{
146
+		return $this->get('MSG_messenger');
147
+	}
148
+
149
+
150
+	/**
151
+	 * Sets messenger
152
+	 *
153
+	 * @param string $messenger
154
+	 */
155
+	public function set_messenger($messenger)
156
+	{
157
+		$this->set('MSG_messenger', $messenger);
158
+	}
159
+
160
+
161
+	/**
162
+	 * Returns corresponding messenger object for the set messenger on this message
163
+	 *
164
+	 * @return EE_messenger | null
165
+	 */
166
+	public function messenger_object()
167
+	{
168
+		return $this->_messenger;
169
+	}
170
+
171
+
172
+	/**
173
+	 * Sets messenger
174
+	 *
175
+	 * @param EE_messenger $messenger
176
+	 */
177
+	public function set_messenger_object(EE_messenger $messenger)
178
+	{
179
+		$this->_messenger = $messenger;
180
+	}
181
+
182
+
183
+	/**
184
+	 * validates messenger
185
+	 *
186
+	 * @param bool $throw_exceptions
187
+	 * @return bool
188
+	 * @throws \EE_Error
189
+	 */
190
+	public function valid_messenger($throw_exceptions = false)
191
+	{
192
+		if ($this->_messenger instanceof EE_messenger) {
193
+			return true;
194
+		}
195
+		if ($throw_exceptions) {
196
+			throw new EE_Error(
197
+				sprintf(
198
+					__(
199
+						'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
200
+						'event_espresso'
201
+					),
202
+					$this->messenger()
203
+				)
204
+			);
205
+		}
206
+		return false;
207
+	}
208
+
209
+
210
+	/**
211
+	 * This returns the set localized label for the messenger on this message.
212
+	 * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
213
+	 * with this message.
214
+	 *
215
+	 * @param   bool $plural whether to return the plural label or not.
216
+	 * @return string
217
+	 */
218
+	public function messenger_label($plural = false)
219
+	{
220
+		$label_type = $plural ? 'plural' : 'singular';
221
+		$messenger = $this->messenger_object();
222
+		return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
223
+	}
224
+
225
+
226
+	/**
227
+	 * Gets message_type
228
+	 *
229
+	 * @return string
230
+	 */
231
+	public function message_type()
232
+	{
233
+		return $this->get('MSG_message_type');
234
+	}
235
+
236
+
237
+	/**
238
+	 * Sets message_type
239
+	 *
240
+	 * @param string $message_type
241
+	 */
242
+	public function set_message_type($message_type)
243
+	{
244
+		$this->set('MSG_message_type', $message_type);
245
+	}
246
+
247
+
248
+	/**
249
+	 * Returns the message type object for the set message type on this message
250
+	 *
251
+	 * @return EE_message_type | null
252
+	 */
253
+	public function message_type_object()
254
+	{
255
+		return $this->_message_type;
256
+	}
257
+
258
+
259
+	/**
260
+	 * Sets message_type
261
+	 *
262
+	 * @param EE_message_type $message_type
263
+	 * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
264
+	 *                                        the message type or not.
265
+	 */
266
+	public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
267
+	{
268
+		$this->_message_type = $message_type;
269
+		if ($set_priority) {
270
+			$this->set_priority($this->_message_type->get_priority());
271
+		}
272
+	}
273
+
274
+
275
+	/**
276
+	 * validates message_type
277
+	 *
278
+	 * @param bool $throw_exceptions
279
+	 * @return bool
280
+	 * @throws \EE_Error
281
+	 */
282
+	public function valid_message_type($throw_exceptions = false)
283
+	{
284
+		if ($this->_message_type instanceof EE_message_type) {
285
+			return true;
286
+		}
287
+		if ($throw_exceptions) {
288
+			throw new EE_Error(
289
+				sprintf(
290
+					__(
291
+						'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
292
+						'event_espresso'
293
+					),
294
+					$this->message_type()
295
+				)
296
+			);
297
+		}
298
+		return false;
299
+	}
300
+
301
+
302
+	/**
303
+	 * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
304
+	 *
305
+	 * @param bool $throw_exceptions
306
+	 * @return bool
307
+	 * @throws \EE_Error
308
+	 */
309
+	public function is_valid($throw_exceptions = false)
310
+	{
311
+		if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
312
+			return true;
313
+		}
314
+		return false;
315
+	}
316
+
317
+
318
+	/**
319
+	 * This validates whether the internal messenger and message type objects are valid for sending.
320
+	 * Three checks are done:
321
+	 * 1. There is a valid messenger object.
322
+	 * 2. There is a valid message type object.
323
+	 * 3. The message type object is active for the messenger.
324
+	 *
325
+	 * @throws EE_Error  But only if $throw_exceptions is set to true.
326
+	 * @param bool $throw_exceptions
327
+	 * @return bool
328
+	 */
329
+	public function is_valid_for_sending_or_generation($throw_exceptions = false)
330
+	{
331
+		$valid = false;
332
+		if ($this->is_valid($throw_exceptions)) {
333
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
334
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
335
+			$valid = $message_resource_manager->is_message_type_active_for_messenger(
336
+				$this->messenger(),
337
+				$this->message_type()
338
+			);
339
+			if (! $valid && $throw_exceptions) {
340
+				throw new EE_Error(
341
+					sprintf(
342
+						__(
343
+							'The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
344
+							'event_espresso'
345
+						),
346
+						$this->message_type(),
347
+						$this->messenger()
348
+					)
349
+				);
350
+			}
351
+		}
352
+		return $valid;
353
+	}
354
+
355
+
356
+	/**
357
+	 * This returns the set localized label for the message type on this message.
358
+	 * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
359
+	 * with this message.
360
+	 *
361
+	 * @param   bool $plural whether to return the plural label or not.
362
+	 * @return string
363
+	 */
364
+	public function message_type_label($plural = false)
365
+	{
366
+		$label_type = $plural ? 'plural' : 'singular';
367
+		$message_type = $this->message_type_object();
368
+		return $message_type instanceof EE_message_type
369
+			? $message_type->label[ $label_type ]
370
+			: str_replace(
371
+				'_',
372
+				' ',
373
+				$this->message_type()
374
+			);
375
+	}
376
+
377
+
378
+	/**
379
+	 * Gets context
380
+	 *
381
+	 * @return string
382
+	 */
383
+	public function context()
384
+	{
385
+		return $this->get('MSG_context');
386
+	}
387
+
388
+
389
+	/**
390
+	 * This returns the corresponding localized label for the given context slug, if possible from installed message
391
+	 * types. Otherwise, this will just return the set context slug on this object.
392
+	 *
393
+	 * @return string
394
+	 */
395
+	public function context_label()
396
+	{
397
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
398
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399
+		$contexts = $message_resource_manager->get_all_contexts();
400
+		return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
401
+	}
402
+
403
+
404
+	/**
405
+	 * Sets context
406
+	 *
407
+	 * @param string $context
408
+	 */
409
+	public function set_context($context)
410
+	{
411
+		$this->set('MSG_context', $context);
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets recipient_ID
417
+	 *
418
+	 * @return int
419
+	 */
420
+	public function recipient_ID()
421
+	{
422
+		return $this->get('MSG_recipient_ID');
423
+	}
424
+
425
+
426
+	/**
427
+	 * Sets recipient_ID
428
+	 *
429
+	 * @param string $recipient_ID
430
+	 */
431
+	public function set_recipient_ID($recipient_ID)
432
+	{
433
+		$this->set('MSG_recipient_ID', $recipient_ID);
434
+	}
435
+
436
+
437
+	/**
438
+	 * Gets recipient_type
439
+	 *
440
+	 * @return string
441
+	 */
442
+	public function recipient_type()
443
+	{
444
+		return $this->get('MSG_recipient_type');
445
+	}
446
+
447
+
448
+	/**
449
+	 * Return the related object matching the recipient type and ID.
450
+	 *
451
+	 * @return EE_Base_Class | null
452
+	 */
453
+	public function recipient_object()
454
+	{
455
+		if (! $this->recipient_type() || ! $this->recipient_ID()) {
456
+			return null;
457
+		}
458
+
459
+		return $this->get_first_related($this->recipient_type());
460
+	}
461
+
462
+
463
+	/**
464
+	 * Sets recipient_type
465
+	 *
466
+	 * @param string $recipient_type
467
+	 */
468
+	public function set_recipient_type($recipient_type)
469
+	{
470
+		$this->set('MSG_recipient_type', $recipient_type);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Gets content
476
+	 *
477
+	 * @return string
478
+	 */
479
+	public function content()
480
+	{
481
+		return $this->get('MSG_content');
482
+	}
483
+
484
+
485
+	/**
486
+	 * Sets content
487
+	 *
488
+	 * @param string $content
489
+	 */
490
+	public function set_content($content)
491
+	{
492
+		$this->set('MSG_content', $content);
493
+	}
494
+
495
+
496
+	/**
497
+	 * Gets subject
498
+	 *
499
+	 * @return string
500
+	 */
501
+	public function subject()
502
+	{
503
+		return $this->get('MSG_subject');
504
+	}
505
+
506
+
507
+	/**
508
+	 * Sets subject
509
+	 *
510
+	 * @param string $subject
511
+	 */
512
+	public function set_subject($subject)
513
+	{
514
+		$this->set('MSG_subject', $subject);
515
+	}
516
+
517
+
518
+	/**
519
+	 * Gets to
520
+	 *
521
+	 * @return string
522
+	 */
523
+	public function to()
524
+	{
525
+		$to = $this->get('MSG_to');
526
+		return empty($to) ? __('No recipient', 'event_espresso') : $to;
527
+	}
528
+
529
+
530
+	/**
531
+	 * Sets to
532
+	 *
533
+	 * @param string $to
534
+	 */
535
+	public function set_to($to)
536
+	{
537
+		$this->set('MSG_to', $to);
538
+	}
539
+
540
+
541
+	/**
542
+	 * Gets from
543
+	 *
544
+	 * @return string
545
+	 */
546
+	public function from()
547
+	{
548
+		return $this->get('MSG_from');
549
+	}
550
+
551
+
552
+	/**
553
+	 * Sets from
554
+	 *
555
+	 * @param string $from
556
+	 */
557
+	public function set_from($from)
558
+	{
559
+		$this->set('MSG_from', $from);
560
+	}
561
+
562
+
563
+	/**
564
+	 * Gets priority
565
+	 *
566
+	 * @return int
567
+	 */
568
+	public function priority()
569
+	{
570
+		return $this->get('MSG_priority');
571
+	}
572
+
573
+
574
+	/**
575
+	 * Sets priority
576
+	 * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
577
+	 * this method calls the send_now method to verify that.
578
+	 *
579
+	 * @param int $priority
580
+	 */
581
+	public function set_priority($priority)
582
+	{
583
+		$priority = $this->send_now() ? EEM_Message::priority_high : $priority;
584
+		parent::set('MSG_priority', $priority);
585
+	}
586
+
587
+
588
+	/**
589
+	 * Overrides parent::set method so we can capture any sets for priority.
590
+	 *
591
+	 * @param string $field_name
592
+	 * @param mixed  $field_value
593
+	 * @param bool   $use_default
594
+	 * @throws EE_Error
595
+	 * @see parent::set() for phpdocs
596
+	 */
597
+	public function set($field_name, $field_value, bool $use_default = false)
598
+	{
599
+		if ($field_name === 'MSG_priority') {
600
+			$this->set_priority($field_value);
601
+		}
602
+		parent::set($field_name, $field_value, $use_default);
603
+	}
604
+
605
+
606
+	/**
607
+	 * @return bool
608
+	 * @throws \EE_Error
609
+	 */
610
+	public function send_now()
611
+	{
612
+		$send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high
613
+			: $this->priority();
614
+		return $send_now === EEM_Message::priority_high ? true : false;
615
+	}
616
+
617
+
618
+	/**
619
+	 * Gets STS_ID
620
+	 *
621
+	 * @return string
622
+	 */
623
+	public function STS_ID()
624
+	{
625
+		return $this->get('STS_ID');
626
+	}
627
+
628
+
629
+	/**
630
+	 * Sets STS_ID
631
+	 *
632
+	 * @param string $STS_ID
633
+	 */
634
+	public function set_STS_ID($STS_ID)
635
+	{
636
+		$this->set('STS_ID', $STS_ID);
637
+	}
638
+
639
+
640
+	/**
641
+	 * Gets created
642
+	 *
643
+	 * @return string
644
+	 */
645
+	public function created()
646
+	{
647
+		return $this->get('MSG_created');
648
+	}
649
+
650
+
651
+	/**
652
+	 * Sets created
653
+	 *
654
+	 * @param string $created
655
+	 */
656
+	public function set_created($created)
657
+	{
658
+		$this->set('MSG_created', $created);
659
+	}
660
+
661
+
662
+	/**
663
+	 * Gets modified
664
+	 *
665
+	 * @return string
666
+	 */
667
+	public function modified()
668
+	{
669
+		return $this->get('MSG_modified');
670
+	}
671
+
672
+
673
+	/**
674
+	 * Sets modified
675
+	 *
676
+	 * @param string $modified
677
+	 */
678
+	public function set_modified($modified)
679
+	{
680
+		$this->set('MSG_modified', $modified);
681
+	}
682
+
683
+
684
+	/**
685
+	 * Sets generation data for this message.
686
+	 *
687
+	 * @param mixed $data
688
+	 */
689
+	public function set_generation_data($data)
690
+	{
691
+		$this->set_field_or_extra_meta('MSG_generation_data', $data);
692
+	}
693
+
694
+
695
+	/**
696
+	 * Returns any set generation data for this message.
697
+	 *
698
+	 * @return mixed|null
699
+	 */
700
+	public function get_generation_data()
701
+	{
702
+		return $this->get_field_or_extra_meta('MSG_generation_data');
703
+	}
704
+
705
+
706
+	/**
707
+	 * Gets any error message.
708
+	 *
709
+	 * @return mixed|null
710
+	 */
711
+	public function error_message()
712
+	{
713
+		return $this->get_field_or_extra_meta('MSG_error');
714
+	}
715
+
716
+
717
+	/**
718
+	 * Sets an error message.
719
+	 *
720
+	 * @param $message
721
+	 * @return bool|int
722
+	 */
723
+	public function set_error_message($message)
724
+	{
725
+		return $this->set_field_or_extra_meta('MSG_error', $message);
726
+	}
727
+
728
+
729
+	/**
730
+	 * This retrieves the associated template pack with this message.
731
+	 *
732
+	 * @return EE_Messages_Template_Pack | null
733
+	 */
734
+	public function get_template_pack()
735
+	{
736
+		/**
737
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738
+		 */
739
+		if (! empty($this->template_pack)) {
740
+			return $this->template_pack;
741
+		}
742
+		/** @type EE_Message_Template_Group $grp */
743
+		$grp = $this->get_first_related('Message_Template_Group');
744
+		// if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
+		if (! $grp instanceof EE_Message_Template_Group) {
746
+			$grp = EEM_Message_Template_Group::instance()->get_one(
747
+				array(
748
+					array(
749
+						'MTP_messenger'    => $this->messenger(),
750
+						'MTP_message_type' => $this->message_type(),
751
+						'MTP_is_global'    => true,
752
+					),
753
+				)
754
+			);
755
+		}
756
+
757
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
758
+	}
759
+
760
+
761
+	/**
762
+	 * Retrieves the variation used for generating this message.
763
+	 *
764
+	 * @return string
765
+	 */
766
+	public function get_template_pack_variation()
767
+	{
768
+		/**
769
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770
+		 */
771
+		if (! empty($this->template_variation)) {
772
+			return $this->template_variation;
773
+		}
774
+
775
+		/** @type EE_Message_Template_Group $grp */
776
+		$grp = $this->get_first_related('Message_Template_Group');
777
+
778
+		// if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
+		if (! $grp instanceof EE_Message_Template_Group) {
780
+			$grp = EEM_Message_Template_Group::instance()->get_one(
781
+				array(
782
+					array(
783
+						'MTP_messenger'    => $this->messenger(),
784
+						'MTP_message_type' => $this->message_type(),
785
+						'MTP_is_global'    => true,
786
+					),
787
+				)
788
+			);
789
+		}
790
+
791
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
792
+	}
793
+
794
+	/**
795
+	 * Return the link to the admin details for the object.
796
+	 *
797
+	 * @return string
798
+	 */
799
+	public function get_admin_details_link()
800
+	{
801
+		EE_Registry::instance()->load_helper('URL');
802
+		EE_Registry::instance()->load_helper('MSG_Template');
803
+		switch ($this->STS_ID()) {
804
+			case EEM_Message::status_failed:
805
+			case EEM_Message::status_debug_only:
806
+				return EEH_MSG_Template::generate_error_display_trigger($this);
807
+				break;
808
+
809
+			case EEM_Message::status_sent:
810
+				return EEH_MSG_Template::generate_browser_trigger($this);
811
+				break;
812
+
813
+			default:
814
+				return '';
815
+		}
816
+	}
817
+
818
+	/**
819
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
820
+	 *
821
+	 * @return string
822
+	 */
823
+	public function get_admin_edit_link()
824
+	{
825
+		return $this->get_admin_details_link();
826
+	}
827
+
828
+	/**
829
+	 * Returns the link to a settings page for the object.
830
+	 *
831
+	 * @return string
832
+	 */
833
+	public function get_admin_settings_link()
834
+	{
835
+		EE_Registry::instance()->load_helper('URL');
836
+		return EEH_URL::add_query_args_and_nonce(
837
+			array(
838
+				'page'   => 'espresso_messages',
839
+				'action' => 'settings',
840
+			),
841
+			admin_url('admin.php')
842
+		);
843
+	}
844
+
845
+	/**
846
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
847
+	 *
848
+	 * @return string
849
+	 */
850
+	public function get_admin_overview_link()
851
+	{
852
+		EE_Registry::instance()->load_helper('URL');
853
+		return EEH_URL::add_query_args_and_nonce(
854
+			array(
855
+				'page'   => 'espresso_messages',
856
+				'action' => 'default',
857
+			),
858
+			admin_url('admin.php')
859
+		);
860
+	}
861
+
862
+
863
+	/**
864
+	 * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
865
+	 * it.
866
+	 * Note this also SAVES the current message object to the db because it adds an error message to accompany the
867
+	 * status.
868
+	 *
869
+	 */
870
+	public function set_messenger_is_executing()
871
+	{
872
+		$this->set_STS_ID(EEM_Message::status_messenger_executing);
873
+		$this->set_error_message(
874
+			esc_html__(
875
+				'A message with this status indicates that there was a problem that occurred while the message was being
876 876
                 processed by the messenger.  It is still possible that the message was sent successfully, but at some
877 877
                 point during the processing there was a failure.  This usually is indicative of a timeout issue with PHP 
878 878
                 or memory limits being reached.  If you see this repeatedly you may want to consider upgrading the memory 
879 879
                 available to PHP on your server.',
880
-                'event_espresso'
881
-            )
882
-        );
883
-    }
880
+				'event_espresso'
881
+			)
882
+		);
883
+	}
884 884
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Transaction.class.php 2 patches
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
         $txn = $has_object
43 43
             ? $has_object
44 44
             : new self($props_n_values, false, $timezone, $date_formats);
45
-        if (! $has_object) {
45
+        if ( ! $has_object) {
46 46
             $txn->set_old_txn_status($txn->status_ID());
47 47
         }
48 48
         return $txn;
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
     public function lock()
75 75
     {
76 76
         // attempt to set lock, but if that fails...
77
-        if (! $this->add_extra_meta('lock', time(), true)) {
77
+        if ( ! $this->add_extra_meta('lock', time(), true)) {
78 78
             // then attempt to remove the lock in case it is expired
79 79
             if ($this->_remove_expired_lock()) {
80 80
                 // if removal was successful, then try setting lock again
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
     public function is_locked()
123 123
     {
124 124
         // if TXN is not locked, then return false immediately
125
-        if (! $this->_get_lock()) {
125
+        if ( ! $this->_get_lock()) {
126 126
             return false;
127 127
         }
128 128
         // if not, then let's try and remove the lock in case it's expired...
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
                 $icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
528 528
                 break;
529 529
         }
530
-        return $icon . $status[ $this->status_ID() ];
530
+        return $icon.$status[$this->status_ID()];
531 531
     }
532 532
 
533 533
 
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
     public function invoice_url($type = 'html')
632 632
     {
633 633
         $REG = $this->primary_registration();
634
-        if (! $REG instanceof EE_Registration) {
634
+        if ( ! $REG instanceof EE_Registration) {
635 635
             return '';
636 636
         }
637 637
         return $REG->invoice_url($type);
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
     public function receipt_url($type = 'html')
674 674
     {
675 675
         $REG = $this->primary_registration();
676
-        if (! $REG instanceof EE_Registration) {
676
+        if ( ! $REG instanceof EE_Registration) {
677 677
             return '';
678 678
         }
679 679
         return $REG->receipt_url($type);
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
     public function total_line_item($create_if_not_found = true)
819 819
     {
820 820
         $item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
821
-        if (! $item && $create_if_not_found) {
821
+        if ( ! $item && $create_if_not_found) {
822 822
             $item = EEH_Line_Item::create_total_line_item($this);
823 823
         }
824 824
         return $item;
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
     public function billing_info()
864 864
     {
865 865
         $payment_method = $this->payment_method();
866
-        if (! $payment_method) {
866
+        if ( ! $payment_method) {
867 867
             EE_Error::add_error(
868 868
                 __(
869 869
                     'Could not find billing info for transaction because no gateway has been used for it yet',
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
             return null;
877 877
         }
878 878
         $primary_reg = $this->primary_registration();
879
-        if (! $primary_reg) {
879
+        if ( ! $primary_reg) {
880 880
             EE_Error::add_error(
881 881
                 __(
882 882
                     'Cannot get billing info for gateway %s on transaction because no primary registration exists',
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
             return null;
890 890
         }
891 891
         $attendee = $primary_reg->attendee();
892
-        if (! $attendee) {
892
+        if ( ! $attendee) {
893 893
             EE_Error::add_error(
894 894
                 __(
895 895
                     'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
@@ -1025,7 +1025,7 @@  discard block
 block discarded – undo
1025 1025
     public function update_based_on_payments()
1026 1026
     {
1027 1027
         EE_Error::doing_it_wrong(
1028
-            __CLASS__ . '::' . __FUNCTION__,
1028
+            __CLASS__.'::'.__FUNCTION__,
1029 1029
             sprintf(
1030 1030
                 __('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1031 1031
                 'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
@@ -1085,13 +1085,13 @@  discard block
 block discarded – undo
1085 1085
     private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1086 1086
     {
1087 1087
         $reg_steps = $this->reg_steps();
1088
-        if (! is_array($reg_steps) || empty($reg_steps)) {
1088
+        if ( ! is_array($reg_steps) || empty($reg_steps)) {
1089 1089
             return false;
1090 1090
         }
1091 1091
         // loop thru reg steps array)
1092 1092
         foreach ($reg_steps as $slug => $reg_step_completed) {
1093 1093
             // if NOT checking ALL steps (only checking one step)
1094
-            if (! $check_all) {
1094
+            if ( ! $check_all) {
1095 1095
                 // and this is the one
1096 1096
                 if ($slug === $reg_step_slug) {
1097 1097
                     return $reg_step_completed;
@@ -1258,30 +1258,30 @@  discard block
 block discarded – undo
1258 1258
         // get reg steps array
1259 1259
         $txn_reg_steps = $this->reg_steps();
1260 1260
         // if reg step does NOT exist
1261
-        if (! isset($txn_reg_steps[ $reg_step_slug ])) {
1261
+        if ( ! isset($txn_reg_steps[$reg_step_slug])) {
1262 1262
             return false;
1263 1263
         }
1264 1264
         // if  we're trying to complete a step that is already completed
1265
-        if ($txn_reg_steps[ $reg_step_slug ] === true) {
1265
+        if ($txn_reg_steps[$reg_step_slug] === true) {
1266 1266
             return true;
1267 1267
         }
1268 1268
         // if  we're trying to complete a step that hasn't even started
1269
-        if ($status === true && $txn_reg_steps[ $reg_step_slug ] === false) {
1269
+        if ($status === true && $txn_reg_steps[$reg_step_slug] === false) {
1270 1270
             return false;
1271 1271
         }
1272 1272
         // if current status value matches the incoming value (no change)
1273 1273
         // type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1274
-        if ((int) $txn_reg_steps[ $reg_step_slug ] === (int) $status) {
1274
+        if ((int) $txn_reg_steps[$reg_step_slug] === (int) $status) {
1275 1275
             // this will happen in cases where multiple AJAX requests occur during the same step
1276 1276
             return true;
1277 1277
         }
1278 1278
         // if we're trying to set a start time, but it has already been set...
1279
-        if (is_numeric($status) && is_numeric($txn_reg_steps[ $reg_step_slug ])) {
1279
+        if (is_numeric($status) && is_numeric($txn_reg_steps[$reg_step_slug])) {
1280 1280
             // skip the update below, but don't return FALSE so that errors won't be displayed
1281 1281
             return true;
1282 1282
         }
1283 1283
         // update completed status
1284
-        $txn_reg_steps[ $reg_step_slug ] = $status;
1284
+        $txn_reg_steps[$reg_step_slug] = $status;
1285 1285
         $this->set_reg_steps($txn_reg_steps);
1286 1286
         $this->save();
1287 1287
         return true;
@@ -1301,7 +1301,7 @@  discard block
 block discarded – undo
1301 1301
     {
1302 1302
         // get reg steps array
1303 1303
         $txn_reg_steps = $this->reg_steps();
1304
-        unset($txn_reg_steps[ $reg_step_slug ]);
1304
+        unset($txn_reg_steps[$reg_step_slug]);
1305 1305
         $this->set_reg_steps($txn_reg_steps);
1306 1306
     }
1307 1307
 
@@ -1374,12 +1374,12 @@  discard block
 block discarded – undo
1374 1374
             return;
1375 1375
         }
1376 1376
         $payments = $this->get_many_related('Payment');
1377
-        if (! empty($payments)) {
1377
+        if ( ! empty($payments)) {
1378 1378
             foreach ($payments as $payment) {
1379 1379
                 if ($payment instanceof EE_Payment) {
1380 1380
                     // kk this TXN should NOT be abandoned
1381 1381
                     $this->update_status_based_on_total_paid();
1382
-                    if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1382
+                    if ( ! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1383 1383
                         EE_Error::add_attention(
1384 1384
                             sprintf(
1385 1385
                                 esc_html__(
Please login to merge, or discard this patch.
Indentation   +1701 added lines, -1701 removed lines patch added patch discarded remove patch
@@ -13,1705 +13,1705 @@
 block discarded – undo
13 13
 class EE_Transaction extends EE_Base_Class implements EEI_Transaction
14 14
 {
15 15
 
16
-    /**
17
-     * The length of time in seconds that a lock is applied before being considered expired.
18
-     * It is not long because a transaction should only be locked for the duration of the request that locked it
19
-     */
20
-    const LOCK_EXPIRATION = 2;
21
-
22
-    /**
23
-     * txn status upon initial construction.
24
-     *
25
-     * @var string
26
-     */
27
-    protected $_old_txn_status;
28
-
29
-
30
-    /**
31
-     * @param array  $props_n_values          incoming values
32
-     * @param string $timezone                incoming timezone
33
-     *                                        (if not set the timezone set for the website will be used.)
34
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
35
-     *                                        date_format and the second value is the time format
36
-     * @return EE_Transaction
37
-     * @throws EE_Error
38
-     * @throws InvalidArgumentException
39
-     * @throws InvalidDataTypeException
40
-     * @throws InvalidInterfaceException
41
-     * @throws ReflectionException
42
-     */
43
-    public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
44
-    {
45
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
46
-        $txn = $has_object
47
-            ? $has_object
48
-            : new self($props_n_values, false, $timezone, $date_formats);
49
-        if (! $has_object) {
50
-            $txn->set_old_txn_status($txn->status_ID());
51
-        }
52
-        return $txn;
53
-    }
54
-
55
-
56
-    /**
57
-     * @param array  $props_n_values  incoming values from the database
58
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
59
-     *                                the website will be used.
60
-     * @return EE_Transaction
61
-     * @throws EE_Error
62
-     * @throws InvalidArgumentException
63
-     * @throws InvalidDataTypeException
64
-     * @throws InvalidInterfaceException
65
-     * @throws ReflectionException
66
-     */
67
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
68
-    {
69
-        $txn = new self($props_n_values, true, $timezone);
70
-        $txn->set_old_txn_status($txn->status_ID());
71
-        return $txn;
72
-    }
73
-
74
-
75
-    /**
76
-     * Sets a meta field indicating that this TXN is locked and should not be updated in the db.
77
-     * If a lock has already been set, then we will attempt to remove it in case it has expired.
78
-     * If that also fails, then an exception is thrown.
79
-     *
80
-     * @throws EE_Error
81
-     * @throws InvalidArgumentException
82
-     * @throws InvalidDataTypeException
83
-     * @throws InvalidInterfaceException
84
-     * @throws ReflectionException
85
-     */
86
-    public function lock()
87
-    {
88
-        // attempt to set lock, but if that fails...
89
-        if (! $this->add_extra_meta('lock', time(), true)) {
90
-            // then attempt to remove the lock in case it is expired
91
-            if ($this->_remove_expired_lock()) {
92
-                // if removal was successful, then try setting lock again
93
-                $this->lock();
94
-            } else {
95
-                // but if the lock can not be removed, then throw an exception
96
-                throw new EE_Error(
97
-                    sprintf(
98
-                        __(
99
-                            'Could not lock Transaction %1$d because it is already locked, meaning another part of the system is currently editing it. It should already be unlocked by the time you read this, so please refresh the page and try again.',
100
-                            'event_espresso'
101
-                        ),
102
-                        $this->ID()
103
-                    )
104
-                );
105
-            }
106
-        }
107
-    }
108
-
109
-
110
-    /**
111
-     * removes transaction lock applied in EE_Transaction::lock()
112
-     *
113
-     * @return int
114
-     * @throws EE_Error
115
-     * @throws InvalidArgumentException
116
-     * @throws InvalidDataTypeException
117
-     * @throws InvalidInterfaceException
118
-     * @throws ReflectionException
119
-     */
120
-    public function unlock()
121
-    {
122
-        return $this->delete_extra_meta('lock');
123
-    }
124
-
125
-
126
-    /**
127
-     * Decides whether or not now is the right time to update the transaction.
128
-     * This is useful because we don't always know if it is safe to update the transaction
129
-     * and its related data. why?
130
-     * because it's possible that the transaction is being used in another
131
-     * request and could overwrite anything we save.
132
-     * So we want to only update the txn once we know that won't happen.
133
-     * We also check that the lock isn't expired, and remove it if it is
134
-     *
135
-     * @return boolean
136
-     * @throws EE_Error
137
-     * @throws InvalidArgumentException
138
-     * @throws InvalidDataTypeException
139
-     * @throws InvalidInterfaceException
140
-     * @throws ReflectionException
141
-     */
142
-    public function is_locked()
143
-    {
144
-        // if TXN is not locked, then return false immediately
145
-        if (! $this->_get_lock()) {
146
-            return false;
147
-        }
148
-        // if not, then let's try and remove the lock in case it's expired...
149
-        // _remove_expired_lock() returns 0 when lock is valid (ie: removed = false)
150
-        // and a positive number if the lock was removed (ie: number of locks deleted),
151
-        // so we need to return the opposite
152
-        return ! $this->_remove_expired_lock() ? true : false;
153
-    }
154
-
155
-
156
-    /**
157
-     * Gets the meta field indicating that this TXN is locked
158
-     *
159
-     * @return int
160
-     * @throws EE_Error
161
-     * @throws InvalidArgumentException
162
-     * @throws InvalidDataTypeException
163
-     * @throws InvalidInterfaceException
164
-     * @throws ReflectionException
165
-     */
166
-    protected function _get_lock()
167
-    {
168
-        return (int) $this->get_extra_meta('lock', true, 0);
169
-    }
170
-
171
-
172
-    /**
173
-     * If the lock on this transaction is expired, then we want to remove it so that the transaction can be updated
174
-     *
175
-     * @return int
176
-     * @throws EE_Error
177
-     * @throws InvalidArgumentException
178
-     * @throws InvalidDataTypeException
179
-     * @throws InvalidInterfaceException
180
-     * @throws ReflectionException
181
-     */
182
-    protected function _remove_expired_lock()
183
-    {
184
-        $locked = $this->_get_lock();
185
-        if ($locked && time() - EE_Transaction::LOCK_EXPIRATION > $locked) {
186
-            return $this->unlock();
187
-        }
188
-        return 0;
189
-    }
190
-
191
-
192
-    /**
193
-     * Set transaction total
194
-     *
195
-     * @param float $total total value of transaction
196
-     * @throws EE_Error
197
-     * @throws InvalidArgumentException
198
-     * @throws InvalidDataTypeException
199
-     * @throws InvalidInterfaceException
200
-     * @throws ReflectionException
201
-     */
202
-    public function set_total($total = 0.00)
203
-    {
204
-        $this->set('TXN_total', (float) $total);
205
-    }
206
-
207
-
208
-    /**
209
-     * Set Total Amount Paid to Date
210
-     *
211
-     * @param float $total_paid total amount paid to date (sum of all payments)
212
-     * @throws EE_Error
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidDataTypeException
215
-     * @throws InvalidInterfaceException
216
-     * @throws ReflectionException
217
-     */
218
-    public function set_paid($total_paid = 0.00)
219
-    {
220
-        $this->set('TXN_paid', (float) $total_paid);
221
-    }
222
-
223
-
224
-    /**
225
-     * Set transaction status
226
-     *
227
-     * @param string $status        whether the transaction is open, declined, accepted,
228
-     *                              or any number of custom values that can be set
229
-     * @throws EE_Error
230
-     * @throws InvalidArgumentException
231
-     * @throws InvalidDataTypeException
232
-     * @throws InvalidInterfaceException
233
-     * @throws ReflectionException
234
-     */
235
-    public function set_status($status = '')
236
-    {
237
-        $this->set('STS_ID', $status);
238
-    }
239
-
240
-
241
-    /**
242
-     * Set hash salt
243
-     *
244
-     * @param string $hash_salt required for some payment gateways
245
-     * @throws EE_Error
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidDataTypeException
248
-     * @throws InvalidInterfaceException
249
-     * @throws ReflectionException
250
-     */
251
-    public function set_hash_salt($hash_salt = '')
252
-    {
253
-        $this->set('TXN_hash_salt', $hash_salt);
254
-    }
255
-
256
-
257
-    /**
258
-     * Sets TXN_reg_steps array
259
-     *
260
-     * @param array $txn_reg_steps
261
-     * @throws EE_Error
262
-     * @throws InvalidArgumentException
263
-     * @throws InvalidDataTypeException
264
-     * @throws InvalidInterfaceException
265
-     * @throws ReflectionException
266
-     */
267
-    public function set_reg_steps(array $txn_reg_steps)
268
-    {
269
-        $this->set('TXN_reg_steps', $txn_reg_steps);
270
-    }
271
-
272
-
273
-    /**
274
-     * Gets TXN_reg_steps
275
-     *
276
-     * @return array
277
-     * @throws EE_Error
278
-     * @throws InvalidArgumentException
279
-     * @throws InvalidDataTypeException
280
-     * @throws InvalidInterfaceException
281
-     * @throws ReflectionException
282
-     */
283
-    public function reg_steps()
284
-    {
285
-        $TXN_reg_steps = $this->get('TXN_reg_steps');
286
-        return is_array($TXN_reg_steps) ? (array) $TXN_reg_steps : array();
287
-    }
288
-
289
-
290
-    /**
291
-     * @return string of transaction's total cost, with currency symbol and decimal
292
-     * @throws EE_Error
293
-     * @throws InvalidArgumentException
294
-     * @throws InvalidDataTypeException
295
-     * @throws InvalidInterfaceException
296
-     * @throws ReflectionException
297
-     */
298
-    public function pretty_total()
299
-    {
300
-        return $this->get_pretty('TXN_total');
301
-    }
302
-
303
-
304
-    /**
305
-     * Gets the amount paid in a pretty string (formatted and with currency symbol)
306
-     *
307
-     * @return string
308
-     * @throws EE_Error
309
-     * @throws InvalidArgumentException
310
-     * @throws InvalidDataTypeException
311
-     * @throws InvalidInterfaceException
312
-     * @throws ReflectionException
313
-     */
314
-    public function pretty_paid()
315
-    {
316
-        return $this->get_pretty('TXN_paid');
317
-    }
318
-
319
-
320
-    /**
321
-     * calculate the amount remaining for this transaction and return;
322
-     *
323
-     * @return float amount remaining
324
-     * @throws EE_Error
325
-     * @throws InvalidArgumentException
326
-     * @throws InvalidDataTypeException
327
-     * @throws InvalidInterfaceException
328
-     * @throws ReflectionException
329
-     */
330
-    public function remaining()
331
-    {
332
-        return $this->total() - $this->paid();
333
-    }
334
-
335
-
336
-    /**
337
-     * get Transaction Total
338
-     *
339
-     * @return float
340
-     * @throws EE_Error
341
-     * @throws InvalidArgumentException
342
-     * @throws InvalidDataTypeException
343
-     * @throws InvalidInterfaceException
344
-     * @throws ReflectionException
345
-     */
346
-    public function total()
347
-    {
348
-        return (float) $this->get('TXN_total');
349
-    }
350
-
351
-
352
-    /**
353
-     * get Total Amount Paid to Date
354
-     *
355
-     * @return float
356
-     * @throws EE_Error
357
-     * @throws InvalidArgumentException
358
-     * @throws InvalidDataTypeException
359
-     * @throws InvalidInterfaceException
360
-     * @throws ReflectionException
361
-     */
362
-    public function paid()
363
-    {
364
-        return (float) $this->get('TXN_paid');
365
-    }
366
-
367
-
368
-    /**
369
-     * @return mixed|null
370
-     * @throws EE_Error
371
-     * @throws InvalidArgumentException
372
-     * @throws InvalidDataTypeException
373
-     * @throws InvalidInterfaceException
374
-     * @throws ReflectionException
375
-     */
376
-    public function get_cart_session()
377
-    {
378
-        $session_data = (array) $this->get('TXN_session_data');
379
-        return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
380
-            ? $session_data['cart']
381
-            : null;
382
-    }
383
-
384
-
385
-    /**
386
-     * get Transaction session data
387
-     *
388
-     * @return array|mixed
389
-     * @throws EE_Error
390
-     * @throws InvalidArgumentException
391
-     * @throws InvalidDataTypeException
392
-     * @throws InvalidInterfaceException
393
-     * @throws ReflectionException
394
-     */
395
-    public function session_data()
396
-    {
397
-        $session_data = $this->get('TXN_session_data');
398
-        if (empty($session_data)) {
399
-            $session_data = array(
400
-                'id'            => null,
401
-                'user_id'       => null,
402
-                'ip_address'    => null,
403
-                'user_agent'    => null,
404
-                'init_access'   => null,
405
-                'last_access'   => null,
406
-                'pages_visited' => array(),
407
-            );
408
-        }
409
-        return $session_data;
410
-    }
411
-
412
-
413
-    /**
414
-     * Set session data within the TXN object
415
-     *
416
-     * @param EE_Session|array $session_data
417
-     * @throws EE_Error
418
-     * @throws InvalidArgumentException
419
-     * @throws InvalidDataTypeException
420
-     * @throws InvalidInterfaceException
421
-     * @throws ReflectionException
422
-     */
423
-    public function set_txn_session_data($session_data)
424
-    {
425
-        if ($session_data instanceof EE_Session) {
426
-            $this->set('TXN_session_data', $session_data->get_session_data(null, true));
427
-        } else {
428
-            $this->set('TXN_session_data', $session_data);
429
-        }
430
-    }
431
-
432
-
433
-    /**
434
-     * get Transaction hash salt
435
-     *
436
-     * @return mixed
437
-     * @throws EE_Error
438
-     * @throws InvalidArgumentException
439
-     * @throws InvalidDataTypeException
440
-     * @throws InvalidInterfaceException
441
-     * @throws ReflectionException
442
-     */
443
-    public function hash_salt_()
444
-    {
445
-        return $this->get('TXN_hash_salt');
446
-    }
447
-
448
-
449
-    /**
450
-     * Returns the transaction datetime as either:
451
-     *            - unix timestamp format ($format = false, $gmt = true)
452
-     *            - formatted date string including the UTC (timezone) offset ($format = true ($gmt
453
-     *              has no affect with this option)), this also may include a timezone abbreviation if the
454
-     *              set timezone in this class differs from what the timezone is on the blog.
455
-     *            - formatted date string including the UTC (timezone) offset (default).
456
-     *
457
-     * @param boolean $format   - whether to return a unix timestamp (default) or formatted date string
458
-     * @param boolean $gmt      - whether to return a unix timestamp with UTC offset applied (default)
459
-     *                          or no UTC offset applied
460
-     * @return string | int
461
-     * @throws EE_Error
462
-     * @throws InvalidArgumentException
463
-     * @throws InvalidDataTypeException
464
-     * @throws InvalidInterfaceException
465
-     * @throws ReflectionException
466
-     */
467
-    public function datetime($format = false, $gmt = false)
468
-    {
469
-        if ($format) {
470
-            return $this->get_pretty('TXN_timestamp');
471
-        }
472
-        if ($gmt) {
473
-            return $this->get_raw('TXN_timestamp');
474
-        }
475
-        return $this->get('TXN_timestamp');
476
-    }
477
-
478
-
479
-    /**
480
-     * Gets registrations on this transaction
481
-     *
482
-     * @param array   $query_params array of query parameters
483
-     * @param boolean $get_cached   TRUE to retrieve cached registrations or FALSE to pull from the db
484
-     * @return EE_Base_Class[]|EE_Registration[]
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     * @throws ReflectionException
490
-     */
491
-    public function registrations($query_params = array(), $get_cached = false)
492
-    {
493
-        $query_params = (empty($query_params) || ! is_array($query_params))
494
-            ? array(
495
-                'order_by' => array(
496
-                    'Event.EVT_name'     => 'ASC',
497
-                    'Attendee.ATT_lname' => 'ASC',
498
-                    'Attendee.ATT_fname' => 'ASC',
499
-                ),
500
-            )
501
-            : $query_params;
502
-        $query_params = $get_cached ? array() : $query_params;
503
-        return $this->get_many_related('Registration', $query_params);
504
-    }
505
-
506
-
507
-    /**
508
-     * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
509
-     * function for getting attendees and how many registrations they each have for an event)
510
-     *
511
-     * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
512
-     * @throws EE_Error
513
-     * @throws InvalidArgumentException
514
-     * @throws InvalidDataTypeException
515
-     * @throws InvalidInterfaceException
516
-     * @throws ReflectionException
517
-     */
518
-    public function attendees()
519
-    {
520
-        return $this->get_many_related('Attendee', array(array('Registration.Transaction.TXN_ID' => $this->ID())));
521
-    }
522
-
523
-
524
-    /**
525
-     * Gets payments for this transaction. Unlike other such functions, order by 'DESC' by default
526
-     *
527
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
528
-     * @return EE_Base_Class[]|EE_Payment[]
529
-     * @throws EE_Error
530
-     * @throws InvalidArgumentException
531
-     * @throws InvalidDataTypeException
532
-     * @throws InvalidInterfaceException
533
-     * @throws ReflectionException
534
-     */
535
-    public function payments($query_params = array())
536
-    {
537
-        return $this->get_many_related('Payment', $query_params);
538
-    }
539
-
540
-
541
-    /**
542
-     * gets only approved payments for this transaction
543
-     *
544
-     * @return EE_Base_Class[]|EE_Payment[]
545
-     * @throws EE_Error
546
-     * @throws InvalidArgumentException
547
-     * @throws ReflectionException
548
-     * @throws InvalidDataTypeException
549
-     * @throws InvalidInterfaceException
550
-     */
551
-    public function approved_payments()
552
-    {
553
-        EE_Registry::instance()->load_model('Payment');
554
-        return $this->get_many_related(
555
-            'Payment',
556
-            array(
557
-                array('STS_ID' => EEM_Payment::status_id_approved),
558
-                'order_by' => array('PAY_timestamp' => 'DESC'),
559
-            )
560
-        );
561
-    }
562
-
563
-
564
-    /**
565
-     * Gets all payments which have not been approved
566
-     *
567
-     * @return EE_Base_Class[]|EEI_Payment[]
568
-     * @throws EE_Error if a model is misconfigured somehow
569
-     * @throws InvalidArgumentException
570
-     * @throws InvalidDataTypeException
571
-     * @throws InvalidInterfaceException
572
-     * @throws ReflectionException
573
-     */
574
-    public function pending_payments()
575
-    {
576
-        return $this->get_many_related(
577
-            'Payment',
578
-            array(
579
-                array(
580
-                    'STS_ID' => EEM_Payment::status_id_pending,
581
-                ),
582
-                'order_by' => array(
583
-                    'PAY_timestamp' => 'DESC',
584
-                ),
585
-            )
586
-        );
587
-    }
588
-
589
-
590
-    /**
591
-     * echoes $this->pretty_status()
592
-     *
593
-     * @param bool $show_icons
594
-     * @throws EE_Error
595
-     * @throws InvalidArgumentException
596
-     * @throws InvalidDataTypeException
597
-     * @throws InvalidInterfaceException
598
-     * @throws ReflectionException
599
-     */
600
-    public function e_pretty_status($show_icons = false)
601
-    {
602
-        echo $this->pretty_status($show_icons);
603
-    }
604
-
605
-
606
-    /**
607
-     * returns a pretty version of the status, good for displaying to users
608
-     *
609
-     * @param bool $show_icons
610
-     * @return string
611
-     * @throws EE_Error
612
-     * @throws InvalidArgumentException
613
-     * @throws InvalidDataTypeException
614
-     * @throws InvalidInterfaceException
615
-     * @throws ReflectionException
616
-     */
617
-    public function pretty_status($show_icons = false)
618
-    {
619
-        $status = EEM_Status::instance()->localized_status(
620
-            array($this->status_ID() => __('unknown', 'event_espresso')),
621
-            false,
622
-            'sentence'
623
-        );
624
-        $icon = '';
625
-        switch ($this->status_ID()) {
626
-            case EEM_Transaction::complete_status_code:
627
-                $icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
628
-                break;
629
-            case EEM_Transaction::incomplete_status_code:
630
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 lt-blue-text"></span>'
631
-                    : '';
632
-                break;
633
-            case EEM_Transaction::abandoned_status_code:
634
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 red-text"></span>' : '';
635
-                break;
636
-            case EEM_Transaction::failed_status_code:
637
-                $icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
638
-                break;
639
-            case EEM_Transaction::overpaid_status_code:
640
-                $icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
641
-                break;
642
-        }
643
-        return $icon . $status[ $this->status_ID() ];
644
-    }
645
-
646
-
647
-    /**
648
-     * get Transaction Status
649
-     *
650
-     * @return mixed
651
-     * @throws EE_Error
652
-     * @throws InvalidArgumentException
653
-     * @throws InvalidDataTypeException
654
-     * @throws InvalidInterfaceException
655
-     * @throws ReflectionException
656
-     */
657
-    public function status_ID()
658
-    {
659
-        return $this->get('STS_ID');
660
-    }
661
-
662
-
663
-    /**
664
-     * Returns TRUE or FALSE for whether or not this transaction cost any money
665
-     *
666
-     * @return boolean
667
-     * @throws EE_Error
668
-     * @throws InvalidArgumentException
669
-     * @throws InvalidDataTypeException
670
-     * @throws InvalidInterfaceException
671
-     * @throws ReflectionException
672
-     */
673
-    public function is_free()
674
-    {
675
-        return EEH_Money::compare_floats($this->get('TXN_total'), 0, '==');
676
-    }
677
-
678
-
679
-    /**
680
-     * Returns whether this transaction is complete
681
-     * Useful in templates and other logic for deciding if we should ask for another payment...
682
-     *
683
-     * @return boolean
684
-     * @throws EE_Error
685
-     * @throws InvalidArgumentException
686
-     * @throws InvalidDataTypeException
687
-     * @throws InvalidInterfaceException
688
-     * @throws ReflectionException
689
-     */
690
-    public function is_completed()
691
-    {
692
-        return $this->status_ID() === EEM_Transaction::complete_status_code;
693
-    }
694
-
695
-
696
-    /**
697
-     * Returns whether this transaction is incomplete
698
-     * Useful in templates and other logic for deciding if we should ask for another payment...
699
-     *
700
-     * @return boolean
701
-     * @throws EE_Error
702
-     * @throws InvalidArgumentException
703
-     * @throws InvalidDataTypeException
704
-     * @throws InvalidInterfaceException
705
-     * @throws ReflectionException
706
-     */
707
-    public function is_incomplete()
708
-    {
709
-        return $this->status_ID() === EEM_Transaction::incomplete_status_code;
710
-    }
711
-
712
-
713
-    /**
714
-     * Returns whether this transaction is overpaid
715
-     * Useful in templates and other logic for deciding if monies need to be refunded
716
-     *
717
-     * @return boolean
718
-     * @throws EE_Error
719
-     * @throws InvalidArgumentException
720
-     * @throws InvalidDataTypeException
721
-     * @throws InvalidInterfaceException
722
-     * @throws ReflectionException
723
-     */
724
-    public function is_overpaid()
725
-    {
726
-        return $this->status_ID() === EEM_Transaction::overpaid_status_code;
727
-    }
728
-
729
-
730
-    /**
731
-     * Returns whether this transaction was abandoned
732
-     * meaning that the transaction/registration process was somehow interrupted and never completed
733
-     * but that contact information exists for at least one registrant
734
-     *
735
-     * @return boolean
736
-     * @throws EE_Error
737
-     * @throws InvalidArgumentException
738
-     * @throws InvalidDataTypeException
739
-     * @throws InvalidInterfaceException
740
-     * @throws ReflectionException
741
-     */
742
-    public function is_abandoned()
743
-    {
744
-        return $this->status_ID() === EEM_Transaction::abandoned_status_code;
745
-    }
746
-
747
-
748
-    /**
749
-     * Returns whether this transaction failed
750
-     * meaning that the transaction/registration process was somehow interrupted and never completed
751
-     * and that NO contact information exists for any registrants
752
-     *
753
-     * @return boolean
754
-     * @throws EE_Error
755
-     * @throws InvalidArgumentException
756
-     * @throws InvalidDataTypeException
757
-     * @throws InvalidInterfaceException
758
-     * @throws ReflectionException
759
-     */
760
-    public function failed()
761
-    {
762
-        return $this->status_ID() === EEM_Transaction::failed_status_code;
763
-    }
764
-
765
-
766
-    /**
767
-     * This returns the url for the invoice of this transaction
768
-     *
769
-     * @param string $type 'html' or 'pdf' (default is pdf)
770
-     * @return string
771
-     * @throws EE_Error
772
-     * @throws InvalidArgumentException
773
-     * @throws InvalidDataTypeException
774
-     * @throws InvalidInterfaceException
775
-     * @throws ReflectionException
776
-     */
777
-    public function invoice_url($type = 'html')
778
-    {
779
-        $REG = $this->primary_registration();
780
-        if (! $REG instanceof EE_Registration) {
781
-            return '';
782
-        }
783
-        return $REG->invoice_url($type);
784
-    }
785
-
786
-
787
-    /**
788
-     * Gets the primary registration only
789
-     *
790
-     * @return EE_Base_Class|EE_Registration
791
-     * @throws EE_Error
792
-     * @throws InvalidArgumentException
793
-     * @throws InvalidDataTypeException
794
-     * @throws InvalidInterfaceException
795
-     * @throws ReflectionException
796
-     */
797
-    public function primary_registration()
798
-    {
799
-        $registrations = (array) $this->get_many_related(
800
-            'Registration',
801
-            array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
802
-        );
803
-        foreach ($registrations as $registration) {
804
-            // valid registration that is NOT cancelled or declined ?
805
-            if (
806
-                $registration instanceof EE_Registration
807
-                && ! in_array($registration->status_ID(), EEM_Registration::closed_reg_statuses(), true)
808
-            ) {
809
-                return $registration;
810
-            }
811
-        }
812
-        // nothing valid found, so just return first thing from array of results
813
-        return reset($registrations);
814
-    }
815
-
816
-
817
-    /**
818
-     * Gets the URL for viewing the receipt
819
-     *
820
-     * @param string $type 'pdf' or 'html' (default is 'html')
821
-     * @return string
822
-     * @throws EE_Error
823
-     * @throws InvalidArgumentException
824
-     * @throws InvalidDataTypeException
825
-     * @throws InvalidInterfaceException
826
-     * @throws ReflectionException
827
-     */
828
-    public function receipt_url($type = 'html')
829
-    {
830
-        $REG = $this->primary_registration();
831
-        if (! $REG instanceof EE_Registration) {
832
-            return '';
833
-        }
834
-        return $REG->receipt_url($type);
835
-    }
836
-
837
-
838
-    /**
839
-     * Gets the URL of the thank you page with this registration REG_url_link added as
840
-     * a query parameter
841
-     *
842
-     * @return string
843
-     * @throws EE_Error
844
-     * @throws InvalidArgumentException
845
-     * @throws InvalidDataTypeException
846
-     * @throws InvalidInterfaceException
847
-     * @throws ReflectionException
848
-     */
849
-    public function payment_overview_url()
850
-    {
851
-        $primary_registration = $this->primary_registration();
852
-        return $primary_registration instanceof EE_Registration ? $primary_registration->payment_overview_url() : false;
853
-    }
854
-
855
-
856
-    /**
857
-     * @return string
858
-     * @throws EE_Error
859
-     * @throws InvalidArgumentException
860
-     * @throws InvalidDataTypeException
861
-     * @throws InvalidInterfaceException
862
-     * @throws ReflectionException
863
-     */
864
-    public function gateway_response_on_transaction()
865
-    {
866
-        $payment = $this->get_first_related('Payment');
867
-        return $payment instanceof EE_Payment ? $payment->gateway_response() : '';
868
-    }
869
-
870
-
871
-    /**
872
-     * Get the status object of this object
873
-     *
874
-     * @return EE_Base_Class|EE_Status
875
-     * @throws EE_Error
876
-     * @throws InvalidArgumentException
877
-     * @throws InvalidDataTypeException
878
-     * @throws InvalidInterfaceException
879
-     * @throws ReflectionException
880
-     */
881
-    public function status_obj()
882
-    {
883
-        return $this->get_first_related('Status');
884
-    }
885
-
886
-
887
-    /**
888
-     * Gets all the extra meta info on this payment
889
-     *
890
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
891
-     * @return EE_Base_Class[]|EE_Extra_Meta
892
-     * @throws EE_Error
893
-     * @throws InvalidArgumentException
894
-     * @throws InvalidDataTypeException
895
-     * @throws InvalidInterfaceException
896
-     * @throws ReflectionException
897
-     */
898
-    public function extra_meta($query_params = array())
899
-    {
900
-        return $this->get_many_related('Extra_Meta', $query_params);
901
-    }
902
-
903
-
904
-    /**
905
-     * Wrapper for _add_relation_to
906
-     *
907
-     * @param EE_Registration $registration
908
-     * @return EE_Base_Class the relation was added to
909
-     * @throws EE_Error
910
-     * @throws InvalidArgumentException
911
-     * @throws InvalidDataTypeException
912
-     * @throws InvalidInterfaceException
913
-     * @throws ReflectionException
914
-     */
915
-    public function add_registration(EE_Registration $registration)
916
-    {
917
-        return $this->_add_relation_to($registration, 'Registration');
918
-    }
919
-
920
-
921
-    /**
922
-     * Removes the given registration from being related (even before saving this transaction).
923
-     * If an ID/index is provided and this transaction isn't saved yet, removes it from list of cached relations
924
-     *
925
-     * @param int $registration_or_id
926
-     * @return EE_Base_Class that was removed from being related
927
-     * @throws EE_Error
928
-     * @throws InvalidArgumentException
929
-     * @throws InvalidDataTypeException
930
-     * @throws InvalidInterfaceException
931
-     * @throws ReflectionException
932
-     */
933
-    public function remove_registration_with_id($registration_or_id)
934
-    {
935
-        return $this->_remove_relation_to($registration_or_id, 'Registration');
936
-    }
937
-
938
-
939
-    /**
940
-     * Gets all the line items which are for ACTUAL items
941
-     *
942
-     * @return EE_Line_Item[]
943
-     * @throws EE_Error
944
-     * @throws InvalidArgumentException
945
-     * @throws InvalidDataTypeException
946
-     * @throws InvalidInterfaceException
947
-     * @throws ReflectionException
948
-     */
949
-    public function items_purchased()
950
-    {
951
-        return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_line_item)));
952
-    }
953
-
954
-
955
-    /**
956
-     * Wrapper for _add_relation_to
957
-     *
958
-     * @param EE_Line_Item $line_item
959
-     * @return EE_Base_Class the relation was added to
960
-     * @throws EE_Error
961
-     * @throws InvalidArgumentException
962
-     * @throws InvalidDataTypeException
963
-     * @throws InvalidInterfaceException
964
-     * @throws ReflectionException
965
-     */
966
-    public function add_line_item(EE_Line_Item $line_item)
967
-    {
968
-        return $this->_add_relation_to($line_item, 'Line_Item');
969
-    }
970
-
971
-
972
-    /**
973
-     * Gets ALL the line items related to this transaction (unstructured)
974
-     *
975
-     * @param array $query_params
976
-     * @return EE_Base_Class[]|EE_Line_Item[]
977
-     * @throws EE_Error
978
-     * @throws InvalidArgumentException
979
-     * @throws InvalidDataTypeException
980
-     * @throws InvalidInterfaceException
981
-     * @throws ReflectionException
982
-     */
983
-    public function line_items($query_params = array())
984
-    {
985
-        return $this->get_many_related('Line_Item', $query_params);
986
-    }
987
-
988
-
989
-    /**
990
-     * Gets all the line items which are taxes on the total
991
-     *
992
-     * @return EE_Line_Item[]
993
-     * @throws EE_Error
994
-     * @throws InvalidArgumentException
995
-     * @throws InvalidDataTypeException
996
-     * @throws InvalidInterfaceException
997
-     * @throws ReflectionException
998
-     */
999
-    public function tax_items()
1000
-    {
1001
-        return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Gets the total line item (which is a parent of all other related line items,
1007
-     * meaning it takes them all into account on its total)
1008
-     *
1009
-     * @param bool $create_if_not_found
1010
-     * @return \EE_Line_Item
1011
-     * @throws EE_Error
1012
-     * @throws InvalidArgumentException
1013
-     * @throws InvalidDataTypeException
1014
-     * @throws InvalidInterfaceException
1015
-     * @throws ReflectionException
1016
-     */
1017
-    public function total_line_item($create_if_not_found = true)
1018
-    {
1019
-        $item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
1020
-        if (! $item && $create_if_not_found) {
1021
-            $item = EEH_Line_Item::create_total_line_item($this);
1022
-        }
1023
-        return $item;
1024
-    }
1025
-
1026
-
1027
-    /**
1028
-     * Returns the total amount of tax on this transaction
1029
-     * (assumes there's only one tax subtotal line item)
1030
-     *
1031
-     * @return float
1032
-     * @throws EE_Error
1033
-     * @throws InvalidArgumentException
1034
-     * @throws InvalidDataTypeException
1035
-     * @throws InvalidInterfaceException
1036
-     * @throws ReflectionException
1037
-     */
1038
-    public function tax_total()
1039
-    {
1040
-        $tax_line_item = $this->tax_total_line_item();
1041
-        if ($tax_line_item) {
1042
-            return (float) $tax_line_item->total();
1043
-        }
1044
-        return (float) 0;
1045
-    }
1046
-
1047
-
1048
-    /**
1049
-     * Gets the tax subtotal line item (assumes there's only one)
1050
-     *
1051
-     * @return EE_Line_Item
1052
-     * @throws EE_Error
1053
-     * @throws InvalidArgumentException
1054
-     * @throws InvalidDataTypeException
1055
-     * @throws InvalidInterfaceException
1056
-     * @throws ReflectionException
1057
-     */
1058
-    public function tax_total_line_item()
1059
-    {
1060
-        return EEH_Line_Item::get_taxes_subtotal($this->total_line_item());
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * Gets the array of billing info for the gateway and for this transaction's primary registration's attendee.
1066
-     *
1067
-     * @return EE_Form_Section_Proper
1068
-     * @throws EE_Error
1069
-     * @throws InvalidArgumentException
1070
-     * @throws InvalidDataTypeException
1071
-     * @throws InvalidInterfaceException
1072
-     * @throws ReflectionException
1073
-     */
1074
-    public function billing_info()
1075
-    {
1076
-        $payment_method = $this->payment_method();
1077
-        if (! $payment_method) {
1078
-            EE_Error::add_error(
1079
-                __(
1080
-                    'Could not find billing info for transaction because no gateway has been used for it yet',
1081
-                    'event_espresso'
1082
-                ),
1083
-                __FILE__,
1084
-                __FUNCTION__,
1085
-                __LINE__
1086
-            );
1087
-            return null;
1088
-        }
1089
-        $primary_reg = $this->primary_registration();
1090
-        if (! $primary_reg) {
1091
-            EE_Error::add_error(
1092
-                __(
1093
-                    'Cannot get billing info for gateway %s on transaction because no primary registration exists',
1094
-                    'event_espresso'
1095
-                ),
1096
-                __FILE__,
1097
-                __FUNCTION__,
1098
-                __LINE__
1099
-            );
1100
-            return null;
1101
-        }
1102
-        $attendee = $primary_reg->attendee();
1103
-        if (! $attendee) {
1104
-            EE_Error::add_error(
1105
-                __(
1106
-                    'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
1107
-                    'event_espresso'
1108
-                ),
1109
-                __FILE__,
1110
-                __FUNCTION__,
1111
-                __LINE__
1112
-            );
1113
-            return null;
1114
-        }
1115
-        return $attendee->billing_info_for_payment_method($payment_method);
1116
-    }
1117
-
1118
-
1119
-    /**
1120
-     * Gets PMD_ID
1121
-     *
1122
-     * @return int
1123
-     * @throws EE_Error
1124
-     * @throws InvalidArgumentException
1125
-     * @throws InvalidDataTypeException
1126
-     * @throws InvalidInterfaceException
1127
-     * @throws ReflectionException
1128
-     */
1129
-    public function payment_method_ID()
1130
-    {
1131
-        return $this->get('PMD_ID');
1132
-    }
1133
-
1134
-
1135
-    /**
1136
-     * Sets PMD_ID
1137
-     *
1138
-     * @param int $PMD_ID
1139
-     * @throws EE_Error
1140
-     * @throws InvalidArgumentException
1141
-     * @throws InvalidDataTypeException
1142
-     * @throws InvalidInterfaceException
1143
-     * @throws ReflectionException
1144
-     */
1145
-    public function set_payment_method_ID($PMD_ID)
1146
-    {
1147
-        $this->set('PMD_ID', $PMD_ID);
1148
-    }
1149
-
1150
-
1151
-    /**
1152
-     * Gets the last-used payment method on this transaction
1153
-     * (we COULD just use the last-made payment, but some payment methods, namely
1154
-     * offline ones, dont' create payments)
1155
-     *
1156
-     * @return EE_Payment_Method
1157
-     * @throws EE_Error
1158
-     * @throws InvalidArgumentException
1159
-     * @throws InvalidDataTypeException
1160
-     * @throws InvalidInterfaceException
1161
-     * @throws ReflectionException
1162
-     */
1163
-    public function payment_method()
1164
-    {
1165
-        $pm = $this->get_first_related('Payment_Method');
1166
-        if ($pm instanceof EE_Payment_Method) {
1167
-            return $pm;
1168
-        }
1169
-        $last_payment = $this->last_payment();
1170
-        if ($last_payment instanceof EE_Payment && $last_payment->payment_method()) {
1171
-            return $last_payment->payment_method();
1172
-        }
1173
-        return null;
1174
-    }
1175
-
1176
-
1177
-    /**
1178
-     * Gets the last payment made
1179
-     *
1180
-     * @return EE_Base_Class|EE_Payment
1181
-     * @throws EE_Error
1182
-     * @throws InvalidArgumentException
1183
-     * @throws InvalidDataTypeException
1184
-     * @throws InvalidInterfaceException
1185
-     * @throws ReflectionException
1186
-     */
1187
-    public function last_payment()
1188
-    {
1189
-        return $this->get_first_related('Payment', array('order_by' => array('PAY_ID' => 'desc')));
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * Gets all the line items which are unrelated to tickets on this transaction
1195
-     *
1196
-     * @return EE_Line_Item[]
1197
-     * @throws EE_Error
1198
-     * @throws InvalidArgumentException
1199
-     * @throws InvalidDataTypeException
1200
-     * @throws InvalidInterfaceException
1201
-     * @throws ReflectionException
1202
-     */
1203
-    public function non_ticket_line_items()
1204
-    {
1205
-        return EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction($this->ID());
1206
-    }
1207
-
1208
-
1209
-    /**
1210
-     * possibly toggles TXN status
1211
-     *
1212
-     * @param  boolean $update whether to save the TXN
1213
-     * @return bool whether the TXN was saved
1214
-     * @throws EE_Error
1215
-     * @throws InvalidArgumentException
1216
-     * @throws InvalidDataTypeException
1217
-     * @throws InvalidInterfaceException
1218
-     * @throws ReflectionException
1219
-     * @throws RuntimeException
1220
-     */
1221
-    public function update_status_based_on_total_paid($update = true)
1222
-    {
1223
-        // set transaction status based on comparison of TXN_paid vs TXN_total
1224
-        if (EEH_Money::compare_floats($this->paid(), $this->total(), '>')) {
1225
-            $new_txn_status = EEM_Transaction::overpaid_status_code;
1226
-        } elseif (EEH_Money::compare_floats($this->paid(), $this->total())) {
1227
-            $new_txn_status = EEM_Transaction::complete_status_code;
1228
-        } elseif (EEH_Money::compare_floats($this->paid(), $this->total(), '<')) {
1229
-            $new_txn_status = EEM_Transaction::incomplete_status_code;
1230
-        } else {
1231
-            throw new RuntimeException(
1232
-                __('The total paid calculation for this transaction is inaccurate.', 'event_espresso')
1233
-            );
1234
-        }
1235
-        if ($new_txn_status !== $this->status_ID()) {
1236
-            $this->set_status($new_txn_status);
1237
-            if ($update) {
1238
-                return $this->save() ? true : false;
1239
-            }
1240
-        }
1241
-        return false;
1242
-    }
1243
-
1244
-
1245
-    /**
1246
-     * Updates the transaction's status and total_paid based on all the payments
1247
-     * that apply to it
1248
-     *
1249
-     * @deprecated
1250
-     * @return array|bool
1251
-     * @throws EE_Error
1252
-     * @throws InvalidArgumentException
1253
-     * @throws ReflectionException
1254
-     * @throws InvalidDataTypeException
1255
-     * @throws InvalidInterfaceException
1256
-     */
1257
-    public function update_based_on_payments()
1258
-    {
1259
-        EE_Error::doing_it_wrong(
1260
-            __CLASS__ . '::' . __FUNCTION__,
1261
-            sprintf(
1262
-                __('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1263
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
1264
-            ),
1265
-            '4.6.0'
1266
-        );
1267
-        /** @type EE_Transaction_Processor $transaction_processor */
1268
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1269
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($this);
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * @return string
1275
-     */
1276
-    public function old_txn_status()
1277
-    {
1278
-        return $this->_old_txn_status;
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * @param string $old_txn_status
1284
-     */
1285
-    public function set_old_txn_status($old_txn_status)
1286
-    {
1287
-        // only set the first time
1288
-        if ($this->_old_txn_status === null) {
1289
-            $this->_old_txn_status = $old_txn_status;
1290
-        }
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     * reg_status_updated
1296
-     *
1297
-     * @return bool
1298
-     * @throws EE_Error
1299
-     * @throws InvalidArgumentException
1300
-     * @throws InvalidDataTypeException
1301
-     * @throws InvalidInterfaceException
1302
-     * @throws ReflectionException
1303
-     */
1304
-    public function txn_status_updated()
1305
-    {
1306
-        return $this->status_ID() !== $this->_old_txn_status && $this->_old_txn_status !== null;
1307
-    }
1308
-
1309
-
1310
-    /**
1311
-     * _reg_steps_completed
1312
-     * if $check_all is TRUE, then returns TRUE if ALL reg steps have been marked as completed,
1313
-     * if a $reg_step_slug is provided, then this step will be skipped when testing for completion
1314
-     * if $check_all is FALSE and a $reg_step_slug is provided, then ONLY that reg step will be tested for completion
1315
-     *
1316
-     * @param string $reg_step_slug
1317
-     * @param bool   $check_all
1318
-     * @return bool|int
1319
-     * @throws EE_Error
1320
-     * @throws InvalidArgumentException
1321
-     * @throws InvalidDataTypeException
1322
-     * @throws InvalidInterfaceException
1323
-     * @throws ReflectionException
1324
-     */
1325
-    private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1326
-    {
1327
-        $reg_steps = $this->reg_steps();
1328
-        if (! is_array($reg_steps) || empty($reg_steps)) {
1329
-            return false;
1330
-        }
1331
-        // loop thru reg steps array)
1332
-        foreach ($reg_steps as $slug => $reg_step_completed) {
1333
-            // if NOT checking ALL steps (only checking one step)
1334
-            if (! $check_all) {
1335
-                // and this is the one
1336
-                if ($slug === $reg_step_slug) {
1337
-                    return $reg_step_completed;
1338
-                }
1339
-                // skip to next reg step in loop
1340
-                continue;
1341
-            }
1342
-            // $check_all must be true, else we would never have gotten to this point
1343
-            if ($slug === $reg_step_slug) {
1344
-                // if we reach this point, then we are testing either:
1345
-                // all_reg_steps_completed_except() or
1346
-                // all_reg_steps_completed_except_final_step(),
1347
-                // and since this is the reg step EXCEPTION being tested
1348
-                // we want to return true (yes true) if this reg step is NOT completed
1349
-                // ie: "is everything completed except the final step?"
1350
-                // "that is correct... the final step is not completed, but all others are."
1351
-                return $reg_step_completed !== true;
1352
-            }
1353
-            if ($reg_step_completed !== true) {
1354
-                // if any reg step is NOT completed, then ALL steps are not completed
1355
-                return false;
1356
-            }
1357
-        }
1358
-        return true;
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * all_reg_steps_completed
1364
-     * returns:
1365
-     *    true if ALL reg steps have been marked as completed
1366
-     *        or false if any step is not completed
1367
-     *
1368
-     * @return bool
1369
-     * @throws EE_Error
1370
-     * @throws InvalidArgumentException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws InvalidInterfaceException
1373
-     * @throws ReflectionException
1374
-     */
1375
-    public function all_reg_steps_completed()
1376
-    {
1377
-        return $this->_reg_steps_completed();
1378
-    }
1379
-
1380
-
1381
-    /**
1382
-     * all_reg_steps_completed_except
1383
-     * returns:
1384
-     *        true if ALL reg steps, except a particular step that you wish to skip over, have been marked as completed
1385
-     *        or false if any other step is not completed
1386
-     *        or false if ALL steps are completed including the exception you are testing !!!
1387
-     *
1388
-     * @param string $exception
1389
-     * @return bool
1390
-     * @throws EE_Error
1391
-     * @throws InvalidArgumentException
1392
-     * @throws InvalidDataTypeException
1393
-     * @throws InvalidInterfaceException
1394
-     * @throws ReflectionException
1395
-     */
1396
-    public function all_reg_steps_completed_except($exception = '')
1397
-    {
1398
-        return $this->_reg_steps_completed($exception);
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * all_reg_steps_completed_except
1404
-     * returns:
1405
-     *        true if ALL reg steps, except the final step, have been marked as completed
1406
-     *        or false if any step is not completed
1407
-     *    or false if ALL steps are completed including the final step !!!
1408
-     *
1409
-     * @return bool
1410
-     * @throws EE_Error
1411
-     * @throws InvalidArgumentException
1412
-     * @throws InvalidDataTypeException
1413
-     * @throws InvalidInterfaceException
1414
-     * @throws ReflectionException
1415
-     */
1416
-    public function all_reg_steps_completed_except_final_step()
1417
-    {
1418
-        return $this->_reg_steps_completed('finalize_registration');
1419
-    }
1420
-
1421
-
1422
-    /**
1423
-     * reg_step_completed
1424
-     * returns:
1425
-     *    true if a specific reg step has been marked as completed
1426
-     *    a Unix timestamp if it has been initialized but not yet completed,
1427
-     *    or false if it has not yet been initialized
1428
-     *
1429
-     * @param string $reg_step_slug
1430
-     * @return bool|int
1431
-     * @throws EE_Error
1432
-     * @throws InvalidArgumentException
1433
-     * @throws InvalidDataTypeException
1434
-     * @throws InvalidInterfaceException
1435
-     * @throws ReflectionException
1436
-     */
1437
-    public function reg_step_completed($reg_step_slug)
1438
-    {
1439
-        return $this->_reg_steps_completed($reg_step_slug, false);
1440
-    }
1441
-
1442
-
1443
-    /**
1444
-     * completed_final_reg_step
1445
-     * returns:
1446
-     *    true if the finalize_registration reg step has been marked as completed
1447
-     *    a Unix timestamp if it has been initialized but not yet completed,
1448
-     *    or false if it has not yet been initialized
1449
-     *
1450
-     * @return bool|int
1451
-     * @throws EE_Error
1452
-     * @throws InvalidArgumentException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws InvalidInterfaceException
1455
-     * @throws ReflectionException
1456
-     */
1457
-    public function final_reg_step_completed()
1458
-    {
1459
-        return $this->_reg_steps_completed('finalize_registration', false);
1460
-    }
1461
-
1462
-
1463
-    /**
1464
-     * set_reg_step_initiated
1465
-     * given a valid TXN_reg_step, this sets it's value to a unix timestamp
1466
-     *
1467
-     * @param string $reg_step_slug
1468
-     * @return boolean
1469
-     * @throws EE_Error
1470
-     * @throws InvalidArgumentException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws InvalidInterfaceException
1473
-     * @throws ReflectionException
1474
-     */
1475
-    public function set_reg_step_initiated($reg_step_slug)
1476
-    {
1477
-        return $this->_set_reg_step_completed_status($reg_step_slug, time());
1478
-    }
1479
-
1480
-
1481
-    /**
1482
-     * set_reg_step_completed
1483
-     * given a valid TXN_reg_step, this sets the step as completed
1484
-     *
1485
-     * @param string $reg_step_slug
1486
-     * @return boolean
1487
-     * @throws EE_Error
1488
-     * @throws InvalidArgumentException
1489
-     * @throws InvalidDataTypeException
1490
-     * @throws InvalidInterfaceException
1491
-     * @throws ReflectionException
1492
-     */
1493
-    public function set_reg_step_completed($reg_step_slug)
1494
-    {
1495
-        return $this->_set_reg_step_completed_status($reg_step_slug, true);
1496
-    }
1497
-
1498
-
1499
-    /**
1500
-     * set_reg_step_completed
1501
-     * given a valid TXN_reg_step slug, this sets the step as NOT completed
1502
-     *
1503
-     * @param string $reg_step_slug
1504
-     * @return boolean
1505
-     * @throws EE_Error
1506
-     * @throws InvalidArgumentException
1507
-     * @throws InvalidDataTypeException
1508
-     * @throws InvalidInterfaceException
1509
-     * @throws ReflectionException
1510
-     */
1511
-    public function set_reg_step_not_completed($reg_step_slug)
1512
-    {
1513
-        return $this->_set_reg_step_completed_status($reg_step_slug, false);
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * set_reg_step_completed
1519
-     * given a valid reg step slug, this sets the TXN_reg_step completed status which is either:
1520
-     *
1521
-     * @param  string      $reg_step_slug
1522
-     * @param  boolean|int $status
1523
-     * @return boolean
1524
-     * @throws EE_Error
1525
-     * @throws InvalidArgumentException
1526
-     * @throws InvalidDataTypeException
1527
-     * @throws InvalidInterfaceException
1528
-     * @throws ReflectionException
1529
-     */
1530
-    private function _set_reg_step_completed_status($reg_step_slug, $status)
1531
-    {
1532
-        // validate status
1533
-        $status = is_bool($status) || is_int($status) ? $status : false;
1534
-        // get reg steps array
1535
-        $txn_reg_steps = $this->reg_steps();
1536
-        // if reg step does NOT exist
1537
-        if (! isset($txn_reg_steps[ $reg_step_slug ])) {
1538
-            return false;
1539
-        }
1540
-        // if  we're trying to complete a step that is already completed
1541
-        if ($txn_reg_steps[ $reg_step_slug ] === true) {
1542
-            return true;
1543
-        }
1544
-        // if  we're trying to complete a step that hasn't even started
1545
-        if ($status === true && $txn_reg_steps[ $reg_step_slug ] === false) {
1546
-            return false;
1547
-        }
1548
-        // if current status value matches the incoming value (no change)
1549
-        // type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1550
-        if ((int) $txn_reg_steps[ $reg_step_slug ] === (int) $status) {
1551
-            // this will happen in cases where multiple AJAX requests occur during the same step
1552
-            return true;
1553
-        }
1554
-        // if we're trying to set a start time, but it has already been set...
1555
-        if (is_numeric($status) && is_numeric($txn_reg_steps[ $reg_step_slug ])) {
1556
-            // skip the update below, but don't return FALSE so that errors won't be displayed
1557
-            return true;
1558
-        }
1559
-        // update completed status
1560
-        $txn_reg_steps[ $reg_step_slug ] = $status;
1561
-        $this->set_reg_steps($txn_reg_steps);
1562
-        $this->save();
1563
-        return true;
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * remove_reg_step
1569
-     * given a valid TXN_reg_step slug, this will remove (unset)
1570
-     * the reg step from the TXN reg step array
1571
-     *
1572
-     * @param string $reg_step_slug
1573
-     * @return void
1574
-     * @throws EE_Error
1575
-     * @throws InvalidArgumentException
1576
-     * @throws InvalidDataTypeException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws ReflectionException
1579
-     */
1580
-    public function remove_reg_step($reg_step_slug)
1581
-    {
1582
-        // get reg steps array
1583
-        $txn_reg_steps = $this->reg_steps();
1584
-        unset($txn_reg_steps[ $reg_step_slug ]);
1585
-        $this->set_reg_steps($txn_reg_steps);
1586
-    }
1587
-
1588
-
1589
-    /**
1590
-     * toggle_failed_transaction_status
1591
-     * upgrades a TXNs status from failed to abandoned,
1592
-     * meaning that contact information has been captured for at least one registrant
1593
-     *
1594
-     * @param bool $save
1595
-     * @return bool
1596
-     * @throws EE_Error
1597
-     * @throws InvalidArgumentException
1598
-     * @throws InvalidDataTypeException
1599
-     * @throws InvalidInterfaceException
1600
-     * @throws ReflectionException
1601
-     */
1602
-    public function toggle_failed_transaction_status($save = true)
1603
-    {
1604
-        // if TXN status is still set as "failed"...
1605
-        if ($this->status_ID() === EEM_Transaction::failed_status_code) {
1606
-            $this->set_status(EEM_Transaction::abandoned_status_code);
1607
-            if ($save) {
1608
-                $this->save();
1609
-            }
1610
-            return true;
1611
-        }
1612
-        return false;
1613
-    }
1614
-
1615
-
1616
-    /**
1617
-     * toggle_abandoned_transaction_status
1618
-     * upgrades a TXNs status from failed or abandoned to incomplete
1619
-     *
1620
-     * @return bool
1621
-     * @throws EE_Error
1622
-     * @throws InvalidArgumentException
1623
-     * @throws InvalidDataTypeException
1624
-     * @throws InvalidInterfaceException
1625
-     * @throws ReflectionException
1626
-     */
1627
-    public function toggle_abandoned_transaction_status()
1628
-    {
1629
-        // if TXN status has not been updated already due to a payment, and is still set as "failed" or "abandoned"...
1630
-        $txn_status = $this->status_ID();
1631
-        if (
1632
-            $txn_status === EEM_Transaction::failed_status_code
1633
-            || $txn_status === EEM_Transaction::abandoned_status_code
1634
-        ) {
1635
-            // if a contact record for the primary registrant has been created
1636
-            if (
1637
-                $this->primary_registration() instanceof EE_Registration
1638
-                && $this->primary_registration()->attendee() instanceof EE_Attendee
1639
-            ) {
1640
-                $this->set_status(EEM_Transaction::incomplete_status_code);
1641
-            } else {
1642
-                // no contact record? yer abandoned!
1643
-                $this->set_status(EEM_Transaction::abandoned_status_code);
1644
-            }
1645
-            return true;
1646
-        }
1647
-        return false;
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * checks if an Abandoned TXN has any related payments, and if so,
1653
-     * updates the TXN status based on the amount paid
1654
-     *
1655
-     * @throws EE_Error
1656
-     * @throws InvalidDataTypeException
1657
-     * @throws InvalidInterfaceException
1658
-     * @throws InvalidArgumentException
1659
-     * @throws RuntimeException
1660
-     * @throws ReflectionException
1661
-     */
1662
-    public function verify_abandoned_transaction_status()
1663
-    {
1664
-        if ($this->status_ID() !== EEM_Transaction::abandoned_status_code) {
1665
-            return;
1666
-        }
1667
-        $payments = $this->get_many_related('Payment');
1668
-        if (! empty($payments)) {
1669
-            foreach ($payments as $payment) {
1670
-                if ($payment instanceof EE_Payment) {
1671
-                    // kk this TXN should NOT be abandoned
1672
-                    $this->update_status_based_on_total_paid();
1673
-                    if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1674
-                        EE_Error::add_attention(
1675
-                            sprintf(
1676
-                                esc_html__(
1677
-                                    'The status for Transaction #%1$d has been updated from "Abandoned" to "%2$s", because at least one payment has been made towards it. If the payment appears in the "Payment Details" table below, you may need to edit its status and/or other details as well.',
1678
-                                    'event_espresso'
1679
-                                ),
1680
-                                $this->ID(),
1681
-                                $this->pretty_status()
1682
-                            )
1683
-                        );
1684
-                    }
1685
-                    // get final reg step status
1686
-                    $finalized = $this->final_reg_step_completed();
1687
-                    // if the 'finalize_registration' step has been initiated (has a timestamp)
1688
-                    // but has not yet been fully completed (TRUE)
1689
-                    if (is_int($finalized) && $finalized !== false && $finalized !== true) {
1690
-                        $this->set_reg_step_completed('finalize_registration');
1691
-                        $this->save();
1692
-                    }
1693
-                }
1694
-            }
1695
-        }
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * @since 4.10.4.p
1701
-     * @throws EE_Error
1702
-     * @throws InvalidArgumentException
1703
-     * @throws InvalidDataTypeException
1704
-     * @throws InvalidInterfaceException
1705
-     * @throws ReflectionException
1706
-     * @throws RuntimeException
1707
-     */
1708
-    public function recalculateLineItems()
1709
-    {
1710
-        $total_line_item = $this->total_line_item(false);
1711
-        if ($total_line_item instanceof EE_Line_Item) {
1712
-            EEH_Line_Item::resetIsTaxableForTickets($total_line_item);
1713
-            return EEH_Line_Item::apply_taxes($total_line_item, true);
1714
-        }
1715
-        return false;
1716
-    }
16
+	/**
17
+	 * The length of time in seconds that a lock is applied before being considered expired.
18
+	 * It is not long because a transaction should only be locked for the duration of the request that locked it
19
+	 */
20
+	const LOCK_EXPIRATION = 2;
21
+
22
+	/**
23
+	 * txn status upon initial construction.
24
+	 *
25
+	 * @var string
26
+	 */
27
+	protected $_old_txn_status;
28
+
29
+
30
+	/**
31
+	 * @param array  $props_n_values          incoming values
32
+	 * @param string $timezone                incoming timezone
33
+	 *                                        (if not set the timezone set for the website will be used.)
34
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
35
+	 *                                        date_format and the second value is the time format
36
+	 * @return EE_Transaction
37
+	 * @throws EE_Error
38
+	 * @throws InvalidArgumentException
39
+	 * @throws InvalidDataTypeException
40
+	 * @throws InvalidInterfaceException
41
+	 * @throws ReflectionException
42
+	 */
43
+	public static function new_instance($props_n_values = array(), $timezone = '', $date_formats = array())
44
+	{
45
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
46
+		$txn = $has_object
47
+			? $has_object
48
+			: new self($props_n_values, false, $timezone, $date_formats);
49
+		if (! $has_object) {
50
+			$txn->set_old_txn_status($txn->status_ID());
51
+		}
52
+		return $txn;
53
+	}
54
+
55
+
56
+	/**
57
+	 * @param array  $props_n_values  incoming values from the database
58
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
59
+	 *                                the website will be used.
60
+	 * @return EE_Transaction
61
+	 * @throws EE_Error
62
+	 * @throws InvalidArgumentException
63
+	 * @throws InvalidDataTypeException
64
+	 * @throws InvalidInterfaceException
65
+	 * @throws ReflectionException
66
+	 */
67
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
68
+	{
69
+		$txn = new self($props_n_values, true, $timezone);
70
+		$txn->set_old_txn_status($txn->status_ID());
71
+		return $txn;
72
+	}
73
+
74
+
75
+	/**
76
+	 * Sets a meta field indicating that this TXN is locked and should not be updated in the db.
77
+	 * If a lock has already been set, then we will attempt to remove it in case it has expired.
78
+	 * If that also fails, then an exception is thrown.
79
+	 *
80
+	 * @throws EE_Error
81
+	 * @throws InvalidArgumentException
82
+	 * @throws InvalidDataTypeException
83
+	 * @throws InvalidInterfaceException
84
+	 * @throws ReflectionException
85
+	 */
86
+	public function lock()
87
+	{
88
+		// attempt to set lock, but if that fails...
89
+		if (! $this->add_extra_meta('lock', time(), true)) {
90
+			// then attempt to remove the lock in case it is expired
91
+			if ($this->_remove_expired_lock()) {
92
+				// if removal was successful, then try setting lock again
93
+				$this->lock();
94
+			} else {
95
+				// but if the lock can not be removed, then throw an exception
96
+				throw new EE_Error(
97
+					sprintf(
98
+						__(
99
+							'Could not lock Transaction %1$d because it is already locked, meaning another part of the system is currently editing it. It should already be unlocked by the time you read this, so please refresh the page and try again.',
100
+							'event_espresso'
101
+						),
102
+						$this->ID()
103
+					)
104
+				);
105
+			}
106
+		}
107
+	}
108
+
109
+
110
+	/**
111
+	 * removes transaction lock applied in EE_Transaction::lock()
112
+	 *
113
+	 * @return int
114
+	 * @throws EE_Error
115
+	 * @throws InvalidArgumentException
116
+	 * @throws InvalidDataTypeException
117
+	 * @throws InvalidInterfaceException
118
+	 * @throws ReflectionException
119
+	 */
120
+	public function unlock()
121
+	{
122
+		return $this->delete_extra_meta('lock');
123
+	}
124
+
125
+
126
+	/**
127
+	 * Decides whether or not now is the right time to update the transaction.
128
+	 * This is useful because we don't always know if it is safe to update the transaction
129
+	 * and its related data. why?
130
+	 * because it's possible that the transaction is being used in another
131
+	 * request and could overwrite anything we save.
132
+	 * So we want to only update the txn once we know that won't happen.
133
+	 * We also check that the lock isn't expired, and remove it if it is
134
+	 *
135
+	 * @return boolean
136
+	 * @throws EE_Error
137
+	 * @throws InvalidArgumentException
138
+	 * @throws InvalidDataTypeException
139
+	 * @throws InvalidInterfaceException
140
+	 * @throws ReflectionException
141
+	 */
142
+	public function is_locked()
143
+	{
144
+		// if TXN is not locked, then return false immediately
145
+		if (! $this->_get_lock()) {
146
+			return false;
147
+		}
148
+		// if not, then let's try and remove the lock in case it's expired...
149
+		// _remove_expired_lock() returns 0 when lock is valid (ie: removed = false)
150
+		// and a positive number if the lock was removed (ie: number of locks deleted),
151
+		// so we need to return the opposite
152
+		return ! $this->_remove_expired_lock() ? true : false;
153
+	}
154
+
155
+
156
+	/**
157
+	 * Gets the meta field indicating that this TXN is locked
158
+	 *
159
+	 * @return int
160
+	 * @throws EE_Error
161
+	 * @throws InvalidArgumentException
162
+	 * @throws InvalidDataTypeException
163
+	 * @throws InvalidInterfaceException
164
+	 * @throws ReflectionException
165
+	 */
166
+	protected function _get_lock()
167
+	{
168
+		return (int) $this->get_extra_meta('lock', true, 0);
169
+	}
170
+
171
+
172
+	/**
173
+	 * If the lock on this transaction is expired, then we want to remove it so that the transaction can be updated
174
+	 *
175
+	 * @return int
176
+	 * @throws EE_Error
177
+	 * @throws InvalidArgumentException
178
+	 * @throws InvalidDataTypeException
179
+	 * @throws InvalidInterfaceException
180
+	 * @throws ReflectionException
181
+	 */
182
+	protected function _remove_expired_lock()
183
+	{
184
+		$locked = $this->_get_lock();
185
+		if ($locked && time() - EE_Transaction::LOCK_EXPIRATION > $locked) {
186
+			return $this->unlock();
187
+		}
188
+		return 0;
189
+	}
190
+
191
+
192
+	/**
193
+	 * Set transaction total
194
+	 *
195
+	 * @param float $total total value of transaction
196
+	 * @throws EE_Error
197
+	 * @throws InvalidArgumentException
198
+	 * @throws InvalidDataTypeException
199
+	 * @throws InvalidInterfaceException
200
+	 * @throws ReflectionException
201
+	 */
202
+	public function set_total($total = 0.00)
203
+	{
204
+		$this->set('TXN_total', (float) $total);
205
+	}
206
+
207
+
208
+	/**
209
+	 * Set Total Amount Paid to Date
210
+	 *
211
+	 * @param float $total_paid total amount paid to date (sum of all payments)
212
+	 * @throws EE_Error
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidDataTypeException
215
+	 * @throws InvalidInterfaceException
216
+	 * @throws ReflectionException
217
+	 */
218
+	public function set_paid($total_paid = 0.00)
219
+	{
220
+		$this->set('TXN_paid', (float) $total_paid);
221
+	}
222
+
223
+
224
+	/**
225
+	 * Set transaction status
226
+	 *
227
+	 * @param string $status        whether the transaction is open, declined, accepted,
228
+	 *                              or any number of custom values that can be set
229
+	 * @throws EE_Error
230
+	 * @throws InvalidArgumentException
231
+	 * @throws InvalidDataTypeException
232
+	 * @throws InvalidInterfaceException
233
+	 * @throws ReflectionException
234
+	 */
235
+	public function set_status($status = '')
236
+	{
237
+		$this->set('STS_ID', $status);
238
+	}
239
+
240
+
241
+	/**
242
+	 * Set hash salt
243
+	 *
244
+	 * @param string $hash_salt required for some payment gateways
245
+	 * @throws EE_Error
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidDataTypeException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws ReflectionException
250
+	 */
251
+	public function set_hash_salt($hash_salt = '')
252
+	{
253
+		$this->set('TXN_hash_salt', $hash_salt);
254
+	}
255
+
256
+
257
+	/**
258
+	 * Sets TXN_reg_steps array
259
+	 *
260
+	 * @param array $txn_reg_steps
261
+	 * @throws EE_Error
262
+	 * @throws InvalidArgumentException
263
+	 * @throws InvalidDataTypeException
264
+	 * @throws InvalidInterfaceException
265
+	 * @throws ReflectionException
266
+	 */
267
+	public function set_reg_steps(array $txn_reg_steps)
268
+	{
269
+		$this->set('TXN_reg_steps', $txn_reg_steps);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Gets TXN_reg_steps
275
+	 *
276
+	 * @return array
277
+	 * @throws EE_Error
278
+	 * @throws InvalidArgumentException
279
+	 * @throws InvalidDataTypeException
280
+	 * @throws InvalidInterfaceException
281
+	 * @throws ReflectionException
282
+	 */
283
+	public function reg_steps()
284
+	{
285
+		$TXN_reg_steps = $this->get('TXN_reg_steps');
286
+		return is_array($TXN_reg_steps) ? (array) $TXN_reg_steps : array();
287
+	}
288
+
289
+
290
+	/**
291
+	 * @return string of transaction's total cost, with currency symbol and decimal
292
+	 * @throws EE_Error
293
+	 * @throws InvalidArgumentException
294
+	 * @throws InvalidDataTypeException
295
+	 * @throws InvalidInterfaceException
296
+	 * @throws ReflectionException
297
+	 */
298
+	public function pretty_total()
299
+	{
300
+		return $this->get_pretty('TXN_total');
301
+	}
302
+
303
+
304
+	/**
305
+	 * Gets the amount paid in a pretty string (formatted and with currency symbol)
306
+	 *
307
+	 * @return string
308
+	 * @throws EE_Error
309
+	 * @throws InvalidArgumentException
310
+	 * @throws InvalidDataTypeException
311
+	 * @throws InvalidInterfaceException
312
+	 * @throws ReflectionException
313
+	 */
314
+	public function pretty_paid()
315
+	{
316
+		return $this->get_pretty('TXN_paid');
317
+	}
318
+
319
+
320
+	/**
321
+	 * calculate the amount remaining for this transaction and return;
322
+	 *
323
+	 * @return float amount remaining
324
+	 * @throws EE_Error
325
+	 * @throws InvalidArgumentException
326
+	 * @throws InvalidDataTypeException
327
+	 * @throws InvalidInterfaceException
328
+	 * @throws ReflectionException
329
+	 */
330
+	public function remaining()
331
+	{
332
+		return $this->total() - $this->paid();
333
+	}
334
+
335
+
336
+	/**
337
+	 * get Transaction Total
338
+	 *
339
+	 * @return float
340
+	 * @throws EE_Error
341
+	 * @throws InvalidArgumentException
342
+	 * @throws InvalidDataTypeException
343
+	 * @throws InvalidInterfaceException
344
+	 * @throws ReflectionException
345
+	 */
346
+	public function total()
347
+	{
348
+		return (float) $this->get('TXN_total');
349
+	}
350
+
351
+
352
+	/**
353
+	 * get Total Amount Paid to Date
354
+	 *
355
+	 * @return float
356
+	 * @throws EE_Error
357
+	 * @throws InvalidArgumentException
358
+	 * @throws InvalidDataTypeException
359
+	 * @throws InvalidInterfaceException
360
+	 * @throws ReflectionException
361
+	 */
362
+	public function paid()
363
+	{
364
+		return (float) $this->get('TXN_paid');
365
+	}
366
+
367
+
368
+	/**
369
+	 * @return mixed|null
370
+	 * @throws EE_Error
371
+	 * @throws InvalidArgumentException
372
+	 * @throws InvalidDataTypeException
373
+	 * @throws InvalidInterfaceException
374
+	 * @throws ReflectionException
375
+	 */
376
+	public function get_cart_session()
377
+	{
378
+		$session_data = (array) $this->get('TXN_session_data');
379
+		return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
380
+			? $session_data['cart']
381
+			: null;
382
+	}
383
+
384
+
385
+	/**
386
+	 * get Transaction session data
387
+	 *
388
+	 * @return array|mixed
389
+	 * @throws EE_Error
390
+	 * @throws InvalidArgumentException
391
+	 * @throws InvalidDataTypeException
392
+	 * @throws InvalidInterfaceException
393
+	 * @throws ReflectionException
394
+	 */
395
+	public function session_data()
396
+	{
397
+		$session_data = $this->get('TXN_session_data');
398
+		if (empty($session_data)) {
399
+			$session_data = array(
400
+				'id'            => null,
401
+				'user_id'       => null,
402
+				'ip_address'    => null,
403
+				'user_agent'    => null,
404
+				'init_access'   => null,
405
+				'last_access'   => null,
406
+				'pages_visited' => array(),
407
+			);
408
+		}
409
+		return $session_data;
410
+	}
411
+
412
+
413
+	/**
414
+	 * Set session data within the TXN object
415
+	 *
416
+	 * @param EE_Session|array $session_data
417
+	 * @throws EE_Error
418
+	 * @throws InvalidArgumentException
419
+	 * @throws InvalidDataTypeException
420
+	 * @throws InvalidInterfaceException
421
+	 * @throws ReflectionException
422
+	 */
423
+	public function set_txn_session_data($session_data)
424
+	{
425
+		if ($session_data instanceof EE_Session) {
426
+			$this->set('TXN_session_data', $session_data->get_session_data(null, true));
427
+		} else {
428
+			$this->set('TXN_session_data', $session_data);
429
+		}
430
+	}
431
+
432
+
433
+	/**
434
+	 * get Transaction hash salt
435
+	 *
436
+	 * @return mixed
437
+	 * @throws EE_Error
438
+	 * @throws InvalidArgumentException
439
+	 * @throws InvalidDataTypeException
440
+	 * @throws InvalidInterfaceException
441
+	 * @throws ReflectionException
442
+	 */
443
+	public function hash_salt_()
444
+	{
445
+		return $this->get('TXN_hash_salt');
446
+	}
447
+
448
+
449
+	/**
450
+	 * Returns the transaction datetime as either:
451
+	 *            - unix timestamp format ($format = false, $gmt = true)
452
+	 *            - formatted date string including the UTC (timezone) offset ($format = true ($gmt
453
+	 *              has no affect with this option)), this also may include a timezone abbreviation if the
454
+	 *              set timezone in this class differs from what the timezone is on the blog.
455
+	 *            - formatted date string including the UTC (timezone) offset (default).
456
+	 *
457
+	 * @param boolean $format   - whether to return a unix timestamp (default) or formatted date string
458
+	 * @param boolean $gmt      - whether to return a unix timestamp with UTC offset applied (default)
459
+	 *                          or no UTC offset applied
460
+	 * @return string | int
461
+	 * @throws EE_Error
462
+	 * @throws InvalidArgumentException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws InvalidInterfaceException
465
+	 * @throws ReflectionException
466
+	 */
467
+	public function datetime($format = false, $gmt = false)
468
+	{
469
+		if ($format) {
470
+			return $this->get_pretty('TXN_timestamp');
471
+		}
472
+		if ($gmt) {
473
+			return $this->get_raw('TXN_timestamp');
474
+		}
475
+		return $this->get('TXN_timestamp');
476
+	}
477
+
478
+
479
+	/**
480
+	 * Gets registrations on this transaction
481
+	 *
482
+	 * @param array   $query_params array of query parameters
483
+	 * @param boolean $get_cached   TRUE to retrieve cached registrations or FALSE to pull from the db
484
+	 * @return EE_Base_Class[]|EE_Registration[]
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 * @throws ReflectionException
490
+	 */
491
+	public function registrations($query_params = array(), $get_cached = false)
492
+	{
493
+		$query_params = (empty($query_params) || ! is_array($query_params))
494
+			? array(
495
+				'order_by' => array(
496
+					'Event.EVT_name'     => 'ASC',
497
+					'Attendee.ATT_lname' => 'ASC',
498
+					'Attendee.ATT_fname' => 'ASC',
499
+				),
500
+			)
501
+			: $query_params;
502
+		$query_params = $get_cached ? array() : $query_params;
503
+		return $this->get_many_related('Registration', $query_params);
504
+	}
505
+
506
+
507
+	/**
508
+	 * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
509
+	 * function for getting attendees and how many registrations they each have for an event)
510
+	 *
511
+	 * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
512
+	 * @throws EE_Error
513
+	 * @throws InvalidArgumentException
514
+	 * @throws InvalidDataTypeException
515
+	 * @throws InvalidInterfaceException
516
+	 * @throws ReflectionException
517
+	 */
518
+	public function attendees()
519
+	{
520
+		return $this->get_many_related('Attendee', array(array('Registration.Transaction.TXN_ID' => $this->ID())));
521
+	}
522
+
523
+
524
+	/**
525
+	 * Gets payments for this transaction. Unlike other such functions, order by 'DESC' by default
526
+	 *
527
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
528
+	 * @return EE_Base_Class[]|EE_Payment[]
529
+	 * @throws EE_Error
530
+	 * @throws InvalidArgumentException
531
+	 * @throws InvalidDataTypeException
532
+	 * @throws InvalidInterfaceException
533
+	 * @throws ReflectionException
534
+	 */
535
+	public function payments($query_params = array())
536
+	{
537
+		return $this->get_many_related('Payment', $query_params);
538
+	}
539
+
540
+
541
+	/**
542
+	 * gets only approved payments for this transaction
543
+	 *
544
+	 * @return EE_Base_Class[]|EE_Payment[]
545
+	 * @throws EE_Error
546
+	 * @throws InvalidArgumentException
547
+	 * @throws ReflectionException
548
+	 * @throws InvalidDataTypeException
549
+	 * @throws InvalidInterfaceException
550
+	 */
551
+	public function approved_payments()
552
+	{
553
+		EE_Registry::instance()->load_model('Payment');
554
+		return $this->get_many_related(
555
+			'Payment',
556
+			array(
557
+				array('STS_ID' => EEM_Payment::status_id_approved),
558
+				'order_by' => array('PAY_timestamp' => 'DESC'),
559
+			)
560
+		);
561
+	}
562
+
563
+
564
+	/**
565
+	 * Gets all payments which have not been approved
566
+	 *
567
+	 * @return EE_Base_Class[]|EEI_Payment[]
568
+	 * @throws EE_Error if a model is misconfigured somehow
569
+	 * @throws InvalidArgumentException
570
+	 * @throws InvalidDataTypeException
571
+	 * @throws InvalidInterfaceException
572
+	 * @throws ReflectionException
573
+	 */
574
+	public function pending_payments()
575
+	{
576
+		return $this->get_many_related(
577
+			'Payment',
578
+			array(
579
+				array(
580
+					'STS_ID' => EEM_Payment::status_id_pending,
581
+				),
582
+				'order_by' => array(
583
+					'PAY_timestamp' => 'DESC',
584
+				),
585
+			)
586
+		);
587
+	}
588
+
589
+
590
+	/**
591
+	 * echoes $this->pretty_status()
592
+	 *
593
+	 * @param bool $show_icons
594
+	 * @throws EE_Error
595
+	 * @throws InvalidArgumentException
596
+	 * @throws InvalidDataTypeException
597
+	 * @throws InvalidInterfaceException
598
+	 * @throws ReflectionException
599
+	 */
600
+	public function e_pretty_status($show_icons = false)
601
+	{
602
+		echo $this->pretty_status($show_icons);
603
+	}
604
+
605
+
606
+	/**
607
+	 * returns a pretty version of the status, good for displaying to users
608
+	 *
609
+	 * @param bool $show_icons
610
+	 * @return string
611
+	 * @throws EE_Error
612
+	 * @throws InvalidArgumentException
613
+	 * @throws InvalidDataTypeException
614
+	 * @throws InvalidInterfaceException
615
+	 * @throws ReflectionException
616
+	 */
617
+	public function pretty_status($show_icons = false)
618
+	{
619
+		$status = EEM_Status::instance()->localized_status(
620
+			array($this->status_ID() => __('unknown', 'event_espresso')),
621
+			false,
622
+			'sentence'
623
+		);
624
+		$icon = '';
625
+		switch ($this->status_ID()) {
626
+			case EEM_Transaction::complete_status_code:
627
+				$icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
628
+				break;
629
+			case EEM_Transaction::incomplete_status_code:
630
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 lt-blue-text"></span>'
631
+					: '';
632
+				break;
633
+			case EEM_Transaction::abandoned_status_code:
634
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 red-text"></span>' : '';
635
+				break;
636
+			case EEM_Transaction::failed_status_code:
637
+				$icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
638
+				break;
639
+			case EEM_Transaction::overpaid_status_code:
640
+				$icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
641
+				break;
642
+		}
643
+		return $icon . $status[ $this->status_ID() ];
644
+	}
645
+
646
+
647
+	/**
648
+	 * get Transaction Status
649
+	 *
650
+	 * @return mixed
651
+	 * @throws EE_Error
652
+	 * @throws InvalidArgumentException
653
+	 * @throws InvalidDataTypeException
654
+	 * @throws InvalidInterfaceException
655
+	 * @throws ReflectionException
656
+	 */
657
+	public function status_ID()
658
+	{
659
+		return $this->get('STS_ID');
660
+	}
661
+
662
+
663
+	/**
664
+	 * Returns TRUE or FALSE for whether or not this transaction cost any money
665
+	 *
666
+	 * @return boolean
667
+	 * @throws EE_Error
668
+	 * @throws InvalidArgumentException
669
+	 * @throws InvalidDataTypeException
670
+	 * @throws InvalidInterfaceException
671
+	 * @throws ReflectionException
672
+	 */
673
+	public function is_free()
674
+	{
675
+		return EEH_Money::compare_floats($this->get('TXN_total'), 0, '==');
676
+	}
677
+
678
+
679
+	/**
680
+	 * Returns whether this transaction is complete
681
+	 * Useful in templates and other logic for deciding if we should ask for another payment...
682
+	 *
683
+	 * @return boolean
684
+	 * @throws EE_Error
685
+	 * @throws InvalidArgumentException
686
+	 * @throws InvalidDataTypeException
687
+	 * @throws InvalidInterfaceException
688
+	 * @throws ReflectionException
689
+	 */
690
+	public function is_completed()
691
+	{
692
+		return $this->status_ID() === EEM_Transaction::complete_status_code;
693
+	}
694
+
695
+
696
+	/**
697
+	 * Returns whether this transaction is incomplete
698
+	 * Useful in templates and other logic for deciding if we should ask for another payment...
699
+	 *
700
+	 * @return boolean
701
+	 * @throws EE_Error
702
+	 * @throws InvalidArgumentException
703
+	 * @throws InvalidDataTypeException
704
+	 * @throws InvalidInterfaceException
705
+	 * @throws ReflectionException
706
+	 */
707
+	public function is_incomplete()
708
+	{
709
+		return $this->status_ID() === EEM_Transaction::incomplete_status_code;
710
+	}
711
+
712
+
713
+	/**
714
+	 * Returns whether this transaction is overpaid
715
+	 * Useful in templates and other logic for deciding if monies need to be refunded
716
+	 *
717
+	 * @return boolean
718
+	 * @throws EE_Error
719
+	 * @throws InvalidArgumentException
720
+	 * @throws InvalidDataTypeException
721
+	 * @throws InvalidInterfaceException
722
+	 * @throws ReflectionException
723
+	 */
724
+	public function is_overpaid()
725
+	{
726
+		return $this->status_ID() === EEM_Transaction::overpaid_status_code;
727
+	}
728
+
729
+
730
+	/**
731
+	 * Returns whether this transaction was abandoned
732
+	 * meaning that the transaction/registration process was somehow interrupted and never completed
733
+	 * but that contact information exists for at least one registrant
734
+	 *
735
+	 * @return boolean
736
+	 * @throws EE_Error
737
+	 * @throws InvalidArgumentException
738
+	 * @throws InvalidDataTypeException
739
+	 * @throws InvalidInterfaceException
740
+	 * @throws ReflectionException
741
+	 */
742
+	public function is_abandoned()
743
+	{
744
+		return $this->status_ID() === EEM_Transaction::abandoned_status_code;
745
+	}
746
+
747
+
748
+	/**
749
+	 * Returns whether this transaction failed
750
+	 * meaning that the transaction/registration process was somehow interrupted and never completed
751
+	 * and that NO contact information exists for any registrants
752
+	 *
753
+	 * @return boolean
754
+	 * @throws EE_Error
755
+	 * @throws InvalidArgumentException
756
+	 * @throws InvalidDataTypeException
757
+	 * @throws InvalidInterfaceException
758
+	 * @throws ReflectionException
759
+	 */
760
+	public function failed()
761
+	{
762
+		return $this->status_ID() === EEM_Transaction::failed_status_code;
763
+	}
764
+
765
+
766
+	/**
767
+	 * This returns the url for the invoice of this transaction
768
+	 *
769
+	 * @param string $type 'html' or 'pdf' (default is pdf)
770
+	 * @return string
771
+	 * @throws EE_Error
772
+	 * @throws InvalidArgumentException
773
+	 * @throws InvalidDataTypeException
774
+	 * @throws InvalidInterfaceException
775
+	 * @throws ReflectionException
776
+	 */
777
+	public function invoice_url($type = 'html')
778
+	{
779
+		$REG = $this->primary_registration();
780
+		if (! $REG instanceof EE_Registration) {
781
+			return '';
782
+		}
783
+		return $REG->invoice_url($type);
784
+	}
785
+
786
+
787
+	/**
788
+	 * Gets the primary registration only
789
+	 *
790
+	 * @return EE_Base_Class|EE_Registration
791
+	 * @throws EE_Error
792
+	 * @throws InvalidArgumentException
793
+	 * @throws InvalidDataTypeException
794
+	 * @throws InvalidInterfaceException
795
+	 * @throws ReflectionException
796
+	 */
797
+	public function primary_registration()
798
+	{
799
+		$registrations = (array) $this->get_many_related(
800
+			'Registration',
801
+			array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
802
+		);
803
+		foreach ($registrations as $registration) {
804
+			// valid registration that is NOT cancelled or declined ?
805
+			if (
806
+				$registration instanceof EE_Registration
807
+				&& ! in_array($registration->status_ID(), EEM_Registration::closed_reg_statuses(), true)
808
+			) {
809
+				return $registration;
810
+			}
811
+		}
812
+		// nothing valid found, so just return first thing from array of results
813
+		return reset($registrations);
814
+	}
815
+
816
+
817
+	/**
818
+	 * Gets the URL for viewing the receipt
819
+	 *
820
+	 * @param string $type 'pdf' or 'html' (default is 'html')
821
+	 * @return string
822
+	 * @throws EE_Error
823
+	 * @throws InvalidArgumentException
824
+	 * @throws InvalidDataTypeException
825
+	 * @throws InvalidInterfaceException
826
+	 * @throws ReflectionException
827
+	 */
828
+	public function receipt_url($type = 'html')
829
+	{
830
+		$REG = $this->primary_registration();
831
+		if (! $REG instanceof EE_Registration) {
832
+			return '';
833
+		}
834
+		return $REG->receipt_url($type);
835
+	}
836
+
837
+
838
+	/**
839
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
840
+	 * a query parameter
841
+	 *
842
+	 * @return string
843
+	 * @throws EE_Error
844
+	 * @throws InvalidArgumentException
845
+	 * @throws InvalidDataTypeException
846
+	 * @throws InvalidInterfaceException
847
+	 * @throws ReflectionException
848
+	 */
849
+	public function payment_overview_url()
850
+	{
851
+		$primary_registration = $this->primary_registration();
852
+		return $primary_registration instanceof EE_Registration ? $primary_registration->payment_overview_url() : false;
853
+	}
854
+
855
+
856
+	/**
857
+	 * @return string
858
+	 * @throws EE_Error
859
+	 * @throws InvalidArgumentException
860
+	 * @throws InvalidDataTypeException
861
+	 * @throws InvalidInterfaceException
862
+	 * @throws ReflectionException
863
+	 */
864
+	public function gateway_response_on_transaction()
865
+	{
866
+		$payment = $this->get_first_related('Payment');
867
+		return $payment instanceof EE_Payment ? $payment->gateway_response() : '';
868
+	}
869
+
870
+
871
+	/**
872
+	 * Get the status object of this object
873
+	 *
874
+	 * @return EE_Base_Class|EE_Status
875
+	 * @throws EE_Error
876
+	 * @throws InvalidArgumentException
877
+	 * @throws InvalidDataTypeException
878
+	 * @throws InvalidInterfaceException
879
+	 * @throws ReflectionException
880
+	 */
881
+	public function status_obj()
882
+	{
883
+		return $this->get_first_related('Status');
884
+	}
885
+
886
+
887
+	/**
888
+	 * Gets all the extra meta info on this payment
889
+	 *
890
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
891
+	 * @return EE_Base_Class[]|EE_Extra_Meta
892
+	 * @throws EE_Error
893
+	 * @throws InvalidArgumentException
894
+	 * @throws InvalidDataTypeException
895
+	 * @throws InvalidInterfaceException
896
+	 * @throws ReflectionException
897
+	 */
898
+	public function extra_meta($query_params = array())
899
+	{
900
+		return $this->get_many_related('Extra_Meta', $query_params);
901
+	}
902
+
903
+
904
+	/**
905
+	 * Wrapper for _add_relation_to
906
+	 *
907
+	 * @param EE_Registration $registration
908
+	 * @return EE_Base_Class the relation was added to
909
+	 * @throws EE_Error
910
+	 * @throws InvalidArgumentException
911
+	 * @throws InvalidDataTypeException
912
+	 * @throws InvalidInterfaceException
913
+	 * @throws ReflectionException
914
+	 */
915
+	public function add_registration(EE_Registration $registration)
916
+	{
917
+		return $this->_add_relation_to($registration, 'Registration');
918
+	}
919
+
920
+
921
+	/**
922
+	 * Removes the given registration from being related (even before saving this transaction).
923
+	 * If an ID/index is provided and this transaction isn't saved yet, removes it from list of cached relations
924
+	 *
925
+	 * @param int $registration_or_id
926
+	 * @return EE_Base_Class that was removed from being related
927
+	 * @throws EE_Error
928
+	 * @throws InvalidArgumentException
929
+	 * @throws InvalidDataTypeException
930
+	 * @throws InvalidInterfaceException
931
+	 * @throws ReflectionException
932
+	 */
933
+	public function remove_registration_with_id($registration_or_id)
934
+	{
935
+		return $this->_remove_relation_to($registration_or_id, 'Registration');
936
+	}
937
+
938
+
939
+	/**
940
+	 * Gets all the line items which are for ACTUAL items
941
+	 *
942
+	 * @return EE_Line_Item[]
943
+	 * @throws EE_Error
944
+	 * @throws InvalidArgumentException
945
+	 * @throws InvalidDataTypeException
946
+	 * @throws InvalidInterfaceException
947
+	 * @throws ReflectionException
948
+	 */
949
+	public function items_purchased()
950
+	{
951
+		return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_line_item)));
952
+	}
953
+
954
+
955
+	/**
956
+	 * Wrapper for _add_relation_to
957
+	 *
958
+	 * @param EE_Line_Item $line_item
959
+	 * @return EE_Base_Class the relation was added to
960
+	 * @throws EE_Error
961
+	 * @throws InvalidArgumentException
962
+	 * @throws InvalidDataTypeException
963
+	 * @throws InvalidInterfaceException
964
+	 * @throws ReflectionException
965
+	 */
966
+	public function add_line_item(EE_Line_Item $line_item)
967
+	{
968
+		return $this->_add_relation_to($line_item, 'Line_Item');
969
+	}
970
+
971
+
972
+	/**
973
+	 * Gets ALL the line items related to this transaction (unstructured)
974
+	 *
975
+	 * @param array $query_params
976
+	 * @return EE_Base_Class[]|EE_Line_Item[]
977
+	 * @throws EE_Error
978
+	 * @throws InvalidArgumentException
979
+	 * @throws InvalidDataTypeException
980
+	 * @throws InvalidInterfaceException
981
+	 * @throws ReflectionException
982
+	 */
983
+	public function line_items($query_params = array())
984
+	{
985
+		return $this->get_many_related('Line_Item', $query_params);
986
+	}
987
+
988
+
989
+	/**
990
+	 * Gets all the line items which are taxes on the total
991
+	 *
992
+	 * @return EE_Line_Item[]
993
+	 * @throws EE_Error
994
+	 * @throws InvalidArgumentException
995
+	 * @throws InvalidDataTypeException
996
+	 * @throws InvalidInterfaceException
997
+	 * @throws ReflectionException
998
+	 */
999
+	public function tax_items()
1000
+	{
1001
+		return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Gets the total line item (which is a parent of all other related line items,
1007
+	 * meaning it takes them all into account on its total)
1008
+	 *
1009
+	 * @param bool $create_if_not_found
1010
+	 * @return \EE_Line_Item
1011
+	 * @throws EE_Error
1012
+	 * @throws InvalidArgumentException
1013
+	 * @throws InvalidDataTypeException
1014
+	 * @throws InvalidInterfaceException
1015
+	 * @throws ReflectionException
1016
+	 */
1017
+	public function total_line_item($create_if_not_found = true)
1018
+	{
1019
+		$item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
1020
+		if (! $item && $create_if_not_found) {
1021
+			$item = EEH_Line_Item::create_total_line_item($this);
1022
+		}
1023
+		return $item;
1024
+	}
1025
+
1026
+
1027
+	/**
1028
+	 * Returns the total amount of tax on this transaction
1029
+	 * (assumes there's only one tax subtotal line item)
1030
+	 *
1031
+	 * @return float
1032
+	 * @throws EE_Error
1033
+	 * @throws InvalidArgumentException
1034
+	 * @throws InvalidDataTypeException
1035
+	 * @throws InvalidInterfaceException
1036
+	 * @throws ReflectionException
1037
+	 */
1038
+	public function tax_total()
1039
+	{
1040
+		$tax_line_item = $this->tax_total_line_item();
1041
+		if ($tax_line_item) {
1042
+			return (float) $tax_line_item->total();
1043
+		}
1044
+		return (float) 0;
1045
+	}
1046
+
1047
+
1048
+	/**
1049
+	 * Gets the tax subtotal line item (assumes there's only one)
1050
+	 *
1051
+	 * @return EE_Line_Item
1052
+	 * @throws EE_Error
1053
+	 * @throws InvalidArgumentException
1054
+	 * @throws InvalidDataTypeException
1055
+	 * @throws InvalidInterfaceException
1056
+	 * @throws ReflectionException
1057
+	 */
1058
+	public function tax_total_line_item()
1059
+	{
1060
+		return EEH_Line_Item::get_taxes_subtotal($this->total_line_item());
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * Gets the array of billing info for the gateway and for this transaction's primary registration's attendee.
1066
+	 *
1067
+	 * @return EE_Form_Section_Proper
1068
+	 * @throws EE_Error
1069
+	 * @throws InvalidArgumentException
1070
+	 * @throws InvalidDataTypeException
1071
+	 * @throws InvalidInterfaceException
1072
+	 * @throws ReflectionException
1073
+	 */
1074
+	public function billing_info()
1075
+	{
1076
+		$payment_method = $this->payment_method();
1077
+		if (! $payment_method) {
1078
+			EE_Error::add_error(
1079
+				__(
1080
+					'Could not find billing info for transaction because no gateway has been used for it yet',
1081
+					'event_espresso'
1082
+				),
1083
+				__FILE__,
1084
+				__FUNCTION__,
1085
+				__LINE__
1086
+			);
1087
+			return null;
1088
+		}
1089
+		$primary_reg = $this->primary_registration();
1090
+		if (! $primary_reg) {
1091
+			EE_Error::add_error(
1092
+				__(
1093
+					'Cannot get billing info for gateway %s on transaction because no primary registration exists',
1094
+					'event_espresso'
1095
+				),
1096
+				__FILE__,
1097
+				__FUNCTION__,
1098
+				__LINE__
1099
+			);
1100
+			return null;
1101
+		}
1102
+		$attendee = $primary_reg->attendee();
1103
+		if (! $attendee) {
1104
+			EE_Error::add_error(
1105
+				__(
1106
+					'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
1107
+					'event_espresso'
1108
+				),
1109
+				__FILE__,
1110
+				__FUNCTION__,
1111
+				__LINE__
1112
+			);
1113
+			return null;
1114
+		}
1115
+		return $attendee->billing_info_for_payment_method($payment_method);
1116
+	}
1117
+
1118
+
1119
+	/**
1120
+	 * Gets PMD_ID
1121
+	 *
1122
+	 * @return int
1123
+	 * @throws EE_Error
1124
+	 * @throws InvalidArgumentException
1125
+	 * @throws InvalidDataTypeException
1126
+	 * @throws InvalidInterfaceException
1127
+	 * @throws ReflectionException
1128
+	 */
1129
+	public function payment_method_ID()
1130
+	{
1131
+		return $this->get('PMD_ID');
1132
+	}
1133
+
1134
+
1135
+	/**
1136
+	 * Sets PMD_ID
1137
+	 *
1138
+	 * @param int $PMD_ID
1139
+	 * @throws EE_Error
1140
+	 * @throws InvalidArgumentException
1141
+	 * @throws InvalidDataTypeException
1142
+	 * @throws InvalidInterfaceException
1143
+	 * @throws ReflectionException
1144
+	 */
1145
+	public function set_payment_method_ID($PMD_ID)
1146
+	{
1147
+		$this->set('PMD_ID', $PMD_ID);
1148
+	}
1149
+
1150
+
1151
+	/**
1152
+	 * Gets the last-used payment method on this transaction
1153
+	 * (we COULD just use the last-made payment, but some payment methods, namely
1154
+	 * offline ones, dont' create payments)
1155
+	 *
1156
+	 * @return EE_Payment_Method
1157
+	 * @throws EE_Error
1158
+	 * @throws InvalidArgumentException
1159
+	 * @throws InvalidDataTypeException
1160
+	 * @throws InvalidInterfaceException
1161
+	 * @throws ReflectionException
1162
+	 */
1163
+	public function payment_method()
1164
+	{
1165
+		$pm = $this->get_first_related('Payment_Method');
1166
+		if ($pm instanceof EE_Payment_Method) {
1167
+			return $pm;
1168
+		}
1169
+		$last_payment = $this->last_payment();
1170
+		if ($last_payment instanceof EE_Payment && $last_payment->payment_method()) {
1171
+			return $last_payment->payment_method();
1172
+		}
1173
+		return null;
1174
+	}
1175
+
1176
+
1177
+	/**
1178
+	 * Gets the last payment made
1179
+	 *
1180
+	 * @return EE_Base_Class|EE_Payment
1181
+	 * @throws EE_Error
1182
+	 * @throws InvalidArgumentException
1183
+	 * @throws InvalidDataTypeException
1184
+	 * @throws InvalidInterfaceException
1185
+	 * @throws ReflectionException
1186
+	 */
1187
+	public function last_payment()
1188
+	{
1189
+		return $this->get_first_related('Payment', array('order_by' => array('PAY_ID' => 'desc')));
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * Gets all the line items which are unrelated to tickets on this transaction
1195
+	 *
1196
+	 * @return EE_Line_Item[]
1197
+	 * @throws EE_Error
1198
+	 * @throws InvalidArgumentException
1199
+	 * @throws InvalidDataTypeException
1200
+	 * @throws InvalidInterfaceException
1201
+	 * @throws ReflectionException
1202
+	 */
1203
+	public function non_ticket_line_items()
1204
+	{
1205
+		return EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction($this->ID());
1206
+	}
1207
+
1208
+
1209
+	/**
1210
+	 * possibly toggles TXN status
1211
+	 *
1212
+	 * @param  boolean $update whether to save the TXN
1213
+	 * @return bool whether the TXN was saved
1214
+	 * @throws EE_Error
1215
+	 * @throws InvalidArgumentException
1216
+	 * @throws InvalidDataTypeException
1217
+	 * @throws InvalidInterfaceException
1218
+	 * @throws ReflectionException
1219
+	 * @throws RuntimeException
1220
+	 */
1221
+	public function update_status_based_on_total_paid($update = true)
1222
+	{
1223
+		// set transaction status based on comparison of TXN_paid vs TXN_total
1224
+		if (EEH_Money::compare_floats($this->paid(), $this->total(), '>')) {
1225
+			$new_txn_status = EEM_Transaction::overpaid_status_code;
1226
+		} elseif (EEH_Money::compare_floats($this->paid(), $this->total())) {
1227
+			$new_txn_status = EEM_Transaction::complete_status_code;
1228
+		} elseif (EEH_Money::compare_floats($this->paid(), $this->total(), '<')) {
1229
+			$new_txn_status = EEM_Transaction::incomplete_status_code;
1230
+		} else {
1231
+			throw new RuntimeException(
1232
+				__('The total paid calculation for this transaction is inaccurate.', 'event_espresso')
1233
+			);
1234
+		}
1235
+		if ($new_txn_status !== $this->status_ID()) {
1236
+			$this->set_status($new_txn_status);
1237
+			if ($update) {
1238
+				return $this->save() ? true : false;
1239
+			}
1240
+		}
1241
+		return false;
1242
+	}
1243
+
1244
+
1245
+	/**
1246
+	 * Updates the transaction's status and total_paid based on all the payments
1247
+	 * that apply to it
1248
+	 *
1249
+	 * @deprecated
1250
+	 * @return array|bool
1251
+	 * @throws EE_Error
1252
+	 * @throws InvalidArgumentException
1253
+	 * @throws ReflectionException
1254
+	 * @throws InvalidDataTypeException
1255
+	 * @throws InvalidInterfaceException
1256
+	 */
1257
+	public function update_based_on_payments()
1258
+	{
1259
+		EE_Error::doing_it_wrong(
1260
+			__CLASS__ . '::' . __FUNCTION__,
1261
+			sprintf(
1262
+				__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1263
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
1264
+			),
1265
+			'4.6.0'
1266
+		);
1267
+		/** @type EE_Transaction_Processor $transaction_processor */
1268
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1269
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($this);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * @return string
1275
+	 */
1276
+	public function old_txn_status()
1277
+	{
1278
+		return $this->_old_txn_status;
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * @param string $old_txn_status
1284
+	 */
1285
+	public function set_old_txn_status($old_txn_status)
1286
+	{
1287
+		// only set the first time
1288
+		if ($this->_old_txn_status === null) {
1289
+			$this->_old_txn_status = $old_txn_status;
1290
+		}
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 * reg_status_updated
1296
+	 *
1297
+	 * @return bool
1298
+	 * @throws EE_Error
1299
+	 * @throws InvalidArgumentException
1300
+	 * @throws InvalidDataTypeException
1301
+	 * @throws InvalidInterfaceException
1302
+	 * @throws ReflectionException
1303
+	 */
1304
+	public function txn_status_updated()
1305
+	{
1306
+		return $this->status_ID() !== $this->_old_txn_status && $this->_old_txn_status !== null;
1307
+	}
1308
+
1309
+
1310
+	/**
1311
+	 * _reg_steps_completed
1312
+	 * if $check_all is TRUE, then returns TRUE if ALL reg steps have been marked as completed,
1313
+	 * if a $reg_step_slug is provided, then this step will be skipped when testing for completion
1314
+	 * if $check_all is FALSE and a $reg_step_slug is provided, then ONLY that reg step will be tested for completion
1315
+	 *
1316
+	 * @param string $reg_step_slug
1317
+	 * @param bool   $check_all
1318
+	 * @return bool|int
1319
+	 * @throws EE_Error
1320
+	 * @throws InvalidArgumentException
1321
+	 * @throws InvalidDataTypeException
1322
+	 * @throws InvalidInterfaceException
1323
+	 * @throws ReflectionException
1324
+	 */
1325
+	private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1326
+	{
1327
+		$reg_steps = $this->reg_steps();
1328
+		if (! is_array($reg_steps) || empty($reg_steps)) {
1329
+			return false;
1330
+		}
1331
+		// loop thru reg steps array)
1332
+		foreach ($reg_steps as $slug => $reg_step_completed) {
1333
+			// if NOT checking ALL steps (only checking one step)
1334
+			if (! $check_all) {
1335
+				// and this is the one
1336
+				if ($slug === $reg_step_slug) {
1337
+					return $reg_step_completed;
1338
+				}
1339
+				// skip to next reg step in loop
1340
+				continue;
1341
+			}
1342
+			// $check_all must be true, else we would never have gotten to this point
1343
+			if ($slug === $reg_step_slug) {
1344
+				// if we reach this point, then we are testing either:
1345
+				// all_reg_steps_completed_except() or
1346
+				// all_reg_steps_completed_except_final_step(),
1347
+				// and since this is the reg step EXCEPTION being tested
1348
+				// we want to return true (yes true) if this reg step is NOT completed
1349
+				// ie: "is everything completed except the final step?"
1350
+				// "that is correct... the final step is not completed, but all others are."
1351
+				return $reg_step_completed !== true;
1352
+			}
1353
+			if ($reg_step_completed !== true) {
1354
+				// if any reg step is NOT completed, then ALL steps are not completed
1355
+				return false;
1356
+			}
1357
+		}
1358
+		return true;
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * all_reg_steps_completed
1364
+	 * returns:
1365
+	 *    true if ALL reg steps have been marked as completed
1366
+	 *        or false if any step is not completed
1367
+	 *
1368
+	 * @return bool
1369
+	 * @throws EE_Error
1370
+	 * @throws InvalidArgumentException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws InvalidInterfaceException
1373
+	 * @throws ReflectionException
1374
+	 */
1375
+	public function all_reg_steps_completed()
1376
+	{
1377
+		return $this->_reg_steps_completed();
1378
+	}
1379
+
1380
+
1381
+	/**
1382
+	 * all_reg_steps_completed_except
1383
+	 * returns:
1384
+	 *        true if ALL reg steps, except a particular step that you wish to skip over, have been marked as completed
1385
+	 *        or false if any other step is not completed
1386
+	 *        or false if ALL steps are completed including the exception you are testing !!!
1387
+	 *
1388
+	 * @param string $exception
1389
+	 * @return bool
1390
+	 * @throws EE_Error
1391
+	 * @throws InvalidArgumentException
1392
+	 * @throws InvalidDataTypeException
1393
+	 * @throws InvalidInterfaceException
1394
+	 * @throws ReflectionException
1395
+	 */
1396
+	public function all_reg_steps_completed_except($exception = '')
1397
+	{
1398
+		return $this->_reg_steps_completed($exception);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * all_reg_steps_completed_except
1404
+	 * returns:
1405
+	 *        true if ALL reg steps, except the final step, have been marked as completed
1406
+	 *        or false if any step is not completed
1407
+	 *    or false if ALL steps are completed including the final step !!!
1408
+	 *
1409
+	 * @return bool
1410
+	 * @throws EE_Error
1411
+	 * @throws InvalidArgumentException
1412
+	 * @throws InvalidDataTypeException
1413
+	 * @throws InvalidInterfaceException
1414
+	 * @throws ReflectionException
1415
+	 */
1416
+	public function all_reg_steps_completed_except_final_step()
1417
+	{
1418
+		return $this->_reg_steps_completed('finalize_registration');
1419
+	}
1420
+
1421
+
1422
+	/**
1423
+	 * reg_step_completed
1424
+	 * returns:
1425
+	 *    true if a specific reg step has been marked as completed
1426
+	 *    a Unix timestamp if it has been initialized but not yet completed,
1427
+	 *    or false if it has not yet been initialized
1428
+	 *
1429
+	 * @param string $reg_step_slug
1430
+	 * @return bool|int
1431
+	 * @throws EE_Error
1432
+	 * @throws InvalidArgumentException
1433
+	 * @throws InvalidDataTypeException
1434
+	 * @throws InvalidInterfaceException
1435
+	 * @throws ReflectionException
1436
+	 */
1437
+	public function reg_step_completed($reg_step_slug)
1438
+	{
1439
+		return $this->_reg_steps_completed($reg_step_slug, false);
1440
+	}
1441
+
1442
+
1443
+	/**
1444
+	 * completed_final_reg_step
1445
+	 * returns:
1446
+	 *    true if the finalize_registration reg step has been marked as completed
1447
+	 *    a Unix timestamp if it has been initialized but not yet completed,
1448
+	 *    or false if it has not yet been initialized
1449
+	 *
1450
+	 * @return bool|int
1451
+	 * @throws EE_Error
1452
+	 * @throws InvalidArgumentException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws InvalidInterfaceException
1455
+	 * @throws ReflectionException
1456
+	 */
1457
+	public function final_reg_step_completed()
1458
+	{
1459
+		return $this->_reg_steps_completed('finalize_registration', false);
1460
+	}
1461
+
1462
+
1463
+	/**
1464
+	 * set_reg_step_initiated
1465
+	 * given a valid TXN_reg_step, this sets it's value to a unix timestamp
1466
+	 *
1467
+	 * @param string $reg_step_slug
1468
+	 * @return boolean
1469
+	 * @throws EE_Error
1470
+	 * @throws InvalidArgumentException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws InvalidInterfaceException
1473
+	 * @throws ReflectionException
1474
+	 */
1475
+	public function set_reg_step_initiated($reg_step_slug)
1476
+	{
1477
+		return $this->_set_reg_step_completed_status($reg_step_slug, time());
1478
+	}
1479
+
1480
+
1481
+	/**
1482
+	 * set_reg_step_completed
1483
+	 * given a valid TXN_reg_step, this sets the step as completed
1484
+	 *
1485
+	 * @param string $reg_step_slug
1486
+	 * @return boolean
1487
+	 * @throws EE_Error
1488
+	 * @throws InvalidArgumentException
1489
+	 * @throws InvalidDataTypeException
1490
+	 * @throws InvalidInterfaceException
1491
+	 * @throws ReflectionException
1492
+	 */
1493
+	public function set_reg_step_completed($reg_step_slug)
1494
+	{
1495
+		return $this->_set_reg_step_completed_status($reg_step_slug, true);
1496
+	}
1497
+
1498
+
1499
+	/**
1500
+	 * set_reg_step_completed
1501
+	 * given a valid TXN_reg_step slug, this sets the step as NOT completed
1502
+	 *
1503
+	 * @param string $reg_step_slug
1504
+	 * @return boolean
1505
+	 * @throws EE_Error
1506
+	 * @throws InvalidArgumentException
1507
+	 * @throws InvalidDataTypeException
1508
+	 * @throws InvalidInterfaceException
1509
+	 * @throws ReflectionException
1510
+	 */
1511
+	public function set_reg_step_not_completed($reg_step_slug)
1512
+	{
1513
+		return $this->_set_reg_step_completed_status($reg_step_slug, false);
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * set_reg_step_completed
1519
+	 * given a valid reg step slug, this sets the TXN_reg_step completed status which is either:
1520
+	 *
1521
+	 * @param  string      $reg_step_slug
1522
+	 * @param  boolean|int $status
1523
+	 * @return boolean
1524
+	 * @throws EE_Error
1525
+	 * @throws InvalidArgumentException
1526
+	 * @throws InvalidDataTypeException
1527
+	 * @throws InvalidInterfaceException
1528
+	 * @throws ReflectionException
1529
+	 */
1530
+	private function _set_reg_step_completed_status($reg_step_slug, $status)
1531
+	{
1532
+		// validate status
1533
+		$status = is_bool($status) || is_int($status) ? $status : false;
1534
+		// get reg steps array
1535
+		$txn_reg_steps = $this->reg_steps();
1536
+		// if reg step does NOT exist
1537
+		if (! isset($txn_reg_steps[ $reg_step_slug ])) {
1538
+			return false;
1539
+		}
1540
+		// if  we're trying to complete a step that is already completed
1541
+		if ($txn_reg_steps[ $reg_step_slug ] === true) {
1542
+			return true;
1543
+		}
1544
+		// if  we're trying to complete a step that hasn't even started
1545
+		if ($status === true && $txn_reg_steps[ $reg_step_slug ] === false) {
1546
+			return false;
1547
+		}
1548
+		// if current status value matches the incoming value (no change)
1549
+		// type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1550
+		if ((int) $txn_reg_steps[ $reg_step_slug ] === (int) $status) {
1551
+			// this will happen in cases where multiple AJAX requests occur during the same step
1552
+			return true;
1553
+		}
1554
+		// if we're trying to set a start time, but it has already been set...
1555
+		if (is_numeric($status) && is_numeric($txn_reg_steps[ $reg_step_slug ])) {
1556
+			// skip the update below, but don't return FALSE so that errors won't be displayed
1557
+			return true;
1558
+		}
1559
+		// update completed status
1560
+		$txn_reg_steps[ $reg_step_slug ] = $status;
1561
+		$this->set_reg_steps($txn_reg_steps);
1562
+		$this->save();
1563
+		return true;
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * remove_reg_step
1569
+	 * given a valid TXN_reg_step slug, this will remove (unset)
1570
+	 * the reg step from the TXN reg step array
1571
+	 *
1572
+	 * @param string $reg_step_slug
1573
+	 * @return void
1574
+	 * @throws EE_Error
1575
+	 * @throws InvalidArgumentException
1576
+	 * @throws InvalidDataTypeException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws ReflectionException
1579
+	 */
1580
+	public function remove_reg_step($reg_step_slug)
1581
+	{
1582
+		// get reg steps array
1583
+		$txn_reg_steps = $this->reg_steps();
1584
+		unset($txn_reg_steps[ $reg_step_slug ]);
1585
+		$this->set_reg_steps($txn_reg_steps);
1586
+	}
1587
+
1588
+
1589
+	/**
1590
+	 * toggle_failed_transaction_status
1591
+	 * upgrades a TXNs status from failed to abandoned,
1592
+	 * meaning that contact information has been captured for at least one registrant
1593
+	 *
1594
+	 * @param bool $save
1595
+	 * @return bool
1596
+	 * @throws EE_Error
1597
+	 * @throws InvalidArgumentException
1598
+	 * @throws InvalidDataTypeException
1599
+	 * @throws InvalidInterfaceException
1600
+	 * @throws ReflectionException
1601
+	 */
1602
+	public function toggle_failed_transaction_status($save = true)
1603
+	{
1604
+		// if TXN status is still set as "failed"...
1605
+		if ($this->status_ID() === EEM_Transaction::failed_status_code) {
1606
+			$this->set_status(EEM_Transaction::abandoned_status_code);
1607
+			if ($save) {
1608
+				$this->save();
1609
+			}
1610
+			return true;
1611
+		}
1612
+		return false;
1613
+	}
1614
+
1615
+
1616
+	/**
1617
+	 * toggle_abandoned_transaction_status
1618
+	 * upgrades a TXNs status from failed or abandoned to incomplete
1619
+	 *
1620
+	 * @return bool
1621
+	 * @throws EE_Error
1622
+	 * @throws InvalidArgumentException
1623
+	 * @throws InvalidDataTypeException
1624
+	 * @throws InvalidInterfaceException
1625
+	 * @throws ReflectionException
1626
+	 */
1627
+	public function toggle_abandoned_transaction_status()
1628
+	{
1629
+		// if TXN status has not been updated already due to a payment, and is still set as "failed" or "abandoned"...
1630
+		$txn_status = $this->status_ID();
1631
+		if (
1632
+			$txn_status === EEM_Transaction::failed_status_code
1633
+			|| $txn_status === EEM_Transaction::abandoned_status_code
1634
+		) {
1635
+			// if a contact record for the primary registrant has been created
1636
+			if (
1637
+				$this->primary_registration() instanceof EE_Registration
1638
+				&& $this->primary_registration()->attendee() instanceof EE_Attendee
1639
+			) {
1640
+				$this->set_status(EEM_Transaction::incomplete_status_code);
1641
+			} else {
1642
+				// no contact record? yer abandoned!
1643
+				$this->set_status(EEM_Transaction::abandoned_status_code);
1644
+			}
1645
+			return true;
1646
+		}
1647
+		return false;
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * checks if an Abandoned TXN has any related payments, and if so,
1653
+	 * updates the TXN status based on the amount paid
1654
+	 *
1655
+	 * @throws EE_Error
1656
+	 * @throws InvalidDataTypeException
1657
+	 * @throws InvalidInterfaceException
1658
+	 * @throws InvalidArgumentException
1659
+	 * @throws RuntimeException
1660
+	 * @throws ReflectionException
1661
+	 */
1662
+	public function verify_abandoned_transaction_status()
1663
+	{
1664
+		if ($this->status_ID() !== EEM_Transaction::abandoned_status_code) {
1665
+			return;
1666
+		}
1667
+		$payments = $this->get_many_related('Payment');
1668
+		if (! empty($payments)) {
1669
+			foreach ($payments as $payment) {
1670
+				if ($payment instanceof EE_Payment) {
1671
+					// kk this TXN should NOT be abandoned
1672
+					$this->update_status_based_on_total_paid();
1673
+					if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1674
+						EE_Error::add_attention(
1675
+							sprintf(
1676
+								esc_html__(
1677
+									'The status for Transaction #%1$d has been updated from "Abandoned" to "%2$s", because at least one payment has been made towards it. If the payment appears in the "Payment Details" table below, you may need to edit its status and/or other details as well.',
1678
+									'event_espresso'
1679
+								),
1680
+								$this->ID(),
1681
+								$this->pretty_status()
1682
+							)
1683
+						);
1684
+					}
1685
+					// get final reg step status
1686
+					$finalized = $this->final_reg_step_completed();
1687
+					// if the 'finalize_registration' step has been initiated (has a timestamp)
1688
+					// but has not yet been fully completed (TRUE)
1689
+					if (is_int($finalized) && $finalized !== false && $finalized !== true) {
1690
+						$this->set_reg_step_completed('finalize_registration');
1691
+						$this->save();
1692
+					}
1693
+				}
1694
+			}
1695
+		}
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * @since 4.10.4.p
1701
+	 * @throws EE_Error
1702
+	 * @throws InvalidArgumentException
1703
+	 * @throws InvalidDataTypeException
1704
+	 * @throws InvalidInterfaceException
1705
+	 * @throws ReflectionException
1706
+	 * @throws RuntimeException
1707
+	 */
1708
+	public function recalculateLineItems()
1709
+	{
1710
+		$total_line_item = $this->total_line_item(false);
1711
+		if ($total_line_item instanceof EE_Line_Item) {
1712
+			EEH_Line_Item::resetIsTaxableForTickets($total_line_item);
1713
+			return EEH_Line_Item::apply_taxes($total_line_item, true);
1714
+		}
1715
+		return false;
1716
+	}
1717 1717
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Question_Group.class.php 1 patch
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -12,280 +12,280 @@
 block discarded – undo
12 12
 class EE_Question_Group extends EE_Soft_Delete_Base_Class
13 13
 {
14 14
 
15
-    /**
16
-     * @param array $props_n_values
17
-     * @return EE_Question_Group|mixed
18
-     */
19
-    public static function new_instance($props_n_values = array())
20
-    {
21
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
22
-        return $has_object ? $has_object : new self($props_n_values);
23
-    }
24
-
25
-
26
-    /**
27
-     * @param array $props_n_values
28
-     * @return EE_Question_Group
29
-     */
30
-    public static function new_instance_from_db($props_n_values = array())
31
-    {
32
-        return new self($props_n_values, true);
33
-    }
34
-
35
-
36
-    /**
37
-     * gets the question group's name
38
-     *
39
-     * @access public
40
-     * @param bool $pretty
41
-     * @return string
42
-     */
43
-    public function name($pretty = false)
44
-    {
45
-        return $pretty ? $this->get_pretty('QSG_name') : $this->get('QSG_name');
46
-    }
47
-
48
-
49
-    /**
50
-     * Gets the question group's internal name
51
-     *
52
-     * @access public
53
-     * @return string
54
-     */
55
-    public function identifier()
56
-    {
57
-        return $this->get('QSG_identifier');
58
-    }
59
-
60
-
61
-    /**
62
-     * Gets the question group's description
63
-     *
64
-     * @access public
65
-     * @param bool $pretty
66
-     * @return string
67
-     */
68
-    public function desc($pretty = false)
69
-    {
70
-        return $pretty ? $this->get_pretty('QSG_desc') : $this->get('QSG_desc');
71
-    }
72
-
73
-
74
-    /**
75
-     * Gets the question group's order number in a sequence
76
-     * of other question groups
77
-     *
78
-     * @access public
79
-     * @return int
80
-     */
81
-    public function order()
82
-    {
83
-        return $this->get('QSG_order');
84
-    }
85
-
86
-
87
-    /**
88
-     * Returns whether to show the group's name on the frontend
89
-     *
90
-     * @access public
91
-     * @return boolean
92
-     */
93
-    public function show_group_name()
94
-    {
95
-        return $this->get('QSG_show_group_name');
96
-    }
97
-
98
-
99
-    /**
100
-     * Returns whether to show the group's description
101
-     * on the frontend
102
-     *
103
-     * @access public
104
-     * @return boolean
105
-     */
106
-    public function show_group_desc()
107
-    {
108
-        return $this->get('QSG_show_group_desc');
109
-    }
110
-
111
-
112
-    /**
113
-     * Returns whether this is a 'system group' (meaning
114
-     * a question group integral to the system, whose questions
115
-     * relate to the attendee table)
116
-     *
117
-     * @access public
118
-     * @return int
119
-     */
120
-    public function system_group()
121
-    {
122
-        return $this->get('QSG_system');
123
-    }
124
-
125
-
126
-    /**
127
-     * get the author of the question group.
128
-     *
129
-     * @since 4.5.0
130
-     *
131
-     * @return int
132
-     */
133
-    public function wp_user()
134
-    {
135
-        return $this->get('QSG_wp_user');
136
-    }
137
-
138
-
139
-    /**
140
-     * Returns whether this question group has
141
-     * been deleted
142
-     *
143
-     * @access public
144
-     * @return boolean
145
-     */
146
-    public function deleted()
147
-    {
148
-        return $this->get('QST_deleted');
149
-    }
150
-
151
-
152
-    /**
153
-     * Gets an array of questions with questions IN the group at the start of the array and questions NOT in the group
154
-     * at the end of the array.  Questions in the group are ordered by Question_Group_Question.QGQ_order and questions
155
-     * NOT in the group are ordered by Question.QGQ_order
156
-     *
157
-     * @return EE_Question[]
158
-     */
159
-    public function questions_in_and_not_in_group()
160
-    {
161
-        $questions_in_group = $this->questions();
162
-        $exclude_question_ids = ! empty($questions_in_group) ? array_keys($questions_in_group) : array();
163
-        $questions_not_in_group = $this->questions_not_in_group($exclude_question_ids);
164
-        return $questions_in_group + $questions_not_in_group;
165
-    }
166
-
167
-
168
-    /**
169
-     * Gets all the questions which are part of this question group (ordered Question_Group_Question.QGQ_order)
170
-     *
171
-     * @param array $query_params
172
-     * @return EE_Question[]
173
-     */
174
-    public function questions($query_params = array())
175
-    {
176
-        $query_params = ! empty($query_params) ? $query_params
177
-            : array('order_by' => array('Question_Group_Question.QGQ_order' => 'ASC'));
178
-        return $this->ID() ? $this->get_many_related('Question', $query_params) : array();
179
-    }
180
-
181
-
182
-    /**
183
-     * Gets all the questions which are NOT part of this question group.
184
-     *
185
-     * @param  mixed $question_IDS_in_group if empty array then all questions returned.  if FALSE then we first get
186
-     *                                      questions in this group and exclude them from questions get all. IF empty
187
-     *                                      array then we just return all questions.
188
-     * @return EE_Question[]
189
-     */
190
-    public function questions_not_in_group($question_IDS_in_group = false)
191
-    {
192
-        if ($question_IDS_in_group === false) {
193
-            $questions = $this->questions();
194
-            $question_IDS_in_group = ! empty($questions) ? array_keys($questions) : array();
195
-        }
196
-        $_where = ! empty($question_IDS_in_group) ? array('QST_ID' => array('not_in', $question_IDS_in_group))
197
-            : array();
198
-
199
-        return EEM_Question::instance()->get_all(array($_where, 'order_by' => array('QST_ID' => 'ASC')));
200
-    }
201
-
202
-
203
-    /**
204
-     * Gets all events which are related to this question group
205
-     *
206
-     * @return EE_Event[]
207
-     */
208
-    public function events()
209
-    {
210
-        return $this->get_many_related('Event');
211
-    }
212
-
213
-
214
-    /**
215
-     * Adds the question to this question group
216
-     *
217
-     * @param EE_Question || int $question object or ID
218
-     * @return boolean if successful
219
-     */
220
-    public function add_question($questionObjectOrID)
221
-    {
222
-        return $this->_add_relation_to($questionObjectOrID, 'Question');
223
-    }
224
-
225
-
226
-    /**
227
-     * Removes the question from this question group
228
-     *
229
-     * @param EE_Question || int $question object or ID
230
-     * @return boolean of success
231
-     */
232
-    public function remove_question($questionObjectOrID)
233
-    {
234
-        return $this->_remove_relation_to($questionObjectOrID, 'Question');
235
-    }
236
-
237
-
238
-    /**
239
-     * @param $questionObjectOrID
240
-     * @param $qst_order
241
-     * @return int
242
-     */
243
-    public function update_question_order($questionObjectOrID, $qst_order)
244
-    {
245
-        $qst_ID = $questionObjectOrID instanceof EE_Question ? $questionObjectOrID->ID() : (int) $questionObjectOrID;
246
-        return EEM_Question_Group_Question::instance()->update(
247
-            array('QGQ_order' => $qst_order),
248
-            array(
249
-                array(
250
-                    'QST_ID' => $qst_ID,
251
-                    'QSG_ID' => $this->ID(),
252
-                ),
253
-            )
254
-        );
255
-    }
256
-
257
-
258
-    /**
259
-     * Basically this is method just returns whether the question group has any questions with answers.  This is used
260
-     * by the admin currently to determine whether we should display the ui for deleting permanently or not b/c
261
-     * question groups with questions that have answers should not be possible to delete permanently
262
-     *
263
-     * @return boolean true if has questions with answers, false if not.
264
-     */
265
-    public function has_questions_with_answers()
266
-    {
267
-        $has_answers = false;
268
-        $questions = $this->get_many_related('Question');
269
-        foreach ($questions as $question) {
270
-            if ($question->count_related('Answer') > 0) {
271
-                $has_answers = true;
272
-            }
273
-        }
274
-        return $has_answers;
275
-    }
276
-
277
-
278
-    /**
279
-     * The purpose of this method is set the question group order for this question group to be the max out of all
280
-     * question groups
281
-     *
282
-     * @access public
283
-     * @return void
284
-     */
285
-    public function set_order_to_latest()
286
-    {
287
-        $latest_order = $this->get_model()->get_latest_question_group_order();
288
-        $latest_order++;
289
-        $this->set('QSG_order', $latest_order);
290
-    }
15
+	/**
16
+	 * @param array $props_n_values
17
+	 * @return EE_Question_Group|mixed
18
+	 */
19
+	public static function new_instance($props_n_values = array())
20
+	{
21
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
22
+		return $has_object ? $has_object : new self($props_n_values);
23
+	}
24
+
25
+
26
+	/**
27
+	 * @param array $props_n_values
28
+	 * @return EE_Question_Group
29
+	 */
30
+	public static function new_instance_from_db($props_n_values = array())
31
+	{
32
+		return new self($props_n_values, true);
33
+	}
34
+
35
+
36
+	/**
37
+	 * gets the question group's name
38
+	 *
39
+	 * @access public
40
+	 * @param bool $pretty
41
+	 * @return string
42
+	 */
43
+	public function name($pretty = false)
44
+	{
45
+		return $pretty ? $this->get_pretty('QSG_name') : $this->get('QSG_name');
46
+	}
47
+
48
+
49
+	/**
50
+	 * Gets the question group's internal name
51
+	 *
52
+	 * @access public
53
+	 * @return string
54
+	 */
55
+	public function identifier()
56
+	{
57
+		return $this->get('QSG_identifier');
58
+	}
59
+
60
+
61
+	/**
62
+	 * Gets the question group's description
63
+	 *
64
+	 * @access public
65
+	 * @param bool $pretty
66
+	 * @return string
67
+	 */
68
+	public function desc($pretty = false)
69
+	{
70
+		return $pretty ? $this->get_pretty('QSG_desc') : $this->get('QSG_desc');
71
+	}
72
+
73
+
74
+	/**
75
+	 * Gets the question group's order number in a sequence
76
+	 * of other question groups
77
+	 *
78
+	 * @access public
79
+	 * @return int
80
+	 */
81
+	public function order()
82
+	{
83
+		return $this->get('QSG_order');
84
+	}
85
+
86
+
87
+	/**
88
+	 * Returns whether to show the group's name on the frontend
89
+	 *
90
+	 * @access public
91
+	 * @return boolean
92
+	 */
93
+	public function show_group_name()
94
+	{
95
+		return $this->get('QSG_show_group_name');
96
+	}
97
+
98
+
99
+	/**
100
+	 * Returns whether to show the group's description
101
+	 * on the frontend
102
+	 *
103
+	 * @access public
104
+	 * @return boolean
105
+	 */
106
+	public function show_group_desc()
107
+	{
108
+		return $this->get('QSG_show_group_desc');
109
+	}
110
+
111
+
112
+	/**
113
+	 * Returns whether this is a 'system group' (meaning
114
+	 * a question group integral to the system, whose questions
115
+	 * relate to the attendee table)
116
+	 *
117
+	 * @access public
118
+	 * @return int
119
+	 */
120
+	public function system_group()
121
+	{
122
+		return $this->get('QSG_system');
123
+	}
124
+
125
+
126
+	/**
127
+	 * get the author of the question group.
128
+	 *
129
+	 * @since 4.5.0
130
+	 *
131
+	 * @return int
132
+	 */
133
+	public function wp_user()
134
+	{
135
+		return $this->get('QSG_wp_user');
136
+	}
137
+
138
+
139
+	/**
140
+	 * Returns whether this question group has
141
+	 * been deleted
142
+	 *
143
+	 * @access public
144
+	 * @return boolean
145
+	 */
146
+	public function deleted()
147
+	{
148
+		return $this->get('QST_deleted');
149
+	}
150
+
151
+
152
+	/**
153
+	 * Gets an array of questions with questions IN the group at the start of the array and questions NOT in the group
154
+	 * at the end of the array.  Questions in the group are ordered by Question_Group_Question.QGQ_order and questions
155
+	 * NOT in the group are ordered by Question.QGQ_order
156
+	 *
157
+	 * @return EE_Question[]
158
+	 */
159
+	public function questions_in_and_not_in_group()
160
+	{
161
+		$questions_in_group = $this->questions();
162
+		$exclude_question_ids = ! empty($questions_in_group) ? array_keys($questions_in_group) : array();
163
+		$questions_not_in_group = $this->questions_not_in_group($exclude_question_ids);
164
+		return $questions_in_group + $questions_not_in_group;
165
+	}
166
+
167
+
168
+	/**
169
+	 * Gets all the questions which are part of this question group (ordered Question_Group_Question.QGQ_order)
170
+	 *
171
+	 * @param array $query_params
172
+	 * @return EE_Question[]
173
+	 */
174
+	public function questions($query_params = array())
175
+	{
176
+		$query_params = ! empty($query_params) ? $query_params
177
+			: array('order_by' => array('Question_Group_Question.QGQ_order' => 'ASC'));
178
+		return $this->ID() ? $this->get_many_related('Question', $query_params) : array();
179
+	}
180
+
181
+
182
+	/**
183
+	 * Gets all the questions which are NOT part of this question group.
184
+	 *
185
+	 * @param  mixed $question_IDS_in_group if empty array then all questions returned.  if FALSE then we first get
186
+	 *                                      questions in this group and exclude them from questions get all. IF empty
187
+	 *                                      array then we just return all questions.
188
+	 * @return EE_Question[]
189
+	 */
190
+	public function questions_not_in_group($question_IDS_in_group = false)
191
+	{
192
+		if ($question_IDS_in_group === false) {
193
+			$questions = $this->questions();
194
+			$question_IDS_in_group = ! empty($questions) ? array_keys($questions) : array();
195
+		}
196
+		$_where = ! empty($question_IDS_in_group) ? array('QST_ID' => array('not_in', $question_IDS_in_group))
197
+			: array();
198
+
199
+		return EEM_Question::instance()->get_all(array($_where, 'order_by' => array('QST_ID' => 'ASC')));
200
+	}
201
+
202
+
203
+	/**
204
+	 * Gets all events which are related to this question group
205
+	 *
206
+	 * @return EE_Event[]
207
+	 */
208
+	public function events()
209
+	{
210
+		return $this->get_many_related('Event');
211
+	}
212
+
213
+
214
+	/**
215
+	 * Adds the question to this question group
216
+	 *
217
+	 * @param EE_Question || int $question object or ID
218
+	 * @return boolean if successful
219
+	 */
220
+	public function add_question($questionObjectOrID)
221
+	{
222
+		return $this->_add_relation_to($questionObjectOrID, 'Question');
223
+	}
224
+
225
+
226
+	/**
227
+	 * Removes the question from this question group
228
+	 *
229
+	 * @param EE_Question || int $question object or ID
230
+	 * @return boolean of success
231
+	 */
232
+	public function remove_question($questionObjectOrID)
233
+	{
234
+		return $this->_remove_relation_to($questionObjectOrID, 'Question');
235
+	}
236
+
237
+
238
+	/**
239
+	 * @param $questionObjectOrID
240
+	 * @param $qst_order
241
+	 * @return int
242
+	 */
243
+	public function update_question_order($questionObjectOrID, $qst_order)
244
+	{
245
+		$qst_ID = $questionObjectOrID instanceof EE_Question ? $questionObjectOrID->ID() : (int) $questionObjectOrID;
246
+		return EEM_Question_Group_Question::instance()->update(
247
+			array('QGQ_order' => $qst_order),
248
+			array(
249
+				array(
250
+					'QST_ID' => $qst_ID,
251
+					'QSG_ID' => $this->ID(),
252
+				),
253
+			)
254
+		);
255
+	}
256
+
257
+
258
+	/**
259
+	 * Basically this is method just returns whether the question group has any questions with answers.  This is used
260
+	 * by the admin currently to determine whether we should display the ui for deleting permanently or not b/c
261
+	 * question groups with questions that have answers should not be possible to delete permanently
262
+	 *
263
+	 * @return boolean true if has questions with answers, false if not.
264
+	 */
265
+	public function has_questions_with_answers()
266
+	{
267
+		$has_answers = false;
268
+		$questions = $this->get_many_related('Question');
269
+		foreach ($questions as $question) {
270
+			if ($question->count_related('Answer') > 0) {
271
+				$has_answers = true;
272
+			}
273
+		}
274
+		return $has_answers;
275
+	}
276
+
277
+
278
+	/**
279
+	 * The purpose of this method is set the question group order for this question group to be the max out of all
280
+	 * question groups
281
+	 *
282
+	 * @access public
283
+	 * @return void
284
+	 */
285
+	public function set_order_to_latest()
286
+	{
287
+		$latest_order = $this->get_model()->get_latest_question_group_order();
288
+		$latest_order++;
289
+		$this->set('QSG_order', $latest_order);
290
+	}
291 291
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Payment_Method.class.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -389,11 +389,11 @@  discard block
 block discarded – undo
389 389
      */
390 390
     public function type_obj()
391 391
     {
392
-        if (! $this->_type_obj) {
392
+        if ( ! $this->_type_obj) {
393 393
             EE_Registry::instance()->load_lib('Payment_Method_Manager');
394 394
             if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($this->type())) {
395 395
                 $class_name = EE_Payment_Method_Manager::instance()->payment_method_class_from_type($this->type());
396
-                if (! class_exists($class_name)) {
396
+                if ( ! class_exists($class_name)) {
397 397
                     throw new EE_Error(
398 398
                         sprintf(
399 399
                             __(
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
                             ),
403 403
                             $class_name,
404 404
                             '<br />',
405
-                            '<a href="' . admin_url('plugins.php') . '">',
405
+                            '<a href="'.admin_url('plugins.php').'">',
406 406
                             '</a>'
407 407
                         )
408 408
                     );
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
         foreach ($fields as $key => $value) {
442 442
             if (strpos($key, 'PMD_') === 0) {
443 443
                 $key_sans_model_prefix = str_replace('PMD_', '', $key);
444
-                $combined_settings_array [ $key_sans_model_prefix ] = $value;
444
+                $combined_settings_array [$key_sans_model_prefix] = $value;
445 445
             }
446 446
         }
447 447
         $combined_settings_array = array_merge($extra_meta, $combined_settings_array);
@@ -464,14 +464,14 @@  discard block
 block discarded – undo
464 464
 		 <div id="'
465 465
                . $this->slug()
466 466
                . '-payment-option-dv" class="'
467
-               . $payment_occurs . '-payment-gateway reg-page-payment-option-dv' . $css_class . '">
467
+               . $payment_occurs.'-payment-gateway reg-page-payment-option-dv'.$css_class.'">
468 468
 			<a id="payment-gateway-button-' . $this->slug()
469 469
                . '" class="reg-page-payment-option-lnk" rel="'
470
-               . $this->slug() . '" href="' . $url . '" >
471
-				<img src="' . $this->button_url() . '" alt="' . sprintf(
470
+               . $this->slug().'" href="'.$url.'" >
471
+				<img src="' . $this->button_url().'" alt="'.sprintf(
472 472
                    esc_attr__('Pay using %s', 'event_espresso'),
473 473
                    $this->get_pretty('PMD_name', 'form_input')
474
-               ) . '" />
474
+               ).'" />
475 475
 			</a>
476 476
 		</div>
477 477
 ';
Please login to merge, or discard this patch.
Indentation   +570 added lines, -570 removed lines patch added patch discarded remove patch
@@ -11,580 +11,580 @@
 block discarded – undo
11 11
 class EE_Payment_Method extends EE_Base_Class
12 12
 {
13 13
 
14
-    /**
15
-     * Payment Method type object, which has all the info about this type of payment method,
16
-     * including functions for processing payments, to get settings forms, etc.
17
-     *
18
-     * @var EE_PMT_Base
19
-     */
20
-    protected $_type_obj;
21
-
22
-
23
-    /**
24
-     * @param array $props_n_values
25
-     * @return EE_Payment_Method
26
-     * @throws \EE_Error
27
-     */
28
-    public static function new_instance($props_n_values = array())
29
-    {
30
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
31
-        return $has_object ? $has_object : new self($props_n_values, false);
32
-    }
33
-
34
-
35
-    /**
36
-     * @param array $props_n_values
37
-     * @return EE_Payment_Method
38
-     * @throws \EE_Error
39
-     */
40
-    public static function new_instance_from_db($props_n_values = array())
41
-    {
42
-        return new self($props_n_values, true);
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * Checks if there is a payment method class of the given 'PMD_type', and if so returns the classname.
49
-     * Otherwise returns a normal EE_Payment_Method
50
-     *
51
-     * @param array $props_n_values where 'PMD_type' is a gateway name like 'Paypal_Standard','Invoice',etc (basically
52
-     *                              the classname minus 'EEPM_')
53
-     * @return string
54
-     */
55
-    // private static function _payment_method_type($props_n_values)
56
-    // {
57
-    //     EE_Registry::instance()->load_lib('Payment_Method_Manager');
58
-    //     $type_string = isset($props_n_values['PMD_type']) ? $props_n_values['PMD_type'] : null;
59
-    //     if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($type_string)) {
60
-    //         return 'EEPM_' . $type_string;
61
-    //     } else {
62
-    //         return __CLASS__;
63
-    //     }
64
-    // }
65
-
66
-
67
-    /**
68
-     * Gets whether this payment method can be used anywhere at all (ie frontend cart, admin, etc)
69
-     *
70
-     * @return boolean
71
-     */
72
-    public function active()
73
-    {
74
-        return array_intersect(array_keys(EEM_Payment_Method::instance()->scopes()), $this->scope());
75
-    }
76
-
77
-
78
-    /**
79
-     * Sets this PM as active by making it usable within the CART scope. Offline gateways
80
-     * are also usable from the admin-scope as well. DOES NOT SAVE it
81
-     *
82
-     * @throws \EE_Error
83
-     */
84
-    public function set_active()
85
-    {
86
-        $default_scopes = array(EEM_Payment_Method::scope_cart);
87
-        if (
88
-            $this->type_obj() &&
89
-            $this->type_obj()->payment_occurs() === EE_PMT_Base::offline
90
-        ) {
91
-            $default_scopes[] = EEM_Payment_Method::scope_admin;
92
-        }
93
-        $this->set_scope($default_scopes);
94
-    }
95
-
96
-
97
-    /**
98
-     * Makes this payment method apply to NO scopes at all. DOES NOT SAVE it.
99
-     */
100
-    public function deactivate()
101
-    {
102
-        $this->set_scope(array());
103
-    }
104
-
105
-
106
-    /**
107
-     * Gets button_url
108
-     *
109
-     * @return string
110
-     */
111
-    public function button_url()
112
-    {
113
-        return $this->get('PMD_button_url');
114
-    }
115
-
116
-
117
-    /**
118
-     * Sets button_url
119
-     *
120
-     * @param string $button_url
121
-     */
122
-    public function set_button_url($button_url)
123
-    {
124
-        $this->set('PMD_button_url', $button_url);
125
-    }
126
-
127
-
128
-    /**
129
-     * Gets debug_mode
130
-     *
131
-     * @return boolean
132
-     */
133
-    public function debug_mode()
134
-    {
135
-        return $this->get('PMD_debug_mode');
136
-    }
137
-
138
-
139
-    /**
140
-     * Sets debug_mode
141
-     *
142
-     * @param boolean $debug_mode
143
-     */
144
-    public function set_debug_mode($debug_mode)
145
-    {
146
-        $this->set('PMD_debug_mode', $debug_mode);
147
-    }
148
-
149
-
150
-    /**
151
-     * Gets description
152
-     *
153
-     * @return string
154
-     */
155
-    public function description()
156
-    {
157
-        return $this->get('PMD_desc');
158
-    }
159
-
160
-
161
-    /**
162
-     * Sets description
163
-     *
164
-     * @param string $description
165
-     */
166
-    public function set_description($description)
167
-    {
168
-        $this->set('PMD_desc', $description);
169
-    }
170
-
171
-
172
-    /**
173
-     * Gets name
174
-     *
175
-     * @return string
176
-     */
177
-    public function name()
178
-    {
179
-        return $this->get('PMD_name');
180
-    }
181
-
182
-
183
-    /**
184
-     * Sets name
185
-     *
186
-     * @param string $name
187
-     */
188
-    public function set_name($name)
189
-    {
190
-        $this->set('PMD_name', $name);
191
-    }
192
-
193
-
194
-    /**
195
-     * Gets open_by_default
196
-     *
197
-     * @return boolean
198
-     */
199
-    public function open_by_default()
200
-    {
201
-        return $this->get('PMD_open_by_default');
202
-    }
203
-
204
-
205
-    /**
206
-     * Sets open_by_default
207
-     *
208
-     * @param boolean $open_by_default
209
-     */
210
-    public function set_open_by_default($open_by_default)
211
-    {
212
-        $this->set('PMD_open_by_default', $open_by_default);
213
-    }
214
-
215
-
216
-    /**
217
-     * Gets order
218
-     *
219
-     * @return int
220
-     */
221
-    public function order()
222
-    {
223
-        return $this->get('PMD_order');
224
-    }
225
-
226
-
227
-    /**
228
-     * Sets order
229
-     *
230
-     * @param int $order
231
-     */
232
-    public function set_order($order)
233
-    {
234
-        $this->set('PMD_order', $order);
235
-    }
236
-
237
-
238
-    /**
239
-     * Gets slug
240
-     *
241
-     * @return string
242
-     */
243
-    public function slug()
244
-    {
245
-        return $this->get('PMD_slug');
246
-    }
247
-
248
-
249
-    /**
250
-     * Sets slug
251
-     *
252
-     * @param string $slug
253
-     */
254
-    public function set_slug($slug)
255
-    {
256
-        $this->set('PMD_slug', $slug);
257
-    }
258
-
259
-
260
-    /**
261
-     * Gets type
262
-     *
263
-     * @return string
264
-     */
265
-    public function type()
266
-    {
267
-        return $this->get('PMD_type');
268
-    }
269
-
270
-
271
-    /**
272
-     * Sets type
273
-     *
274
-     * @param string $type
275
-     */
276
-    public function set_type($type)
277
-    {
278
-        $this->set('PMD_type', $type);
279
-    }
280
-
281
-
282
-    /**
283
-     * Gets wp_user
284
-     *
285
-     * @return int
286
-     */
287
-    public function wp_user()
288
-    {
289
-        return $this->get('PMD_wp_user');
290
-    }
291
-
292
-
293
-    /**
294
-     * Sets wp_user
295
-     *
296
-     * @param int $wp_user_id
297
-     */
298
-    public function set_wp_user($wp_user_id)
299
-    {
300
-        $this->set('PMD_wp_user', $wp_user_id);
301
-    }
302
-
303
-    /**
304
-     * Overrides parent so when PMD_type is changed we refresh the _type_obj
305
-     *
306
-     * @param string  $field_name
307
-     * @param mixed   $field_value
308
-     * @param boolean $use_default
309
-     */
310
-    public function set($field_name, $field_value, bool $use_default = false)
311
-    {
312
-        if ($field_name === 'PMD_type') {
313
-            // the type has probably changed, so forget about its old type object
314
-            $this->_type_obj = null;
315
-        }
316
-        parent::set($field_name, $field_value, $use_default);
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets admin_name
322
-     *
323
-     * @return string
324
-     */
325
-    public function admin_name()
326
-    {
327
-        return $this->get('PMD_admin_name');
328
-    }
329
-
330
-
331
-    /**
332
-     * Sets admin_name
333
-     *
334
-     * @param string $admin_name
335
-     */
336
-    public function set_admin_name($admin_name)
337
-    {
338
-        $this->set('PMD_admin_name', $admin_name);
339
-    }
340
-
341
-
342
-    /**
343
-     * Gets admin_desc
344
-     *
345
-     * @return string
346
-     */
347
-    public function admin_desc()
348
-    {
349
-        return $this->get('PMD_admin_desc');
350
-    }
351
-
352
-
353
-    /**
354
-     * Sets admin_desc
355
-     *
356
-     * @param string $admin_desc
357
-     */
358
-    public function set_admin_desc($admin_desc)
359
-    {
360
-        $this->set('PMD_admin_desc', $admin_desc);
361
-    }
362
-
363
-
364
-    /**
365
-     * Gets scope
366
-     *
367
-     * @return array
368
-     */
369
-    public function scope()
370
-    {
371
-        return $this->get('PMD_scope');
372
-    }
373
-
374
-
375
-    /**
376
-     * Sets scope
377
-     *
378
-     * @param array $scope
379
-     */
380
-    public function set_scope($scope)
381
-    {
382
-        $this->set('PMD_scope', $scope);
383
-    }
384
-
385
-
386
-    /**
387
-     * Gets the payment method type for this payment method instance
388
-     *
389
-     * @return EE_PMT_Base
390
-     * @throws EE_Error
391
-     */
392
-    public function type_obj()
393
-    {
394
-        if (! $this->_type_obj) {
395
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
396
-            if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($this->type())) {
397
-                $class_name = EE_Payment_Method_Manager::instance()->payment_method_class_from_type($this->type());
398
-                if (! class_exists($class_name)) {
399
-                    throw new EE_Error(
400
-                        sprintf(
401
-                            __(
402
-                                'An attempt to use the "%1$s" payment method failed, so it was deactivated.%2$sWas the "%1$s" Plugin recently deactivated? It can be reactivated on the %3$sPlugins Admin Page%4$s',
403
-                                'event_espresso'
404
-                            ),
405
-                            $class_name,
406
-                            '<br />',
407
-                            '<a href="' . admin_url('plugins.php') . '">',
408
-                            '</a>'
409
-                        )
410
-                    );
411
-                }
412
-                $r = new ReflectionClass($class_name);
413
-                $this->_type_obj = $r->newInstanceArgs(array($this));
414
-            } else {
415
-                throw new EE_Error(
416
-                    sprintf(
417
-                        __(
418
-                            'A payment method of type "%1$s" does not exist. Only ones existing are: %2$s',
419
-                            'event_espresso'
420
-                        ),
421
-                        $this->type(),
422
-                        implode(',', EE_Payment_Method_Manager::instance()->payment_method_type_names())
423
-                    )
424
-                );
425
-            }
426
-        }
427
-        return $this->_type_obj;
428
-    }
429
-
430
-
431
-    /**
432
-     * Returns a simple array of key-value pairs combining the payment method's fields (without the 'PMD_' prefix)
433
-     * and the extra meta. Mostly used for passing off ot gateways.     *
434
-     *
435
-     * @return array
436
-     */
437
-    public function settings_array()
438
-    {
439
-        $fields = $this->model_field_array();
440
-        $extra_meta = $this->all_extra_meta_array();
441
-        // remove the model's prefix from the fields
442
-        $combined_settings_array = array();
443
-        foreach ($fields as $key => $value) {
444
-            if (strpos($key, 'PMD_') === 0) {
445
-                $key_sans_model_prefix = str_replace('PMD_', '', $key);
446
-                $combined_settings_array [ $key_sans_model_prefix ] = $value;
447
-            }
448
-        }
449
-        $combined_settings_array = array_merge($extra_meta, $combined_settings_array);
450
-        return $combined_settings_array;
451
-    }
452
-
453
-
454
-    /**
455
-     * Gets the HTML for displaying the payment method on a page.
456
-     *
457
-     * @param string $url
458
-     * @param string $css_class
459
-     * @return string of HTML for displaying the button
460
-     * @throws \EE_Error
461
-     */
462
-    public function button_html($url = '', $css_class = '')
463
-    {
464
-        $payment_occurs = $this->type_obj()->payment_occurs();
465
-        return '
14
+	/**
15
+	 * Payment Method type object, which has all the info about this type of payment method,
16
+	 * including functions for processing payments, to get settings forms, etc.
17
+	 *
18
+	 * @var EE_PMT_Base
19
+	 */
20
+	protected $_type_obj;
21
+
22
+
23
+	/**
24
+	 * @param array $props_n_values
25
+	 * @return EE_Payment_Method
26
+	 * @throws \EE_Error
27
+	 */
28
+	public static function new_instance($props_n_values = array())
29
+	{
30
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
31
+		return $has_object ? $has_object : new self($props_n_values, false);
32
+	}
33
+
34
+
35
+	/**
36
+	 * @param array $props_n_values
37
+	 * @return EE_Payment_Method
38
+	 * @throws \EE_Error
39
+	 */
40
+	public static function new_instance_from_db($props_n_values = array())
41
+	{
42
+		return new self($props_n_values, true);
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * Checks if there is a payment method class of the given 'PMD_type', and if so returns the classname.
49
+	 * Otherwise returns a normal EE_Payment_Method
50
+	 *
51
+	 * @param array $props_n_values where 'PMD_type' is a gateway name like 'Paypal_Standard','Invoice',etc (basically
52
+	 *                              the classname minus 'EEPM_')
53
+	 * @return string
54
+	 */
55
+	// private static function _payment_method_type($props_n_values)
56
+	// {
57
+	//     EE_Registry::instance()->load_lib('Payment_Method_Manager');
58
+	//     $type_string = isset($props_n_values['PMD_type']) ? $props_n_values['PMD_type'] : null;
59
+	//     if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($type_string)) {
60
+	//         return 'EEPM_' . $type_string;
61
+	//     } else {
62
+	//         return __CLASS__;
63
+	//     }
64
+	// }
65
+
66
+
67
+	/**
68
+	 * Gets whether this payment method can be used anywhere at all (ie frontend cart, admin, etc)
69
+	 *
70
+	 * @return boolean
71
+	 */
72
+	public function active()
73
+	{
74
+		return array_intersect(array_keys(EEM_Payment_Method::instance()->scopes()), $this->scope());
75
+	}
76
+
77
+
78
+	/**
79
+	 * Sets this PM as active by making it usable within the CART scope. Offline gateways
80
+	 * are also usable from the admin-scope as well. DOES NOT SAVE it
81
+	 *
82
+	 * @throws \EE_Error
83
+	 */
84
+	public function set_active()
85
+	{
86
+		$default_scopes = array(EEM_Payment_Method::scope_cart);
87
+		if (
88
+			$this->type_obj() &&
89
+			$this->type_obj()->payment_occurs() === EE_PMT_Base::offline
90
+		) {
91
+			$default_scopes[] = EEM_Payment_Method::scope_admin;
92
+		}
93
+		$this->set_scope($default_scopes);
94
+	}
95
+
96
+
97
+	/**
98
+	 * Makes this payment method apply to NO scopes at all. DOES NOT SAVE it.
99
+	 */
100
+	public function deactivate()
101
+	{
102
+		$this->set_scope(array());
103
+	}
104
+
105
+
106
+	/**
107
+	 * Gets button_url
108
+	 *
109
+	 * @return string
110
+	 */
111
+	public function button_url()
112
+	{
113
+		return $this->get('PMD_button_url');
114
+	}
115
+
116
+
117
+	/**
118
+	 * Sets button_url
119
+	 *
120
+	 * @param string $button_url
121
+	 */
122
+	public function set_button_url($button_url)
123
+	{
124
+		$this->set('PMD_button_url', $button_url);
125
+	}
126
+
127
+
128
+	/**
129
+	 * Gets debug_mode
130
+	 *
131
+	 * @return boolean
132
+	 */
133
+	public function debug_mode()
134
+	{
135
+		return $this->get('PMD_debug_mode');
136
+	}
137
+
138
+
139
+	/**
140
+	 * Sets debug_mode
141
+	 *
142
+	 * @param boolean $debug_mode
143
+	 */
144
+	public function set_debug_mode($debug_mode)
145
+	{
146
+		$this->set('PMD_debug_mode', $debug_mode);
147
+	}
148
+
149
+
150
+	/**
151
+	 * Gets description
152
+	 *
153
+	 * @return string
154
+	 */
155
+	public function description()
156
+	{
157
+		return $this->get('PMD_desc');
158
+	}
159
+
160
+
161
+	/**
162
+	 * Sets description
163
+	 *
164
+	 * @param string $description
165
+	 */
166
+	public function set_description($description)
167
+	{
168
+		$this->set('PMD_desc', $description);
169
+	}
170
+
171
+
172
+	/**
173
+	 * Gets name
174
+	 *
175
+	 * @return string
176
+	 */
177
+	public function name()
178
+	{
179
+		return $this->get('PMD_name');
180
+	}
181
+
182
+
183
+	/**
184
+	 * Sets name
185
+	 *
186
+	 * @param string $name
187
+	 */
188
+	public function set_name($name)
189
+	{
190
+		$this->set('PMD_name', $name);
191
+	}
192
+
193
+
194
+	/**
195
+	 * Gets open_by_default
196
+	 *
197
+	 * @return boolean
198
+	 */
199
+	public function open_by_default()
200
+	{
201
+		return $this->get('PMD_open_by_default');
202
+	}
203
+
204
+
205
+	/**
206
+	 * Sets open_by_default
207
+	 *
208
+	 * @param boolean $open_by_default
209
+	 */
210
+	public function set_open_by_default($open_by_default)
211
+	{
212
+		$this->set('PMD_open_by_default', $open_by_default);
213
+	}
214
+
215
+
216
+	/**
217
+	 * Gets order
218
+	 *
219
+	 * @return int
220
+	 */
221
+	public function order()
222
+	{
223
+		return $this->get('PMD_order');
224
+	}
225
+
226
+
227
+	/**
228
+	 * Sets order
229
+	 *
230
+	 * @param int $order
231
+	 */
232
+	public function set_order($order)
233
+	{
234
+		$this->set('PMD_order', $order);
235
+	}
236
+
237
+
238
+	/**
239
+	 * Gets slug
240
+	 *
241
+	 * @return string
242
+	 */
243
+	public function slug()
244
+	{
245
+		return $this->get('PMD_slug');
246
+	}
247
+
248
+
249
+	/**
250
+	 * Sets slug
251
+	 *
252
+	 * @param string $slug
253
+	 */
254
+	public function set_slug($slug)
255
+	{
256
+		$this->set('PMD_slug', $slug);
257
+	}
258
+
259
+
260
+	/**
261
+	 * Gets type
262
+	 *
263
+	 * @return string
264
+	 */
265
+	public function type()
266
+	{
267
+		return $this->get('PMD_type');
268
+	}
269
+
270
+
271
+	/**
272
+	 * Sets type
273
+	 *
274
+	 * @param string $type
275
+	 */
276
+	public function set_type($type)
277
+	{
278
+		$this->set('PMD_type', $type);
279
+	}
280
+
281
+
282
+	/**
283
+	 * Gets wp_user
284
+	 *
285
+	 * @return int
286
+	 */
287
+	public function wp_user()
288
+	{
289
+		return $this->get('PMD_wp_user');
290
+	}
291
+
292
+
293
+	/**
294
+	 * Sets wp_user
295
+	 *
296
+	 * @param int $wp_user_id
297
+	 */
298
+	public function set_wp_user($wp_user_id)
299
+	{
300
+		$this->set('PMD_wp_user', $wp_user_id);
301
+	}
302
+
303
+	/**
304
+	 * Overrides parent so when PMD_type is changed we refresh the _type_obj
305
+	 *
306
+	 * @param string  $field_name
307
+	 * @param mixed   $field_value
308
+	 * @param boolean $use_default
309
+	 */
310
+	public function set($field_name, $field_value, bool $use_default = false)
311
+	{
312
+		if ($field_name === 'PMD_type') {
313
+			// the type has probably changed, so forget about its old type object
314
+			$this->_type_obj = null;
315
+		}
316
+		parent::set($field_name, $field_value, $use_default);
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets admin_name
322
+	 *
323
+	 * @return string
324
+	 */
325
+	public function admin_name()
326
+	{
327
+		return $this->get('PMD_admin_name');
328
+	}
329
+
330
+
331
+	/**
332
+	 * Sets admin_name
333
+	 *
334
+	 * @param string $admin_name
335
+	 */
336
+	public function set_admin_name($admin_name)
337
+	{
338
+		$this->set('PMD_admin_name', $admin_name);
339
+	}
340
+
341
+
342
+	/**
343
+	 * Gets admin_desc
344
+	 *
345
+	 * @return string
346
+	 */
347
+	public function admin_desc()
348
+	{
349
+		return $this->get('PMD_admin_desc');
350
+	}
351
+
352
+
353
+	/**
354
+	 * Sets admin_desc
355
+	 *
356
+	 * @param string $admin_desc
357
+	 */
358
+	public function set_admin_desc($admin_desc)
359
+	{
360
+		$this->set('PMD_admin_desc', $admin_desc);
361
+	}
362
+
363
+
364
+	/**
365
+	 * Gets scope
366
+	 *
367
+	 * @return array
368
+	 */
369
+	public function scope()
370
+	{
371
+		return $this->get('PMD_scope');
372
+	}
373
+
374
+
375
+	/**
376
+	 * Sets scope
377
+	 *
378
+	 * @param array $scope
379
+	 */
380
+	public function set_scope($scope)
381
+	{
382
+		$this->set('PMD_scope', $scope);
383
+	}
384
+
385
+
386
+	/**
387
+	 * Gets the payment method type for this payment method instance
388
+	 *
389
+	 * @return EE_PMT_Base
390
+	 * @throws EE_Error
391
+	 */
392
+	public function type_obj()
393
+	{
394
+		if (! $this->_type_obj) {
395
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
396
+			if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($this->type())) {
397
+				$class_name = EE_Payment_Method_Manager::instance()->payment_method_class_from_type($this->type());
398
+				if (! class_exists($class_name)) {
399
+					throw new EE_Error(
400
+						sprintf(
401
+							__(
402
+								'An attempt to use the "%1$s" payment method failed, so it was deactivated.%2$sWas the "%1$s" Plugin recently deactivated? It can be reactivated on the %3$sPlugins Admin Page%4$s',
403
+								'event_espresso'
404
+							),
405
+							$class_name,
406
+							'<br />',
407
+							'<a href="' . admin_url('plugins.php') . '">',
408
+							'</a>'
409
+						)
410
+					);
411
+				}
412
+				$r = new ReflectionClass($class_name);
413
+				$this->_type_obj = $r->newInstanceArgs(array($this));
414
+			} else {
415
+				throw new EE_Error(
416
+					sprintf(
417
+						__(
418
+							'A payment method of type "%1$s" does not exist. Only ones existing are: %2$s',
419
+							'event_espresso'
420
+						),
421
+						$this->type(),
422
+						implode(',', EE_Payment_Method_Manager::instance()->payment_method_type_names())
423
+					)
424
+				);
425
+			}
426
+		}
427
+		return $this->_type_obj;
428
+	}
429
+
430
+
431
+	/**
432
+	 * Returns a simple array of key-value pairs combining the payment method's fields (without the 'PMD_' prefix)
433
+	 * and the extra meta. Mostly used for passing off ot gateways.     *
434
+	 *
435
+	 * @return array
436
+	 */
437
+	public function settings_array()
438
+	{
439
+		$fields = $this->model_field_array();
440
+		$extra_meta = $this->all_extra_meta_array();
441
+		// remove the model's prefix from the fields
442
+		$combined_settings_array = array();
443
+		foreach ($fields as $key => $value) {
444
+			if (strpos($key, 'PMD_') === 0) {
445
+				$key_sans_model_prefix = str_replace('PMD_', '', $key);
446
+				$combined_settings_array [ $key_sans_model_prefix ] = $value;
447
+			}
448
+		}
449
+		$combined_settings_array = array_merge($extra_meta, $combined_settings_array);
450
+		return $combined_settings_array;
451
+	}
452
+
453
+
454
+	/**
455
+	 * Gets the HTML for displaying the payment method on a page.
456
+	 *
457
+	 * @param string $url
458
+	 * @param string $css_class
459
+	 * @return string of HTML for displaying the button
460
+	 * @throws \EE_Error
461
+	 */
462
+	public function button_html($url = '', $css_class = '')
463
+	{
464
+		$payment_occurs = $this->type_obj()->payment_occurs();
465
+		return '
466 466
 		 <div id="'
467
-               . $this->slug()
468
-               . '-payment-option-dv" class="'
469
-               . $payment_occurs . '-payment-gateway reg-page-payment-option-dv' . $css_class . '">
467
+			   . $this->slug()
468
+			   . '-payment-option-dv" class="'
469
+			   . $payment_occurs . '-payment-gateway reg-page-payment-option-dv' . $css_class . '">
470 470
 			<a id="payment-gateway-button-' . $this->slug()
471
-               . '" class="reg-page-payment-option-lnk" rel="'
472
-               . $this->slug() . '" href="' . $url . '" >
471
+			   . '" class="reg-page-payment-option-lnk" rel="'
472
+			   . $this->slug() . '" href="' . $url . '" >
473 473
 				<img src="' . $this->button_url() . '" alt="' . sprintf(
474
-                   esc_attr__('Pay using %s', 'event_espresso'),
475
-                   $this->get_pretty('PMD_name', 'form_input')
476
-               ) . '" />
474
+				   esc_attr__('Pay using %s', 'event_espresso'),
475
+				   $this->get_pretty('PMD_name', 'form_input')
476
+			   ) . '" />
477 477
 			</a>
478 478
 		</div>
479 479
 ';
480
-    }
481
-
482
-
483
-    /**
484
-     * Gets all the currencies which are an option for this payment method
485
-     * (as defined by the gateway and the currently active currencies)
486
-     *
487
-     * @return EE_Currency[]
488
-     * @throws \EE_Error
489
-     */
490
-    public function get_all_usable_currencies()
491
-    {
492
-        return EEM_Currency::instance()->get_all_currencies_usable_by($this->type_obj());
493
-    }
494
-
495
-
496
-    /**
497
-     * Reports whether or not this payment method can be used for this payment method
498
-     *
499
-     * @param string $currency_code currency ID (code)
500
-     * @return boolean
501
-     * @throws \EE_Error
502
-     */
503
-    public function usable_for_currency($currency_code)
504
-    {
505
-        foreach ($this->get_all_usable_currencies() as $currency_obj) {
506
-            if ($currency_obj->ID() === $currency_code) {
507
-                return true;
508
-            }
509
-        }
510
-        return false;
511
-    }
512
-
513
-
514
-    /**
515
-     * Returns TRUE if this payment method's gateway is an instance of EE_Onsite_Gateway
516
-     *
517
-     * @return bool
518
-     * @throws \EE_Error
519
-     */
520
-    public function is_on_site()
521
-    {
522
-        return $this->type_obj()->payment_occurs() === EE_PMT_Base::onsite;
523
-    }
524
-
525
-
526
-    /**
527
-     * Returns TRUE if this payment method's gateway is an instance of EE_Offsite_Gateway
528
-     *
529
-     * @return bool
530
-     * @throws \EE_Error
531
-     */
532
-    public function is_off_site()
533
-    {
534
-        return $this->type_obj()->payment_occurs() === EE_PMT_Base::offsite;
535
-    }
536
-
537
-
538
-    /**
539
-     * Returns TRUE if this payment method does not utilize a gateway
540
-     *
541
-     * @return bool
542
-     * @throws \EE_Error
543
-     */
544
-    public function is_off_line()
545
-    {
546
-        return $this->type_obj()->payment_occurs() === EE_PMT_Base::offline;
547
-    }
548
-
549
-    /**
550
-     * Overrides default __sleep so the object type is NOT cached.
551
-     * This way we can rely on the normal EE_Payment_Method::type_obj() logic
552
-     * to load the required classes, and don't need them at the time of unserialization
553
-     *
554
-     * @return array
555
-     */
556
-    public function __sleep()
557
-    {
558
-        $properties = get_object_vars($this);
559
-        unset($properties['_type_obj']);
560
-        return array_keys($properties);
561
-    }
562
-
563
-
564
-    /**
565
-     * Overrides parent to add some logging for when payment methods get deactivated
566
-     *
567
-     * @param array $set_cols_n_values
568
-     * @return int @see EE_Base_Class::save()
569
-     * @throws \EE_Error
570
-     */
571
-    public function save(array $set_cols_n_values = array())
572
-    {
573
-        $results = parent::save($set_cols_n_values);
574
-        if ($this->get_original('PMD_scope') !== $this->get('PMD_scope')) {
575
-            EE_Log::instance()->log(
576
-                __FILE__,
577
-                __FUNCTION__,
578
-                sprintf(
579
-                    __('Set new scope on payment method %1$s to %2$s from %3$s on URL %4$s', 'event_espresso'),
580
-                    $this->name(),
581
-                    serialize($this->get_original('PMD_scope')),
582
-                    serialize($this->get('PMD_scope')),
583
-                    EE_Registry::instance()->REQ->get_current_page_permalink()
584
-                ),
585
-                'payment_method_change'
586
-            );
587
-        }
588
-        return $results;
589
-    }
480
+	}
481
+
482
+
483
+	/**
484
+	 * Gets all the currencies which are an option for this payment method
485
+	 * (as defined by the gateway and the currently active currencies)
486
+	 *
487
+	 * @return EE_Currency[]
488
+	 * @throws \EE_Error
489
+	 */
490
+	public function get_all_usable_currencies()
491
+	{
492
+		return EEM_Currency::instance()->get_all_currencies_usable_by($this->type_obj());
493
+	}
494
+
495
+
496
+	/**
497
+	 * Reports whether or not this payment method can be used for this payment method
498
+	 *
499
+	 * @param string $currency_code currency ID (code)
500
+	 * @return boolean
501
+	 * @throws \EE_Error
502
+	 */
503
+	public function usable_for_currency($currency_code)
504
+	{
505
+		foreach ($this->get_all_usable_currencies() as $currency_obj) {
506
+			if ($currency_obj->ID() === $currency_code) {
507
+				return true;
508
+			}
509
+		}
510
+		return false;
511
+	}
512
+
513
+
514
+	/**
515
+	 * Returns TRUE if this payment method's gateway is an instance of EE_Onsite_Gateway
516
+	 *
517
+	 * @return bool
518
+	 * @throws \EE_Error
519
+	 */
520
+	public function is_on_site()
521
+	{
522
+		return $this->type_obj()->payment_occurs() === EE_PMT_Base::onsite;
523
+	}
524
+
525
+
526
+	/**
527
+	 * Returns TRUE if this payment method's gateway is an instance of EE_Offsite_Gateway
528
+	 *
529
+	 * @return bool
530
+	 * @throws \EE_Error
531
+	 */
532
+	public function is_off_site()
533
+	{
534
+		return $this->type_obj()->payment_occurs() === EE_PMT_Base::offsite;
535
+	}
536
+
537
+
538
+	/**
539
+	 * Returns TRUE if this payment method does not utilize a gateway
540
+	 *
541
+	 * @return bool
542
+	 * @throws \EE_Error
543
+	 */
544
+	public function is_off_line()
545
+	{
546
+		return $this->type_obj()->payment_occurs() === EE_PMT_Base::offline;
547
+	}
548
+
549
+	/**
550
+	 * Overrides default __sleep so the object type is NOT cached.
551
+	 * This way we can rely on the normal EE_Payment_Method::type_obj() logic
552
+	 * to load the required classes, and don't need them at the time of unserialization
553
+	 *
554
+	 * @return array
555
+	 */
556
+	public function __sleep()
557
+	{
558
+		$properties = get_object_vars($this);
559
+		unset($properties['_type_obj']);
560
+		return array_keys($properties);
561
+	}
562
+
563
+
564
+	/**
565
+	 * Overrides parent to add some logging for when payment methods get deactivated
566
+	 *
567
+	 * @param array $set_cols_n_values
568
+	 * @return int @see EE_Base_Class::save()
569
+	 * @throws \EE_Error
570
+	 */
571
+	public function save(array $set_cols_n_values = array())
572
+	{
573
+		$results = parent::save($set_cols_n_values);
574
+		if ($this->get_original('PMD_scope') !== $this->get('PMD_scope')) {
575
+			EE_Log::instance()->log(
576
+				__FILE__,
577
+				__FUNCTION__,
578
+				sprintf(
579
+					__('Set new scope on payment method %1$s to %2$s from %3$s on URL %4$s', 'event_espresso'),
580
+					$this->name(),
581
+					serialize($this->get_original('PMD_scope')),
582
+					serialize($this->get('PMD_scope')),
583
+					EE_Registry::instance()->REQ->get_current_page_permalink()
584
+				),
585
+				'payment_method_change'
586
+			);
587
+		}
588
+		return $results;
589
+	}
590 590
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event_Venue.class.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -6,23 +6,23 @@
 block discarded – undo
6 6
 class EE_Event_Venue extends EE_Base_Class
7 7
 {
8 8
 
9
-    /**
10
-     * @param array $props_n_values
11
-     * @return EE_Event_Venue|mixed
12
-     */
13
-    public static function new_instance($props_n_values = array())
14
-    {
15
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
16
-        return $has_object ? $has_object : new self($props_n_values);
17
-    }
9
+	/**
10
+	 * @param array $props_n_values
11
+	 * @return EE_Event_Venue|mixed
12
+	 */
13
+	public static function new_instance($props_n_values = array())
14
+	{
15
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
16
+		return $has_object ? $has_object : new self($props_n_values);
17
+	}
18 18
 
19 19
 
20
-    /**
21
-     * @param array $props_n_values
22
-     * @return EE_Event_Venue
23
-     */
24
-    public static function new_instance_from_db($props_n_values = array())
25
-    {
26
-        return new self($props_n_values, true);
27
-    }
20
+	/**
21
+	 * @param array $props_n_values
22
+	 * @return EE_Event_Venue
23
+	 */
24
+	public static function new_instance_from_db($props_n_values = array())
25
+	{
26
+		return new self($props_n_values, true);
27
+	}
28 28
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Soft_Delete_Base_Class.class.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -12,53 +12,53 @@
 block discarded – undo
12 12
 {
13 13
 
14 14
 
15
-    /**
16
-     * Overrides parent _delete() so that we do soft deletes.
17
-     *
18
-     * @return bool|int
19
-     */
20
-    protected function _delete()
21
-    {
22
-        return $this->delete_or_restore();
23
-    }
15
+	/**
16
+	 * Overrides parent _delete() so that we do soft deletes.
17
+	 *
18
+	 * @return bool|int
19
+	 */
20
+	protected function _delete()
21
+	{
22
+		return $this->delete_or_restore();
23
+	}
24 24
 
25 25
 
26
-    /**
27
-     * Deletes or restores this object.
28
-     *
29
-     * @param bool $delete true=>delete, false=>restore
30
-     * @return bool|int
31
-     */
32
-    public function delete_or_restore($delete = true)
33
-    {
34
-        /**
35
-         * Called just before trashing (soft delete) or restoring a trashed item.
36
-         *
37
-         * @param EE_Base_Class $model_object about to be trashed or restored
38
-         * @param bool          $delete       true the item is being trashed, false the item is being restored.
39
-         */
40
-        do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__before', $this, $delete);
41
-        $model = $this->get_model();
42
-        $result = $model->delete_or_restore_by_ID($delete, $this->ID());
43
-        /**
44
-         * Called just after trashing (soft delete) or restoring a trashed item.
45
-         *
46
-         * @param EE_Base_Class $model_object that was just trashed or restored.
47
-         * @param bool          $delete       true the item is being trashed, false the item is being restored.
48
-         * @param bool|int      $result
49
-         */
50
-        do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after', $this, $delete, $result);
51
-        return $result;
52
-    }
26
+	/**
27
+	 * Deletes or restores this object.
28
+	 *
29
+	 * @param bool $delete true=>delete, false=>restore
30
+	 * @return bool|int
31
+	 */
32
+	public function delete_or_restore($delete = true)
33
+	{
34
+		/**
35
+		 * Called just before trashing (soft delete) or restoring a trashed item.
36
+		 *
37
+		 * @param EE_Base_Class $model_object about to be trashed or restored
38
+		 * @param bool          $delete       true the item is being trashed, false the item is being restored.
39
+		 */
40
+		do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__before', $this, $delete);
41
+		$model = $this->get_model();
42
+		$result = $model->delete_or_restore_by_ID($delete, $this->ID());
43
+		/**
44
+		 * Called just after trashing (soft delete) or restoring a trashed item.
45
+		 *
46
+		 * @param EE_Base_Class $model_object that was just trashed or restored.
47
+		 * @param bool          $delete       true the item is being trashed, false the item is being restored.
48
+		 * @param bool|int      $result
49
+		 */
50
+		do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after', $this, $delete, $result);
51
+		return $result;
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * Performs a restoration (un-deletes) this object
57
-     *
58
-     * @return bool|int
59
-     */
60
-    public function restore()
61
-    {
62
-        return $this->delete_or_restore(false);
63
-    }
55
+	/**
56
+	 * Performs a restoration (un-deletes) this object
57
+	 *
58
+	 * @return bool|int
59
+	 */
60
+	public function restore()
61
+	{
62
+		return $this->delete_or_restore(false);
63
+	}
64 64
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event_Question_Group.class.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -6,23 +6,23 @@
 block discarded – undo
6 6
 class EE_Event_Question_Group extends EE_Base_Class
7 7
 {
8 8
 
9
-    /**
10
-     * @param array $props_n_values
11
-     * @return EE_Event_Question_Group|mixed
12
-     */
13
-    public static function new_instance($props_n_values = array())
14
-    {
15
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
16
-        return $has_object ? $has_object : new self($props_n_values);
17
-    }
9
+	/**
10
+	 * @param array $props_n_values
11
+	 * @return EE_Event_Question_Group|mixed
12
+	 */
13
+	public static function new_instance($props_n_values = array())
14
+	{
15
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
16
+		return $has_object ? $has_object : new self($props_n_values);
17
+	}
18 18
 
19 19
 
20
-    /**
21
-     * @param array $props_n_values
22
-     * @return EE_Event_Question_Group
23
-     */
24
-    public static function new_instance_from_db($props_n_values = array())
25
-    {
26
-        return new self($props_n_values, true);
27
-    }
20
+	/**
21
+	 * @param array $props_n_values
22
+	 * @return EE_Event_Question_Group
23
+	 */
24
+	public static function new_instance_from_db($props_n_values = array())
25
+	{
26
+		return new self($props_n_values, true);
27
+	}
28 28
 }
Please login to merge, or discard this patch.