Completed
Branch FET/extract-doc-block-from-eem... (b14d68)
by
unknown
08:28 queued 21s
created
core/db_classes/EE_Export.class.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
     /**
70 70
      * @Export Event Espresso data - routes export requests
71 71
      * @access public
72
-     * @return void | bool
72
+     * @return false|null | bool
73 73
      */
74 74
     public function export()
75 75
     {
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
      * @access    private
751 751
      * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
752 752
      *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
753
-     * @return array on success, FALSE on fail
753
+     * @return boolean on success, FALSE on fail
754 754
      */
755 755
     private function _get_export_data_for_models($models_to_export = array())
756 756
     {
Please login to merge, or discard this patch.
Indentation   +773 added lines, -773 removed lines patch added patch discarded remove patch
@@ -16,777 +16,777 @@
 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 = null;
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 (EEM_Datetime::instance()->get_all_wpdb_results(
548
-                        array(
549
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
550
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
551
-                            'default_where_conditions' => 'none',
552
-                        )
553
-                    ) as $datetime) {
554
-                        $datetimes_strings[] = $this->_prepare_value_from_db_for_display(
555
-                            EEM_Datetime::instance(),
556
-                            'DTT_EVT_start',
557
-                            $datetime['Datetime.DTT_EVT_start']
558
-                        );
559
-                    }
560
-                } else {
561
-                    $ticket_name = __('Unknown', 'event_espresso');
562
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
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);
566
-                // get datetime(s) of registration
567
-
568
-                // add attendee columns
569
-                foreach ($att_fields_to_include as $att_field_name) {
570
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
571
-                    if ($reg_row['Attendee_CPT.ID']) {
572
-                        if ($att_field_name == 'STA_ID') {
573
-                            $value = EEM_State::instance()->get_var(
574
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
575
-                                'STA_name'
576
-                            );
577
-                        } elseif ($att_field_name == 'CNT_ISO') {
578
-                            $value = EEM_Country::instance()->get_var(
579
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
580
-                                'CNT_name'
581
-                            );
582
-                        } else {
583
-                            $value = $this->_prepare_value_from_db_for_display(
584
-                                EEM_Attendee::instance(),
585
-                                $att_field_name,
586
-                                $reg_row[ $field_obj->get_qualified_column() ]
587
-                            );
588
-                        }
589
-                    } else {
590
-                        $value = '';
591
-                    }
592
-
593
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
594
-                }
595
-
596
-                // make sure each registration has the same questions in the same order
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;
600
-                    }
601
-                }
602
-                // now fill out the questions THEY answered
603
-                foreach (EEM_Answer::instance()->get_all_wpdb_results(
604
-                    array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
605
-                ) as $answer_row) {
606
-                    /* @var $answer EE_Answer */
607
-                    if ($answer_row['Question.QST_ID']) {
608
-                        $question_label = $this->_prepare_value_from_db_for_display(
609
-                            EEM_Question::instance(),
610
-                            'QST_admin_label',
611
-                            $answer_row['Question.QST_admin_label']
612
-                        );
613
-                    } else {
614
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615
-                    }
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(
618
-                            $answer_row['Answer.ANS_value']
619
-                        );
620
-                    } else {
621
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
622
-                            EEM_Answer::instance(),
623
-                            'ANS_value',
624
-                            $answer_row['Answer.ANS_value']
625
-                        );
626
-                    }
627
-                }
628
-                $registrations_csv_ready_array[] = apply_filters(
629
-                    'FHEE__EE_Export__report_registrations__reg_csv_array',
630
-                    $reg_csv_array,
631
-                    $reg_row
632
-                );
633
-            }
634
-        }
635
-
636
-        // if we couldn't export anything, we want to at least show the column headers
637
-        if (empty($registrations_csv_ready_array)) {
638
-            $reg_csv_array = array();
639
-            $model_and_fields_to_include = array(
640
-                'Registration' => $reg_fields_to_include,
641
-                'Attendee'     => $att_fields_to_include,
642
-            );
643
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
644
-                $model = EE_Registry::instance()->load_model($model_name);
645
-                foreach ($field_list as $field_name) {
646
-                    $field = $model->field_settings_for($field_name);
647
-                    $reg_csv_array[ $this->_get_column_name_for_field(
648
-                        $field
649
-                    ) ] = null;// $registration->get($field->get_name());
650
-                }
651
-            }
652
-            $registrations_csv_ready_array [] = $reg_csv_array;
653
-        }
654
-        if ($event_id) {
655
-            $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
-            if (! $event_slug) {
657
-                $event_slug = __('unknown', 'event_espresso');
658
-            }
659
-        } else {
660
-            $event_slug = __('all', 'event_espresso');
661
-        }
662
-        $filename = sprintf("registrations-for-%s", $event_slug);
663
-
664
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
665
-        $this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
666
-        $this->EE_CSV->end_sending_csv($handle);
667
-    }
668
-
669
-    /**
670
-     * Gets the 'normal' column named for fields
671
-     *
672
-     * @param EE_Model_Field_Base $field
673
-     * @return string
674
-     */
675
-    protected function _get_column_name_for_field(EE_Model_Field_Base $field)
676
-    {
677
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
678
-    }
679
-
680
-
681
-    /**
682
-     * @Export data for ALL events
683
-     * @access public
684
-     * @return void
685
-     */
686
-    public function export_categories()
687
-    {
688
-        // are any Event IDs set?
689
-        $query_params = array();
690
-        if (isset($this->_req_data['EVT_CAT_ID'])) {
691
-            // do we have an array of IDs ?
692
-            if (is_array($this->_req_data['EVT_CAT_ID'])) {
693
-                // generate an "IN (CSV)" where clause
694
-                $EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
695
-                $filename = 'event-categories';
696
-                $query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
697
-            } else {
698
-                // generate regular where = clause
699
-                $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
-                $filename = 'event-category#' . $EVT_CAT_ID;
701
-                $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702
-            }
703
-        } else {
704
-            // no IDs means we will d/l the entire table
705
-            $filename = 'all-categories';
706
-        }
707
-
708
-        $tables_to_export = array(
709
-            'Term_Taxonomy' => $query_params,
710
-        );
711
-
712
-        $table_data = $this->_get_export_data_for_models($tables_to_export);
713
-        $filename = $this->generate_filename($filename);
714
-
715
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716
-            EE_Error::add_error(
717
-                __(
718
-                    'An error occurred and the Category details could not be exported from the database.',
719
-                    'event_espresso'
720
-                ),
721
-                __FILE__,
722
-                __FUNCTION__,
723
-                __LINE__
724
-            );
725
-        }
726
-    }
727
-
728
-
729
-    /**
730
-     * @process export name to create a suitable filename
731
-     * @access  private
732
-     * @param string - export_name
733
-     * @return string on success, FALSE on fail
734
-     */
735
-    private function generate_filename($export_name = '')
736
-    {
737
-        if ($export_name != '') {
738
-            $filename = get_bloginfo('name') . '-' . $export_name;
739
-            $filename = sanitize_key($filename) . '-' . $this->today;
740
-            return $filename;
741
-        } else {
742
-            EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
743
-        }
744
-        return false;
745
-    }
746
-
747
-
748
-    /**
749
-     * @recursive function for exporting table data and merging the results with the next results
750
-     * @access    private
751
-     * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
752
-     *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
753
-     * @return array on success, FALSE on fail
754
-     */
755
-    private function _get_export_data_for_models($models_to_export = array())
756
-    {
757
-        $table_data = false;
758
-        if (is_array($models_to_export)) {
759
-            foreach ($models_to_export as $model_name => $query_params) {
760
-                // check for a numerically-indexed array. in that case, $model_name is the value!!
761
-                if (is_int($model_name)) {
762
-                    $model_name = $query_params;
763
-                    $query_params = array();
764
-                }
765
-                $model = EE_Registry::instance()->load_model($model_name);
766
-                $model_objects = $model->get_all($query_params);
767
-
768
-                $table_data[ $model_name ] = array();
769
-                foreach ($model_objects as $model_object) {
770
-                    $model_data_array = array();
771
-                    $fields = $model->field_settings();
772
-                    foreach ($fields as $field) {
773
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
774
-                        if ($field instanceof EE_Datetime_Field) {
775
-                            // $field->set_date_format('Y-m-d');
776
-                            // $field->set_time_format('H:i:s');
777
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
778
-                                $field->get_name(),
779
-                                'Y-m-d',
780
-                                'H:i:s'
781
-                            );
782
-                        } else {
783
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
784
-                        }
785
-                    }
786
-                    $table_data[ $model_name ][] = $model_data_array;
787
-                }
788
-            }
789
-        }
790
-        return $table_data;
791
-    }
19
+	const option_prefix = 'ee_report_job_';
20
+
21
+
22
+	// instance of the EE_Export object
23
+	private static $_instance = null;
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 (EEM_Datetime::instance()->get_all_wpdb_results(
548
+						array(
549
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
550
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
551
+							'default_where_conditions' => 'none',
552
+						)
553
+					) as $datetime) {
554
+						$datetimes_strings[] = $this->_prepare_value_from_db_for_display(
555
+							EEM_Datetime::instance(),
556
+							'DTT_EVT_start',
557
+							$datetime['Datetime.DTT_EVT_start']
558
+						);
559
+					}
560
+				} else {
561
+					$ticket_name = __('Unknown', 'event_espresso');
562
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
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);
566
+				// get datetime(s) of registration
567
+
568
+				// add attendee columns
569
+				foreach ($att_fields_to_include as $att_field_name) {
570
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
571
+					if ($reg_row['Attendee_CPT.ID']) {
572
+						if ($att_field_name == 'STA_ID') {
573
+							$value = EEM_State::instance()->get_var(
574
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
575
+								'STA_name'
576
+							);
577
+						} elseif ($att_field_name == 'CNT_ISO') {
578
+							$value = EEM_Country::instance()->get_var(
579
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
580
+								'CNT_name'
581
+							);
582
+						} else {
583
+							$value = $this->_prepare_value_from_db_for_display(
584
+								EEM_Attendee::instance(),
585
+								$att_field_name,
586
+								$reg_row[ $field_obj->get_qualified_column() ]
587
+							);
588
+						}
589
+					} else {
590
+						$value = '';
591
+					}
592
+
593
+					$reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
594
+				}
595
+
596
+				// make sure each registration has the same questions in the same order
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;
600
+					}
601
+				}
602
+				// now fill out the questions THEY answered
603
+				foreach (EEM_Answer::instance()->get_all_wpdb_results(
604
+					array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
605
+				) as $answer_row) {
606
+					/* @var $answer EE_Answer */
607
+					if ($answer_row['Question.QST_ID']) {
608
+						$question_label = $this->_prepare_value_from_db_for_display(
609
+							EEM_Question::instance(),
610
+							'QST_admin_label',
611
+							$answer_row['Question.QST_admin_label']
612
+						);
613
+					} else {
614
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615
+					}
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(
618
+							$answer_row['Answer.ANS_value']
619
+						);
620
+					} else {
621
+						$reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
622
+							EEM_Answer::instance(),
623
+							'ANS_value',
624
+							$answer_row['Answer.ANS_value']
625
+						);
626
+					}
627
+				}
628
+				$registrations_csv_ready_array[] = apply_filters(
629
+					'FHEE__EE_Export__report_registrations__reg_csv_array',
630
+					$reg_csv_array,
631
+					$reg_row
632
+				);
633
+			}
634
+		}
635
+
636
+		// if we couldn't export anything, we want to at least show the column headers
637
+		if (empty($registrations_csv_ready_array)) {
638
+			$reg_csv_array = array();
639
+			$model_and_fields_to_include = array(
640
+				'Registration' => $reg_fields_to_include,
641
+				'Attendee'     => $att_fields_to_include,
642
+			);
643
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
644
+				$model = EE_Registry::instance()->load_model($model_name);
645
+				foreach ($field_list as $field_name) {
646
+					$field = $model->field_settings_for($field_name);
647
+					$reg_csv_array[ $this->_get_column_name_for_field(
648
+						$field
649
+					) ] = null;// $registration->get($field->get_name());
650
+				}
651
+			}
652
+			$registrations_csv_ready_array [] = $reg_csv_array;
653
+		}
654
+		if ($event_id) {
655
+			$event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
+			if (! $event_slug) {
657
+				$event_slug = __('unknown', 'event_espresso');
658
+			}
659
+		} else {
660
+			$event_slug = __('all', 'event_espresso');
661
+		}
662
+		$filename = sprintf("registrations-for-%s", $event_slug);
663
+
664
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
665
+		$this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
666
+		$this->EE_CSV->end_sending_csv($handle);
667
+	}
668
+
669
+	/**
670
+	 * Gets the 'normal' column named for fields
671
+	 *
672
+	 * @param EE_Model_Field_Base $field
673
+	 * @return string
674
+	 */
675
+	protected function _get_column_name_for_field(EE_Model_Field_Base $field)
676
+	{
677
+		return $field->get_nicename() . "[" . $field->get_name() . "]";
678
+	}
679
+
680
+
681
+	/**
682
+	 * @Export data for ALL events
683
+	 * @access public
684
+	 * @return void
685
+	 */
686
+	public function export_categories()
687
+	{
688
+		// are any Event IDs set?
689
+		$query_params = array();
690
+		if (isset($this->_req_data['EVT_CAT_ID'])) {
691
+			// do we have an array of IDs ?
692
+			if (is_array($this->_req_data['EVT_CAT_ID'])) {
693
+				// generate an "IN (CSV)" where clause
694
+				$EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
695
+				$filename = 'event-categories';
696
+				$query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
697
+			} else {
698
+				// generate regular where = clause
699
+				$EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
+				$filename = 'event-category#' . $EVT_CAT_ID;
701
+				$query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702
+			}
703
+		} else {
704
+			// no IDs means we will d/l the entire table
705
+			$filename = 'all-categories';
706
+		}
707
+
708
+		$tables_to_export = array(
709
+			'Term_Taxonomy' => $query_params,
710
+		);
711
+
712
+		$table_data = $this->_get_export_data_for_models($tables_to_export);
713
+		$filename = $this->generate_filename($filename);
714
+
715
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716
+			EE_Error::add_error(
717
+				__(
718
+					'An error occurred and the Category details could not be exported from the database.',
719
+					'event_espresso'
720
+				),
721
+				__FILE__,
722
+				__FUNCTION__,
723
+				__LINE__
724
+			);
725
+		}
726
+	}
727
+
728
+
729
+	/**
730
+	 * @process export name to create a suitable filename
731
+	 * @access  private
732
+	 * @param string - export_name
733
+	 * @return string on success, FALSE on fail
734
+	 */
735
+	private function generate_filename($export_name = '')
736
+	{
737
+		if ($export_name != '') {
738
+			$filename = get_bloginfo('name') . '-' . $export_name;
739
+			$filename = sanitize_key($filename) . '-' . $this->today;
740
+			return $filename;
741
+		} else {
742
+			EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
743
+		}
744
+		return false;
745
+	}
746
+
747
+
748
+	/**
749
+	 * @recursive function for exporting table data and merging the results with the next results
750
+	 * @access    private
751
+	 * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
752
+	 *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
753
+	 * @return array on success, FALSE on fail
754
+	 */
755
+	private function _get_export_data_for_models($models_to_export = array())
756
+	{
757
+		$table_data = false;
758
+		if (is_array($models_to_export)) {
759
+			foreach ($models_to_export as $model_name => $query_params) {
760
+				// check for a numerically-indexed array. in that case, $model_name is the value!!
761
+				if (is_int($model_name)) {
762
+					$model_name = $query_params;
763
+					$query_params = array();
764
+				}
765
+				$model = EE_Registry::instance()->load_model($model_name);
766
+				$model_objects = $model->get_all($query_params);
767
+
768
+				$table_data[ $model_name ] = array();
769
+				foreach ($model_objects as $model_object) {
770
+					$model_data_array = array();
771
+					$fields = $model->field_settings();
772
+					foreach ($fields as $field) {
773
+						$column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
774
+						if ($field instanceof EE_Datetime_Field) {
775
+							// $field->set_date_format('Y-m-d');
776
+							// $field->set_time_format('H:i:s');
777
+							$model_data_array[ $column_name ] = $model_object->get_datetime(
778
+								$field->get_name(),
779
+								'Y-m-d',
780
+								'H:i:s'
781
+							);
782
+						} else {
783
+							$model_data_array[ $column_name ] = $model_object->get($field->get_name());
784
+						}
785
+					}
786
+					$table_data[ $model_name ][] = $model_data_array;
787
+				}
788
+			}
789
+		}
790
+		return $table_data;
791
+	}
792 792
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Payment.class.php 2 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
      * @param array  $props_n_values          incoming values
14 14
      * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
15 15
      *                                        used.)
16
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
16
+     * @param string[]  $date_formats            incoming date_formats in an array where the first value is the
17 17
      *                                        date_format and the second value is the time format
18 18
      * @return EE_Payment
19 19
      * @throws \EE_Error
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
      * Gets all the extra meta info on this payment
589 589
      *
590 590
      * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
591
-     * @return EE_Extra_Meta
591
+     * @return EE_Base_Class[]
592 592
      * @throws \EE_Error
593 593
      */
594 594
     public function extra_meta($query_params = array())
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
     /**
837 837
      * Returns the payment's transaction's primary registration
838 838
      *
839
-     * @return EE_Registration|null
839
+     * @return EE_Base_Class|null
840 840
      */
841 841
     public function get_primary_registration()
842 842
     {
Please login to merge, or discard this patch.
Indentation   +851 added lines, -851 removed lines patch added patch discarded remove patch
@@ -9,855 +9,855 @@
 block discarded – undo
9 9
 class EE_Payment extends EE_Base_Class implements EEI_Payment
10 10
 {
11 11
 
12
-    /**
13
-     * @param array  $props_n_values          incoming values
14
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
15
-     *                                        used.)
16
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
17
-     *                                        date_format and the second value is the time format
18
-     * @return EE_Payment
19
-     * @throws \EE_Error
20
-     */
21
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
22
-    {
23
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
24
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
25
-    }
26
-
27
-
28
-    /**
29
-     * @param array  $props_n_values  incoming values from the database
30
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
31
-     *                                the website will be used.
32
-     * @return EE_Payment
33
-     * @throws \EE_Error
34
-     */
35
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
36
-    {
37
-        return new self($props_n_values, true, $timezone);
38
-    }
39
-
40
-
41
-    /**
42
-     * Set Transaction ID
43
-     *
44
-     * @access public
45
-     * @param int $TXN_ID
46
-     * @throws \EE_Error
47
-     */
48
-    public function set_transaction_id($TXN_ID = 0)
49
-    {
50
-        $this->set('TXN_ID', $TXN_ID);
51
-    }
52
-
53
-
54
-    /**
55
-     * Gets the transaction related to this payment
56
-     *
57
-     * @return EE_Transaction
58
-     * @throws \EE_Error
59
-     */
60
-    public function transaction()
61
-    {
62
-        return $this->get_first_related('Transaction');
63
-    }
64
-
65
-
66
-    /**
67
-     * Set Status
68
-     *
69
-     * @access public
70
-     * @param string $STS_ID
71
-     * @throws \EE_Error
72
-     */
73
-    public function set_status($STS_ID = '')
74
-    {
75
-        $this->set('STS_ID', $STS_ID);
76
-    }
77
-
78
-
79
-    /**
80
-     * Set Payment Timestamp
81
-     *
82
-     * @access public
83
-     * @param int $timestamp
84
-     * @throws \EE_Error
85
-     */
86
-    public function set_timestamp($timestamp = 0)
87
-    {
88
-        $this->set('PAY_timestamp', $timestamp);
89
-    }
90
-
91
-
92
-    /**
93
-     * Set Payment Method
94
-     *
95
-     * @access public
96
-     * @param string $PAY_source
97
-     * @throws \EE_Error
98
-     */
99
-    public function set_source($PAY_source = '')
100
-    {
101
-        $this->set('PAY_source', $PAY_source);
102
-    }
103
-
104
-
105
-    /**
106
-     * Set Payment Amount
107
-     *
108
-     * @access public
109
-     * @param float $amount
110
-     * @throws \EE_Error
111
-     */
112
-    public function set_amount($amount = 0.00)
113
-    {
114
-        $this->set('PAY_amount', (float) $amount);
115
-    }
116
-
117
-
118
-    /**
119
-     * Set Payment Gateway Response
120
-     *
121
-     * @access public
122
-     * @param string $gateway_response
123
-     * @throws \EE_Error
124
-     */
125
-    public function set_gateway_response($gateway_response = '')
126
-    {
127
-        $this->set('PAY_gateway_response', $gateway_response);
128
-    }
129
-
130
-
131
-    /**
132
-     * Returns the name of the payment method used on this payment (previously known merely as 'gateway')
133
-     * but since 4.6.0, payment methods are models and the payment keeps a foreign key to the payment method
134
-     * used on it
135
-     *
136
-     * @deprecated
137
-     * @return string
138
-     * @throws \EE_Error
139
-     */
140
-    public function gateway()
141
-    {
142
-        EE_Error::doing_it_wrong(
143
-            'EE_Payment::gateway',
144
-            __(
145
-                'The method EE_Payment::gateway() has been deprecated. Consider instead using EE_Payment::payment_method()->name()',
146
-                'event_espresso'
147
-            ),
148
-            '4.6.0'
149
-        );
150
-        return $this->payment_method() ? $this->payment_method()->name() : __('Unknown', 'event_espresso');
151
-    }
152
-
153
-
154
-    /**
155
-     * Set Gateway Transaction ID
156
-     *
157
-     * @access public
158
-     * @param string $txn_id_chq_nmbr
159
-     * @throws \EE_Error
160
-     */
161
-    public function set_txn_id_chq_nmbr($txn_id_chq_nmbr = '')
162
-    {
163
-        $this->set('PAY_txn_id_chq_nmbr', $txn_id_chq_nmbr);
164
-    }
165
-
166
-
167
-    /**
168
-     * Set Purchase Order Number
169
-     *
170
-     * @access public
171
-     * @param string $po_number
172
-     * @throws \EE_Error
173
-     */
174
-    public function set_po_number($po_number = '')
175
-    {
176
-        $this->set('PAY_po_number', $po_number);
177
-    }
178
-
179
-
180
-    /**
181
-     * Set Extra Accounting Field
182
-     *
183
-     * @access public
184
-     * @param string $extra_accntng
185
-     * @throws \EE_Error
186
-     */
187
-    public function set_extra_accntng($extra_accntng = '')
188
-    {
189
-        $this->set('PAY_extra_accntng', $extra_accntng);
190
-    }
191
-
192
-
193
-    /**
194
-     * Set Payment made via admin flag
195
-     *
196
-     * @access public
197
-     * @param bool $via_admin
198
-     * @throws \EE_Error
199
-     */
200
-    public function set_payment_made_via_admin($via_admin = false)
201
-    {
202
-        if ($via_admin) {
203
-            $this->set('PAY_source', EEM_Payment_Method::scope_admin);
204
-        } else {
205
-            $this->set('PAY_source', EEM_Payment_Method::scope_cart);
206
-        }
207
-    }
208
-
209
-
210
-    /**
211
-     * Set Payment Details
212
-     *
213
-     * @access public
214
-     * @param string|array $details
215
-     * @throws \EE_Error
216
-     */
217
-    public function set_details($details = '')
218
-    {
219
-        if (is_array($details)) {
220
-            array_walk_recursive($details, array($this, '_strip_all_tags_within_array'));
221
-        } else {
222
-            $details = wp_strip_all_tags($details);
223
-        }
224
-        $this->set('PAY_details', $details);
225
-    }
226
-
227
-
228
-    /**
229
-     * Sets redirect_url
230
-     *
231
-     * @param string $redirect_url
232
-     * @throws \EE_Error
233
-     */
234
-    public function set_redirect_url($redirect_url)
235
-    {
236
-        $this->set('PAY_redirect_url', $redirect_url);
237
-    }
238
-
239
-
240
-    /**
241
-     * Sets redirect_args
242
-     *
243
-     * @param array $redirect_args
244
-     * @throws \EE_Error
245
-     */
246
-    public function set_redirect_args($redirect_args)
247
-    {
248
-        $this->set('PAY_redirect_args', $redirect_args);
249
-    }
250
-
251
-
252
-    /**
253
-     * get Payment Transaction ID
254
-     *
255
-     * @access public
256
-     * @throws \EE_Error
257
-     */
258
-    public function TXN_ID()
259
-    {
260
-        return $this->get('TXN_ID');
261
-    }
262
-
263
-
264
-    /**
265
-     * get Payment Status
266
-     *
267
-     * @access public
268
-     * @throws \EE_Error
269
-     */
270
-    public function status()
271
-    {
272
-        return $this->get('STS_ID');
273
-    }
274
-
275
-
276
-    /**
277
-     * get Payment Status
278
-     *
279
-     * @access public
280
-     * @throws \EE_Error
281
-     */
282
-    public function STS_ID()
283
-    {
284
-        return $this->get('STS_ID');
285
-    }
286
-
287
-
288
-    /**
289
-     * get Payment Timestamp
290
-     *
291
-     * @access public
292
-     * @param string $dt_frmt
293
-     * @param string $tm_frmt
294
-     * @return string
295
-     * @throws \EE_Error
296
-     */
297
-    public function timestamp($dt_frmt = '', $tm_frmt = '')
298
-    {
299
-        return $this->get_i18n_datetime('PAY_timestamp', trim($dt_frmt . ' ' . $tm_frmt));
300
-    }
301
-
302
-
303
-    /**
304
-     * get Payment Source
305
-     *
306
-     * @access public
307
-     * @throws \EE_Error
308
-     */
309
-    public function source()
310
-    {
311
-        return $this->get('PAY_source');
312
-    }
313
-
314
-
315
-    /**
316
-     * get Payment Amount
317
-     *
318
-     * @access public
319
-     * @return float
320
-     * @throws \EE_Error
321
-     */
322
-    public function amount()
323
-    {
324
-        return (float) $this->get('PAY_amount');
325
-    }
326
-
327
-
328
-    /**
329
-     * @return mixed
330
-     * @throws \EE_Error
331
-     */
332
-    public function amount_no_code()
333
-    {
334
-        return $this->get_pretty('PAY_amount', 'no_currency_code');
335
-    }
336
-
337
-
338
-    /**
339
-     * get Payment Gateway Response
340
-     *
341
-     * @access public
342
-     * @throws \EE_Error
343
-     */
344
-    public function gateway_response()
345
-    {
346
-        return $this->get('PAY_gateway_response');
347
-    }
348
-
349
-
350
-    /**
351
-     * get Payment Gateway Transaction ID
352
-     *
353
-     * @access public
354
-     * @throws \EE_Error
355
-     */
356
-    public function txn_id_chq_nmbr()
357
-    {
358
-        return $this->get('PAY_txn_id_chq_nmbr');
359
-    }
360
-
361
-
362
-    /**
363
-     * get Purchase Order Number
364
-     *
365
-     * @access public
366
-     * @throws \EE_Error
367
-     */
368
-    public function po_number()
369
-    {
370
-        return $this->get('PAY_po_number');
371
-    }
372
-
373
-
374
-    /**
375
-     * get Extra Accounting Field
376
-     *
377
-     * @access public
378
-     * @throws \EE_Error
379
-     */
380
-    public function extra_accntng()
381
-    {
382
-        return $this->get('PAY_extra_accntng');
383
-    }
384
-
385
-
386
-    /**
387
-     * get Payment made via admin source
388
-     *
389
-     * @access public
390
-     * @throws \EE_Error
391
-     */
392
-    public function payment_made_via_admin()
393
-    {
394
-        return ($this->get('PAY_source') === EEM_Payment_Method::scope_admin);
395
-    }
396
-
397
-
398
-    /**
399
-     * get Payment Details
400
-     *
401
-     * @access public
402
-     * @throws \EE_Error
403
-     */
404
-    public function details()
405
-    {
406
-        return $this->get('PAY_details');
407
-    }
408
-
409
-
410
-    /**
411
-     * Gets redirect_url
412
-     *
413
-     * @return string
414
-     * @throws \EE_Error
415
-     */
416
-    public function redirect_url()
417
-    {
418
-        return $this->get('PAY_redirect_url');
419
-    }
420
-
421
-
422
-    /**
423
-     * Gets redirect_args
424
-     *
425
-     * @return array
426
-     * @throws \EE_Error
427
-     */
428
-    public function redirect_args()
429
-    {
430
-        return $this->get('PAY_redirect_args');
431
-    }
432
-
433
-
434
-    /**
435
-     * echoes $this->pretty_status()
436
-     *
437
-     * @param bool $show_icons
438
-     * @return void
439
-     * @throws \EE_Error
440
-     */
441
-    public function e_pretty_status($show_icons = false)
442
-    {
443
-        echo $this->pretty_status($show_icons);
444
-    }
445
-
446
-
447
-    /**
448
-     * returns a pretty version of the status, good for displaying to users
449
-     *
450
-     * @param bool $show_icons
451
-     * @return string
452
-     * @throws \EE_Error
453
-     */
454
-    public function pretty_status($show_icons = false)
455
-    {
456
-        $status = EEM_Status::instance()->localized_status(
457
-            array($this->STS_ID() => __('unknown', 'event_espresso')),
458
-            false,
459
-            'sentence'
460
-        );
461
-        $icon = '';
462
-        switch ($this->STS_ID()) {
463
-            case EEM_Payment::status_id_approved:
464
-                $icon = $show_icons
465
-                    ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>'
466
-                    : '';
467
-                break;
468
-            case EEM_Payment::status_id_pending:
469
-                $icon = $show_icons
470
-                    ? '<span class="dashicons dashicons-clock ee-icon-size-16 orange-text"></span>'
471
-                    : '';
472
-                break;
473
-            case EEM_Payment::status_id_cancelled:
474
-                $icon = $show_icons
475
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
476
-                    : '';
477
-                break;
478
-            case EEM_Payment::status_id_declined:
479
-                $icon = $show_icons
480
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
481
-                    : '';
482
-                break;
483
-        }
484
-        return $icon . $status[ $this->STS_ID() ];
485
-    }
486
-
487
-
488
-    /**
489
-     * For determining the status of the payment
490
-     *
491
-     * @return boolean whether the payment is approved or not
492
-     * @throws \EE_Error
493
-     */
494
-    public function is_approved()
495
-    {
496
-        return $this->status_is(EEM_Payment::status_id_approved);
497
-    }
498
-
499
-
500
-    /**
501
-     * Generally determines if the status of this payment equals
502
-     * the $STS_ID string
503
-     *
504
-     * @param string $STS_ID an ID from the esp_status table/
505
-     *                       one of the status_id_* on the EEM_Payment model
506
-     * @return boolean whether the status of this payment equals the status id
507
-     * @throws \EE_Error
508
-     */
509
-    protected function status_is($STS_ID)
510
-    {
511
-        return $STS_ID === $this->STS_ID() ? true : false;
512
-    }
513
-
514
-
515
-    /**
516
-     * For determining the status of the payment
517
-     *
518
-     * @return boolean whether the payment is pending or not
519
-     * @throws \EE_Error
520
-     */
521
-    public function is_pending()
522
-    {
523
-        return $this->status_is(EEM_Payment::status_id_pending);
524
-    }
525
-
526
-
527
-    /**
528
-     * For determining the status of the payment
529
-     *
530
-     * @return boolean
531
-     * @throws \EE_Error
532
-     */
533
-    public function is_cancelled()
534
-    {
535
-        return $this->status_is(EEM_Payment::status_id_cancelled);
536
-    }
537
-
538
-
539
-    /**
540
-     * For determining the status of the payment
541
-     *
542
-     * @return boolean
543
-     * @throws \EE_Error
544
-     */
545
-    public function is_declined()
546
-    {
547
-        return $this->status_is(EEM_Payment::status_id_declined);
548
-    }
549
-
550
-
551
-    /**
552
-     * For determining the status of the payment
553
-     *
554
-     * @return boolean
555
-     * @throws \EE_Error
556
-     */
557
-    public function is_failed()
558
-    {
559
-        return $this->status_is(EEM_Payment::status_id_failed);
560
-    }
561
-
562
-
563
-    /**
564
-     * For determining if the payment is actually a refund ( ie: has a negative value )
565
-     *
566
-     * @return boolean
567
-     * @throws \EE_Error
568
-     */
569
-    public function is_a_refund()
570
-    {
571
-        return $this->amount() < 0 ? true : false;
572
-    }
573
-
574
-
575
-    /**
576
-     * Get the status object of this object
577
-     *
578
-     * @return EE_Status
579
-     * @throws \EE_Error
580
-     */
581
-    public function status_obj()
582
-    {
583
-        return $this->get_first_related('Status');
584
-    }
585
-
586
-
587
-    /**
588
-     * Gets all the extra meta info on this payment
589
-     *
590
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
591
-     * @return EE_Extra_Meta
592
-     * @throws \EE_Error
593
-     */
594
-    public function extra_meta($query_params = array())
595
-    {
596
-        return $this->get_many_related('Extra_Meta', $query_params);
597
-    }
598
-
599
-
600
-    /**
601
-     * Gets the last-used payment method on this transaction
602
-     * (we COULD just use the last-made payment, but some payment methods, namely
603
-     * offline ones, dont' create payments)
604
-     *
605
-     * @return EE_Payment_Method
606
-     * @throws \EE_Error
607
-     */
608
-    public function payment_method()
609
-    {
610
-        return $this->get_first_related('Payment_Method');
611
-    }
612
-
613
-
614
-    /**
615
-     * Gets the HTML for redirecting the user to an offsite gateway
616
-     * You can pass it special content to put inside the form, or use
617
-     * the default inner content (or possibly generate this all yourself using
618
-     * redirect_url() and redirect_args() or redirect_args_as_inputs()).
619
-     * Creates a POST request by default, but if no redirect args are specified, creates a GET request instead
620
-     * (and any querystring variables in the redirect_url are converted into html inputs
621
-     * so browsers submit them properly)
622
-     *
623
-     * @param string $inside_form_html
624
-     * @return string html
625
-     * @throws \EE_Error
626
-     */
627
-    public function redirect_form($inside_form_html = null)
628
-    {
629
-        $redirect_url = $this->redirect_url();
630
-        if (! empty($redirect_url)) {
631
-            // what ? no inner form content?
632
-            if ($inside_form_html === null) {
633
-                $inside_form_html = EEH_HTML::p(
634
-                    sprintf(
635
-                        __(
636
-                            'If you are not automatically redirected to the payment website within 10 seconds... %1$s %2$s Click Here %3$s',
637
-                            'event_espresso'
638
-                        ),
639
-                        EEH_HTML::br(2),
640
-                        '<input type="submit" value="',
641
-                        '">'
642
-                    ),
643
-                    '',
644
-                    '',
645
-                    'text-align:center;'
646
-                );
647
-            }
648
-            $method = apply_filters(
649
-                'FHEE__EE_Payment__redirect_form__method',
650
-                $this->redirect_args() ? 'POST' : 'GET',
651
-                $this
652
-            );
653
-            // if it's a GET request, we need to remove all the GET params in the querystring
654
-            // and put them into the form instead
655
-            if ($method === 'GET') {
656
-                $querystring = parse_url($redirect_url, PHP_URL_QUERY);
657
-                $get_params = null;
658
-                parse_str($querystring, $get_params);
659
-                $inside_form_html .= $this->_args_as_inputs($get_params);
660
-                $redirect_url = str_replace('?' . $querystring, '', $redirect_url);
661
-            }
662
-            $form = EEH_HTML::nl(1)
663
-                    . '<form method="'
664
-                    . $method
665
-                    . '" name="gateway_form" action="'
666
-                    . $redirect_url
667
-                    . '">';
668
-            $form .= EEH_HTML::nl(1) . $this->redirect_args_as_inputs();
669
-            $form .= $inside_form_html;
670
-            $form .= EEH_HTML::nl(-1) . '</form>' . EEH_HTML::nl(-1);
671
-            return $form;
672
-        } else {
673
-            return null;
674
-        }
675
-    }
676
-
677
-
678
-    /**
679
-     * Changes all the name-value pairs of the redirect args into html inputs
680
-     * and returns the html as a string
681
-     *
682
-     * @return string
683
-     * @throws \EE_Error
684
-     */
685
-    public function redirect_args_as_inputs()
686
-    {
687
-        return $this->_args_as_inputs($this->redirect_args());
688
-    }
689
-
690
-
691
-    /**
692
-     * Converts a 1d array of key-value pairs into html hidden inputs
693
-     * and returns the string of html
694
-     *
695
-     * @param array $args key-value pairs
696
-     * @return string
697
-     */
698
-    protected function _args_as_inputs($args)
699
-    {
700
-        $html = '';
701
-        if ($args !== null && is_array($args)) {
702
-            foreach ($args as $name => $value) {
703
-                $html .= EEH_HTML::nl(0)
704
-                         . '<input type="hidden" name="'
705
-                         . $name
706
-                         . '" value="'
707
-                         . esc_attr($value)
708
-                         . '"/>';
709
-            }
710
-        }
711
-        return $html;
712
-    }
713
-
714
-
715
-    /**
716
-     * Returns the currency of the payment.
717
-     * (At the time of writing, this will always be the currency in the configuration;
718
-     * however in the future it is anticipated that this will be stored on the payment
719
-     * object itself)
720
-     *
721
-     * @return string for the currency code
722
-     */
723
-    public function currency_code()
724
-    {
725
-        return EE_Config::instance()->currency->code;
726
-    }
727
-
728
-
729
-    /**
730
-     * apply wp_strip_all_tags to all elements within an array
731
-     *
732
-     * @access private
733
-     * @param mixed $item
734
-     */
735
-    private function _strip_all_tags_within_array(&$item)
736
-    {
737
-        if (is_object($item)) {
738
-            $item = (array) $item;
739
-        }
740
-        if (is_array($item)) {
741
-            array_walk_recursive($item, array($this, '_strip_all_tags_within_array'));
742
-        } else {
743
-            $item = wp_strip_all_tags($item);
744
-        }
745
-    }
746
-
747
-
748
-    /**
749
-     * Returns TRUE is this payment was set to approved during this request (or
750
-     * is approved and was created during this request). False otherwise.
751
-     *
752
-     * @return boolean
753
-     * @throws \EE_Error
754
-     */
755
-    public function just_approved()
756
-    {
757
-        $original_status = EEH_Array::is_set(
758
-            $this->_props_n_values_provided_in_constructor,
759
-            'STS_ID',
760
-            $this->get_model()->field_settings_for('STS_ID')->get_default_value()
761
-        );
762
-        $current_status = $this->status();
763
-        if ($original_status !== EEM_Payment::status_id_approved
764
-            && $current_status === EEM_Payment::status_id_approved
765
-        ) {
766
-            return true;
767
-        } else {
768
-            return false;
769
-        }
770
-    }
771
-
772
-
773
-    /**
774
-     * Overrides parents' get_pretty() function just for legacy reasons
775
-     * (to allow ticket https://events.codebasehq.com/projects/event-espresso/tickets/7420)
776
-     *
777
-     * @param string $field_name
778
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
779
-     *                                (in cases where the same property may be used for different outputs
780
-     *                                - i.e. datetime, money etc.)
781
-     * @return mixed
782
-     * @throws \EE_Error
783
-     */
784
-    public function get_pretty($field_name, $extra_cache_ref = null)
785
-    {
786
-        if ($field_name === 'PAY_gateway') {
787
-            return $this->payment_method() ? $this->payment_method()->name() : __('Unknown', 'event_espresso');
788
-        }
789
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
790
-    }
791
-
792
-
793
-    /**
794
-     * Gets details regarding which registrations this payment was applied to
795
-     *
796
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
797
-     * @return EE_Registration_Payment[]
798
-     * @throws \EE_Error
799
-     */
800
-    public function registration_payments($query_params = array())
801
-    {
802
-        return $this->get_many_related('Registration_Payment', $query_params);
803
-    }
804
-
805
-
806
-    /**
807
-     * Gets the first event for this payment (it's possible that it could be for multiple)
808
-     *
809
-     * @return EE_Event|null
810
-     */
811
-    public function get_first_event()
812
-    {
813
-        $transaction = $this->transaction();
814
-        if ($transaction instanceof EE_Transaction) {
815
-            $primary_registrant = $transaction->primary_registration();
816
-            if ($primary_registrant instanceof EE_Registration) {
817
-                return $primary_registrant->event_obj();
818
-            }
819
-        }
820
-        return null;
821
-    }
822
-
823
-
824
-    /**
825
-     * Gets the name of the first event for which is being paid
826
-     *
827
-     * @return string
828
-     */
829
-    public function get_first_event_name()
830
-    {
831
-        $event = $this->get_first_event();
832
-        return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
833
-    }
834
-
835
-
836
-    /**
837
-     * Returns the payment's transaction's primary registration
838
-     *
839
-     * @return EE_Registration|null
840
-     */
841
-    public function get_primary_registration()
842
-    {
843
-        if ($this->transaction() instanceof EE_Transaction) {
844
-            return $this->transaction()->primary_registration();
845
-        }
846
-        return null;
847
-    }
848
-
849
-
850
-    /**
851
-     * Gets the payment's transaction's primary registration's attendee, or null
852
-     *
853
-     * @return EE_Attendee|null
854
-     */
855
-    public function get_primary_attendee()
856
-    {
857
-        $primary_reg = $this->get_primary_registration();
858
-        if ($primary_reg instanceof EE_Registration) {
859
-            return $primary_reg->attendee();
860
-        }
861
-        return null;
862
-    }
12
+	/**
13
+	 * @param array  $props_n_values          incoming values
14
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
15
+	 *                                        used.)
16
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
17
+	 *                                        date_format and the second value is the time format
18
+	 * @return EE_Payment
19
+	 * @throws \EE_Error
20
+	 */
21
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
22
+	{
23
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
24
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
25
+	}
26
+
27
+
28
+	/**
29
+	 * @param array  $props_n_values  incoming values from the database
30
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
31
+	 *                                the website will be used.
32
+	 * @return EE_Payment
33
+	 * @throws \EE_Error
34
+	 */
35
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
36
+	{
37
+		return new self($props_n_values, true, $timezone);
38
+	}
39
+
40
+
41
+	/**
42
+	 * Set Transaction ID
43
+	 *
44
+	 * @access public
45
+	 * @param int $TXN_ID
46
+	 * @throws \EE_Error
47
+	 */
48
+	public function set_transaction_id($TXN_ID = 0)
49
+	{
50
+		$this->set('TXN_ID', $TXN_ID);
51
+	}
52
+
53
+
54
+	/**
55
+	 * Gets the transaction related to this payment
56
+	 *
57
+	 * @return EE_Transaction
58
+	 * @throws \EE_Error
59
+	 */
60
+	public function transaction()
61
+	{
62
+		return $this->get_first_related('Transaction');
63
+	}
64
+
65
+
66
+	/**
67
+	 * Set Status
68
+	 *
69
+	 * @access public
70
+	 * @param string $STS_ID
71
+	 * @throws \EE_Error
72
+	 */
73
+	public function set_status($STS_ID = '')
74
+	{
75
+		$this->set('STS_ID', $STS_ID);
76
+	}
77
+
78
+
79
+	/**
80
+	 * Set Payment Timestamp
81
+	 *
82
+	 * @access public
83
+	 * @param int $timestamp
84
+	 * @throws \EE_Error
85
+	 */
86
+	public function set_timestamp($timestamp = 0)
87
+	{
88
+		$this->set('PAY_timestamp', $timestamp);
89
+	}
90
+
91
+
92
+	/**
93
+	 * Set Payment Method
94
+	 *
95
+	 * @access public
96
+	 * @param string $PAY_source
97
+	 * @throws \EE_Error
98
+	 */
99
+	public function set_source($PAY_source = '')
100
+	{
101
+		$this->set('PAY_source', $PAY_source);
102
+	}
103
+
104
+
105
+	/**
106
+	 * Set Payment Amount
107
+	 *
108
+	 * @access public
109
+	 * @param float $amount
110
+	 * @throws \EE_Error
111
+	 */
112
+	public function set_amount($amount = 0.00)
113
+	{
114
+		$this->set('PAY_amount', (float) $amount);
115
+	}
116
+
117
+
118
+	/**
119
+	 * Set Payment Gateway Response
120
+	 *
121
+	 * @access public
122
+	 * @param string $gateway_response
123
+	 * @throws \EE_Error
124
+	 */
125
+	public function set_gateway_response($gateway_response = '')
126
+	{
127
+		$this->set('PAY_gateway_response', $gateway_response);
128
+	}
129
+
130
+
131
+	/**
132
+	 * Returns the name of the payment method used on this payment (previously known merely as 'gateway')
133
+	 * but since 4.6.0, payment methods are models and the payment keeps a foreign key to the payment method
134
+	 * used on it
135
+	 *
136
+	 * @deprecated
137
+	 * @return string
138
+	 * @throws \EE_Error
139
+	 */
140
+	public function gateway()
141
+	{
142
+		EE_Error::doing_it_wrong(
143
+			'EE_Payment::gateway',
144
+			__(
145
+				'The method EE_Payment::gateway() has been deprecated. Consider instead using EE_Payment::payment_method()->name()',
146
+				'event_espresso'
147
+			),
148
+			'4.6.0'
149
+		);
150
+		return $this->payment_method() ? $this->payment_method()->name() : __('Unknown', 'event_espresso');
151
+	}
152
+
153
+
154
+	/**
155
+	 * Set Gateway Transaction ID
156
+	 *
157
+	 * @access public
158
+	 * @param string $txn_id_chq_nmbr
159
+	 * @throws \EE_Error
160
+	 */
161
+	public function set_txn_id_chq_nmbr($txn_id_chq_nmbr = '')
162
+	{
163
+		$this->set('PAY_txn_id_chq_nmbr', $txn_id_chq_nmbr);
164
+	}
165
+
166
+
167
+	/**
168
+	 * Set Purchase Order Number
169
+	 *
170
+	 * @access public
171
+	 * @param string $po_number
172
+	 * @throws \EE_Error
173
+	 */
174
+	public function set_po_number($po_number = '')
175
+	{
176
+		$this->set('PAY_po_number', $po_number);
177
+	}
178
+
179
+
180
+	/**
181
+	 * Set Extra Accounting Field
182
+	 *
183
+	 * @access public
184
+	 * @param string $extra_accntng
185
+	 * @throws \EE_Error
186
+	 */
187
+	public function set_extra_accntng($extra_accntng = '')
188
+	{
189
+		$this->set('PAY_extra_accntng', $extra_accntng);
190
+	}
191
+
192
+
193
+	/**
194
+	 * Set Payment made via admin flag
195
+	 *
196
+	 * @access public
197
+	 * @param bool $via_admin
198
+	 * @throws \EE_Error
199
+	 */
200
+	public function set_payment_made_via_admin($via_admin = false)
201
+	{
202
+		if ($via_admin) {
203
+			$this->set('PAY_source', EEM_Payment_Method::scope_admin);
204
+		} else {
205
+			$this->set('PAY_source', EEM_Payment_Method::scope_cart);
206
+		}
207
+	}
208
+
209
+
210
+	/**
211
+	 * Set Payment Details
212
+	 *
213
+	 * @access public
214
+	 * @param string|array $details
215
+	 * @throws \EE_Error
216
+	 */
217
+	public function set_details($details = '')
218
+	{
219
+		if (is_array($details)) {
220
+			array_walk_recursive($details, array($this, '_strip_all_tags_within_array'));
221
+		} else {
222
+			$details = wp_strip_all_tags($details);
223
+		}
224
+		$this->set('PAY_details', $details);
225
+	}
226
+
227
+
228
+	/**
229
+	 * Sets redirect_url
230
+	 *
231
+	 * @param string $redirect_url
232
+	 * @throws \EE_Error
233
+	 */
234
+	public function set_redirect_url($redirect_url)
235
+	{
236
+		$this->set('PAY_redirect_url', $redirect_url);
237
+	}
238
+
239
+
240
+	/**
241
+	 * Sets redirect_args
242
+	 *
243
+	 * @param array $redirect_args
244
+	 * @throws \EE_Error
245
+	 */
246
+	public function set_redirect_args($redirect_args)
247
+	{
248
+		$this->set('PAY_redirect_args', $redirect_args);
249
+	}
250
+
251
+
252
+	/**
253
+	 * get Payment Transaction ID
254
+	 *
255
+	 * @access public
256
+	 * @throws \EE_Error
257
+	 */
258
+	public function TXN_ID()
259
+	{
260
+		return $this->get('TXN_ID');
261
+	}
262
+
263
+
264
+	/**
265
+	 * get Payment Status
266
+	 *
267
+	 * @access public
268
+	 * @throws \EE_Error
269
+	 */
270
+	public function status()
271
+	{
272
+		return $this->get('STS_ID');
273
+	}
274
+
275
+
276
+	/**
277
+	 * get Payment Status
278
+	 *
279
+	 * @access public
280
+	 * @throws \EE_Error
281
+	 */
282
+	public function STS_ID()
283
+	{
284
+		return $this->get('STS_ID');
285
+	}
286
+
287
+
288
+	/**
289
+	 * get Payment Timestamp
290
+	 *
291
+	 * @access public
292
+	 * @param string $dt_frmt
293
+	 * @param string $tm_frmt
294
+	 * @return string
295
+	 * @throws \EE_Error
296
+	 */
297
+	public function timestamp($dt_frmt = '', $tm_frmt = '')
298
+	{
299
+		return $this->get_i18n_datetime('PAY_timestamp', trim($dt_frmt . ' ' . $tm_frmt));
300
+	}
301
+
302
+
303
+	/**
304
+	 * get Payment Source
305
+	 *
306
+	 * @access public
307
+	 * @throws \EE_Error
308
+	 */
309
+	public function source()
310
+	{
311
+		return $this->get('PAY_source');
312
+	}
313
+
314
+
315
+	/**
316
+	 * get Payment Amount
317
+	 *
318
+	 * @access public
319
+	 * @return float
320
+	 * @throws \EE_Error
321
+	 */
322
+	public function amount()
323
+	{
324
+		return (float) $this->get('PAY_amount');
325
+	}
326
+
327
+
328
+	/**
329
+	 * @return mixed
330
+	 * @throws \EE_Error
331
+	 */
332
+	public function amount_no_code()
333
+	{
334
+		return $this->get_pretty('PAY_amount', 'no_currency_code');
335
+	}
336
+
337
+
338
+	/**
339
+	 * get Payment Gateway Response
340
+	 *
341
+	 * @access public
342
+	 * @throws \EE_Error
343
+	 */
344
+	public function gateway_response()
345
+	{
346
+		return $this->get('PAY_gateway_response');
347
+	}
348
+
349
+
350
+	/**
351
+	 * get Payment Gateway Transaction ID
352
+	 *
353
+	 * @access public
354
+	 * @throws \EE_Error
355
+	 */
356
+	public function txn_id_chq_nmbr()
357
+	{
358
+		return $this->get('PAY_txn_id_chq_nmbr');
359
+	}
360
+
361
+
362
+	/**
363
+	 * get Purchase Order Number
364
+	 *
365
+	 * @access public
366
+	 * @throws \EE_Error
367
+	 */
368
+	public function po_number()
369
+	{
370
+		return $this->get('PAY_po_number');
371
+	}
372
+
373
+
374
+	/**
375
+	 * get Extra Accounting Field
376
+	 *
377
+	 * @access public
378
+	 * @throws \EE_Error
379
+	 */
380
+	public function extra_accntng()
381
+	{
382
+		return $this->get('PAY_extra_accntng');
383
+	}
384
+
385
+
386
+	/**
387
+	 * get Payment made via admin source
388
+	 *
389
+	 * @access public
390
+	 * @throws \EE_Error
391
+	 */
392
+	public function payment_made_via_admin()
393
+	{
394
+		return ($this->get('PAY_source') === EEM_Payment_Method::scope_admin);
395
+	}
396
+
397
+
398
+	/**
399
+	 * get Payment Details
400
+	 *
401
+	 * @access public
402
+	 * @throws \EE_Error
403
+	 */
404
+	public function details()
405
+	{
406
+		return $this->get('PAY_details');
407
+	}
408
+
409
+
410
+	/**
411
+	 * Gets redirect_url
412
+	 *
413
+	 * @return string
414
+	 * @throws \EE_Error
415
+	 */
416
+	public function redirect_url()
417
+	{
418
+		return $this->get('PAY_redirect_url');
419
+	}
420
+
421
+
422
+	/**
423
+	 * Gets redirect_args
424
+	 *
425
+	 * @return array
426
+	 * @throws \EE_Error
427
+	 */
428
+	public function redirect_args()
429
+	{
430
+		return $this->get('PAY_redirect_args');
431
+	}
432
+
433
+
434
+	/**
435
+	 * echoes $this->pretty_status()
436
+	 *
437
+	 * @param bool $show_icons
438
+	 * @return void
439
+	 * @throws \EE_Error
440
+	 */
441
+	public function e_pretty_status($show_icons = false)
442
+	{
443
+		echo $this->pretty_status($show_icons);
444
+	}
445
+
446
+
447
+	/**
448
+	 * returns a pretty version of the status, good for displaying to users
449
+	 *
450
+	 * @param bool $show_icons
451
+	 * @return string
452
+	 * @throws \EE_Error
453
+	 */
454
+	public function pretty_status($show_icons = false)
455
+	{
456
+		$status = EEM_Status::instance()->localized_status(
457
+			array($this->STS_ID() => __('unknown', 'event_espresso')),
458
+			false,
459
+			'sentence'
460
+		);
461
+		$icon = '';
462
+		switch ($this->STS_ID()) {
463
+			case EEM_Payment::status_id_approved:
464
+				$icon = $show_icons
465
+					? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>'
466
+					: '';
467
+				break;
468
+			case EEM_Payment::status_id_pending:
469
+				$icon = $show_icons
470
+					? '<span class="dashicons dashicons-clock ee-icon-size-16 orange-text"></span>'
471
+					: '';
472
+				break;
473
+			case EEM_Payment::status_id_cancelled:
474
+				$icon = $show_icons
475
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
476
+					: '';
477
+				break;
478
+			case EEM_Payment::status_id_declined:
479
+				$icon = $show_icons
480
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
481
+					: '';
482
+				break;
483
+		}
484
+		return $icon . $status[ $this->STS_ID() ];
485
+	}
486
+
487
+
488
+	/**
489
+	 * For determining the status of the payment
490
+	 *
491
+	 * @return boolean whether the payment is approved or not
492
+	 * @throws \EE_Error
493
+	 */
494
+	public function is_approved()
495
+	{
496
+		return $this->status_is(EEM_Payment::status_id_approved);
497
+	}
498
+
499
+
500
+	/**
501
+	 * Generally determines if the status of this payment equals
502
+	 * the $STS_ID string
503
+	 *
504
+	 * @param string $STS_ID an ID from the esp_status table/
505
+	 *                       one of the status_id_* on the EEM_Payment model
506
+	 * @return boolean whether the status of this payment equals the status id
507
+	 * @throws \EE_Error
508
+	 */
509
+	protected function status_is($STS_ID)
510
+	{
511
+		return $STS_ID === $this->STS_ID() ? true : false;
512
+	}
513
+
514
+
515
+	/**
516
+	 * For determining the status of the payment
517
+	 *
518
+	 * @return boolean whether the payment is pending or not
519
+	 * @throws \EE_Error
520
+	 */
521
+	public function is_pending()
522
+	{
523
+		return $this->status_is(EEM_Payment::status_id_pending);
524
+	}
525
+
526
+
527
+	/**
528
+	 * For determining the status of the payment
529
+	 *
530
+	 * @return boolean
531
+	 * @throws \EE_Error
532
+	 */
533
+	public function is_cancelled()
534
+	{
535
+		return $this->status_is(EEM_Payment::status_id_cancelled);
536
+	}
537
+
538
+
539
+	/**
540
+	 * For determining the status of the payment
541
+	 *
542
+	 * @return boolean
543
+	 * @throws \EE_Error
544
+	 */
545
+	public function is_declined()
546
+	{
547
+		return $this->status_is(EEM_Payment::status_id_declined);
548
+	}
549
+
550
+
551
+	/**
552
+	 * For determining the status of the payment
553
+	 *
554
+	 * @return boolean
555
+	 * @throws \EE_Error
556
+	 */
557
+	public function is_failed()
558
+	{
559
+		return $this->status_is(EEM_Payment::status_id_failed);
560
+	}
561
+
562
+
563
+	/**
564
+	 * For determining if the payment is actually a refund ( ie: has a negative value )
565
+	 *
566
+	 * @return boolean
567
+	 * @throws \EE_Error
568
+	 */
569
+	public function is_a_refund()
570
+	{
571
+		return $this->amount() < 0 ? true : false;
572
+	}
573
+
574
+
575
+	/**
576
+	 * Get the status object of this object
577
+	 *
578
+	 * @return EE_Status
579
+	 * @throws \EE_Error
580
+	 */
581
+	public function status_obj()
582
+	{
583
+		return $this->get_first_related('Status');
584
+	}
585
+
586
+
587
+	/**
588
+	 * Gets all the extra meta info on this payment
589
+	 *
590
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
591
+	 * @return EE_Extra_Meta
592
+	 * @throws \EE_Error
593
+	 */
594
+	public function extra_meta($query_params = array())
595
+	{
596
+		return $this->get_many_related('Extra_Meta', $query_params);
597
+	}
598
+
599
+
600
+	/**
601
+	 * Gets the last-used payment method on this transaction
602
+	 * (we COULD just use the last-made payment, but some payment methods, namely
603
+	 * offline ones, dont' create payments)
604
+	 *
605
+	 * @return EE_Payment_Method
606
+	 * @throws \EE_Error
607
+	 */
608
+	public function payment_method()
609
+	{
610
+		return $this->get_first_related('Payment_Method');
611
+	}
612
+
613
+
614
+	/**
615
+	 * Gets the HTML for redirecting the user to an offsite gateway
616
+	 * You can pass it special content to put inside the form, or use
617
+	 * the default inner content (or possibly generate this all yourself using
618
+	 * redirect_url() and redirect_args() or redirect_args_as_inputs()).
619
+	 * Creates a POST request by default, but if no redirect args are specified, creates a GET request instead
620
+	 * (and any querystring variables in the redirect_url are converted into html inputs
621
+	 * so browsers submit them properly)
622
+	 *
623
+	 * @param string $inside_form_html
624
+	 * @return string html
625
+	 * @throws \EE_Error
626
+	 */
627
+	public function redirect_form($inside_form_html = null)
628
+	{
629
+		$redirect_url = $this->redirect_url();
630
+		if (! empty($redirect_url)) {
631
+			// what ? no inner form content?
632
+			if ($inside_form_html === null) {
633
+				$inside_form_html = EEH_HTML::p(
634
+					sprintf(
635
+						__(
636
+							'If you are not automatically redirected to the payment website within 10 seconds... %1$s %2$s Click Here %3$s',
637
+							'event_espresso'
638
+						),
639
+						EEH_HTML::br(2),
640
+						'<input type="submit" value="',
641
+						'">'
642
+					),
643
+					'',
644
+					'',
645
+					'text-align:center;'
646
+				);
647
+			}
648
+			$method = apply_filters(
649
+				'FHEE__EE_Payment__redirect_form__method',
650
+				$this->redirect_args() ? 'POST' : 'GET',
651
+				$this
652
+			);
653
+			// if it's a GET request, we need to remove all the GET params in the querystring
654
+			// and put them into the form instead
655
+			if ($method === 'GET') {
656
+				$querystring = parse_url($redirect_url, PHP_URL_QUERY);
657
+				$get_params = null;
658
+				parse_str($querystring, $get_params);
659
+				$inside_form_html .= $this->_args_as_inputs($get_params);
660
+				$redirect_url = str_replace('?' . $querystring, '', $redirect_url);
661
+			}
662
+			$form = EEH_HTML::nl(1)
663
+					. '<form method="'
664
+					. $method
665
+					. '" name="gateway_form" action="'
666
+					. $redirect_url
667
+					. '">';
668
+			$form .= EEH_HTML::nl(1) . $this->redirect_args_as_inputs();
669
+			$form .= $inside_form_html;
670
+			$form .= EEH_HTML::nl(-1) . '</form>' . EEH_HTML::nl(-1);
671
+			return $form;
672
+		} else {
673
+			return null;
674
+		}
675
+	}
676
+
677
+
678
+	/**
679
+	 * Changes all the name-value pairs of the redirect args into html inputs
680
+	 * and returns the html as a string
681
+	 *
682
+	 * @return string
683
+	 * @throws \EE_Error
684
+	 */
685
+	public function redirect_args_as_inputs()
686
+	{
687
+		return $this->_args_as_inputs($this->redirect_args());
688
+	}
689
+
690
+
691
+	/**
692
+	 * Converts a 1d array of key-value pairs into html hidden inputs
693
+	 * and returns the string of html
694
+	 *
695
+	 * @param array $args key-value pairs
696
+	 * @return string
697
+	 */
698
+	protected function _args_as_inputs($args)
699
+	{
700
+		$html = '';
701
+		if ($args !== null && is_array($args)) {
702
+			foreach ($args as $name => $value) {
703
+				$html .= EEH_HTML::nl(0)
704
+						 . '<input type="hidden" name="'
705
+						 . $name
706
+						 . '" value="'
707
+						 . esc_attr($value)
708
+						 . '"/>';
709
+			}
710
+		}
711
+		return $html;
712
+	}
713
+
714
+
715
+	/**
716
+	 * Returns the currency of the payment.
717
+	 * (At the time of writing, this will always be the currency in the configuration;
718
+	 * however in the future it is anticipated that this will be stored on the payment
719
+	 * object itself)
720
+	 *
721
+	 * @return string for the currency code
722
+	 */
723
+	public function currency_code()
724
+	{
725
+		return EE_Config::instance()->currency->code;
726
+	}
727
+
728
+
729
+	/**
730
+	 * apply wp_strip_all_tags to all elements within an array
731
+	 *
732
+	 * @access private
733
+	 * @param mixed $item
734
+	 */
735
+	private function _strip_all_tags_within_array(&$item)
736
+	{
737
+		if (is_object($item)) {
738
+			$item = (array) $item;
739
+		}
740
+		if (is_array($item)) {
741
+			array_walk_recursive($item, array($this, '_strip_all_tags_within_array'));
742
+		} else {
743
+			$item = wp_strip_all_tags($item);
744
+		}
745
+	}
746
+
747
+
748
+	/**
749
+	 * Returns TRUE is this payment was set to approved during this request (or
750
+	 * is approved and was created during this request). False otherwise.
751
+	 *
752
+	 * @return boolean
753
+	 * @throws \EE_Error
754
+	 */
755
+	public function just_approved()
756
+	{
757
+		$original_status = EEH_Array::is_set(
758
+			$this->_props_n_values_provided_in_constructor,
759
+			'STS_ID',
760
+			$this->get_model()->field_settings_for('STS_ID')->get_default_value()
761
+		);
762
+		$current_status = $this->status();
763
+		if ($original_status !== EEM_Payment::status_id_approved
764
+			&& $current_status === EEM_Payment::status_id_approved
765
+		) {
766
+			return true;
767
+		} else {
768
+			return false;
769
+		}
770
+	}
771
+
772
+
773
+	/**
774
+	 * Overrides parents' get_pretty() function just for legacy reasons
775
+	 * (to allow ticket https://events.codebasehq.com/projects/event-espresso/tickets/7420)
776
+	 *
777
+	 * @param string $field_name
778
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
779
+	 *                                (in cases where the same property may be used for different outputs
780
+	 *                                - i.e. datetime, money etc.)
781
+	 * @return mixed
782
+	 * @throws \EE_Error
783
+	 */
784
+	public function get_pretty($field_name, $extra_cache_ref = null)
785
+	{
786
+		if ($field_name === 'PAY_gateway') {
787
+			return $this->payment_method() ? $this->payment_method()->name() : __('Unknown', 'event_espresso');
788
+		}
789
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
790
+	}
791
+
792
+
793
+	/**
794
+	 * Gets details regarding which registrations this payment was applied to
795
+	 *
796
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
797
+	 * @return EE_Registration_Payment[]
798
+	 * @throws \EE_Error
799
+	 */
800
+	public function registration_payments($query_params = array())
801
+	{
802
+		return $this->get_many_related('Registration_Payment', $query_params);
803
+	}
804
+
805
+
806
+	/**
807
+	 * Gets the first event for this payment (it's possible that it could be for multiple)
808
+	 *
809
+	 * @return EE_Event|null
810
+	 */
811
+	public function get_first_event()
812
+	{
813
+		$transaction = $this->transaction();
814
+		if ($transaction instanceof EE_Transaction) {
815
+			$primary_registrant = $transaction->primary_registration();
816
+			if ($primary_registrant instanceof EE_Registration) {
817
+				return $primary_registrant->event_obj();
818
+			}
819
+		}
820
+		return null;
821
+	}
822
+
823
+
824
+	/**
825
+	 * Gets the name of the first event for which is being paid
826
+	 *
827
+	 * @return string
828
+	 */
829
+	public function get_first_event_name()
830
+	{
831
+		$event = $this->get_first_event();
832
+		return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
833
+	}
834
+
835
+
836
+	/**
837
+	 * Returns the payment's transaction's primary registration
838
+	 *
839
+	 * @return EE_Registration|null
840
+	 */
841
+	public function get_primary_registration()
842
+	{
843
+		if ($this->transaction() instanceof EE_Transaction) {
844
+			return $this->transaction()->primary_registration();
845
+		}
846
+		return null;
847
+	}
848
+
849
+
850
+	/**
851
+	 * Gets the payment's transaction's primary registration's attendee, or null
852
+	 *
853
+	 * @return EE_Attendee|null
854
+	 */
855
+	public function get_primary_attendee()
856
+	{
857
+		$primary_reg = $this->get_primary_registration();
858
+		if ($primary_reg instanceof EE_Registration) {
859
+			return $primary_reg->attendee();
860
+		}
861
+		return null;
862
+	}
863 863
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Doc Comments   +15 added lines, -13 removed lines patch added patch discarded remove patch
@@ -862,7 +862,7 @@  discard block
 block discarded – undo
862 862
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
863 863
      * foreign key to the WP_User table)
864 864
      *
865
-     * @return string|boolean string on success, boolean false when there is no
865
+     * @return string|false string on success, boolean false when there is no
866 866
      * foreign key to the WP_User table
867 867
      */
868 868
     public function wp_user_field_name()
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
      *
994 994
      * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
995 995
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
996
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
996
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
997 997
      *                                  fields on the model, and the models we joined to in the query. However, you can
998 998
      *                                  override this and set the select to "*", or a specific column name, like
999 999
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1419,7 +1419,7 @@  discard block
 block discarded – undo
1419 1419
      * @param string $field_name The name of the field the formats are being retrieved for.
1420 1420
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1421 1421
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1422
-     * @return array formats in an array with the date format first, and the time format last.
1422
+     * @return string[] formats in an array with the date format first, and the time format last.
1423 1423
      */
1424 1424
     public function get_formats_for($field_name, $pretty = false)
1425 1425
     {
@@ -1456,7 +1456,7 @@  discard block
 block discarded – undo
1456 1456
      *                                 be returned.
1457 1457
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1458 1458
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1459
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1459
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1460 1460
      *                                 exception is triggered.
1461 1461
      */
1462 1462
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1496,7 +1496,7 @@  discard block
 block discarded – undo
1496 1496
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1497 1497
      *                                format is
1498 1498
      *                                'U', this is ignored.
1499
-     * @return DateTime
1499
+     * @return string
1500 1500
      * @throws EE_Error
1501 1501
      */
1502 1502
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2387,7 +2387,7 @@  discard block
 block discarded – undo
2387 2387
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2388 2388
      * EEM_Base::$_db_verification_level
2389 2389
      *
2390
-     * @param $wpdb_method
2390
+     * @param string $wpdb_method
2391 2391
      * @param $arguments_to_provide
2392 2392
      * @return string
2393 2393
      */
@@ -2513,6 +2513,7 @@  discard block
 block discarded – undo
2513 2513
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2514 2514
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2515 2515
      *                             because these will be inserted in any new rows created as well.
2516
+     * @param EE_Base_Class $id_or_obj
2516 2517
      */
2517 2518
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2518 2519
     {
@@ -2523,7 +2524,7 @@  discard block
 block discarded – undo
2523 2524
 
2524 2525
 
2525 2526
     /**
2526
-     * @param mixed           $id_or_obj
2527
+     * @param EE_Base_Class           $id_or_obj
2527 2528
      * @param string          $relationName
2528 2529
      * @param array           $where_query_params
2529 2530
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2564,7 +2565,7 @@  discard block
 block discarded – undo
2564 2565
      * However, if the model objects can't be deleted because of blocking related model objects, then
2565 2566
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2566 2567
      *
2567
-     * @param EE_Base_Class|int|string $id_or_obj
2568
+     * @param EE_Base_Class $id_or_obj
2568 2569
      * @param string                   $model_name
2569 2570
      * @param array                    $query_params
2570 2571
      * @return int how many deleted
@@ -2585,7 +2586,7 @@  discard block
 block discarded – undo
2585 2586
      * the model objects can't be hard deleted because of blocking related model objects,
2586 2587
      * just does a soft-delete on them instead.
2587 2588
      *
2588
-     * @param EE_Base_Class|int|string $id_or_obj
2589
+     * @param EE_Base_Class $id_or_obj
2589 2590
      * @param string                   $model_name
2590 2591
      * @param array                    $query_params
2591 2592
      * @return int how many deleted
@@ -2642,6 +2643,7 @@  discard block
 block discarded – undo
2642 2643
      * @param string $model_name   like 'Event', or 'Registration'
2643 2644
      * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2644 2645
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2646
+     * @param EE_Base_Class $id_or_obj
2645 2647
      * @return float
2646 2648
      * @throws EE_Error
2647 2649
      */
@@ -3645,7 +3647,7 @@  discard block
 block discarded – undo
3645 3647
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3646 3648
      * We should use default where conditions on related models when they requested to use default where conditions
3647 3649
      * on all models, or specifically just on other related models
3648
-     * @param      $default_where_conditions_value
3650
+     * @param      string $default_where_conditions_value
3649 3651
      * @param bool $for_this_model false means this is for OTHER related models
3650 3652
      * @return bool
3651 3653
      */
@@ -3683,7 +3685,7 @@  discard block
 block discarded – undo
3683 3685
      * where conditions.
3684 3686
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3685 3687
      * on this model or others
3686
-     * @param      $default_where_conditions_value
3688
+     * @param      string $default_where_conditions_value
3687 3689
      * @param bool $for_this_model false means this is for OTHER related models
3688 3690
      * @return bool
3689 3691
      */
@@ -4862,7 +4864,7 @@  discard block
 block discarded – undo
4862 4864
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4863 4865
      * Eg, on EE_Answer that would be ANS_ID field object
4864 4866
      *
4865
-     * @param $field_obj
4867
+     * @param EE_Model_Field_Base $field_obj
4866 4868
      * @return boolean
4867 4869
      */
4868 4870
     public function is_primary_key_field($field_obj)
@@ -5654,7 +5656,7 @@  discard block
 block discarded – undo
5654 5656
     /**
5655 5657
      * Read comments for assume_values_already_prepared_by_model_object()
5656 5658
      *
5657
-     * @return int
5659
+     * @return boolean
5658 5660
      */
5659 5661
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5660 5662
     {
Please login to merge, or discard this patch.
Indentation   +6222 added lines, -6222 removed lines patch added patch discarded remove patch
@@ -34,6228 +34,6228 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error(
520
-                sprintf(
521
-                    __(
522
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
-                        'event_espresso'
524
-                    ),
525
-                    get_class($this)
526
-                )
527
-            );
528
-        }
529
-        /**
530
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
-         */
532
-        if (empty(EEM_Base::$_model_query_blog_id)) {
533
-            EEM_Base::set_model_query_blog_id();
534
-        }
535
-        /**
536
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
-         * just use EE_Register_Model_Extension
538
-         *
539
-         * @var EE_Table_Base[] $_tables
540
-         */
541
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
-        foreach ($this->_tables as $table_alias => $table_obj) {
543
-            /** @var $table_obj EE_Table_Base */
544
-            $table_obj->_construct_finalize_with_alias($table_alias);
545
-            if ($table_obj instanceof EE_Secondary_Table) {
546
-                /** @var $table_obj EE_Secondary_Table */
547
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
-            }
549
-        }
550
-        /**
551
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
-         * EE_Register_Model_Extension
553
-         *
554
-         * @param EE_Model_Field_Base[] $_fields
555
-         */
556
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
-        $this->_invalidate_field_caches();
558
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
559
-            if (! array_key_exists($table_alias, $this->_tables)) {
560
-                throw new EE_Error(sprintf(__(
561
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
-                    'event_espresso'
563
-                ), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                // primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            // make extra meta related to everything, but don't block deleting things just
575
-            // because they have related extra meta info. For now just orphan those extra meta
576
-            // in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        // and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = (array) apply_filters(
590
-            'FHEE__' . get_class($this) . '__construct__model_relations',
591
-            $this->_model_relations
592
-        );
593
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
594
-            /** @var $relation_obj EE_Model_Relation_Base */
595
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
-        }
597
-        foreach ($this->_indexes as $index_name => $index_obj) {
598
-            /** @var $index_obj EE_Index */
599
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
-        }
601
-        $this->set_timezone($timezone);
602
-        // finalize default where condition strategy, or set default
603
-        if (! $this->_default_where_conditions_strategy) {
604
-            // nothing was set during child constructor, so set default
605
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
608
-        if (! $this->_minimum_where_conditions_strategy) {
609
-            // nothing was set during child constructor, so set default
610
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
-        }
612
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
614
-        // to indicate to NOT set it, set it to the logical default
615
-        if ($this->_caps_slug === null) {
616
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
-        }
618
-        // initialize the standard cap restriction generators if none were specified by the child constructor
619
-        if ($this->_cap_restriction_generators !== false) {
620
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
-                        new EE_Restriction_Generator_Protected(),
625
-                        $cap_context,
626
-                        $this
627
-                    );
628
-                }
629
-            }
630
-        }
631
-        // if there are cap restriction generators, use them to make the default cap restrictions
632
-        if ($this->_cap_restriction_generators !== false) {
633
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
-                if (! $generator_object) {
635
-                    continue;
636
-                }
637
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
-                    throw new EE_Error(
639
-                        sprintf(
640
-                            __(
641
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
642
-                                'event_espresso'
643
-                            ),
644
-                            $context,
645
-                            $this->get_this_model_name()
646
-                        )
647
-                    );
648
-                }
649
-                $action = $this->cap_action_for_context($context);
650
-                if (! $generator_object->construction_finalized()) {
651
-                    $generator_object->_construct_finalize($this, $action);
652
-                }
653
-            }
654
-        }
655
-        do_action('AHEE__' . get_class($this) . '__construct__end');
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     * Used to set the $_model_query_blog_id static property.
662
-     *
663
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
-     *                      value for get_current_blog_id() will be used.
665
-     */
666
-    public static function set_model_query_blog_id($blog_id = 0)
667
-    {
668
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * Returns whatever is set as the internal $model_query_blog_id.
675
-     *
676
-     * @return int
677
-     */
678
-    public static function get_model_query_blog_id()
679
-    {
680
-        return EEM_Base::$_model_query_blog_id;
681
-    }
682
-
683
-
684
-
685
-    /**
686
-     * This function is a singleton method used to instantiate the Espresso_model object
687
-     *
688
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
-     *                                (and any incoming timezone data that gets saved).
690
-     *                                Note this just sends the timezone info to the date time model field objects.
691
-     *                                Default is NULL
692
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
-     * @return static (as in the concrete child class)
694
-     * @throws EE_Error
695
-     * @throws InvalidArgumentException
696
-     * @throws InvalidDataTypeException
697
-     * @throws InvalidInterfaceException
698
-     */
699
-    public static function instance($timezone = null)
700
-    {
701
-        // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
703
-            // instantiate Espresso_model
704
-            static::$_instance = new static(
705
-                $timezone,
706
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
-            );
708
-        }
709
-        // we might have a timezone set, let set_timezone decide what to do with it
710
-        static::$_instance->set_timezone($timezone);
711
-        // Espresso_model object
712
-        return static::$_instance;
713
-    }
714
-
715
-
716
-
717
-    /**
718
-     * resets the model and returns it
719
-     *
720
-     * @param null | string $timezone
721
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
-     * all its properties reset; if it wasn't instantiated, returns null)
723
-     * @throws EE_Error
724
-     * @throws ReflectionException
725
-     * @throws InvalidArgumentException
726
-     * @throws InvalidDataTypeException
727
-     * @throws InvalidInterfaceException
728
-     */
729
-    public static function reset($timezone = null)
730
-    {
731
-        if (static::$_instance instanceof EEM_Base) {
732
-            // let's try to NOT swap out the current instance for a new one
733
-            // because if someone has a reference to it, we can't remove their reference
734
-            // so it's best to keep using the same reference, but change the original object
735
-            // reset all its properties to their original values as defined in the class
736
-            $r = new ReflectionClass(get_class(static::$_instance));
737
-            $static_properties = $r->getStaticProperties();
738
-            foreach ($r->getDefaultProperties() as $property => $value) {
739
-                // don't set instance to null like it was originally,
740
-                // but it's static anyways, and we're ignoring static properties (for now at least)
741
-                if (! isset($static_properties[ $property ])) {
742
-                    static::$_instance->{$property} = $value;
743
-                }
744
-            }
745
-            // and then directly call its constructor again, like we would if we were creating a new one
746
-            static::$_instance->__construct(
747
-                $timezone,
748
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
-            );
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * @return LoaderInterface
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     */
763
-    private static function getLoader()
764
-    {
765
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
766
-            EEM_Base::$loader = LoaderFactory::getLoader();
767
-        }
768
-        return EEM_Base::$loader;
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
-     *
776
-     * @param  boolean $translated return localized strings or JUST the array.
777
-     * @return array
778
-     * @throws EE_Error
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidDataTypeException
781
-     * @throws InvalidInterfaceException
782
-     */
783
-    public function status_array($translated = false)
784
-    {
785
-        if (! array_key_exists('Status', $this->_model_relations)) {
786
-            return array();
787
-        }
788
-        $model_name = $this->get_this_model_name();
789
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
-        $status_array = array();
792
-        foreach ($stati as $status) {
793
-            $status_array[ $status->ID() ] = $status->get('STS_code');
794
-        }
795
-        return $translated
796
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
-            : $status_array;
798
-    }
799
-
800
-
801
-
802
-    /**
803
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
-     *
805
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
806
-     *                             or if you have the development copy of EE you can view this at the path:
807
-     *                             /docs/G--Model-System/model-query-params.md
808
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
809
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
810
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
811
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
812
-     *                                        array( array(
813
-     *                                        'OR'=>array(
814
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
815
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
816
-     *                                        )
817
-     *                                        ),
818
-     *                                        'limit'=>10,
819
-     *                                        'group_by'=>'TXN_ID'
820
-     *                                        ));
821
-     *                                        get all the answers to the question titled "shirt size" for event with id
822
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
823
-     *                                        'Question.QST_display_text'=>'shirt size',
824
-     *                                        'Registration.Event.EVT_ID'=>12
825
-     *                                        ),
826
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
827
-     *                                        ));
828
-     * @throws EE_Error
829
-     */
830
-    public function get_all($query_params = array())
831
-    {
832
-        if (isset($query_params['limit'])
833
-            && ! isset($query_params['group_by'])
834
-        ) {
835
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
836
-        }
837
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * Modifies the query parameters so we only get back model objects
844
-     * that "belong" to the current user
845
-     *
846
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
847
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
848
-     */
849
-    public function alter_query_params_to_only_include_mine($query_params = array())
850
-    {
851
-        $wp_user_field_name = $this->wp_user_field_name();
852
-        if ($wp_user_field_name) {
853
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
854
-        }
855
-        return $query_params;
856
-    }
857
-
858
-
859
-
860
-    /**
861
-     * Returns the name of the field's name that points to the WP_User table
862
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
863
-     * foreign key to the WP_User table)
864
-     *
865
-     * @return string|boolean string on success, boolean false when there is no
866
-     * foreign key to the WP_User table
867
-     */
868
-    public function wp_user_field_name()
869
-    {
870
-        try {
871
-            if (! empty($this->_model_chain_to_wp_user)) {
872
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
873
-                $last_model_name = end($models_to_follow_to_wp_users);
874
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
875
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
876
-            } else {
877
-                $model_with_fk_to_wp_users = $this;
878
-                $model_chain_to_wp_user = '';
879
-            }
880
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
881
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
882
-        } catch (EE_Error $e) {
883
-            return false;
884
-        }
885
-    }
886
-
887
-
888
-
889
-    /**
890
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
891
-     * (or transiently-related model) has a foreign key to the wp_users table;
892
-     * useful for finding if model objects of this type are 'owned' by the current user.
893
-     * This is an empty string when the foreign key is on this model and when it isn't,
894
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
895
-     * (or transiently-related model)
896
-     *
897
-     * @return string
898
-     */
899
-    public function model_chain_to_wp_user()
900
-    {
901
-        return $this->_model_chain_to_wp_user;
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
908
-     * like how registrations don't have a foreign key to wp_users, but the
909
-     * events they are for are), or is unrelated to wp users.
910
-     * generally available
911
-     *
912
-     * @return boolean
913
-     */
914
-    public function is_owned()
915
-    {
916
-        if ($this->model_chain_to_wp_user()) {
917
-            return true;
918
-        }
919
-        try {
920
-            $this->get_foreign_key_to('WP_User');
921
-            return true;
922
-        } catch (EE_Error $e) {
923
-            return false;
924
-        }
925
-    }
926
-
927
-
928
-    /**
929
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
930
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
931
-     * the model)
932
-     *
933
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
934
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
935
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
936
-     *                                  fields on the model, and the models we joined to in the query. However, you can
937
-     *                                  override this and set the select to "*", or a specific column name, like
938
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
939
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
940
-     *                                  the aliases used to refer to this selection, and values are to be
941
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
942
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
943
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
944
-     * @throws EE_Error
945
-     * @throws InvalidArgumentException
946
-     */
947
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
948
-    {
949
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
950
-        ;
951
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
952
-        $select_expressions = $columns_to_select === null
953
-            ? $this->_construct_default_select_sql($model_query_info)
954
-            : '';
955
-        if ($this->_custom_selections instanceof CustomSelects) {
956
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
957
-            $select_expressions .= $select_expressions
958
-                ? ', ' . $custom_expressions
959
-                : $custom_expressions;
960
-        }
961
-
962
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
963
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
964
-    }
965
-
966
-
967
-    /**
968
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
969
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
970
-     * method of including extra select information.
971
-     *
972
-     * @param array             $query_params
973
-     * @param null|array|string $columns_to_select
974
-     * @return null|CustomSelects
975
-     * @throws InvalidArgumentException
976
-     */
977
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
978
-    {
979
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
980
-            return null;
981
-        }
982
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
983
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
984
-        return new CustomSelects($selects);
985
-    }
986
-
987
-
988
-
989
-    /**
990
-     * Gets an array of rows from the database just like $wpdb->get_results would,
991
-     * but you can use the model query params to more easily
992
-     * take care of joins, field preparation etc.
993
-     *
994
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
995
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
996
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
997
-     *                                  fields on the model, and the models we joined to in the query. However, you can
998
-     *                                  override this and set the select to "*", or a specific column name, like
999
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1000
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1001
-     *                                  the aliases used to refer to this selection, and values are to be
1002
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1003
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1004
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1005
-     * @throws EE_Error
1006
-     */
1007
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1008
-    {
1009
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1010
-    }
1011
-
1012
-
1013
-
1014
-    /**
1015
-     * For creating a custom select statement
1016
-     *
1017
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1018
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1019
-     *                                 SQL, and 1=>is the datatype
1020
-     * @throws EE_Error
1021
-     * @return string
1022
-     */
1023
-    private function _construct_select_from_input($columns_to_select)
1024
-    {
1025
-        if (is_array($columns_to_select)) {
1026
-            $select_sql_array = array();
1027
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1028
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1029
-                    throw new EE_Error(
1030
-                        sprintf(
1031
-                            __(
1032
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1033
-                                'event_espresso'
1034
-                            ),
1035
-                            $selection_and_datatype,
1036
-                            $alias
1037
-                        )
1038
-                    );
1039
-                }
1040
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1041
-                    throw new EE_Error(
1042
-                        sprintf(
1043
-                            esc_html__(
1044
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1045
-                                'event_espresso'
1046
-                            ),
1047
-                            $selection_and_datatype[1],
1048
-                            $selection_and_datatype[0],
1049
-                            $alias,
1050
-                            implode(', ', $this->_valid_wpdb_data_types)
1051
-                        )
1052
-                    );
1053
-                }
1054
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1055
-            }
1056
-            $columns_to_select_string = implode(', ', $select_sql_array);
1057
-        } else {
1058
-            $columns_to_select_string = $columns_to_select;
1059
-        }
1060
-        return $columns_to_select_string;
1061
-    }
1062
-
1063
-
1064
-
1065
-    /**
1066
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1067
-     *
1068
-     * @return string
1069
-     * @throws EE_Error
1070
-     */
1071
-    public function primary_key_name()
1072
-    {
1073
-        return $this->get_primary_key_field()->get_name();
1074
-    }
1075
-
1076
-
1077
-
1078
-    /**
1079
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1080
-     * If there is no primary key on this model, $id is treated as primary key string
1081
-     *
1082
-     * @param mixed $id int or string, depending on the type of the model's primary key
1083
-     * @return EE_Base_Class
1084
-     */
1085
-    public function get_one_by_ID($id)
1086
-    {
1087
-        if ($this->get_from_entity_map($id)) {
1088
-            return $this->get_from_entity_map($id);
1089
-        }
1090
-        return $this->get_one(
1091
-            $this->alter_query_params_to_restrict_by_ID(
1092
-                $id,
1093
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1094
-            )
1095
-        );
1096
-    }
1097
-
1098
-
1099
-
1100
-    /**
1101
-     * Alters query parameters to only get items with this ID are returned.
1102
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1103
-     * or could just be a simple primary key ID
1104
-     *
1105
-     * @param int   $id
1106
-     * @param array $query_params
1107
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1111
-    {
1112
-        if (! isset($query_params[0])) {
1113
-            $query_params[0] = array();
1114
-        }
1115
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1116
-        if ($conditions_from_id === null) {
1117
-            $query_params[0][ $this->primary_key_name() ] = $id;
1118
-        } else {
1119
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1120
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1121
-        }
1122
-        return $query_params;
1123
-    }
1124
-
1125
-
1126
-
1127
-    /**
1128
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1129
-     * array. If no item is found, null is returned.
1130
-     *
1131
-     * @param array $query_params like EEM_Base's $query_params variable.
1132
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1133
-     * @throws EE_Error
1134
-     */
1135
-    public function get_one($query_params = array())
1136
-    {
1137
-        if (! is_array($query_params)) {
1138
-            EE_Error::doing_it_wrong(
1139
-                'EEM_Base::get_one',
1140
-                sprintf(
1141
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1142
-                    gettype($query_params)
1143
-                ),
1144
-                '4.6.0'
1145
-            );
1146
-            $query_params = array();
1147
-        }
1148
-        $query_params['limit'] = 1;
1149
-        $items = $this->get_all($query_params);
1150
-        if (empty($items)) {
1151
-            return null;
1152
-        }
1153
-        return array_shift($items);
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * Returns the next x number of items in sequence from the given value as
1160
-     * found in the database matching the given query conditions.
1161
-     *
1162
-     * @param mixed $current_field_value    Value used for the reference point.
1163
-     * @param null  $field_to_order_by      What field is used for the
1164
-     *                                      reference point.
1165
-     * @param int   $limit                  How many to return.
1166
-     * @param array $query_params           Extra conditions on the query.
1167
-     * @param null  $columns_to_select      If left null, then an array of
1168
-     *                                      EE_Base_Class objects is returned,
1169
-     *                                      otherwise you can indicate just the
1170
-     *                                      columns you want returned.
1171
-     * @return EE_Base_Class[]|array
1172
-     * @throws EE_Error
1173
-     */
1174
-    public function next_x(
1175
-        $current_field_value,
1176
-        $field_to_order_by = null,
1177
-        $limit = 1,
1178
-        $query_params = array(),
1179
-        $columns_to_select = null
1180
-    ) {
1181
-        return $this->_get_consecutive(
1182
-            $current_field_value,
1183
-            '>',
1184
-            $field_to_order_by,
1185
-            $limit,
1186
-            $query_params,
1187
-            $columns_to_select
1188
-        );
1189
-    }
1190
-
1191
-
1192
-
1193
-    /**
1194
-     * Returns the previous x number of items in sequence from the given value
1195
-     * as found in the database matching the given query conditions.
1196
-     *
1197
-     * @param mixed $current_field_value    Value used for the reference point.
1198
-     * @param null  $field_to_order_by      What field is used for the
1199
-     *                                      reference point.
1200
-     * @param int   $limit                  How many to return.
1201
-     * @param array $query_params           Extra conditions on the query.
1202
-     * @param null  $columns_to_select      If left null, then an array of
1203
-     *                                      EE_Base_Class objects is returned,
1204
-     *                                      otherwise you can indicate just the
1205
-     *                                      columns you want returned.
1206
-     * @return EE_Base_Class[]|array
1207
-     * @throws EE_Error
1208
-     */
1209
-    public function previous_x(
1210
-        $current_field_value,
1211
-        $field_to_order_by = null,
1212
-        $limit = 1,
1213
-        $query_params = array(),
1214
-        $columns_to_select = null
1215
-    ) {
1216
-        return $this->_get_consecutive(
1217
-            $current_field_value,
1218
-            '<',
1219
-            $field_to_order_by,
1220
-            $limit,
1221
-            $query_params,
1222
-            $columns_to_select
1223
-        );
1224
-    }
1225
-
1226
-
1227
-
1228
-    /**
1229
-     * Returns the next item in sequence from the given value as found in the
1230
-     * database matching the given query conditions.
1231
-     *
1232
-     * @param mixed $current_field_value    Value used for the reference point.
1233
-     * @param null  $field_to_order_by      What field is used for the
1234
-     *                                      reference point.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1237
-     *                                      object is returned, otherwise you
1238
-     *                                      can indicate just the columns you
1239
-     *                                      want and a single array indexed by
1240
-     *                                      the columns will be returned.
1241
-     * @return EE_Base_Class|null|array()
1242
-     * @throws EE_Error
1243
-     */
1244
-    public function next(
1245
-        $current_field_value,
1246
-        $field_to_order_by = null,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        $results = $this->_get_consecutive(
1251
-            $current_field_value,
1252
-            '>',
1253
-            $field_to_order_by,
1254
-            1,
1255
-            $query_params,
1256
-            $columns_to_select
1257
-        );
1258
-        return empty($results) ? null : reset($results);
1259
-    }
1260
-
1261
-
1262
-
1263
-    /**
1264
-     * Returns the previous item in sequence from the given value as found in
1265
-     * the database matching the given query conditions.
1266
-     *
1267
-     * @param mixed $current_field_value    Value used for the reference point.
1268
-     * @param null  $field_to_order_by      What field is used for the
1269
-     *                                      reference point.
1270
-     * @param array $query_params           Extra conditions on the query.
1271
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1272
-     *                                      object is returned, otherwise you
1273
-     *                                      can indicate just the columns you
1274
-     *                                      want and a single array indexed by
1275
-     *                                      the columns will be returned.
1276
-     * @return EE_Base_Class|null|array()
1277
-     * @throws EE_Error
1278
-     */
1279
-    public function previous(
1280
-        $current_field_value,
1281
-        $field_to_order_by = null,
1282
-        $query_params = array(),
1283
-        $columns_to_select = null
1284
-    ) {
1285
-        $results = $this->_get_consecutive(
1286
-            $current_field_value,
1287
-            '<',
1288
-            $field_to_order_by,
1289
-            1,
1290
-            $query_params,
1291
-            $columns_to_select
1292
-        );
1293
-        return empty($results) ? null : reset($results);
1294
-    }
1295
-
1296
-
1297
-
1298
-    /**
1299
-     * Returns the a consecutive number of items in sequence from the given
1300
-     * value as found in the database matching the given query conditions.
1301
-     *
1302
-     * @param mixed  $current_field_value   Value used for the reference point.
1303
-     * @param string $operand               What operand is used for the sequence.
1304
-     * @param string $field_to_order_by     What field is used for the reference point.
1305
-     * @param int    $limit                 How many to return.
1306
-     * @param array  $query_params          Extra conditions on the query.
1307
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1308
-     *                                      otherwise you can indicate just the columns you want returned.
1309
-     * @return EE_Base_Class[]|array
1310
-     * @throws EE_Error
1311
-     */
1312
-    protected function _get_consecutive(
1313
-        $current_field_value,
1314
-        $operand = '>',
1315
-        $field_to_order_by = null,
1316
-        $limit = 1,
1317
-        $query_params = array(),
1318
-        $columns_to_select = null
1319
-    ) {
1320
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1321
-        if (empty($field_to_order_by)) {
1322
-            if ($this->has_primary_key_field()) {
1323
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1324
-            } else {
1325
-                if (WP_DEBUG) {
1326
-                    throw new EE_Error(__(
1327
-                        'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1328
-                        'event_espresso'
1329
-                    ));
1330
-                }
1331
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1332
-                return array();
1333
-            }
1334
-        }
1335
-        if (! is_array($query_params)) {
1336
-            EE_Error::doing_it_wrong(
1337
-                'EEM_Base::_get_consecutive',
1338
-                sprintf(
1339
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1340
-                    gettype($query_params)
1341
-                ),
1342
-                '4.6.0'
1343
-            );
1344
-            $query_params = array();
1345
-        }
1346
-        // let's add the where query param for consecutive look up.
1347
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1348
-        $query_params['limit'] = $limit;
1349
-        // set direction
1350
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1351
-        $query_params['order_by'] = $operand === '>'
1352
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1353
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1354
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1355
-        if (empty($columns_to_select)) {
1356
-            return $this->get_all($query_params);
1357
-        }
1358
-        // getting just the fields
1359
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1360
-    }
1361
-
1362
-
1363
-
1364
-    /**
1365
-     * This sets the _timezone property after model object has been instantiated.
1366
-     *
1367
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1368
-     */
1369
-    public function set_timezone($timezone)
1370
-    {
1371
-        if ($timezone !== null) {
1372
-            $this->_timezone = $timezone;
1373
-        }
1374
-        // note we need to loop through relations and set the timezone on those objects as well.
1375
-        foreach ($this->_model_relations as $relation) {
1376
-            $relation->set_timezone($timezone);
1377
-        }
1378
-        // and finally we do the same for any datetime fields
1379
-        foreach ($this->_fields as $field) {
1380
-            if ($field instanceof EE_Datetime_Field) {
1381
-                $field->set_timezone($timezone);
1382
-            }
1383
-        }
1384
-    }
1385
-
1386
-
1387
-
1388
-    /**
1389
-     * This just returns whatever is set for the current timezone.
1390
-     *
1391
-     * @access public
1392
-     * @return string
1393
-     */
1394
-    public function get_timezone()
1395
-    {
1396
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1397
-        if (empty($this->_timezone)) {
1398
-            foreach ($this->_fields as $field) {
1399
-                if ($field instanceof EE_Datetime_Field) {
1400
-                    $this->set_timezone($field->get_timezone());
1401
-                    break;
1402
-                }
1403
-            }
1404
-        }
1405
-        // if timezone STILL empty then return the default timezone for the site.
1406
-        if (empty($this->_timezone)) {
1407
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1408
-        }
1409
-        return $this->_timezone;
1410
-    }
1411
-
1412
-
1413
-
1414
-    /**
1415
-     * This returns the date formats set for the given field name and also ensures that
1416
-     * $this->_timezone property is set correctly.
1417
-     *
1418
-     * @since 4.6.x
1419
-     * @param string $field_name The name of the field the formats are being retrieved for.
1420
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1421
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1422
-     * @return array formats in an array with the date format first, and the time format last.
1423
-     */
1424
-    public function get_formats_for($field_name, $pretty = false)
1425
-    {
1426
-        $field_settings = $this->field_settings_for($field_name);
1427
-        // if not a valid EE_Datetime_Field then throw error
1428
-        if (! $field_settings instanceof EE_Datetime_Field) {
1429
-            throw new EE_Error(sprintf(__(
1430
-                'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1431
-                'event_espresso'
1432
-            ), $field_name));
1433
-        }
1434
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1435
-        // the field.
1436
-        $this->_timezone = $field_settings->get_timezone();
1437
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1438
-    }
1439
-
1440
-
1441
-
1442
-    /**
1443
-     * This returns the current time in a format setup for a query on this model.
1444
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1445
-     * it will return:
1446
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1447
-     *  NOW
1448
-     *  - or a unix timestamp (equivalent to time())
1449
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1450
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1451
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1452
-     * @since 4.6.x
1453
-     * @param string $field_name       The field the current time is needed for.
1454
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1455
-     *                                 formatted string matching the set format for the field in the set timezone will
1456
-     *                                 be returned.
1457
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1458
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1459
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1460
-     *                                 exception is triggered.
1461
-     */
1462
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1463
-    {
1464
-        $formats = $this->get_formats_for($field_name);
1465
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1466
-        if ($timestamp) {
1467
-            return $DateTime->format('U');
1468
-        }
1469
-        // not returning timestamp, so return formatted string in timezone.
1470
-        switch ($what) {
1471
-            case 'time':
1472
-                return $DateTime->format($formats[1]);
1473
-                break;
1474
-            case 'date':
1475
-                return $DateTime->format($formats[0]);
1476
-                break;
1477
-            default:
1478
-                return $DateTime->format(implode(' ', $formats));
1479
-                break;
1480
-        }
1481
-    }
1482
-
1483
-
1484
-
1485
-    /**
1486
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1487
-     * for the model are.  Returns a DateTime object.
1488
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1489
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1490
-     * ignored.
1491
-     *
1492
-     * @param string $field_name      The field being setup.
1493
-     * @param string $timestring      The date time string being used.
1494
-     * @param string $incoming_format The format for the time string.
1495
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1496
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1497
-     *                                format is
1498
-     *                                'U', this is ignored.
1499
-     * @return DateTime
1500
-     * @throws EE_Error
1501
-     */
1502
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1503
-    {
1504
-        // just using this to ensure the timezone is set correctly internally
1505
-        $this->get_formats_for($field_name);
1506
-        // load EEH_DTT_Helper
1507
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1508
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1509
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1510
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1511
-    }
1512
-
1513
-
1514
-
1515
-    /**
1516
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1517
-     *
1518
-     * @return EE_Table_Base[]
1519
-     */
1520
-    public function get_tables()
1521
-    {
1522
-        return $this->_tables;
1523
-    }
1524
-
1525
-
1526
-
1527
-    /**
1528
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1529
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1530
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1531
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1532
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1533
-     * model object with EVT_ID = 1
1534
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1535
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1536
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1537
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1538
-     * are not specified)
1539
-     *
1540
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1541
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1542
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1543
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1544
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1545
-     *                                         ID=34, we'd use this method as follows:
1546
-     *                                         EEM_Transaction::instance()->update(
1547
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1548
-     *                                         array(array('TXN_ID'=>34)));
1549
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1550
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1551
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1552
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1553
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1554
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1555
-     *                                         TRUE, it is assumed that you've already called
1556
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1557
-     *                                         malicious javascript. However, if
1558
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1559
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1560
-     *                                         and every other field, before insertion. We provide this parameter
1561
-     *                                         because model objects perform their prepare_for_set function on all
1562
-     *                                         their values, and so don't need to be called again (and in many cases,
1563
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1564
-     *                                         prepare_for_set method...)
1565
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1566
-     *                                         in this model's entity map according to $fields_n_values that match
1567
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1568
-     *                                         by setting this to FALSE, but be aware that model objects being used
1569
-     *                                         could get out-of-sync with the database
1570
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1571
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1572
-     *                                         bad)
1573
-     * @throws EE_Error
1574
-     */
1575
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1576
-    {
1577
-        if (! is_array($query_params)) {
1578
-            EE_Error::doing_it_wrong(
1579
-                'EEM_Base::update',
1580
-                sprintf(
1581
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1582
-                    gettype($query_params)
1583
-                ),
1584
-                '4.6.0'
1585
-            );
1586
-            $query_params = array();
1587
-        }
1588
-        /**
1589
-         * Action called before a model update call has been made.
1590
-         *
1591
-         * @param EEM_Base $model
1592
-         * @param array    $fields_n_values the updated fields and their new values
1593
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1594
-         */
1595
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1596
-        /**
1597
-         * Filters the fields about to be updated given the query parameters. You can provide the
1598
-         * $query_params to $this->get_all() to find exactly which records will be updated
1599
-         *
1600
-         * @param array    $fields_n_values fields and their new values
1601
-         * @param EEM_Base $model           the model being queried
1602
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1603
-         */
1604
-        $fields_n_values = (array) apply_filters(
1605
-            'FHEE__EEM_Base__update__fields_n_values',
1606
-            $fields_n_values,
1607
-            $this,
1608
-            $query_params
1609
-        );
1610
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1611
-        // to do that, for each table, verify that it's PK isn't null.
1612
-        $tables = $this->get_tables();
1613
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1614
-        // NOTE: we should make this code more efficient by NOT querying twice
1615
-        // before the real update, but that needs to first go through ALPHA testing
1616
-        // as it's dangerous. says Mike August 8 2014
1617
-        // we want to make sure the default_where strategy is ignored
1618
-        $this->_ignore_where_strategy = true;
1619
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1620
-        foreach ($wpdb_select_results as $wpdb_result) {
1621
-            // type cast stdClass as array
1622
-            $wpdb_result = (array) $wpdb_result;
1623
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1624
-            if ($this->has_primary_key_field()) {
1625
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1626
-            } else {
1627
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1628
-                $main_table_pk_value = null;
1629
-            }
1630
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1631
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1632
-            if (count($tables) > 1) {
1633
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1634
-                // in that table, and so we'll want to insert one
1635
-                foreach ($tables as $table_obj) {
1636
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1637
-                    // if there is no private key for this table on the results, it means there's no entry
1638
-                    // in this table, right? so insert a row in the current table, using any fields available
1639
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1640
-                           && $wpdb_result[ $this_table_pk_column ])
1641
-                    ) {
1642
-                        $success = $this->_insert_into_specific_table(
1643
-                            $table_obj,
1644
-                            $fields_n_values,
1645
-                            $main_table_pk_value
1646
-                        );
1647
-                        // if we died here, report the error
1648
-                        if (! $success) {
1649
-                            return false;
1650
-                        }
1651
-                    }
1652
-                }
1653
-            }
1654
-            //              //and now check that if we have cached any models by that ID on the model, that
1655
-            //              //they also get updated properly
1656
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1657
-            //              if( $model_object ){
1658
-            //                  foreach( $fields_n_values as $field => $value ){
1659
-            //                      $model_object->set($field, $value);
1660
-            // let's make sure default_where strategy is followed now
1661
-            $this->_ignore_where_strategy = false;
1662
-        }
1663
-        // if we want to keep model objects in sync, AND
1664
-        // if this wasn't called from a model object (to update itself)
1665
-        // then we want to make sure we keep all the existing
1666
-        // model objects in sync with the db
1667
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1668
-            if ($this->has_primary_key_field()) {
1669
-                $model_objs_affected_ids = $this->get_col($query_params);
1670
-            } else {
1671
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1672
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1673
-                $model_objs_affected_ids = array();
1674
-                foreach ($models_affected_key_columns as $row) {
1675
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1676
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1677
-                }
1678
-            }
1679
-            if (! $model_objs_affected_ids) {
1680
-                // wait wait wait- if nothing was affected let's stop here
1681
-                return 0;
1682
-            }
1683
-            foreach ($model_objs_affected_ids as $id) {
1684
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1685
-                if ($model_obj_in_entity_map) {
1686
-                    foreach ($fields_n_values as $field => $new_value) {
1687
-                        $model_obj_in_entity_map->set($field, $new_value);
1688
-                    }
1689
-                }
1690
-            }
1691
-            // if there is a primary key on this model, we can now do a slight optimization
1692
-            if ($this->has_primary_key_field()) {
1693
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1694
-                $query_params = array(
1695
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1696
-                    'limit'                    => count($model_objs_affected_ids),
1697
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1698
-                );
1699
-            }
1700
-        }
1701
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1702
-        $SQL = "UPDATE "
1703
-               . $model_query_info->get_full_join_sql()
1704
-               . " SET "
1705
-               . $this->_construct_update_sql($fields_n_values)
1706
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1707
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1708
-        /**
1709
-         * Action called after a model update call has been made.
1710
-         *
1711
-         * @param EEM_Base $model
1712
-         * @param array    $fields_n_values the updated fields and their new values
1713
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1714
-         * @param int      $rows_affected
1715
-         */
1716
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1717
-        return $rows_affected;// how many supposedly got updated
1718
-    }
1719
-
1720
-
1721
-
1722
-    /**
1723
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1724
-     * are teh values of the field specified (or by default the primary key field)
1725
-     * that matched the query params. Note that you should pass the name of the
1726
-     * model FIELD, not the database table's column name.
1727
-     *
1728
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1729
-     * @param string $field_to_select
1730
-     * @return array just like $wpdb->get_col()
1731
-     * @throws EE_Error
1732
-     */
1733
-    public function get_col($query_params = array(), $field_to_select = null)
1734
-    {
1735
-        if ($field_to_select) {
1736
-            $field = $this->field_settings_for($field_to_select);
1737
-        } elseif ($this->has_primary_key_field()) {
1738
-            $field = $this->get_primary_key_field();
1739
-        } else {
1740
-            // no primary key, just grab the first column
1741
-            $field = reset($this->field_settings());
1742
-        }
1743
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1744
-        $select_expressions = $field->get_qualified_column();
1745
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1746
-        return $this->_do_wpdb_query('get_col', array($SQL));
1747
-    }
1748
-
1749
-
1750
-
1751
-    /**
1752
-     * Returns a single column value for a single row from the database
1753
-     *
1754
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1755
-     * @param string $field_to_select @see EEM_Base::get_col()
1756
-     * @return string
1757
-     * @throws EE_Error
1758
-     */
1759
-    public function get_var($query_params = array(), $field_to_select = null)
1760
-    {
1761
-        $query_params['limit'] = 1;
1762
-        $col = $this->get_col($query_params, $field_to_select);
1763
-        if (! empty($col)) {
1764
-            return reset($col);
1765
-        }
1766
-        return null;
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1773
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1774
-     * injection, but currently no further filtering is done
1775
-     *
1776
-     * @global      $wpdb
1777
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1778
-     *                               be updated to in the DB
1779
-     * @return string of SQL
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function _construct_update_sql($fields_n_values)
1783
-    {
1784
-        /** @type WPDB $wpdb */
1785
-        global $wpdb;
1786
-        $cols_n_values = array();
1787
-        foreach ($fields_n_values as $field_name => $value) {
1788
-            $field_obj = $this->field_settings_for($field_name);
1789
-            // if the value is NULL, we want to assign the value to that.
1790
-            // wpdb->prepare doesn't really handle that properly
1791
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1792
-            $value_sql = $prepared_value === null ? 'NULL'
1793
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1794
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1795
-        }
1796
-        return implode(",", $cols_n_values);
1797
-    }
1798
-
1799
-
1800
-
1801
-    /**
1802
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1803
-     * Performs a HARD delete, meaning the database row should always be removed,
1804
-     * not just have a flag field on it switched
1805
-     * Wrapper for EEM_Base::delete_permanently()
1806
-     *
1807
-     * @param mixed $id
1808
-     * @param boolean $allow_blocking
1809
-     * @return int the number of rows deleted
1810
-     * @throws EE_Error
1811
-     */
1812
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1813
-    {
1814
-        return $this->delete_permanently(
1815
-            array(
1816
-                array($this->get_primary_key_field()->get_name() => $id),
1817
-                'limit' => 1,
1818
-            ),
1819
-            $allow_blocking
1820
-        );
1821
-    }
1822
-
1823
-
1824
-
1825
-    /**
1826
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
-     * Wrapper for EEM_Base::delete()
1828
-     *
1829
-     * @param mixed $id
1830
-     * @param boolean $allow_blocking
1831
-     * @return int the number of rows deleted
1832
-     * @throws EE_Error
1833
-     */
1834
-    public function delete_by_ID($id, $allow_blocking = true)
1835
-    {
1836
-        return $this->delete(
1837
-            array(
1838
-                array($this->get_primary_key_field()->get_name() => $id),
1839
-                'limit' => 1,
1840
-            ),
1841
-            $allow_blocking
1842
-        );
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1849
-     * meaning if the model has a field that indicates its been "trashed" or
1850
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1851
-     *
1852
-     * @see EEM_Base::delete_permanently
1853
-     * @param array   $query_params
1854
-     * @param boolean $allow_blocking
1855
-     * @return int how many rows got deleted
1856
-     * @throws EE_Error
1857
-     */
1858
-    public function delete($query_params, $allow_blocking = true)
1859
-    {
1860
-        return $this->delete_permanently($query_params, $allow_blocking);
1861
-    }
1862
-
1863
-
1864
-
1865
-    /**
1866
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1867
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1868
-     * as archived, not actually deleted
1869
-     *
1870
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1871
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1872
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1873
-     *                                deletes regardless of other objects which may depend on it. Its generally
1874
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1875
-     *                                DB
1876
-     * @return int how many rows got deleted
1877
-     * @throws EE_Error
1878
-     */
1879
-    public function delete_permanently($query_params, $allow_blocking = true)
1880
-    {
1881
-        /**
1882
-         * Action called just before performing a real deletion query. You can use the
1883
-         * model and its $query_params to find exactly which items will be deleted
1884
-         *
1885
-         * @param EEM_Base $model
1886
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1887
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1888
-         *                                 to block (prevent) this deletion
1889
-         */
1890
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1891
-        // some MySQL databases may be running safe mode, which may restrict
1892
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1893
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1894
-        // to delete them
1895
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1896
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1897
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1898
-            $columns_and_ids_for_deleting
1899
-        );
1900
-        /**
1901
-         * Allows client code to act on the items being deleted before the query is actually executed.
1902
-         *
1903
-         * @param EEM_Base $this  The model instance being acted on.
1904
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1905
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1906
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1907
-         *                                                  derived from the incoming query parameters.
1908
-         *                                                  @see details on the structure of this array in the phpdocs
1909
-         *                                                  for the `_get_ids_for_delete_method`
1910
-         *
1911
-         */
1912
-        do_action(
1913
-            'AHEE__EEM_Base__delete__before_query',
1914
-            $this,
1915
-            $query_params,
1916
-            $allow_blocking,
1917
-            $columns_and_ids_for_deleting
1918
-        );
1919
-        if ($deletion_where_query_part) {
1920
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
-            $table_aliases = array_keys($this->_tables);
1922
-            $SQL = "DELETE "
1923
-                   . implode(", ", $table_aliases)
1924
-                   . " FROM "
1925
-                   . $model_query_info->get_full_join_sql()
1926
-                   . " WHERE "
1927
-                   . $deletion_where_query_part;
1928
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
-        } else {
1930
-            $rows_deleted = 0;
1931
-        }
1932
-
1933
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1934
-        // there was no error with the delete query.
1935
-        if ($this->has_primary_key_field()
1936
-            && $rows_deleted !== false
1937
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1938
-        ) {
1939
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1940
-            foreach ($ids_for_removal as $id) {
1941
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1942
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1943
-                }
1944
-            }
1945
-
1946
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1947
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1948
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1949
-            // (although it is possible).
1950
-            // Note this can be skipped by using the provided filter and returning false.
1951
-            if (apply_filters(
1952
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1953
-                ! $this instanceof EEM_Extra_Meta,
1954
-                $this
1955
-            )) {
1956
-                EEM_Extra_Meta::instance()->delete_permanently(array(
1957
-                    0 => array(
1958
-                        'EXM_type' => $this->get_this_model_name(),
1959
-                        'OBJ_ID'   => array(
1960
-                            'IN',
1961
-                            $ids_for_removal
1962
-                        )
1963
-                    )
1964
-                ));
1965
-            }
1966
-        }
1967
-
1968
-        /**
1969
-         * Action called just after performing a real deletion query. Although at this point the
1970
-         * items should have been deleted
1971
-         *
1972
-         * @param EEM_Base $model
1973
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1974
-         * @param int      $rows_deleted
1975
-         */
1976
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1977
-        return $rows_deleted;// how many supposedly got deleted
1978
-    }
1979
-
1980
-
1981
-
1982
-    /**
1983
-     * Checks all the relations that throw error messages when there are blocking related objects
1984
-     * for related model objects. If there are any related model objects on those relations,
1985
-     * adds an EE_Error, and return true
1986
-     *
1987
-     * @param EE_Base_Class|int $this_model_obj_or_id
1988
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1989
-     *                                                 should be ignored when determining whether there are related
1990
-     *                                                 model objects which block this model object's deletion. Useful
1991
-     *                                                 if you know A is related to B and are considering deleting A,
1992
-     *                                                 but want to see if A has any other objects blocking its deletion
1993
-     *                                                 before removing the relation between A and B
1994
-     * @return boolean
1995
-     * @throws EE_Error
1996
-     */
1997
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1998
-    {
1999
-        // first, if $ignore_this_model_obj was supplied, get its model
2000
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2001
-            $ignored_model = $ignore_this_model_obj->get_model();
2002
-        } else {
2003
-            $ignored_model = null;
2004
-        }
2005
-        // now check all the relations of $this_model_obj_or_id and see if there
2006
-        // are any related model objects blocking it?
2007
-        $is_blocked = false;
2008
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2009
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2010
-                // if $ignore_this_model_obj was supplied, then for the query
2011
-                // on that model needs to be told to ignore $ignore_this_model_obj
2012
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2013
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2014
-                        array(
2015
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2016
-                                '!=',
2017
-                                $ignore_this_model_obj->ID(),
2018
-                            ),
2019
-                        ),
2020
-                    ));
2021
-                } else {
2022
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2023
-                }
2024
-                if ($related_model_objects) {
2025
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2026
-                    $is_blocked = true;
2027
-                }
2028
-            }
2029
-        }
2030
-        return $is_blocked;
2031
-    }
2032
-
2033
-
2034
-    /**
2035
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2036
-     * @param array $row_results_for_deleting
2037
-     * @param bool  $allow_blocking
2038
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2039
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2040
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2041
-     *                 deleted. Example:
2042
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2043
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2044
-     *                 where each element is a group of columns and values that get deleted. Example:
2045
-     *                      array(
2046
-     *                          0 => array(
2047
-     *                              'Term_Relationship.object_id' => 1
2048
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2049
-     *                          ),
2050
-     *                          1 => array(
2051
-     *                              'Term_Relationship.object_id' => 1
2052
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2053
-     *                          )
2054
-     *                      )
2055
-     * @throws EE_Error
2056
-     */
2057
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2058
-    {
2059
-        $ids_to_delete_indexed_by_column = array();
2060
-        if ($this->has_primary_key_field()) {
2061
-            $primary_table = $this->_get_main_table();
2062
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2063
-            $other_tables = $this->_get_other_tables();
2064
-            $ids_to_delete_indexed_by_column = $query = array();
2065
-            foreach ($row_results_for_deleting as $item_to_delete) {
2066
-                // before we mark this item for deletion,
2067
-                // make sure there's no related entities blocking its deletion (if we're checking)
2068
-                if ($allow_blocking
2069
-                    && $this->delete_is_blocked_by_related_models(
2070
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2071
-                    )
2072
-                ) {
2073
-                    continue;
2074
-                }
2075
-                // primary table deletes
2076
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2077
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2078
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2079
-                }
2080
-            }
2081
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2082
-            $fields = $this->get_combined_primary_key_fields();
2083
-            foreach ($row_results_for_deleting as $item_to_delete) {
2084
-                $ids_to_delete_indexed_by_column_for_row = array();
2085
-                foreach ($fields as $cpk_field) {
2086
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2087
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2088
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2089
-                    }
2090
-                }
2091
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2092
-            }
2093
-        } else {
2094
-            // so there's no primary key and no combined key...
2095
-            // sorry, can't help you
2096
-            throw new EE_Error(
2097
-                sprintf(
2098
-                    __(
2099
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2100
-                        "event_espresso"
2101
-                    ),
2102
-                    get_class($this)
2103
-                )
2104
-            );
2105
-        }
2106
-        return $ids_to_delete_indexed_by_column;
2107
-    }
2108
-
2109
-
2110
-    /**
2111
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2112
-     * the corresponding query_part for the query performing the delete.
2113
-     *
2114
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2115
-     * @return string
2116
-     * @throws EE_Error
2117
-     */
2118
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2119
-    {
2120
-        $query_part = '';
2121
-        if (empty($ids_to_delete_indexed_by_column)) {
2122
-            return $query_part;
2123
-        } elseif ($this->has_primary_key_field()) {
2124
-            $query = array();
2125
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2126
-                // make sure we have unique $ids
2127
-                $ids = array_unique($ids);
2128
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2129
-            }
2130
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2131
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2132
-            $ways_to_identify_a_row = array();
2133
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2134
-                $values_for_each_combined_primary_key_for_a_row = array();
2135
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2136
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2137
-                }
2138
-                $ways_to_identify_a_row[] = '('
2139
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2140
-                                            . ')';
2141
-            }
2142
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2143
-        }
2144
-        return $query_part;
2145
-    }
2146
-
2147
-
2148
-
2149
-    /**
2150
-     * Gets the model field by the fully qualified name
2151
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2152
-     * @return EE_Model_Field_Base
2153
-     */
2154
-    public function get_field_by_column($qualified_column_name)
2155
-    {
2156
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2157
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2158
-                return $field_obj;
2159
-            }
2160
-        }
2161
-        throw new EE_Error(
2162
-            sprintf(
2163
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2164
-                $this->get_this_model_name(),
2165
-                $qualified_column_name
2166
-            )
2167
-        );
2168
-    }
2169
-
2170
-
2171
-
2172
-    /**
2173
-     * Count all the rows that match criteria the model query params.
2174
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2175
-     * column
2176
-     *
2177
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2178
-     * @param string $field_to_count field on model to count by (not column name)
2179
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2180
-     *                               that by the setting $distinct to TRUE;
2181
-     * @return int
2182
-     * @throws EE_Error
2183
-     */
2184
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2185
-    {
2186
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2187
-        if ($field_to_count) {
2188
-            $field_obj = $this->field_settings_for($field_to_count);
2189
-            $column_to_count = $field_obj->get_qualified_column();
2190
-        } elseif ($this->has_primary_key_field()) {
2191
-            $pk_field_obj = $this->get_primary_key_field();
2192
-            $column_to_count = $pk_field_obj->get_qualified_column();
2193
-        } else {
2194
-            // there's no primary key
2195
-            // if we're counting distinct items, and there's no primary key,
2196
-            // we need to list out the columns for distinction;
2197
-            // otherwise we can just use star
2198
-            if ($distinct) {
2199
-                $columns_to_use = array();
2200
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2201
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2202
-                }
2203
-                $column_to_count = implode(',', $columns_to_use);
2204
-            } else {
2205
-                $column_to_count = '*';
2206
-            }
2207
-        }
2208
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2209
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2210
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2211
-    }
2212
-
2213
-
2214
-
2215
-    /**
2216
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2217
-     *
2218
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2219
-     * @param string $field_to_sum name of field (array key in $_fields array)
2220
-     * @return float
2221
-     * @throws EE_Error
2222
-     */
2223
-    public function sum($query_params, $field_to_sum = null)
2224
-    {
2225
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2226
-        if ($field_to_sum) {
2227
-            $field_obj = $this->field_settings_for($field_to_sum);
2228
-        } else {
2229
-            $field_obj = $this->get_primary_key_field();
2230
-        }
2231
-        $column_to_count = $field_obj->get_qualified_column();
2232
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2233
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2234
-        $data_type = $field_obj->get_wpdb_data_type();
2235
-        if ($data_type === '%d' || $data_type === '%s') {
2236
-            return (float) $return_value;
2237
-        }
2238
-        // must be %f
2239
-        return (float) $return_value;
2240
-    }
2241
-
2242
-
2243
-
2244
-    /**
2245
-     * Just calls the specified method on $wpdb with the given arguments
2246
-     * Consolidates a little extra error handling code
2247
-     *
2248
-     * @param string $wpdb_method
2249
-     * @param array  $arguments_to_provide
2250
-     * @throws EE_Error
2251
-     * @global wpdb  $wpdb
2252
-     * @return mixed
2253
-     */
2254
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2255
-    {
2256
-        // if we're in maintenance mode level 2, DON'T run any queries
2257
-        // because level 2 indicates the database needs updating and
2258
-        // is probably out of sync with the code
2259
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2260
-            throw new EE_Error(sprintf(__(
2261
-                "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2262
-                "event_espresso"
2263
-            )));
2264
-        }
2265
-        /** @type WPDB $wpdb */
2266
-        global $wpdb;
2267
-        if (! method_exists($wpdb, $wpdb_method)) {
2268
-            throw new EE_Error(sprintf(__(
2269
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2270
-                'event_espresso'
2271
-            ), $wpdb_method));
2272
-        }
2273
-        if (WP_DEBUG) {
2274
-            $old_show_errors_value = $wpdb->show_errors;
2275
-            $wpdb->show_errors(false);
2276
-        }
2277
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2278
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2279
-        if (WP_DEBUG) {
2280
-            $wpdb->show_errors($old_show_errors_value);
2281
-            if (! empty($wpdb->last_error)) {
2282
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2283
-            }
2284
-            if ($result === false) {
2285
-                throw new EE_Error(sprintf(__(
2286
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2287
-                    'event_espresso'
2288
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2289
-            }
2290
-        } elseif ($result === false) {
2291
-            EE_Error::add_error(
2292
-                sprintf(
2293
-                    __(
2294
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2295
-                        'event_espresso'
2296
-                    ),
2297
-                    $wpdb_method,
2298
-                    var_export($arguments_to_provide, true),
2299
-                    $wpdb->last_error
2300
-                ),
2301
-                __FILE__,
2302
-                __FUNCTION__,
2303
-                __LINE__
2304
-            );
2305
-        }
2306
-        return $result;
2307
-    }
2308
-
2309
-
2310
-
2311
-    /**
2312
-     * Attempts to run the indicated WPDB method with the provided arguments,
2313
-     * and if there's an error tries to verify the DB is correct. Uses
2314
-     * the static property EEM_Base::$_db_verification_level to determine whether
2315
-     * we should try to fix the EE core db, the addons, or just give up
2316
-     *
2317
-     * @param string $wpdb_method
2318
-     * @param array  $arguments_to_provide
2319
-     * @return mixed
2320
-     */
2321
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2322
-    {
2323
-        /** @type WPDB $wpdb */
2324
-        global $wpdb;
2325
-        $wpdb->last_error = null;
2326
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2327
-        // was there an error running the query? but we don't care on new activations
2328
-        // (we're going to setup the DB anyway on new activations)
2329
-        if (($result === false || ! empty($wpdb->last_error))
2330
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2331
-        ) {
2332
-            switch (EEM_Base::$_db_verification_level) {
2333
-                case EEM_Base::db_verified_none:
2334
-                    // let's double-check core's DB
2335
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2336
-                    break;
2337
-                case EEM_Base::db_verified_core:
2338
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2339
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2340
-                    break;
2341
-                case EEM_Base::db_verified_addons:
2342
-                    // ummmm... you in trouble
2343
-                    return $result;
2344
-                    break;
2345
-            }
2346
-            if (! empty($error_message)) {
2347
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2348
-                trigger_error($error_message);
2349
-            }
2350
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2351
-        }
2352
-        return $result;
2353
-    }
2354
-
2355
-
2356
-
2357
-    /**
2358
-     * Verifies the EE core database is up-to-date and records that we've done it on
2359
-     * EEM_Base::$_db_verification_level
2360
-     *
2361
-     * @param string $wpdb_method
2362
-     * @param array  $arguments_to_provide
2363
-     * @return string
2364
-     */
2365
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2366
-    {
2367
-        /** @type WPDB $wpdb */
2368
-        global $wpdb;
2369
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2370
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2371
-        $error_message = sprintf(
2372
-            __(
2373
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2374
-                'event_espresso'
2375
-            ),
2376
-            $wpdb->last_error,
2377
-            $wpdb_method,
2378
-            wp_json_encode($arguments_to_provide)
2379
-        );
2380
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2381
-        return $error_message;
2382
-    }
2383
-
2384
-
2385
-
2386
-    /**
2387
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2388
-     * EEM_Base::$_db_verification_level
2389
-     *
2390
-     * @param $wpdb_method
2391
-     * @param $arguments_to_provide
2392
-     * @return string
2393
-     */
2394
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2395
-    {
2396
-        /** @type WPDB $wpdb */
2397
-        global $wpdb;
2398
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2399
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2400
-        $error_message = sprintf(
2401
-            __(
2402
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2403
-                'event_espresso'
2404
-            ),
2405
-            $wpdb->last_error,
2406
-            $wpdb_method,
2407
-            wp_json_encode($arguments_to_provide)
2408
-        );
2409
-        EE_System::instance()->initialize_addons();
2410
-        return $error_message;
2411
-    }
2412
-
2413
-
2414
-
2415
-    /**
2416
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2417
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2418
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2419
-     * ..."
2420
-     *
2421
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2422
-     * @return string
2423
-     */
2424
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2425
-    {
2426
-        return " FROM " . $model_query_info->get_full_join_sql() .
2427
-               $model_query_info->get_where_sql() .
2428
-               $model_query_info->get_group_by_sql() .
2429
-               $model_query_info->get_having_sql() .
2430
-               $model_query_info->get_order_by_sql() .
2431
-               $model_query_info->get_limit_sql();
2432
-    }
2433
-
2434
-
2435
-
2436
-    /**
2437
-     * Set to easily debug the next X queries ran from this model.
2438
-     *
2439
-     * @param int $count
2440
-     */
2441
-    public function show_next_x_db_queries($count = 1)
2442
-    {
2443
-        $this->_show_next_x_db_queries = $count;
2444
-    }
2445
-
2446
-
2447
-
2448
-    /**
2449
-     * @param $sql_query
2450
-     */
2451
-    public function show_db_query_if_previously_requested($sql_query)
2452
-    {
2453
-        if ($this->_show_next_x_db_queries > 0) {
2454
-            echo $sql_query;
2455
-            $this->_show_next_x_db_queries--;
2456
-        }
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2463
-     * There are the 3 cases:
2464
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2465
-     * $otherModelObject has no ID, it is first saved.
2466
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2467
-     * has no ID, it is first saved.
2468
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2469
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2470
-     * join table
2471
-     *
2472
-     * @param        EE_Base_Class                     /int $thisModelObject
2473
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2474
-     * @param string $relationName                     , key in EEM_Base::_relations
2475
-     *                                                 an attendee to a group, you also want to specify which role they
2476
-     *                                                 will have in that group. So you would use this parameter to
2477
-     *                                                 specify array('role-column-name'=>'role-id')
2478
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2479
-     *                                                 to for relation to methods that allow you to further specify
2480
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2481
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2482
-     *                                                 because these will be inserted in any new rows created as well.
2483
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2484
-     * @throws EE_Error
2485
-     */
2486
-    public function add_relationship_to(
2487
-        $id_or_obj,
2488
-        $other_model_id_or_obj,
2489
-        $relationName,
2490
-        $extra_join_model_fields_n_values = array()
2491
-    ) {
2492
-        $relation_obj = $this->related_settings_for($relationName);
2493
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2494
-    }
2495
-
2496
-
2497
-
2498
-    /**
2499
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2500
-     * There are the 3 cases:
2501
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2502
-     * error
2503
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2504
-     * an error
2505
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2506
-     *
2507
-     * @param        EE_Base_Class /int $id_or_obj
2508
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2509
-     * @param string $relationName key in EEM_Base::_relations
2510
-     * @return boolean of success
2511
-     * @throws EE_Error
2512
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2513
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2514
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2515
-     *                             because these will be inserted in any new rows created as well.
2516
-     */
2517
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2518
-    {
2519
-        $relation_obj = $this->related_settings_for($relationName);
2520
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2521
-    }
2522
-
2523
-
2524
-
2525
-    /**
2526
-     * @param mixed           $id_or_obj
2527
-     * @param string          $relationName
2528
-     * @param array           $where_query_params
2529
-     * @param EE_Base_Class[] objects to which relations were removed
2530
-     * @return \EE_Base_Class[]
2531
-     * @throws EE_Error
2532
-     */
2533
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2534
-    {
2535
-        $relation_obj = $this->related_settings_for($relationName);
2536
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2537
-    }
2538
-
2539
-
2540
-
2541
-    /**
2542
-     * Gets all the related items of the specified $model_name, using $query_params.
2543
-     * Note: by default, we remove the "default query params"
2544
-     * because we want to get even deleted items etc.
2545
-     *
2546
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2547
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2548
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
-     * @return EE_Base_Class[]
2550
-     * @throws EE_Error
2551
-     */
2552
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2553
-    {
2554
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2555
-        $relation_settings = $this->related_settings_for($model_name);
2556
-        return $relation_settings->get_all_related($model_obj, $query_params);
2557
-    }
2558
-
2559
-
2560
-
2561
-    /**
2562
-     * Deletes all the model objects across the relation indicated by $model_name
2563
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2564
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2565
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2566
-     *
2567
-     * @param EE_Base_Class|int|string $id_or_obj
2568
-     * @param string                   $model_name
2569
-     * @param array                    $query_params
2570
-     * @return int how many deleted
2571
-     * @throws EE_Error
2572
-     */
2573
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2574
-    {
2575
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2576
-        $relation_settings = $this->related_settings_for($model_name);
2577
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2578
-    }
2579
-
2580
-
2581
-
2582
-    /**
2583
-     * Hard deletes all the model objects across the relation indicated by $model_name
2584
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2585
-     * the model objects can't be hard deleted because of blocking related model objects,
2586
-     * just does a soft-delete on them instead.
2587
-     *
2588
-     * @param EE_Base_Class|int|string $id_or_obj
2589
-     * @param string                   $model_name
2590
-     * @param array                    $query_params
2591
-     * @return int how many deleted
2592
-     * @throws EE_Error
2593
-     */
2594
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2595
-    {
2596
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2597
-        $relation_settings = $this->related_settings_for($model_name);
2598
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2599
-    }
2600
-
2601
-
2602
-
2603
-    /**
2604
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2605
-     * unless otherwise specified in the $query_params
2606
-     *
2607
-     * @param        int             /EE_Base_Class $id_or_obj
2608
-     * @param string $model_name     like 'Event', or 'Registration'
2609
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2610
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2611
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2612
-     *                               that by the setting $distinct to TRUE;
2613
-     * @return int
2614
-     * @throws EE_Error
2615
-     */
2616
-    public function count_related(
2617
-        $id_or_obj,
2618
-        $model_name,
2619
-        $query_params = array(),
2620
-        $field_to_count = null,
2621
-        $distinct = false
2622
-    ) {
2623
-        $related_model = $this->get_related_model_obj($model_name);
2624
-        // we're just going to use the query params on the related model's normal get_all query,
2625
-        // except add a condition to say to match the current mod
2626
-        if (! isset($query_params['default_where_conditions'])) {
2627
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2628
-        }
2629
-        $this_model_name = $this->get_this_model_name();
2630
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2631
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2632
-        return $related_model->count($query_params, $field_to_count, $distinct);
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2639
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2640
-     *
2641
-     * @param        int           /EE_Base_Class $id_or_obj
2642
-     * @param string $model_name   like 'Event', or 'Registration'
2643
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2644
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2645
-     * @return float
2646
-     * @throws EE_Error
2647
-     */
2648
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2649
-    {
2650
-        $related_model = $this->get_related_model_obj($model_name);
2651
-        if (! is_array($query_params)) {
2652
-            EE_Error::doing_it_wrong(
2653
-                'EEM_Base::sum_related',
2654
-                sprintf(
2655
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2656
-                    gettype($query_params)
2657
-                ),
2658
-                '4.6.0'
2659
-            );
2660
-            $query_params = array();
2661
-        }
2662
-        // we're just going to use the query params on the related model's normal get_all query,
2663
-        // except add a condition to say to match the current mod
2664
-        if (! isset($query_params['default_where_conditions'])) {
2665
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2666
-        }
2667
-        $this_model_name = $this->get_this_model_name();
2668
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2669
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2670
-        return $related_model->sum($query_params, $field_to_sum);
2671
-    }
2672
-
2673
-
2674
-
2675
-    /**
2676
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2677
-     * $modelObject
2678
-     *
2679
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2680
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2681
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2682
-     * @return EE_Base_Class
2683
-     * @throws EE_Error
2684
-     */
2685
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2686
-    {
2687
-        $query_params['limit'] = 1;
2688
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2689
-        if ($results) {
2690
-            return array_shift($results);
2691
-        }
2692
-        return null;
2693
-    }
2694
-
2695
-
2696
-
2697
-    /**
2698
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2699
-     *
2700
-     * @return string
2701
-     */
2702
-    public function get_this_model_name()
2703
-    {
2704
-        return str_replace("EEM_", "", get_class($this));
2705
-    }
2706
-
2707
-
2708
-
2709
-    /**
2710
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2711
-     *
2712
-     * @return EE_Any_Foreign_Model_Name_Field
2713
-     * @throws EE_Error
2714
-     */
2715
-    public function get_field_containing_related_model_name()
2716
-    {
2717
-        foreach ($this->field_settings(true) as $field) {
2718
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2719
-                $field_with_model_name = $field;
2720
-            }
2721
-        }
2722
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2723
-            throw new EE_Error(sprintf(
2724
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2725
-                $this->get_this_model_name()
2726
-            ));
2727
-        }
2728
-        return $field_with_model_name;
2729
-    }
2730
-
2731
-
2732
-
2733
-    /**
2734
-     * Inserts a new entry into the database, for each table.
2735
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2736
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2737
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2738
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2739
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2740
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2741
-     *
2742
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2743
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2744
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2745
-     *                              of EEM_Base)
2746
-     * @return int|string new primary key on main table that got inserted
2747
-     * @throws EE_Error
2748
-     */
2749
-    public function insert($field_n_values)
2750
-    {
2751
-        /**
2752
-         * Filters the fields and their values before inserting an item using the models
2753
-         *
2754
-         * @param array    $fields_n_values keys are the fields and values are their new values
2755
-         * @param EEM_Base $model           the model used
2756
-         */
2757
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2758
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2759
-            $main_table = $this->_get_main_table();
2760
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2761
-            if ($new_id !== false) {
2762
-                foreach ($this->_get_other_tables() as $other_table) {
2763
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2764
-                }
2765
-            }
2766
-            /**
2767
-             * Done just after attempting to insert a new model object
2768
-             *
2769
-             * @param EEM_Base   $model           used
2770
-             * @param array      $fields_n_values fields and their values
2771
-             * @param int|string the              ID of the newly-inserted model object
2772
-             */
2773
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2774
-            return $new_id;
2775
-        }
2776
-        return false;
2777
-    }
2778
-
2779
-
2780
-
2781
-    /**
2782
-     * Checks that the result would satisfy the unique indexes on this model
2783
-     *
2784
-     * @param array  $field_n_values
2785
-     * @param string $action
2786
-     * @return boolean
2787
-     * @throws EE_Error
2788
-     */
2789
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2790
-    {
2791
-        foreach ($this->unique_indexes() as $index_name => $index) {
2792
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2793
-            if ($this->exists(array($uniqueness_where_params))) {
2794
-                EE_Error::add_error(
2795
-                    sprintf(
2796
-                        __(
2797
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2798
-                            "event_espresso"
2799
-                        ),
2800
-                        $action,
2801
-                        $this->_get_class_name(),
2802
-                        $index_name,
2803
-                        implode(",", $index->field_names()),
2804
-                        http_build_query($uniqueness_where_params)
2805
-                    ),
2806
-                    __FILE__,
2807
-                    __FUNCTION__,
2808
-                    __LINE__
2809
-                );
2810
-                return false;
2811
-            }
2812
-        }
2813
-        return true;
2814
-    }
2815
-
2816
-
2817
-
2818
-    /**
2819
-     * Checks the database for an item that conflicts (ie, if this item were
2820
-     * saved to the DB would break some uniqueness requirement, like a primary key
2821
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2822
-     * can be either an EE_Base_Class or an array of fields n values
2823
-     *
2824
-     * @param EE_Base_Class|array $obj_or_fields_array
2825
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2826
-     *                                                 when looking for conflicts
2827
-     *                                                 (ie, if false, we ignore the model object's primary key
2828
-     *                                                 when finding "conflicts". If true, it's also considered).
2829
-     *                                                 Only works for INT primary key,
2830
-     *                                                 STRING primary keys cannot be ignored
2831
-     * @throws EE_Error
2832
-     * @return EE_Base_Class|array
2833
-     */
2834
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2835
-    {
2836
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2837
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2838
-        } elseif (is_array($obj_or_fields_array)) {
2839
-            $fields_n_values = $obj_or_fields_array;
2840
-        } else {
2841
-            throw new EE_Error(
2842
-                sprintf(
2843
-                    __(
2844
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2845
-                        "event_espresso"
2846
-                    ),
2847
-                    get_class($this),
2848
-                    $obj_or_fields_array
2849
-                )
2850
-            );
2851
-        }
2852
-        $query_params = array();
2853
-        if ($this->has_primary_key_field()
2854
-            && ($include_primary_key
2855
-                || $this->get_primary_key_field()
2856
-                   instanceof
2857
-                   EE_Primary_Key_String_Field)
2858
-            && isset($fields_n_values[ $this->primary_key_name() ])
2859
-        ) {
2860
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2861
-        }
2862
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2863
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2864
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2865
-        }
2866
-        // if there is nothing to base this search on, then we shouldn't find anything
2867
-        if (empty($query_params)) {
2868
-            return array();
2869
-        }
2870
-        return $this->get_one($query_params);
2871
-    }
2872
-
2873
-
2874
-
2875
-    /**
2876
-     * Like count, but is optimized and returns a boolean instead of an int
2877
-     *
2878
-     * @param array $query_params
2879
-     * @return boolean
2880
-     * @throws EE_Error
2881
-     */
2882
-    public function exists($query_params)
2883
-    {
2884
-        $query_params['limit'] = 1;
2885
-        return $this->count($query_params) > 0;
2886
-    }
2887
-
2888
-
2889
-
2890
-    /**
2891
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2892
-     *
2893
-     * @param int|string $id
2894
-     * @return boolean
2895
-     * @throws EE_Error
2896
-     */
2897
-    public function exists_by_ID($id)
2898
-    {
2899
-        return $this->exists(
2900
-            array(
2901
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2902
-                array(
2903
-                    $this->primary_key_name() => $id,
2904
-                ),
2905
-            )
2906
-        );
2907
-    }
2908
-
2909
-
2910
-
2911
-    /**
2912
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2913
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2914
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2915
-     * on the main table)
2916
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2917
-     * cases where we want to call it directly rather than via insert().
2918
-     *
2919
-     * @access   protected
2920
-     * @param EE_Table_Base $table
2921
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2922
-     *                                       float
2923
-     * @param int           $new_id          for now we assume only int keys
2924
-     * @throws EE_Error
2925
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2926
-     * @return int ID of new row inserted, or FALSE on failure
2927
-     */
2928
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2929
-    {
2930
-        global $wpdb;
2931
-        $insertion_col_n_values = array();
2932
-        $format_for_insertion = array();
2933
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2934
-        foreach ($fields_on_table as $field_name => $field_obj) {
2935
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2936
-            if ($field_obj->is_auto_increment()) {
2937
-                continue;
2938
-            }
2939
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2940
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2941
-            if ($prepared_value !== null) {
2942
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2943
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2944
-            }
2945
-        }
2946
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2947
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2948
-            // so add the fk to the main table as a column
2949
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2950
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2951
-        }
2952
-        // insert the new entry
2953
-        $result = $this->_do_wpdb_query(
2954
-            'insert',
2955
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
2956
-        );
2957
-        if ($result === false) {
2958
-            return false;
2959
-        }
2960
-        // ok, now what do we return for the ID of the newly-inserted thing?
2961
-        if ($this->has_primary_key_field()) {
2962
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2963
-                return $wpdb->insert_id;
2964
-            }
2965
-            // it's not an auto-increment primary key, so
2966
-            // it must have been supplied
2967
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
2968
-        }
2969
-        // we can't return a  primary key because there is none. instead return
2970
-        // a unique string indicating this model
2971
-        return $this->get_index_primary_key_string($fields_n_values);
2972
-    }
2973
-
2974
-
2975
-
2976
-    /**
2977
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2978
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2979
-     * and there is no default, we pass it along. WPDB will take care of it)
2980
-     *
2981
-     * @param EE_Model_Field_Base $field_obj
2982
-     * @param array               $fields_n_values
2983
-     * @return mixed string|int|float depending on what the table column will be expecting
2984
-     * @throws EE_Error
2985
-     */
2986
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2987
-    {
2988
-        // if this field doesn't allow nullable, don't allow it
2989
-        if (! $field_obj->is_nullable()
2990
-            && (
2991
-                ! isset($fields_n_values[ $field_obj->get_name() ])
2992
-                || $fields_n_values[ $field_obj->get_name() ] === null
2993
-            )
2994
-        ) {
2995
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2996
-        }
2997
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
2998
-            ? $fields_n_values[ $field_obj->get_name() ]
2999
-            : null;
3000
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3001
-    }
3002
-
3003
-
3004
-
3005
-    /**
3006
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3007
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3008
-     * the field's prepare_for_set() method.
3009
-     *
3010
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3011
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3012
-     *                                   top of file)
3013
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3014
-     *                                   $value is a custom selection
3015
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3016
-     */
3017
-    private function _prepare_value_for_use_in_db($value, $field)
3018
-    {
3019
-        if ($field && $field instanceof EE_Model_Field_Base) {
3020
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3021
-            switch ($this->_values_already_prepared_by_model_object) {
3022
-                /** @noinspection PhpMissingBreakStatementInspection */
3023
-                case self::not_prepared_by_model_object:
3024
-                    $value = $field->prepare_for_set($value);
3025
-                // purposefully left out "return"
3026
-                case self::prepared_by_model_object:
3027
-                    /** @noinspection SuspiciousAssignmentsInspection */
3028
-                    $value = $field->prepare_for_use_in_db($value);
3029
-                case self::prepared_for_use_in_db:
3030
-                    // leave the value alone
3031
-            }
3032
-            return $value;
3033
-            // phpcs:enable
3034
-        }
3035
-        return $value;
3036
-    }
3037
-
3038
-
3039
-
3040
-    /**
3041
-     * Returns the main table on this model
3042
-     *
3043
-     * @return EE_Primary_Table
3044
-     * @throws EE_Error
3045
-     */
3046
-    protected function _get_main_table()
3047
-    {
3048
-        foreach ($this->_tables as $table) {
3049
-            if ($table instanceof EE_Primary_Table) {
3050
-                return $table;
3051
-            }
3052
-        }
3053
-        throw new EE_Error(sprintf(__(
3054
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3055
-            'event_espresso'
3056
-        ), get_class($this)));
3057
-    }
3058
-
3059
-
3060
-
3061
-    /**
3062
-     * table
3063
-     * returns EE_Primary_Table table name
3064
-     *
3065
-     * @return string
3066
-     * @throws EE_Error
3067
-     */
3068
-    public function table()
3069
-    {
3070
-        return $this->_get_main_table()->get_table_name();
3071
-    }
3072
-
3073
-
3074
-
3075
-    /**
3076
-     * table
3077
-     * returns first EE_Secondary_Table table name
3078
-     *
3079
-     * @return string
3080
-     */
3081
-    public function second_table()
3082
-    {
3083
-        // grab second table from tables array
3084
-        $second_table = end($this->_tables);
3085
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3086
-    }
3087
-
3088
-
3089
-
3090
-    /**
3091
-     * get_table_obj_by_alias
3092
-     * returns table name given it's alias
3093
-     *
3094
-     * @param string $table_alias
3095
-     * @return EE_Primary_Table | EE_Secondary_Table
3096
-     */
3097
-    public function get_table_obj_by_alias($table_alias = '')
3098
-    {
3099
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3100
-    }
3101
-
3102
-
3103
-
3104
-    /**
3105
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3106
-     *
3107
-     * @return EE_Secondary_Table[]
3108
-     */
3109
-    protected function _get_other_tables()
3110
-    {
3111
-        $other_tables = array();
3112
-        foreach ($this->_tables as $table_alias => $table) {
3113
-            if ($table instanceof EE_Secondary_Table) {
3114
-                $other_tables[ $table_alias ] = $table;
3115
-            }
3116
-        }
3117
-        return $other_tables;
3118
-    }
3119
-
3120
-
3121
-
3122
-    /**
3123
-     * Finds all the fields that correspond to the given table
3124
-     *
3125
-     * @param string $table_alias , array key in EEM_Base::_tables
3126
-     * @return EE_Model_Field_Base[]
3127
-     */
3128
-    public function _get_fields_for_table($table_alias)
3129
-    {
3130
-        return $this->_fields[ $table_alias ];
3131
-    }
3132
-
3133
-
3134
-
3135
-    /**
3136
-     * Recurses through all the where parameters, and finds all the related models we'll need
3137
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3138
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3139
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3140
-     * related Registration, Transaction, and Payment models.
3141
-     *
3142
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3143
-     * @return EE_Model_Query_Info_Carrier
3144
-     * @throws EE_Error
3145
-     */
3146
-    public function _extract_related_models_from_query($query_params)
3147
-    {
3148
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3149
-        if (array_key_exists(0, $query_params)) {
3150
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3151
-        }
3152
-        if (array_key_exists('group_by', $query_params)) {
3153
-            if (is_array($query_params['group_by'])) {
3154
-                $this->_extract_related_models_from_sub_params_array_values(
3155
-                    $query_params['group_by'],
3156
-                    $query_info_carrier,
3157
-                    'group_by'
3158
-                );
3159
-            } elseif (! empty($query_params['group_by'])) {
3160
-                $this->_extract_related_model_info_from_query_param(
3161
-                    $query_params['group_by'],
3162
-                    $query_info_carrier,
3163
-                    'group_by'
3164
-                );
3165
-            }
3166
-        }
3167
-        if (array_key_exists('having', $query_params)) {
3168
-            $this->_extract_related_models_from_sub_params_array_keys(
3169
-                $query_params[0],
3170
-                $query_info_carrier,
3171
-                'having'
3172
-            );
3173
-        }
3174
-        if (array_key_exists('order_by', $query_params)) {
3175
-            if (is_array($query_params['order_by'])) {
3176
-                $this->_extract_related_models_from_sub_params_array_keys(
3177
-                    $query_params['order_by'],
3178
-                    $query_info_carrier,
3179
-                    'order_by'
3180
-                );
3181
-            } elseif (! empty($query_params['order_by'])) {
3182
-                $this->_extract_related_model_info_from_query_param(
3183
-                    $query_params['order_by'],
3184
-                    $query_info_carrier,
3185
-                    'order_by'
3186
-                );
3187
-            }
3188
-        }
3189
-        if (array_key_exists('force_join', $query_params)) {
3190
-            $this->_extract_related_models_from_sub_params_array_values(
3191
-                $query_params['force_join'],
3192
-                $query_info_carrier,
3193
-                'force_join'
3194
-            );
3195
-        }
3196
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3197
-        return $query_info_carrier;
3198
-    }
3199
-
3200
-
3201
-
3202
-    /**
3203
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3204
-     *
3205
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3206
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3207
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3208
-     * @throws EE_Error
3209
-     * @return \EE_Model_Query_Info_Carrier
3210
-     */
3211
-    private function _extract_related_models_from_sub_params_array_keys(
3212
-        $sub_query_params,
3213
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3214
-        $query_param_type
3215
-    ) {
3216
-        if (! empty($sub_query_params)) {
3217
-            $sub_query_params = (array) $sub_query_params;
3218
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3219
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3220
-                $this->_extract_related_model_info_from_query_param(
3221
-                    $param,
3222
-                    $model_query_info_carrier,
3223
-                    $query_param_type
3224
-                );
3225
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3226
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3227
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3228
-                // of array('Registration.TXN_ID'=>23)
3229
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3230
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3231
-                    if (! is_array($possibly_array_of_params)) {
3232
-                        throw new EE_Error(sprintf(
3233
-                            __(
3234
-                                "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3235
-                                "event_espresso"
3236
-                            ),
3237
-                            $param,
3238
-                            $possibly_array_of_params
3239
-                        ));
3240
-                    }
3241
-                    $this->_extract_related_models_from_sub_params_array_keys(
3242
-                        $possibly_array_of_params,
3243
-                        $model_query_info_carrier,
3244
-                        $query_param_type
3245
-                    );
3246
-                } elseif ($query_param_type === 0 // ie WHERE
3247
-                          && is_array($possibly_array_of_params)
3248
-                          && isset($possibly_array_of_params[2])
3249
-                          && $possibly_array_of_params[2] == true
3250
-                ) {
3251
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3252
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3253
-                    // from which we should extract query parameters!
3254
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3255
-                        throw new EE_Error(sprintf(__(
3256
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3257
-                            "event_espresso"
3258
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3259
-                    }
3260
-                    $this->_extract_related_model_info_from_query_param(
3261
-                        $possibly_array_of_params[1],
3262
-                        $model_query_info_carrier,
3263
-                        $query_param_type
3264
-                    );
3265
-                }
3266
-            }
3267
-        }
3268
-        return $model_query_info_carrier;
3269
-    }
3270
-
3271
-
3272
-
3273
-    /**
3274
-     * For extracting related models from forced_joins, where the array values contain the info about what
3275
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3276
-     *
3277
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3278
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3279
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3280
-     * @throws EE_Error
3281
-     * @return \EE_Model_Query_Info_Carrier
3282
-     */
3283
-    private function _extract_related_models_from_sub_params_array_values(
3284
-        $sub_query_params,
3285
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3286
-        $query_param_type
3287
-    ) {
3288
-        if (! empty($sub_query_params)) {
3289
-            if (! is_array($sub_query_params)) {
3290
-                throw new EE_Error(sprintf(
3291
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3292
-                    $sub_query_params
3293
-                ));
3294
-            }
3295
-            foreach ($sub_query_params as $param) {
3296
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3297
-                $this->_extract_related_model_info_from_query_param(
3298
-                    $param,
3299
-                    $model_query_info_carrier,
3300
-                    $query_param_type
3301
-                );
3302
-            }
3303
-        }
3304
-        return $model_query_info_carrier;
3305
-    }
3306
-
3307
-
3308
-
3309
-    /**
3310
-     * Extract all the query parts from  model query params
3311
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3312
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3313
-     * but use them in a different order. Eg, we need to know what models we are querying
3314
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3315
-     * other models before we can finalize the where clause SQL.
3316
-     *
3317
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3318
-     * @throws EE_Error
3319
-     * @return EE_Model_Query_Info_Carrier
3320
-     */
3321
-    public function _create_model_query_info_carrier($query_params)
3322
-    {
3323
-        if (! is_array($query_params)) {
3324
-            EE_Error::doing_it_wrong(
3325
-                'EEM_Base::_create_model_query_info_carrier',
3326
-                sprintf(
3327
-                    __(
3328
-                        '$query_params should be an array, you passed a variable of type %s',
3329
-                        'event_espresso'
3330
-                    ),
3331
-                    gettype($query_params)
3332
-                ),
3333
-                '4.6.0'
3334
-            );
3335
-            $query_params = array();
3336
-        }
3337
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3338
-        // first check if we should alter the query to account for caps or not
3339
-        // because the caps might require us to do extra joins
3340
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3341
-            $query_params[0] = $where_query_params = array_replace_recursive(
3342
-                $where_query_params,
3343
-                $this->caps_where_conditions(
3344
-                    $query_params['caps']
3345
-                )
3346
-            );
3347
-        }
3348
-        $query_object = $this->_extract_related_models_from_query($query_params);
3349
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3350
-        foreach ($where_query_params as $key => $value) {
3351
-            if (is_int($key)) {
3352
-                throw new EE_Error(
3353
-                    sprintf(
3354
-                        __(
3355
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3356
-                            "event_espresso"
3357
-                        ),
3358
-                        $key,
3359
-                        var_export($value, true),
3360
-                        var_export($query_params, true),
3361
-                        get_class($this)
3362
-                    )
3363
-                );
3364
-            }
3365
-        }
3366
-        if (array_key_exists('default_where_conditions', $query_params)
3367
-            && ! empty($query_params['default_where_conditions'])
3368
-        ) {
3369
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3370
-        } else {
3371
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3372
-        }
3373
-        $where_query_params = array_merge(
3374
-            $this->_get_default_where_conditions_for_models_in_query(
3375
-                $query_object,
3376
-                $use_default_where_conditions,
3377
-                $where_query_params
3378
-            ),
3379
-            $where_query_params
3380
-        );
3381
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3382
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3383
-        // So we need to setup a subquery and use that for the main join.
3384
-        // Note for now this only works on the primary table for the model.
3385
-        // So for instance, you could set the limit array like this:
3386
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3387
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3388
-            $query_object->set_main_model_join_sql(
3389
-                $this->_construct_limit_join_select(
3390
-                    $query_params['on_join_limit'][0],
3391
-                    $query_params['on_join_limit'][1]
3392
-                )
3393
-            );
3394
-        }
3395
-        // set limit
3396
-        if (array_key_exists('limit', $query_params)) {
3397
-            if (is_array($query_params['limit'])) {
3398
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3399
-                    $e = sprintf(
3400
-                        __(
3401
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3402
-                            "event_espresso"
3403
-                        ),
3404
-                        http_build_query($query_params['limit'])
3405
-                    );
3406
-                    throw new EE_Error($e . "|" . $e);
3407
-                }
3408
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3409
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3410
-            } elseif (! empty($query_params['limit'])) {
3411
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3412
-            }
3413
-        }
3414
-        // set order by
3415
-        if (array_key_exists('order_by', $query_params)) {
3416
-            if (is_array($query_params['order_by'])) {
3417
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3418
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3419
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3420
-                if (array_key_exists('order', $query_params)) {
3421
-                    throw new EE_Error(
3422
-                        sprintf(
3423
-                            __(
3424
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3425
-                                "event_espresso"
3426
-                            ),
3427
-                            get_class($this),
3428
-                            implode(", ", array_keys($query_params['order_by'])),
3429
-                            implode(", ", $query_params['order_by']),
3430
-                            $query_params['order']
3431
-                        )
3432
-                    );
3433
-                }
3434
-                $this->_extract_related_models_from_sub_params_array_keys(
3435
-                    $query_params['order_by'],
3436
-                    $query_object,
3437
-                    'order_by'
3438
-                );
3439
-                // assume it's an array of fields to order by
3440
-                $order_array = array();
3441
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3442
-                    $order = $this->_extract_order($order);
3443
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3444
-                }
3445
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3446
-            } elseif (! empty($query_params['order_by'])) {
3447
-                $this->_extract_related_model_info_from_query_param(
3448
-                    $query_params['order_by'],
3449
-                    $query_object,
3450
-                    'order',
3451
-                    $query_params['order_by']
3452
-                );
3453
-                $order = isset($query_params['order'])
3454
-                    ? $this->_extract_order($query_params['order'])
3455
-                    : 'DESC';
3456
-                $query_object->set_order_by_sql(
3457
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3458
-                );
3459
-            }
3460
-        }
3461
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3462
-        if (! array_key_exists('order_by', $query_params)
3463
-            && array_key_exists('order', $query_params)
3464
-            && ! empty($query_params['order'])
3465
-        ) {
3466
-            $pk_field = $this->get_primary_key_field();
3467
-            $order = $this->_extract_order($query_params['order']);
3468
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3469
-        }
3470
-        // set group by
3471
-        if (array_key_exists('group_by', $query_params)) {
3472
-            if (is_array($query_params['group_by'])) {
3473
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3474
-                $group_by_array = array();
3475
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3476
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3477
-                }
3478
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3479
-            } elseif (! empty($query_params['group_by'])) {
3480
-                $query_object->set_group_by_sql(
3481
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3482
-                );
3483
-            }
3484
-        }
3485
-        // set having
3486
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3487
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3488
-        }
3489
-        // now, just verify they didn't pass anything wack
3490
-        foreach ($query_params as $query_key => $query_value) {
3491
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3492
-                throw new EE_Error(
3493
-                    sprintf(
3494
-                        __(
3495
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3496
-                            'event_espresso'
3497
-                        ),
3498
-                        $query_key,
3499
-                        get_class($this),
3500
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3501
-                        implode(',', $this->_allowed_query_params)
3502
-                    )
3503
-                );
3504
-            }
3505
-        }
3506
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3507
-        if (empty($main_model_join_sql)) {
3508
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3509
-        }
3510
-        return $query_object;
3511
-    }
3512
-
3513
-
3514
-
3515
-    /**
3516
-     * Gets the where conditions that should be imposed on the query based on the
3517
-     * context (eg reading frontend, backend, edit or delete).
3518
-     *
3519
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3520
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3521
-     * @throws EE_Error
3522
-     */
3523
-    public function caps_where_conditions($context = self::caps_read)
3524
-    {
3525
-        EEM_Base::verify_is_valid_cap_context($context);
3526
-        $cap_where_conditions = array();
3527
-        $cap_restrictions = $this->caps_missing($context);
3528
-        /**
3529
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3530
-         */
3531
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3532
-            $cap_where_conditions = array_replace_recursive(
3533
-                $cap_where_conditions,
3534
-                $restriction_if_no_cap->get_default_where_conditions()
3535
-            );
3536
-        }
3537
-        return apply_filters(
3538
-            'FHEE__EEM_Base__caps_where_conditions__return',
3539
-            $cap_where_conditions,
3540
-            $this,
3541
-            $context,
3542
-            $cap_restrictions
3543
-        );
3544
-    }
3545
-
3546
-
3547
-
3548
-    /**
3549
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3550
-     * otherwise throws an exception
3551
-     *
3552
-     * @param string $should_be_order_string
3553
-     * @return string either ASC, asc, DESC or desc
3554
-     * @throws EE_Error
3555
-     */
3556
-    private function _extract_order($should_be_order_string)
3557
-    {
3558
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3559
-            return $should_be_order_string;
3560
-        }
3561
-        throw new EE_Error(
3562
-            sprintf(
3563
-                __(
3564
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3565
-                    "event_espresso"
3566
-                ),
3567
-                get_class($this),
3568
-                $should_be_order_string
3569
-            )
3570
-        );
3571
-    }
3572
-
3573
-
3574
-
3575
-    /**
3576
-     * Looks at all the models which are included in this query, and asks each
3577
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3578
-     * so they can be merged
3579
-     *
3580
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3581
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3582
-     *                                                                  'none' means NO default where conditions will
3583
-     *                                                                  be used AT ALL during this query.
3584
-     *                                                                  'other_models_only' means default where
3585
-     *                                                                  conditions from other models will be used, but
3586
-     *                                                                  not for this primary model. 'all', the default,
3587
-     *                                                                  means default where conditions will apply as
3588
-     *                                                                  normal
3589
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3590
-     * @throws EE_Error
3591
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3592
-     */
3593
-    private function _get_default_where_conditions_for_models_in_query(
3594
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3595
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3596
-        $where_query_params = array()
3597
-    ) {
3598
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3599
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3600
-            throw new EE_Error(sprintf(
3601
-                __(
3602
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3603
-                    "event_espresso"
3604
-                ),
3605
-                $use_default_where_conditions,
3606
-                implode(", ", $allowed_used_default_where_conditions_values)
3607
-            ));
3608
-        }
3609
-        $universal_query_params = array();
3610
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3611
-            $universal_query_params = $this->_get_default_where_conditions();
3612
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3613
-            $universal_query_params = $this->_get_minimum_where_conditions();
3614
-        }
3615
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3616
-            $related_model = $this->get_related_model_obj($model_name);
3617
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3618
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3619
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3620
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3621
-            } else {
3622
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3623
-                continue;
3624
-            }
3625
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3626
-                $related_model_universal_where_params,
3627
-                $where_query_params,
3628
-                $related_model,
3629
-                $model_relation_path
3630
-            );
3631
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3632
-                $universal_query_params,
3633
-                $overrides
3634
-            );
3635
-        }
3636
-        return $universal_query_params;
3637
-    }
3638
-
3639
-
3640
-
3641
-    /**
3642
-     * Determines whether or not we should use default where conditions for the model in question
3643
-     * (this model, or other related models).
3644
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3645
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3646
-     * We should use default where conditions on related models when they requested to use default where conditions
3647
-     * on all models, or specifically just on other related models
3648
-     * @param      $default_where_conditions_value
3649
-     * @param bool $for_this_model false means this is for OTHER related models
3650
-     * @return bool
3651
-     */
3652
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3653
-    {
3654
-        return (
3655
-                   $for_this_model
3656
-                   && in_array(
3657
-                       $default_where_conditions_value,
3658
-                       array(
3659
-                           EEM_Base::default_where_conditions_all,
3660
-                           EEM_Base::default_where_conditions_this_only,
3661
-                           EEM_Base::default_where_conditions_minimum_others,
3662
-                       ),
3663
-                       true
3664
-                   )
3665
-               )
3666
-               || (
3667
-                   ! $for_this_model
3668
-                   && in_array(
3669
-                       $default_where_conditions_value,
3670
-                       array(
3671
-                           EEM_Base::default_where_conditions_all,
3672
-                           EEM_Base::default_where_conditions_others_only,
3673
-                       ),
3674
-                       true
3675
-                   )
3676
-               );
3677
-    }
3678
-
3679
-    /**
3680
-     * Determines whether or not we should use default minimum conditions for the model in question
3681
-     * (this model, or other related models).
3682
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3683
-     * where conditions.
3684
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3685
-     * on this model or others
3686
-     * @param      $default_where_conditions_value
3687
-     * @param bool $for_this_model false means this is for OTHER related models
3688
-     * @return bool
3689
-     */
3690
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3691
-    {
3692
-        return (
3693
-                   $for_this_model
3694
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3695
-               )
3696
-               || (
3697
-                   ! $for_this_model
3698
-                   && in_array(
3699
-                       $default_where_conditions_value,
3700
-                       array(
3701
-                           EEM_Base::default_where_conditions_minimum_others,
3702
-                           EEM_Base::default_where_conditions_minimum_all,
3703
-                       ),
3704
-                       true
3705
-                   )
3706
-               );
3707
-    }
3708
-
3709
-
3710
-    /**
3711
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3712
-     * then we also add a special where condition which allows for that model's primary key
3713
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3714
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3715
-     *
3716
-     * @param array    $default_where_conditions
3717
-     * @param array    $provided_where_conditions
3718
-     * @param EEM_Base $model
3719
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3720
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3721
-     * @throws EE_Error
3722
-     */
3723
-    private function _override_defaults_or_make_null_friendly(
3724
-        $default_where_conditions,
3725
-        $provided_where_conditions,
3726
-        $model,
3727
-        $model_relation_path
3728
-    ) {
3729
-        $null_friendly_where_conditions = array();
3730
-        $none_overridden = true;
3731
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3732
-        foreach ($default_where_conditions as $key => $val) {
3733
-            if (isset($provided_where_conditions[ $key ])) {
3734
-                $none_overridden = false;
3735
-            } else {
3736
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3737
-            }
3738
-        }
3739
-        if ($none_overridden && $default_where_conditions) {
3740
-            if ($model->has_primary_key_field()) {
3741
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3742
-                                                                                . "."
3743
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3744
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error(
520
+				sprintf(
521
+					__(
522
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
+						'event_espresso'
524
+					),
525
+					get_class($this)
526
+				)
527
+			);
528
+		}
529
+		/**
530
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
531
+		 */
532
+		if (empty(EEM_Base::$_model_query_blog_id)) {
533
+			EEM_Base::set_model_query_blog_id();
534
+		}
535
+		/**
536
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
537
+		 * just use EE_Register_Model_Extension
538
+		 *
539
+		 * @var EE_Table_Base[] $_tables
540
+		 */
541
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
542
+		foreach ($this->_tables as $table_alias => $table_obj) {
543
+			/** @var $table_obj EE_Table_Base */
544
+			$table_obj->_construct_finalize_with_alias($table_alias);
545
+			if ($table_obj instanceof EE_Secondary_Table) {
546
+				/** @var $table_obj EE_Secondary_Table */
547
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
548
+			}
549
+		}
550
+		/**
551
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
552
+		 * EE_Register_Model_Extension
553
+		 *
554
+		 * @param EE_Model_Field_Base[] $_fields
555
+		 */
556
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
557
+		$this->_invalidate_field_caches();
558
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
559
+			if (! array_key_exists($table_alias, $this->_tables)) {
560
+				throw new EE_Error(sprintf(__(
561
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
562
+					'event_espresso'
563
+				), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				// primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			// make extra meta related to everything, but don't block deleting things just
575
+			// because they have related extra meta info. For now just orphan those extra meta
576
+			// in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		// and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = (array) apply_filters(
590
+			'FHEE__' . get_class($this) . '__construct__model_relations',
591
+			$this->_model_relations
592
+		);
593
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
594
+			/** @var $relation_obj EE_Model_Relation_Base */
595
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
596
+		}
597
+		foreach ($this->_indexes as $index_name => $index_obj) {
598
+			/** @var $index_obj EE_Index */
599
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
600
+		}
601
+		$this->set_timezone($timezone);
602
+		// finalize default where condition strategy, or set default
603
+		if (! $this->_default_where_conditions_strategy) {
604
+			// nothing was set during child constructor, so set default
605
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
608
+		if (! $this->_minimum_where_conditions_strategy) {
609
+			// nothing was set during child constructor, so set default
610
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
611
+		}
612
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
613
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
614
+		// to indicate to NOT set it, set it to the logical default
615
+		if ($this->_caps_slug === null) {
616
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
617
+		}
618
+		// initialize the standard cap restriction generators if none were specified by the child constructor
619
+		if ($this->_cap_restriction_generators !== false) {
620
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
621
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
622
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
623
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
624
+						new EE_Restriction_Generator_Protected(),
625
+						$cap_context,
626
+						$this
627
+					);
628
+				}
629
+			}
630
+		}
631
+		// if there are cap restriction generators, use them to make the default cap restrictions
632
+		if ($this->_cap_restriction_generators !== false) {
633
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
634
+				if (! $generator_object) {
635
+					continue;
636
+				}
637
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
638
+					throw new EE_Error(
639
+						sprintf(
640
+							__(
641
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
642
+								'event_espresso'
643
+							),
644
+							$context,
645
+							$this->get_this_model_name()
646
+						)
647
+					);
648
+				}
649
+				$action = $this->cap_action_for_context($context);
650
+				if (! $generator_object->construction_finalized()) {
651
+					$generator_object->_construct_finalize($this, $action);
652
+				}
653
+			}
654
+		}
655
+		do_action('AHEE__' . get_class($this) . '__construct__end');
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 * Used to set the $_model_query_blog_id static property.
662
+	 *
663
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
664
+	 *                      value for get_current_blog_id() will be used.
665
+	 */
666
+	public static function set_model_query_blog_id($blog_id = 0)
667
+	{
668
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * Returns whatever is set as the internal $model_query_blog_id.
675
+	 *
676
+	 * @return int
677
+	 */
678
+	public static function get_model_query_blog_id()
679
+	{
680
+		return EEM_Base::$_model_query_blog_id;
681
+	}
682
+
683
+
684
+
685
+	/**
686
+	 * This function is a singleton method used to instantiate the Espresso_model object
687
+	 *
688
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
689
+	 *                                (and any incoming timezone data that gets saved).
690
+	 *                                Note this just sends the timezone info to the date time model field objects.
691
+	 *                                Default is NULL
692
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
693
+	 * @return static (as in the concrete child class)
694
+	 * @throws EE_Error
695
+	 * @throws InvalidArgumentException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws InvalidInterfaceException
698
+	 */
699
+	public static function instance($timezone = null)
700
+	{
701
+		// check if instance of Espresso_model already exists
702
+		if (! static::$_instance instanceof static) {
703
+			// instantiate Espresso_model
704
+			static::$_instance = new static(
705
+				$timezone,
706
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
707
+			);
708
+		}
709
+		// we might have a timezone set, let set_timezone decide what to do with it
710
+		static::$_instance->set_timezone($timezone);
711
+		// Espresso_model object
712
+		return static::$_instance;
713
+	}
714
+
715
+
716
+
717
+	/**
718
+	 * resets the model and returns it
719
+	 *
720
+	 * @param null | string $timezone
721
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
722
+	 * all its properties reset; if it wasn't instantiated, returns null)
723
+	 * @throws EE_Error
724
+	 * @throws ReflectionException
725
+	 * @throws InvalidArgumentException
726
+	 * @throws InvalidDataTypeException
727
+	 * @throws InvalidInterfaceException
728
+	 */
729
+	public static function reset($timezone = null)
730
+	{
731
+		if (static::$_instance instanceof EEM_Base) {
732
+			// let's try to NOT swap out the current instance for a new one
733
+			// because if someone has a reference to it, we can't remove their reference
734
+			// so it's best to keep using the same reference, but change the original object
735
+			// reset all its properties to their original values as defined in the class
736
+			$r = new ReflectionClass(get_class(static::$_instance));
737
+			$static_properties = $r->getStaticProperties();
738
+			foreach ($r->getDefaultProperties() as $property => $value) {
739
+				// don't set instance to null like it was originally,
740
+				// but it's static anyways, and we're ignoring static properties (for now at least)
741
+				if (! isset($static_properties[ $property ])) {
742
+					static::$_instance->{$property} = $value;
743
+				}
744
+			}
745
+			// and then directly call its constructor again, like we would if we were creating a new one
746
+			static::$_instance->__construct(
747
+				$timezone,
748
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
749
+			);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * @return LoaderInterface
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 */
763
+	private static function getLoader()
764
+	{
765
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
766
+			EEM_Base::$loader = LoaderFactory::getLoader();
767
+		}
768
+		return EEM_Base::$loader;
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
775
+	 *
776
+	 * @param  boolean $translated return localized strings or JUST the array.
777
+	 * @return array
778
+	 * @throws EE_Error
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws InvalidInterfaceException
782
+	 */
783
+	public function status_array($translated = false)
784
+	{
785
+		if (! array_key_exists('Status', $this->_model_relations)) {
786
+			return array();
787
+		}
788
+		$model_name = $this->get_this_model_name();
789
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
790
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
791
+		$status_array = array();
792
+		foreach ($stati as $status) {
793
+			$status_array[ $status->ID() ] = $status->get('STS_code');
794
+		}
795
+		return $translated
796
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
797
+			: $status_array;
798
+	}
799
+
800
+
801
+
802
+	/**
803
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
804
+	 *
805
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
806
+	 *                             or if you have the development copy of EE you can view this at the path:
807
+	 *                             /docs/G--Model-System/model-query-params.md
808
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
809
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
810
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
811
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
812
+	 *                                        array( array(
813
+	 *                                        'OR'=>array(
814
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
815
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
816
+	 *                                        )
817
+	 *                                        ),
818
+	 *                                        'limit'=>10,
819
+	 *                                        'group_by'=>'TXN_ID'
820
+	 *                                        ));
821
+	 *                                        get all the answers to the question titled "shirt size" for event with id
822
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
823
+	 *                                        'Question.QST_display_text'=>'shirt size',
824
+	 *                                        'Registration.Event.EVT_ID'=>12
825
+	 *                                        ),
826
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
827
+	 *                                        ));
828
+	 * @throws EE_Error
829
+	 */
830
+	public function get_all($query_params = array())
831
+	{
832
+		if (isset($query_params['limit'])
833
+			&& ! isset($query_params['group_by'])
834
+		) {
835
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
836
+		}
837
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * Modifies the query parameters so we only get back model objects
844
+	 * that "belong" to the current user
845
+	 *
846
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
847
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
848
+	 */
849
+	public function alter_query_params_to_only_include_mine($query_params = array())
850
+	{
851
+		$wp_user_field_name = $this->wp_user_field_name();
852
+		if ($wp_user_field_name) {
853
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
854
+		}
855
+		return $query_params;
856
+	}
857
+
858
+
859
+
860
+	/**
861
+	 * Returns the name of the field's name that points to the WP_User table
862
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
863
+	 * foreign key to the WP_User table)
864
+	 *
865
+	 * @return string|boolean string on success, boolean false when there is no
866
+	 * foreign key to the WP_User table
867
+	 */
868
+	public function wp_user_field_name()
869
+	{
870
+		try {
871
+			if (! empty($this->_model_chain_to_wp_user)) {
872
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
873
+				$last_model_name = end($models_to_follow_to_wp_users);
874
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
875
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
876
+			} else {
877
+				$model_with_fk_to_wp_users = $this;
878
+				$model_chain_to_wp_user = '';
879
+			}
880
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
881
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
882
+		} catch (EE_Error $e) {
883
+			return false;
884
+		}
885
+	}
886
+
887
+
888
+
889
+	/**
890
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
891
+	 * (or transiently-related model) has a foreign key to the wp_users table;
892
+	 * useful for finding if model objects of this type are 'owned' by the current user.
893
+	 * This is an empty string when the foreign key is on this model and when it isn't,
894
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
895
+	 * (or transiently-related model)
896
+	 *
897
+	 * @return string
898
+	 */
899
+	public function model_chain_to_wp_user()
900
+	{
901
+		return $this->_model_chain_to_wp_user;
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
908
+	 * like how registrations don't have a foreign key to wp_users, but the
909
+	 * events they are for are), or is unrelated to wp users.
910
+	 * generally available
911
+	 *
912
+	 * @return boolean
913
+	 */
914
+	public function is_owned()
915
+	{
916
+		if ($this->model_chain_to_wp_user()) {
917
+			return true;
918
+		}
919
+		try {
920
+			$this->get_foreign_key_to('WP_User');
921
+			return true;
922
+		} catch (EE_Error $e) {
923
+			return false;
924
+		}
925
+	}
926
+
927
+
928
+	/**
929
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
930
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
931
+	 * the model)
932
+	 *
933
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
934
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
935
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
936
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
937
+	 *                                  override this and set the select to "*", or a specific column name, like
938
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
939
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
940
+	 *                                  the aliases used to refer to this selection, and values are to be
941
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
942
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
943
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
944
+	 * @throws EE_Error
945
+	 * @throws InvalidArgumentException
946
+	 */
947
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
948
+	{
949
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
950
+		;
951
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
952
+		$select_expressions = $columns_to_select === null
953
+			? $this->_construct_default_select_sql($model_query_info)
954
+			: '';
955
+		if ($this->_custom_selections instanceof CustomSelects) {
956
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
957
+			$select_expressions .= $select_expressions
958
+				? ', ' . $custom_expressions
959
+				: $custom_expressions;
960
+		}
961
+
962
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
963
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
964
+	}
965
+
966
+
967
+	/**
968
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
969
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
970
+	 * method of including extra select information.
971
+	 *
972
+	 * @param array             $query_params
973
+	 * @param null|array|string $columns_to_select
974
+	 * @return null|CustomSelects
975
+	 * @throws InvalidArgumentException
976
+	 */
977
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
978
+	{
979
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
980
+			return null;
981
+		}
982
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
983
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
984
+		return new CustomSelects($selects);
985
+	}
986
+
987
+
988
+
989
+	/**
990
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
991
+	 * but you can use the model query params to more easily
992
+	 * take care of joins, field preparation etc.
993
+	 *
994
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
995
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
996
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
997
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
998
+	 *                                  override this and set the select to "*", or a specific column name, like
999
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1000
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1001
+	 *                                  the aliases used to refer to this selection, and values are to be
1002
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1003
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1004
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1005
+	 * @throws EE_Error
1006
+	 */
1007
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1008
+	{
1009
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1010
+	}
1011
+
1012
+
1013
+
1014
+	/**
1015
+	 * For creating a custom select statement
1016
+	 *
1017
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1018
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1019
+	 *                                 SQL, and 1=>is the datatype
1020
+	 * @throws EE_Error
1021
+	 * @return string
1022
+	 */
1023
+	private function _construct_select_from_input($columns_to_select)
1024
+	{
1025
+		if (is_array($columns_to_select)) {
1026
+			$select_sql_array = array();
1027
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1028
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1029
+					throw new EE_Error(
1030
+						sprintf(
1031
+							__(
1032
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1033
+								'event_espresso'
1034
+							),
1035
+							$selection_and_datatype,
1036
+							$alias
1037
+						)
1038
+					);
1039
+				}
1040
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1041
+					throw new EE_Error(
1042
+						sprintf(
1043
+							esc_html__(
1044
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1045
+								'event_espresso'
1046
+							),
1047
+							$selection_and_datatype[1],
1048
+							$selection_and_datatype[0],
1049
+							$alias,
1050
+							implode(', ', $this->_valid_wpdb_data_types)
1051
+						)
1052
+					);
1053
+				}
1054
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1055
+			}
1056
+			$columns_to_select_string = implode(', ', $select_sql_array);
1057
+		} else {
1058
+			$columns_to_select_string = $columns_to_select;
1059
+		}
1060
+		return $columns_to_select_string;
1061
+	}
1062
+
1063
+
1064
+
1065
+	/**
1066
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1067
+	 *
1068
+	 * @return string
1069
+	 * @throws EE_Error
1070
+	 */
1071
+	public function primary_key_name()
1072
+	{
1073
+		return $this->get_primary_key_field()->get_name();
1074
+	}
1075
+
1076
+
1077
+
1078
+	/**
1079
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1080
+	 * If there is no primary key on this model, $id is treated as primary key string
1081
+	 *
1082
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1083
+	 * @return EE_Base_Class
1084
+	 */
1085
+	public function get_one_by_ID($id)
1086
+	{
1087
+		if ($this->get_from_entity_map($id)) {
1088
+			return $this->get_from_entity_map($id);
1089
+		}
1090
+		return $this->get_one(
1091
+			$this->alter_query_params_to_restrict_by_ID(
1092
+				$id,
1093
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1094
+			)
1095
+		);
1096
+	}
1097
+
1098
+
1099
+
1100
+	/**
1101
+	 * Alters query parameters to only get items with this ID are returned.
1102
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1103
+	 * or could just be a simple primary key ID
1104
+	 *
1105
+	 * @param int   $id
1106
+	 * @param array $query_params
1107
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1111
+	{
1112
+		if (! isset($query_params[0])) {
1113
+			$query_params[0] = array();
1114
+		}
1115
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1116
+		if ($conditions_from_id === null) {
1117
+			$query_params[0][ $this->primary_key_name() ] = $id;
1118
+		} else {
1119
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1120
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1121
+		}
1122
+		return $query_params;
1123
+	}
1124
+
1125
+
1126
+
1127
+	/**
1128
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1129
+	 * array. If no item is found, null is returned.
1130
+	 *
1131
+	 * @param array $query_params like EEM_Base's $query_params variable.
1132
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1133
+	 * @throws EE_Error
1134
+	 */
1135
+	public function get_one($query_params = array())
1136
+	{
1137
+		if (! is_array($query_params)) {
1138
+			EE_Error::doing_it_wrong(
1139
+				'EEM_Base::get_one',
1140
+				sprintf(
1141
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1142
+					gettype($query_params)
1143
+				),
1144
+				'4.6.0'
1145
+			);
1146
+			$query_params = array();
1147
+		}
1148
+		$query_params['limit'] = 1;
1149
+		$items = $this->get_all($query_params);
1150
+		if (empty($items)) {
1151
+			return null;
1152
+		}
1153
+		return array_shift($items);
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * Returns the next x number of items in sequence from the given value as
1160
+	 * found in the database matching the given query conditions.
1161
+	 *
1162
+	 * @param mixed $current_field_value    Value used for the reference point.
1163
+	 * @param null  $field_to_order_by      What field is used for the
1164
+	 *                                      reference point.
1165
+	 * @param int   $limit                  How many to return.
1166
+	 * @param array $query_params           Extra conditions on the query.
1167
+	 * @param null  $columns_to_select      If left null, then an array of
1168
+	 *                                      EE_Base_Class objects is returned,
1169
+	 *                                      otherwise you can indicate just the
1170
+	 *                                      columns you want returned.
1171
+	 * @return EE_Base_Class[]|array
1172
+	 * @throws EE_Error
1173
+	 */
1174
+	public function next_x(
1175
+		$current_field_value,
1176
+		$field_to_order_by = null,
1177
+		$limit = 1,
1178
+		$query_params = array(),
1179
+		$columns_to_select = null
1180
+	) {
1181
+		return $this->_get_consecutive(
1182
+			$current_field_value,
1183
+			'>',
1184
+			$field_to_order_by,
1185
+			$limit,
1186
+			$query_params,
1187
+			$columns_to_select
1188
+		);
1189
+	}
1190
+
1191
+
1192
+
1193
+	/**
1194
+	 * Returns the previous x number of items in sequence from the given value
1195
+	 * as found in the database matching the given query conditions.
1196
+	 *
1197
+	 * @param mixed $current_field_value    Value used for the reference point.
1198
+	 * @param null  $field_to_order_by      What field is used for the
1199
+	 *                                      reference point.
1200
+	 * @param int   $limit                  How many to return.
1201
+	 * @param array $query_params           Extra conditions on the query.
1202
+	 * @param null  $columns_to_select      If left null, then an array of
1203
+	 *                                      EE_Base_Class objects is returned,
1204
+	 *                                      otherwise you can indicate just the
1205
+	 *                                      columns you want returned.
1206
+	 * @return EE_Base_Class[]|array
1207
+	 * @throws EE_Error
1208
+	 */
1209
+	public function previous_x(
1210
+		$current_field_value,
1211
+		$field_to_order_by = null,
1212
+		$limit = 1,
1213
+		$query_params = array(),
1214
+		$columns_to_select = null
1215
+	) {
1216
+		return $this->_get_consecutive(
1217
+			$current_field_value,
1218
+			'<',
1219
+			$field_to_order_by,
1220
+			$limit,
1221
+			$query_params,
1222
+			$columns_to_select
1223
+		);
1224
+	}
1225
+
1226
+
1227
+
1228
+	/**
1229
+	 * Returns the next item in sequence from the given value as found in the
1230
+	 * database matching the given query conditions.
1231
+	 *
1232
+	 * @param mixed $current_field_value    Value used for the reference point.
1233
+	 * @param null  $field_to_order_by      What field is used for the
1234
+	 *                                      reference point.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1237
+	 *                                      object is returned, otherwise you
1238
+	 *                                      can indicate just the columns you
1239
+	 *                                      want and a single array indexed by
1240
+	 *                                      the columns will be returned.
1241
+	 * @return EE_Base_Class|null|array()
1242
+	 * @throws EE_Error
1243
+	 */
1244
+	public function next(
1245
+		$current_field_value,
1246
+		$field_to_order_by = null,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		$results = $this->_get_consecutive(
1251
+			$current_field_value,
1252
+			'>',
1253
+			$field_to_order_by,
1254
+			1,
1255
+			$query_params,
1256
+			$columns_to_select
1257
+		);
1258
+		return empty($results) ? null : reset($results);
1259
+	}
1260
+
1261
+
1262
+
1263
+	/**
1264
+	 * Returns the previous item in sequence from the given value as found in
1265
+	 * the database matching the given query conditions.
1266
+	 *
1267
+	 * @param mixed $current_field_value    Value used for the reference point.
1268
+	 * @param null  $field_to_order_by      What field is used for the
1269
+	 *                                      reference point.
1270
+	 * @param array $query_params           Extra conditions on the query.
1271
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1272
+	 *                                      object is returned, otherwise you
1273
+	 *                                      can indicate just the columns you
1274
+	 *                                      want and a single array indexed by
1275
+	 *                                      the columns will be returned.
1276
+	 * @return EE_Base_Class|null|array()
1277
+	 * @throws EE_Error
1278
+	 */
1279
+	public function previous(
1280
+		$current_field_value,
1281
+		$field_to_order_by = null,
1282
+		$query_params = array(),
1283
+		$columns_to_select = null
1284
+	) {
1285
+		$results = $this->_get_consecutive(
1286
+			$current_field_value,
1287
+			'<',
1288
+			$field_to_order_by,
1289
+			1,
1290
+			$query_params,
1291
+			$columns_to_select
1292
+		);
1293
+		return empty($results) ? null : reset($results);
1294
+	}
1295
+
1296
+
1297
+
1298
+	/**
1299
+	 * Returns the a consecutive number of items in sequence from the given
1300
+	 * value as found in the database matching the given query conditions.
1301
+	 *
1302
+	 * @param mixed  $current_field_value   Value used for the reference point.
1303
+	 * @param string $operand               What operand is used for the sequence.
1304
+	 * @param string $field_to_order_by     What field is used for the reference point.
1305
+	 * @param int    $limit                 How many to return.
1306
+	 * @param array  $query_params          Extra conditions on the query.
1307
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1308
+	 *                                      otherwise you can indicate just the columns you want returned.
1309
+	 * @return EE_Base_Class[]|array
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	protected function _get_consecutive(
1313
+		$current_field_value,
1314
+		$operand = '>',
1315
+		$field_to_order_by = null,
1316
+		$limit = 1,
1317
+		$query_params = array(),
1318
+		$columns_to_select = null
1319
+	) {
1320
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1321
+		if (empty($field_to_order_by)) {
1322
+			if ($this->has_primary_key_field()) {
1323
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1324
+			} else {
1325
+				if (WP_DEBUG) {
1326
+					throw new EE_Error(__(
1327
+						'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1328
+						'event_espresso'
1329
+					));
1330
+				}
1331
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1332
+				return array();
1333
+			}
1334
+		}
1335
+		if (! is_array($query_params)) {
1336
+			EE_Error::doing_it_wrong(
1337
+				'EEM_Base::_get_consecutive',
1338
+				sprintf(
1339
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1340
+					gettype($query_params)
1341
+				),
1342
+				'4.6.0'
1343
+			);
1344
+			$query_params = array();
1345
+		}
1346
+		// let's add the where query param for consecutive look up.
1347
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1348
+		$query_params['limit'] = $limit;
1349
+		// set direction
1350
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1351
+		$query_params['order_by'] = $operand === '>'
1352
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1353
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1354
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1355
+		if (empty($columns_to_select)) {
1356
+			return $this->get_all($query_params);
1357
+		}
1358
+		// getting just the fields
1359
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1360
+	}
1361
+
1362
+
1363
+
1364
+	/**
1365
+	 * This sets the _timezone property after model object has been instantiated.
1366
+	 *
1367
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1368
+	 */
1369
+	public function set_timezone($timezone)
1370
+	{
1371
+		if ($timezone !== null) {
1372
+			$this->_timezone = $timezone;
1373
+		}
1374
+		// note we need to loop through relations and set the timezone on those objects as well.
1375
+		foreach ($this->_model_relations as $relation) {
1376
+			$relation->set_timezone($timezone);
1377
+		}
1378
+		// and finally we do the same for any datetime fields
1379
+		foreach ($this->_fields as $field) {
1380
+			if ($field instanceof EE_Datetime_Field) {
1381
+				$field->set_timezone($timezone);
1382
+			}
1383
+		}
1384
+	}
1385
+
1386
+
1387
+
1388
+	/**
1389
+	 * This just returns whatever is set for the current timezone.
1390
+	 *
1391
+	 * @access public
1392
+	 * @return string
1393
+	 */
1394
+	public function get_timezone()
1395
+	{
1396
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1397
+		if (empty($this->_timezone)) {
1398
+			foreach ($this->_fields as $field) {
1399
+				if ($field instanceof EE_Datetime_Field) {
1400
+					$this->set_timezone($field->get_timezone());
1401
+					break;
1402
+				}
1403
+			}
1404
+		}
1405
+		// if timezone STILL empty then return the default timezone for the site.
1406
+		if (empty($this->_timezone)) {
1407
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1408
+		}
1409
+		return $this->_timezone;
1410
+	}
1411
+
1412
+
1413
+
1414
+	/**
1415
+	 * This returns the date formats set for the given field name and also ensures that
1416
+	 * $this->_timezone property is set correctly.
1417
+	 *
1418
+	 * @since 4.6.x
1419
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1420
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1421
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1422
+	 * @return array formats in an array with the date format first, and the time format last.
1423
+	 */
1424
+	public function get_formats_for($field_name, $pretty = false)
1425
+	{
1426
+		$field_settings = $this->field_settings_for($field_name);
1427
+		// if not a valid EE_Datetime_Field then throw error
1428
+		if (! $field_settings instanceof EE_Datetime_Field) {
1429
+			throw new EE_Error(sprintf(__(
1430
+				'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1431
+				'event_espresso'
1432
+			), $field_name));
1433
+		}
1434
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1435
+		// the field.
1436
+		$this->_timezone = $field_settings->get_timezone();
1437
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1438
+	}
1439
+
1440
+
1441
+
1442
+	/**
1443
+	 * This returns the current time in a format setup for a query on this model.
1444
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1445
+	 * it will return:
1446
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1447
+	 *  NOW
1448
+	 *  - or a unix timestamp (equivalent to time())
1449
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1450
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1451
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1452
+	 * @since 4.6.x
1453
+	 * @param string $field_name       The field the current time is needed for.
1454
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1455
+	 *                                 formatted string matching the set format for the field in the set timezone will
1456
+	 *                                 be returned.
1457
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1458
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1459
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1460
+	 *                                 exception is triggered.
1461
+	 */
1462
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1463
+	{
1464
+		$formats = $this->get_formats_for($field_name);
1465
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1466
+		if ($timestamp) {
1467
+			return $DateTime->format('U');
1468
+		}
1469
+		// not returning timestamp, so return formatted string in timezone.
1470
+		switch ($what) {
1471
+			case 'time':
1472
+				return $DateTime->format($formats[1]);
1473
+				break;
1474
+			case 'date':
1475
+				return $DateTime->format($formats[0]);
1476
+				break;
1477
+			default:
1478
+				return $DateTime->format(implode(' ', $formats));
1479
+				break;
1480
+		}
1481
+	}
1482
+
1483
+
1484
+
1485
+	/**
1486
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1487
+	 * for the model are.  Returns a DateTime object.
1488
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1489
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1490
+	 * ignored.
1491
+	 *
1492
+	 * @param string $field_name      The field being setup.
1493
+	 * @param string $timestring      The date time string being used.
1494
+	 * @param string $incoming_format The format for the time string.
1495
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1496
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1497
+	 *                                format is
1498
+	 *                                'U', this is ignored.
1499
+	 * @return DateTime
1500
+	 * @throws EE_Error
1501
+	 */
1502
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1503
+	{
1504
+		// just using this to ensure the timezone is set correctly internally
1505
+		$this->get_formats_for($field_name);
1506
+		// load EEH_DTT_Helper
1507
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1508
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1509
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1510
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1511
+	}
1512
+
1513
+
1514
+
1515
+	/**
1516
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1517
+	 *
1518
+	 * @return EE_Table_Base[]
1519
+	 */
1520
+	public function get_tables()
1521
+	{
1522
+		return $this->_tables;
1523
+	}
1524
+
1525
+
1526
+
1527
+	/**
1528
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1529
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1530
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1531
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1532
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1533
+	 * model object with EVT_ID = 1
1534
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1535
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1536
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1537
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1538
+	 * are not specified)
1539
+	 *
1540
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1541
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1542
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1543
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1544
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1545
+	 *                                         ID=34, we'd use this method as follows:
1546
+	 *                                         EEM_Transaction::instance()->update(
1547
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1548
+	 *                                         array(array('TXN_ID'=>34)));
1549
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1550
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1551
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1552
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1553
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1554
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1555
+	 *                                         TRUE, it is assumed that you've already called
1556
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1557
+	 *                                         malicious javascript. However, if
1558
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1559
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1560
+	 *                                         and every other field, before insertion. We provide this parameter
1561
+	 *                                         because model objects perform their prepare_for_set function on all
1562
+	 *                                         their values, and so don't need to be called again (and in many cases,
1563
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1564
+	 *                                         prepare_for_set method...)
1565
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1566
+	 *                                         in this model's entity map according to $fields_n_values that match
1567
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1568
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1569
+	 *                                         could get out-of-sync with the database
1570
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1571
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1572
+	 *                                         bad)
1573
+	 * @throws EE_Error
1574
+	 */
1575
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1576
+	{
1577
+		if (! is_array($query_params)) {
1578
+			EE_Error::doing_it_wrong(
1579
+				'EEM_Base::update',
1580
+				sprintf(
1581
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1582
+					gettype($query_params)
1583
+				),
1584
+				'4.6.0'
1585
+			);
1586
+			$query_params = array();
1587
+		}
1588
+		/**
1589
+		 * Action called before a model update call has been made.
1590
+		 *
1591
+		 * @param EEM_Base $model
1592
+		 * @param array    $fields_n_values the updated fields and their new values
1593
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1594
+		 */
1595
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1596
+		/**
1597
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1598
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1599
+		 *
1600
+		 * @param array    $fields_n_values fields and their new values
1601
+		 * @param EEM_Base $model           the model being queried
1602
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1603
+		 */
1604
+		$fields_n_values = (array) apply_filters(
1605
+			'FHEE__EEM_Base__update__fields_n_values',
1606
+			$fields_n_values,
1607
+			$this,
1608
+			$query_params
1609
+		);
1610
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1611
+		// to do that, for each table, verify that it's PK isn't null.
1612
+		$tables = $this->get_tables();
1613
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1614
+		// NOTE: we should make this code more efficient by NOT querying twice
1615
+		// before the real update, but that needs to first go through ALPHA testing
1616
+		// as it's dangerous. says Mike August 8 2014
1617
+		// we want to make sure the default_where strategy is ignored
1618
+		$this->_ignore_where_strategy = true;
1619
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1620
+		foreach ($wpdb_select_results as $wpdb_result) {
1621
+			// type cast stdClass as array
1622
+			$wpdb_result = (array) $wpdb_result;
1623
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1624
+			if ($this->has_primary_key_field()) {
1625
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1626
+			} else {
1627
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1628
+				$main_table_pk_value = null;
1629
+			}
1630
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1631
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1632
+			if (count($tables) > 1) {
1633
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1634
+				// in that table, and so we'll want to insert one
1635
+				foreach ($tables as $table_obj) {
1636
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1637
+					// if there is no private key for this table on the results, it means there's no entry
1638
+					// in this table, right? so insert a row in the current table, using any fields available
1639
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1640
+						   && $wpdb_result[ $this_table_pk_column ])
1641
+					) {
1642
+						$success = $this->_insert_into_specific_table(
1643
+							$table_obj,
1644
+							$fields_n_values,
1645
+							$main_table_pk_value
1646
+						);
1647
+						// if we died here, report the error
1648
+						if (! $success) {
1649
+							return false;
1650
+						}
1651
+					}
1652
+				}
1653
+			}
1654
+			//              //and now check that if we have cached any models by that ID on the model, that
1655
+			//              //they also get updated properly
1656
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1657
+			//              if( $model_object ){
1658
+			//                  foreach( $fields_n_values as $field => $value ){
1659
+			//                      $model_object->set($field, $value);
1660
+			// let's make sure default_where strategy is followed now
1661
+			$this->_ignore_where_strategy = false;
1662
+		}
1663
+		// if we want to keep model objects in sync, AND
1664
+		// if this wasn't called from a model object (to update itself)
1665
+		// then we want to make sure we keep all the existing
1666
+		// model objects in sync with the db
1667
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1668
+			if ($this->has_primary_key_field()) {
1669
+				$model_objs_affected_ids = $this->get_col($query_params);
1670
+			} else {
1671
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1672
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1673
+				$model_objs_affected_ids = array();
1674
+				foreach ($models_affected_key_columns as $row) {
1675
+					$combined_index_key = $this->get_index_primary_key_string($row);
1676
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1677
+				}
1678
+			}
1679
+			if (! $model_objs_affected_ids) {
1680
+				// wait wait wait- if nothing was affected let's stop here
1681
+				return 0;
1682
+			}
1683
+			foreach ($model_objs_affected_ids as $id) {
1684
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1685
+				if ($model_obj_in_entity_map) {
1686
+					foreach ($fields_n_values as $field => $new_value) {
1687
+						$model_obj_in_entity_map->set($field, $new_value);
1688
+					}
1689
+				}
1690
+			}
1691
+			// if there is a primary key on this model, we can now do a slight optimization
1692
+			if ($this->has_primary_key_field()) {
1693
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1694
+				$query_params = array(
1695
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1696
+					'limit'                    => count($model_objs_affected_ids),
1697
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1698
+				);
1699
+			}
1700
+		}
1701
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1702
+		$SQL = "UPDATE "
1703
+			   . $model_query_info->get_full_join_sql()
1704
+			   . " SET "
1705
+			   . $this->_construct_update_sql($fields_n_values)
1706
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1707
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1708
+		/**
1709
+		 * Action called after a model update call has been made.
1710
+		 *
1711
+		 * @param EEM_Base $model
1712
+		 * @param array    $fields_n_values the updated fields and their new values
1713
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1714
+		 * @param int      $rows_affected
1715
+		 */
1716
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1717
+		return $rows_affected;// how many supposedly got updated
1718
+	}
1719
+
1720
+
1721
+
1722
+	/**
1723
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1724
+	 * are teh values of the field specified (or by default the primary key field)
1725
+	 * that matched the query params. Note that you should pass the name of the
1726
+	 * model FIELD, not the database table's column name.
1727
+	 *
1728
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1729
+	 * @param string $field_to_select
1730
+	 * @return array just like $wpdb->get_col()
1731
+	 * @throws EE_Error
1732
+	 */
1733
+	public function get_col($query_params = array(), $field_to_select = null)
1734
+	{
1735
+		if ($field_to_select) {
1736
+			$field = $this->field_settings_for($field_to_select);
1737
+		} elseif ($this->has_primary_key_field()) {
1738
+			$field = $this->get_primary_key_field();
1739
+		} else {
1740
+			// no primary key, just grab the first column
1741
+			$field = reset($this->field_settings());
1742
+		}
1743
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1744
+		$select_expressions = $field->get_qualified_column();
1745
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1746
+		return $this->_do_wpdb_query('get_col', array($SQL));
1747
+	}
1748
+
1749
+
1750
+
1751
+	/**
1752
+	 * Returns a single column value for a single row from the database
1753
+	 *
1754
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1755
+	 * @param string $field_to_select @see EEM_Base::get_col()
1756
+	 * @return string
1757
+	 * @throws EE_Error
1758
+	 */
1759
+	public function get_var($query_params = array(), $field_to_select = null)
1760
+	{
1761
+		$query_params['limit'] = 1;
1762
+		$col = $this->get_col($query_params, $field_to_select);
1763
+		if (! empty($col)) {
1764
+			return reset($col);
1765
+		}
1766
+		return null;
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1773
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1774
+	 * injection, but currently no further filtering is done
1775
+	 *
1776
+	 * @global      $wpdb
1777
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1778
+	 *                               be updated to in the DB
1779
+	 * @return string of SQL
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function _construct_update_sql($fields_n_values)
1783
+	{
1784
+		/** @type WPDB $wpdb */
1785
+		global $wpdb;
1786
+		$cols_n_values = array();
1787
+		foreach ($fields_n_values as $field_name => $value) {
1788
+			$field_obj = $this->field_settings_for($field_name);
1789
+			// if the value is NULL, we want to assign the value to that.
1790
+			// wpdb->prepare doesn't really handle that properly
1791
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1792
+			$value_sql = $prepared_value === null ? 'NULL'
1793
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1794
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1795
+		}
1796
+		return implode(",", $cols_n_values);
1797
+	}
1798
+
1799
+
1800
+
1801
+	/**
1802
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1803
+	 * Performs a HARD delete, meaning the database row should always be removed,
1804
+	 * not just have a flag field on it switched
1805
+	 * Wrapper for EEM_Base::delete_permanently()
1806
+	 *
1807
+	 * @param mixed $id
1808
+	 * @param boolean $allow_blocking
1809
+	 * @return int the number of rows deleted
1810
+	 * @throws EE_Error
1811
+	 */
1812
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1813
+	{
1814
+		return $this->delete_permanently(
1815
+			array(
1816
+				array($this->get_primary_key_field()->get_name() => $id),
1817
+				'limit' => 1,
1818
+			),
1819
+			$allow_blocking
1820
+		);
1821
+	}
1822
+
1823
+
1824
+
1825
+	/**
1826
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
+	 * Wrapper for EEM_Base::delete()
1828
+	 *
1829
+	 * @param mixed $id
1830
+	 * @param boolean $allow_blocking
1831
+	 * @return int the number of rows deleted
1832
+	 * @throws EE_Error
1833
+	 */
1834
+	public function delete_by_ID($id, $allow_blocking = true)
1835
+	{
1836
+		return $this->delete(
1837
+			array(
1838
+				array($this->get_primary_key_field()->get_name() => $id),
1839
+				'limit' => 1,
1840
+			),
1841
+			$allow_blocking
1842
+		);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1849
+	 * meaning if the model has a field that indicates its been "trashed" or
1850
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1851
+	 *
1852
+	 * @see EEM_Base::delete_permanently
1853
+	 * @param array   $query_params
1854
+	 * @param boolean $allow_blocking
1855
+	 * @return int how many rows got deleted
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	public function delete($query_params, $allow_blocking = true)
1859
+	{
1860
+		return $this->delete_permanently($query_params, $allow_blocking);
1861
+	}
1862
+
1863
+
1864
+
1865
+	/**
1866
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1867
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1868
+	 * as archived, not actually deleted
1869
+	 *
1870
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1871
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1872
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1873
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1874
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1875
+	 *                                DB
1876
+	 * @return int how many rows got deleted
1877
+	 * @throws EE_Error
1878
+	 */
1879
+	public function delete_permanently($query_params, $allow_blocking = true)
1880
+	{
1881
+		/**
1882
+		 * Action called just before performing a real deletion query. You can use the
1883
+		 * model and its $query_params to find exactly which items will be deleted
1884
+		 *
1885
+		 * @param EEM_Base $model
1886
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1887
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1888
+		 *                                 to block (prevent) this deletion
1889
+		 */
1890
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1891
+		// some MySQL databases may be running safe mode, which may restrict
1892
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1893
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1894
+		// to delete them
1895
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1896
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1897
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1898
+			$columns_and_ids_for_deleting
1899
+		);
1900
+		/**
1901
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1902
+		 *
1903
+		 * @param EEM_Base $this  The model instance being acted on.
1904
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1905
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1906
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1907
+		 *                                                  derived from the incoming query parameters.
1908
+		 *                                                  @see details on the structure of this array in the phpdocs
1909
+		 *                                                  for the `_get_ids_for_delete_method`
1910
+		 *
1911
+		 */
1912
+		do_action(
1913
+			'AHEE__EEM_Base__delete__before_query',
1914
+			$this,
1915
+			$query_params,
1916
+			$allow_blocking,
1917
+			$columns_and_ids_for_deleting
1918
+		);
1919
+		if ($deletion_where_query_part) {
1920
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
+			$table_aliases = array_keys($this->_tables);
1922
+			$SQL = "DELETE "
1923
+				   . implode(", ", $table_aliases)
1924
+				   . " FROM "
1925
+				   . $model_query_info->get_full_join_sql()
1926
+				   . " WHERE "
1927
+				   . $deletion_where_query_part;
1928
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
+		} else {
1930
+			$rows_deleted = 0;
1931
+		}
1932
+
1933
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1934
+		// there was no error with the delete query.
1935
+		if ($this->has_primary_key_field()
1936
+			&& $rows_deleted !== false
1937
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1938
+		) {
1939
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1940
+			foreach ($ids_for_removal as $id) {
1941
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1942
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1943
+				}
1944
+			}
1945
+
1946
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1947
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1948
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1949
+			// (although it is possible).
1950
+			// Note this can be skipped by using the provided filter and returning false.
1951
+			if (apply_filters(
1952
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1953
+				! $this instanceof EEM_Extra_Meta,
1954
+				$this
1955
+			)) {
1956
+				EEM_Extra_Meta::instance()->delete_permanently(array(
1957
+					0 => array(
1958
+						'EXM_type' => $this->get_this_model_name(),
1959
+						'OBJ_ID'   => array(
1960
+							'IN',
1961
+							$ids_for_removal
1962
+						)
1963
+					)
1964
+				));
1965
+			}
1966
+		}
1967
+
1968
+		/**
1969
+		 * Action called just after performing a real deletion query. Although at this point the
1970
+		 * items should have been deleted
1971
+		 *
1972
+		 * @param EEM_Base $model
1973
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1974
+		 * @param int      $rows_deleted
1975
+		 */
1976
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1977
+		return $rows_deleted;// how many supposedly got deleted
1978
+	}
1979
+
1980
+
1981
+
1982
+	/**
1983
+	 * Checks all the relations that throw error messages when there are blocking related objects
1984
+	 * for related model objects. If there are any related model objects on those relations,
1985
+	 * adds an EE_Error, and return true
1986
+	 *
1987
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1988
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1989
+	 *                                                 should be ignored when determining whether there are related
1990
+	 *                                                 model objects which block this model object's deletion. Useful
1991
+	 *                                                 if you know A is related to B and are considering deleting A,
1992
+	 *                                                 but want to see if A has any other objects blocking its deletion
1993
+	 *                                                 before removing the relation between A and B
1994
+	 * @return boolean
1995
+	 * @throws EE_Error
1996
+	 */
1997
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1998
+	{
1999
+		// first, if $ignore_this_model_obj was supplied, get its model
2000
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2001
+			$ignored_model = $ignore_this_model_obj->get_model();
2002
+		} else {
2003
+			$ignored_model = null;
2004
+		}
2005
+		// now check all the relations of $this_model_obj_or_id and see if there
2006
+		// are any related model objects blocking it?
2007
+		$is_blocked = false;
2008
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2009
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2010
+				// if $ignore_this_model_obj was supplied, then for the query
2011
+				// on that model needs to be told to ignore $ignore_this_model_obj
2012
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2013
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2014
+						array(
2015
+							$ignored_model->get_primary_key_field()->get_name() => array(
2016
+								'!=',
2017
+								$ignore_this_model_obj->ID(),
2018
+							),
2019
+						),
2020
+					));
2021
+				} else {
2022
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2023
+				}
2024
+				if ($related_model_objects) {
2025
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2026
+					$is_blocked = true;
2027
+				}
2028
+			}
2029
+		}
2030
+		return $is_blocked;
2031
+	}
2032
+
2033
+
2034
+	/**
2035
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2036
+	 * @param array $row_results_for_deleting
2037
+	 * @param bool  $allow_blocking
2038
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2039
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2040
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2041
+	 *                 deleted. Example:
2042
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2043
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2044
+	 *                 where each element is a group of columns and values that get deleted. Example:
2045
+	 *                      array(
2046
+	 *                          0 => array(
2047
+	 *                              'Term_Relationship.object_id' => 1
2048
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2049
+	 *                          ),
2050
+	 *                          1 => array(
2051
+	 *                              'Term_Relationship.object_id' => 1
2052
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2053
+	 *                          )
2054
+	 *                      )
2055
+	 * @throws EE_Error
2056
+	 */
2057
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2058
+	{
2059
+		$ids_to_delete_indexed_by_column = array();
2060
+		if ($this->has_primary_key_field()) {
2061
+			$primary_table = $this->_get_main_table();
2062
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2063
+			$other_tables = $this->_get_other_tables();
2064
+			$ids_to_delete_indexed_by_column = $query = array();
2065
+			foreach ($row_results_for_deleting as $item_to_delete) {
2066
+				// before we mark this item for deletion,
2067
+				// make sure there's no related entities blocking its deletion (if we're checking)
2068
+				if ($allow_blocking
2069
+					&& $this->delete_is_blocked_by_related_models(
2070
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2071
+					)
2072
+				) {
2073
+					continue;
2074
+				}
2075
+				// primary table deletes
2076
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2077
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2078
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2079
+				}
2080
+			}
2081
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2082
+			$fields = $this->get_combined_primary_key_fields();
2083
+			foreach ($row_results_for_deleting as $item_to_delete) {
2084
+				$ids_to_delete_indexed_by_column_for_row = array();
2085
+				foreach ($fields as $cpk_field) {
2086
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2087
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2088
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2089
+					}
2090
+				}
2091
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2092
+			}
2093
+		} else {
2094
+			// so there's no primary key and no combined key...
2095
+			// sorry, can't help you
2096
+			throw new EE_Error(
2097
+				sprintf(
2098
+					__(
2099
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2100
+						"event_espresso"
2101
+					),
2102
+					get_class($this)
2103
+				)
2104
+			);
2105
+		}
2106
+		return $ids_to_delete_indexed_by_column;
2107
+	}
2108
+
2109
+
2110
+	/**
2111
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2112
+	 * the corresponding query_part for the query performing the delete.
2113
+	 *
2114
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2115
+	 * @return string
2116
+	 * @throws EE_Error
2117
+	 */
2118
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2119
+	{
2120
+		$query_part = '';
2121
+		if (empty($ids_to_delete_indexed_by_column)) {
2122
+			return $query_part;
2123
+		} elseif ($this->has_primary_key_field()) {
2124
+			$query = array();
2125
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2126
+				// make sure we have unique $ids
2127
+				$ids = array_unique($ids);
2128
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2129
+			}
2130
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2131
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2132
+			$ways_to_identify_a_row = array();
2133
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2134
+				$values_for_each_combined_primary_key_for_a_row = array();
2135
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2136
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2137
+				}
2138
+				$ways_to_identify_a_row[] = '('
2139
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2140
+											. ')';
2141
+			}
2142
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2143
+		}
2144
+		return $query_part;
2145
+	}
2146
+
2147
+
2148
+
2149
+	/**
2150
+	 * Gets the model field by the fully qualified name
2151
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2152
+	 * @return EE_Model_Field_Base
2153
+	 */
2154
+	public function get_field_by_column($qualified_column_name)
2155
+	{
2156
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2157
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2158
+				return $field_obj;
2159
+			}
2160
+		}
2161
+		throw new EE_Error(
2162
+			sprintf(
2163
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2164
+				$this->get_this_model_name(),
2165
+				$qualified_column_name
2166
+			)
2167
+		);
2168
+	}
2169
+
2170
+
2171
+
2172
+	/**
2173
+	 * Count all the rows that match criteria the model query params.
2174
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2175
+	 * column
2176
+	 *
2177
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2178
+	 * @param string $field_to_count field on model to count by (not column name)
2179
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2180
+	 *                               that by the setting $distinct to TRUE;
2181
+	 * @return int
2182
+	 * @throws EE_Error
2183
+	 */
2184
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2185
+	{
2186
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2187
+		if ($field_to_count) {
2188
+			$field_obj = $this->field_settings_for($field_to_count);
2189
+			$column_to_count = $field_obj->get_qualified_column();
2190
+		} elseif ($this->has_primary_key_field()) {
2191
+			$pk_field_obj = $this->get_primary_key_field();
2192
+			$column_to_count = $pk_field_obj->get_qualified_column();
2193
+		} else {
2194
+			// there's no primary key
2195
+			// if we're counting distinct items, and there's no primary key,
2196
+			// we need to list out the columns for distinction;
2197
+			// otherwise we can just use star
2198
+			if ($distinct) {
2199
+				$columns_to_use = array();
2200
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2201
+					$columns_to_use[] = $field_obj->get_qualified_column();
2202
+				}
2203
+				$column_to_count = implode(',', $columns_to_use);
2204
+			} else {
2205
+				$column_to_count = '*';
2206
+			}
2207
+		}
2208
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2209
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2210
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2211
+	}
2212
+
2213
+
2214
+
2215
+	/**
2216
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2217
+	 *
2218
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2219
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2220
+	 * @return float
2221
+	 * @throws EE_Error
2222
+	 */
2223
+	public function sum($query_params, $field_to_sum = null)
2224
+	{
2225
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2226
+		if ($field_to_sum) {
2227
+			$field_obj = $this->field_settings_for($field_to_sum);
2228
+		} else {
2229
+			$field_obj = $this->get_primary_key_field();
2230
+		}
2231
+		$column_to_count = $field_obj->get_qualified_column();
2232
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2233
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2234
+		$data_type = $field_obj->get_wpdb_data_type();
2235
+		if ($data_type === '%d' || $data_type === '%s') {
2236
+			return (float) $return_value;
2237
+		}
2238
+		// must be %f
2239
+		return (float) $return_value;
2240
+	}
2241
+
2242
+
2243
+
2244
+	/**
2245
+	 * Just calls the specified method on $wpdb with the given arguments
2246
+	 * Consolidates a little extra error handling code
2247
+	 *
2248
+	 * @param string $wpdb_method
2249
+	 * @param array  $arguments_to_provide
2250
+	 * @throws EE_Error
2251
+	 * @global wpdb  $wpdb
2252
+	 * @return mixed
2253
+	 */
2254
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2255
+	{
2256
+		// if we're in maintenance mode level 2, DON'T run any queries
2257
+		// because level 2 indicates the database needs updating and
2258
+		// is probably out of sync with the code
2259
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2260
+			throw new EE_Error(sprintf(__(
2261
+				"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2262
+				"event_espresso"
2263
+			)));
2264
+		}
2265
+		/** @type WPDB $wpdb */
2266
+		global $wpdb;
2267
+		if (! method_exists($wpdb, $wpdb_method)) {
2268
+			throw new EE_Error(sprintf(__(
2269
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2270
+				'event_espresso'
2271
+			), $wpdb_method));
2272
+		}
2273
+		if (WP_DEBUG) {
2274
+			$old_show_errors_value = $wpdb->show_errors;
2275
+			$wpdb->show_errors(false);
2276
+		}
2277
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2278
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2279
+		if (WP_DEBUG) {
2280
+			$wpdb->show_errors($old_show_errors_value);
2281
+			if (! empty($wpdb->last_error)) {
2282
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2283
+			}
2284
+			if ($result === false) {
2285
+				throw new EE_Error(sprintf(__(
2286
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2287
+					'event_espresso'
2288
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2289
+			}
2290
+		} elseif ($result === false) {
2291
+			EE_Error::add_error(
2292
+				sprintf(
2293
+					__(
2294
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2295
+						'event_espresso'
2296
+					),
2297
+					$wpdb_method,
2298
+					var_export($arguments_to_provide, true),
2299
+					$wpdb->last_error
2300
+				),
2301
+				__FILE__,
2302
+				__FUNCTION__,
2303
+				__LINE__
2304
+			);
2305
+		}
2306
+		return $result;
2307
+	}
2308
+
2309
+
2310
+
2311
+	/**
2312
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2313
+	 * and if there's an error tries to verify the DB is correct. Uses
2314
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2315
+	 * we should try to fix the EE core db, the addons, or just give up
2316
+	 *
2317
+	 * @param string $wpdb_method
2318
+	 * @param array  $arguments_to_provide
2319
+	 * @return mixed
2320
+	 */
2321
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2322
+	{
2323
+		/** @type WPDB $wpdb */
2324
+		global $wpdb;
2325
+		$wpdb->last_error = null;
2326
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2327
+		// was there an error running the query? but we don't care on new activations
2328
+		// (we're going to setup the DB anyway on new activations)
2329
+		if (($result === false || ! empty($wpdb->last_error))
2330
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2331
+		) {
2332
+			switch (EEM_Base::$_db_verification_level) {
2333
+				case EEM_Base::db_verified_none:
2334
+					// let's double-check core's DB
2335
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2336
+					break;
2337
+				case EEM_Base::db_verified_core:
2338
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2339
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2340
+					break;
2341
+				case EEM_Base::db_verified_addons:
2342
+					// ummmm... you in trouble
2343
+					return $result;
2344
+					break;
2345
+			}
2346
+			if (! empty($error_message)) {
2347
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2348
+				trigger_error($error_message);
2349
+			}
2350
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2351
+		}
2352
+		return $result;
2353
+	}
2354
+
2355
+
2356
+
2357
+	/**
2358
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2359
+	 * EEM_Base::$_db_verification_level
2360
+	 *
2361
+	 * @param string $wpdb_method
2362
+	 * @param array  $arguments_to_provide
2363
+	 * @return string
2364
+	 */
2365
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2366
+	{
2367
+		/** @type WPDB $wpdb */
2368
+		global $wpdb;
2369
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2370
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2371
+		$error_message = sprintf(
2372
+			__(
2373
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2374
+				'event_espresso'
2375
+			),
2376
+			$wpdb->last_error,
2377
+			$wpdb_method,
2378
+			wp_json_encode($arguments_to_provide)
2379
+		);
2380
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2381
+		return $error_message;
2382
+	}
2383
+
2384
+
2385
+
2386
+	/**
2387
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2388
+	 * EEM_Base::$_db_verification_level
2389
+	 *
2390
+	 * @param $wpdb_method
2391
+	 * @param $arguments_to_provide
2392
+	 * @return string
2393
+	 */
2394
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2395
+	{
2396
+		/** @type WPDB $wpdb */
2397
+		global $wpdb;
2398
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2399
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2400
+		$error_message = sprintf(
2401
+			__(
2402
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2403
+				'event_espresso'
2404
+			),
2405
+			$wpdb->last_error,
2406
+			$wpdb_method,
2407
+			wp_json_encode($arguments_to_provide)
2408
+		);
2409
+		EE_System::instance()->initialize_addons();
2410
+		return $error_message;
2411
+	}
2412
+
2413
+
2414
+
2415
+	/**
2416
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2417
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2418
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2419
+	 * ..."
2420
+	 *
2421
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2422
+	 * @return string
2423
+	 */
2424
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2425
+	{
2426
+		return " FROM " . $model_query_info->get_full_join_sql() .
2427
+			   $model_query_info->get_where_sql() .
2428
+			   $model_query_info->get_group_by_sql() .
2429
+			   $model_query_info->get_having_sql() .
2430
+			   $model_query_info->get_order_by_sql() .
2431
+			   $model_query_info->get_limit_sql();
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * Set to easily debug the next X queries ran from this model.
2438
+	 *
2439
+	 * @param int $count
2440
+	 */
2441
+	public function show_next_x_db_queries($count = 1)
2442
+	{
2443
+		$this->_show_next_x_db_queries = $count;
2444
+	}
2445
+
2446
+
2447
+
2448
+	/**
2449
+	 * @param $sql_query
2450
+	 */
2451
+	public function show_db_query_if_previously_requested($sql_query)
2452
+	{
2453
+		if ($this->_show_next_x_db_queries > 0) {
2454
+			echo $sql_query;
2455
+			$this->_show_next_x_db_queries--;
2456
+		}
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2463
+	 * There are the 3 cases:
2464
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2465
+	 * $otherModelObject has no ID, it is first saved.
2466
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2467
+	 * has no ID, it is first saved.
2468
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2469
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2470
+	 * join table
2471
+	 *
2472
+	 * @param        EE_Base_Class                     /int $thisModelObject
2473
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2474
+	 * @param string $relationName                     , key in EEM_Base::_relations
2475
+	 *                                                 an attendee to a group, you also want to specify which role they
2476
+	 *                                                 will have in that group. So you would use this parameter to
2477
+	 *                                                 specify array('role-column-name'=>'role-id')
2478
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2479
+	 *                                                 to for relation to methods that allow you to further specify
2480
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2481
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2482
+	 *                                                 because these will be inserted in any new rows created as well.
2483
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2484
+	 * @throws EE_Error
2485
+	 */
2486
+	public function add_relationship_to(
2487
+		$id_or_obj,
2488
+		$other_model_id_or_obj,
2489
+		$relationName,
2490
+		$extra_join_model_fields_n_values = array()
2491
+	) {
2492
+		$relation_obj = $this->related_settings_for($relationName);
2493
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2494
+	}
2495
+
2496
+
2497
+
2498
+	/**
2499
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2500
+	 * There are the 3 cases:
2501
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2502
+	 * error
2503
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2504
+	 * an error
2505
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2506
+	 *
2507
+	 * @param        EE_Base_Class /int $id_or_obj
2508
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2509
+	 * @param string $relationName key in EEM_Base::_relations
2510
+	 * @return boolean of success
2511
+	 * @throws EE_Error
2512
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2513
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2514
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2515
+	 *                             because these will be inserted in any new rows created as well.
2516
+	 */
2517
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2518
+	{
2519
+		$relation_obj = $this->related_settings_for($relationName);
2520
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2521
+	}
2522
+
2523
+
2524
+
2525
+	/**
2526
+	 * @param mixed           $id_or_obj
2527
+	 * @param string          $relationName
2528
+	 * @param array           $where_query_params
2529
+	 * @param EE_Base_Class[] objects to which relations were removed
2530
+	 * @return \EE_Base_Class[]
2531
+	 * @throws EE_Error
2532
+	 */
2533
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2534
+	{
2535
+		$relation_obj = $this->related_settings_for($relationName);
2536
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2537
+	}
2538
+
2539
+
2540
+
2541
+	/**
2542
+	 * Gets all the related items of the specified $model_name, using $query_params.
2543
+	 * Note: by default, we remove the "default query params"
2544
+	 * because we want to get even deleted items etc.
2545
+	 *
2546
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2547
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2548
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
+	 * @return EE_Base_Class[]
2550
+	 * @throws EE_Error
2551
+	 */
2552
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2553
+	{
2554
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2555
+		$relation_settings = $this->related_settings_for($model_name);
2556
+		return $relation_settings->get_all_related($model_obj, $query_params);
2557
+	}
2558
+
2559
+
2560
+
2561
+	/**
2562
+	 * Deletes all the model objects across the relation indicated by $model_name
2563
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2564
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2565
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2566
+	 *
2567
+	 * @param EE_Base_Class|int|string $id_or_obj
2568
+	 * @param string                   $model_name
2569
+	 * @param array                    $query_params
2570
+	 * @return int how many deleted
2571
+	 * @throws EE_Error
2572
+	 */
2573
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2574
+	{
2575
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2576
+		$relation_settings = $this->related_settings_for($model_name);
2577
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2578
+	}
2579
+
2580
+
2581
+
2582
+	/**
2583
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2584
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2585
+	 * the model objects can't be hard deleted because of blocking related model objects,
2586
+	 * just does a soft-delete on them instead.
2587
+	 *
2588
+	 * @param EE_Base_Class|int|string $id_or_obj
2589
+	 * @param string                   $model_name
2590
+	 * @param array                    $query_params
2591
+	 * @return int how many deleted
2592
+	 * @throws EE_Error
2593
+	 */
2594
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2595
+	{
2596
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2597
+		$relation_settings = $this->related_settings_for($model_name);
2598
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2599
+	}
2600
+
2601
+
2602
+
2603
+	/**
2604
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2605
+	 * unless otherwise specified in the $query_params
2606
+	 *
2607
+	 * @param        int             /EE_Base_Class $id_or_obj
2608
+	 * @param string $model_name     like 'Event', or 'Registration'
2609
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2610
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2611
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2612
+	 *                               that by the setting $distinct to TRUE;
2613
+	 * @return int
2614
+	 * @throws EE_Error
2615
+	 */
2616
+	public function count_related(
2617
+		$id_or_obj,
2618
+		$model_name,
2619
+		$query_params = array(),
2620
+		$field_to_count = null,
2621
+		$distinct = false
2622
+	) {
2623
+		$related_model = $this->get_related_model_obj($model_name);
2624
+		// we're just going to use the query params on the related model's normal get_all query,
2625
+		// except add a condition to say to match the current mod
2626
+		if (! isset($query_params['default_where_conditions'])) {
2627
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2628
+		}
2629
+		$this_model_name = $this->get_this_model_name();
2630
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2631
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2632
+		return $related_model->count($query_params, $field_to_count, $distinct);
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2639
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2640
+	 *
2641
+	 * @param        int           /EE_Base_Class $id_or_obj
2642
+	 * @param string $model_name   like 'Event', or 'Registration'
2643
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2644
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2645
+	 * @return float
2646
+	 * @throws EE_Error
2647
+	 */
2648
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2649
+	{
2650
+		$related_model = $this->get_related_model_obj($model_name);
2651
+		if (! is_array($query_params)) {
2652
+			EE_Error::doing_it_wrong(
2653
+				'EEM_Base::sum_related',
2654
+				sprintf(
2655
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2656
+					gettype($query_params)
2657
+				),
2658
+				'4.6.0'
2659
+			);
2660
+			$query_params = array();
2661
+		}
2662
+		// we're just going to use the query params on the related model's normal get_all query,
2663
+		// except add a condition to say to match the current mod
2664
+		if (! isset($query_params['default_where_conditions'])) {
2665
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2666
+		}
2667
+		$this_model_name = $this->get_this_model_name();
2668
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2669
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2670
+		return $related_model->sum($query_params, $field_to_sum);
2671
+	}
2672
+
2673
+
2674
+
2675
+	/**
2676
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2677
+	 * $modelObject
2678
+	 *
2679
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2680
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2681
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2682
+	 * @return EE_Base_Class
2683
+	 * @throws EE_Error
2684
+	 */
2685
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2686
+	{
2687
+		$query_params['limit'] = 1;
2688
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2689
+		if ($results) {
2690
+			return array_shift($results);
2691
+		}
2692
+		return null;
2693
+	}
2694
+
2695
+
2696
+
2697
+	/**
2698
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2699
+	 *
2700
+	 * @return string
2701
+	 */
2702
+	public function get_this_model_name()
2703
+	{
2704
+		return str_replace("EEM_", "", get_class($this));
2705
+	}
2706
+
2707
+
2708
+
2709
+	/**
2710
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2711
+	 *
2712
+	 * @return EE_Any_Foreign_Model_Name_Field
2713
+	 * @throws EE_Error
2714
+	 */
2715
+	public function get_field_containing_related_model_name()
2716
+	{
2717
+		foreach ($this->field_settings(true) as $field) {
2718
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2719
+				$field_with_model_name = $field;
2720
+			}
2721
+		}
2722
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2723
+			throw new EE_Error(sprintf(
2724
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2725
+				$this->get_this_model_name()
2726
+			));
2727
+		}
2728
+		return $field_with_model_name;
2729
+	}
2730
+
2731
+
2732
+
2733
+	/**
2734
+	 * Inserts a new entry into the database, for each table.
2735
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2736
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2737
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2738
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2739
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2740
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2741
+	 *
2742
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2743
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2744
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2745
+	 *                              of EEM_Base)
2746
+	 * @return int|string new primary key on main table that got inserted
2747
+	 * @throws EE_Error
2748
+	 */
2749
+	public function insert($field_n_values)
2750
+	{
2751
+		/**
2752
+		 * Filters the fields and their values before inserting an item using the models
2753
+		 *
2754
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2755
+		 * @param EEM_Base $model           the model used
2756
+		 */
2757
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2758
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2759
+			$main_table = $this->_get_main_table();
2760
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2761
+			if ($new_id !== false) {
2762
+				foreach ($this->_get_other_tables() as $other_table) {
2763
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2764
+				}
2765
+			}
2766
+			/**
2767
+			 * Done just after attempting to insert a new model object
2768
+			 *
2769
+			 * @param EEM_Base   $model           used
2770
+			 * @param array      $fields_n_values fields and their values
2771
+			 * @param int|string the              ID of the newly-inserted model object
2772
+			 */
2773
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2774
+			return $new_id;
2775
+		}
2776
+		return false;
2777
+	}
2778
+
2779
+
2780
+
2781
+	/**
2782
+	 * Checks that the result would satisfy the unique indexes on this model
2783
+	 *
2784
+	 * @param array  $field_n_values
2785
+	 * @param string $action
2786
+	 * @return boolean
2787
+	 * @throws EE_Error
2788
+	 */
2789
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2790
+	{
2791
+		foreach ($this->unique_indexes() as $index_name => $index) {
2792
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2793
+			if ($this->exists(array($uniqueness_where_params))) {
2794
+				EE_Error::add_error(
2795
+					sprintf(
2796
+						__(
2797
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2798
+							"event_espresso"
2799
+						),
2800
+						$action,
2801
+						$this->_get_class_name(),
2802
+						$index_name,
2803
+						implode(",", $index->field_names()),
2804
+						http_build_query($uniqueness_where_params)
2805
+					),
2806
+					__FILE__,
2807
+					__FUNCTION__,
2808
+					__LINE__
2809
+				);
2810
+				return false;
2811
+			}
2812
+		}
2813
+		return true;
2814
+	}
2815
+
2816
+
2817
+
2818
+	/**
2819
+	 * Checks the database for an item that conflicts (ie, if this item were
2820
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2821
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2822
+	 * can be either an EE_Base_Class or an array of fields n values
2823
+	 *
2824
+	 * @param EE_Base_Class|array $obj_or_fields_array
2825
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2826
+	 *                                                 when looking for conflicts
2827
+	 *                                                 (ie, if false, we ignore the model object's primary key
2828
+	 *                                                 when finding "conflicts". If true, it's also considered).
2829
+	 *                                                 Only works for INT primary key,
2830
+	 *                                                 STRING primary keys cannot be ignored
2831
+	 * @throws EE_Error
2832
+	 * @return EE_Base_Class|array
2833
+	 */
2834
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2835
+	{
2836
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2837
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2838
+		} elseif (is_array($obj_or_fields_array)) {
2839
+			$fields_n_values = $obj_or_fields_array;
2840
+		} else {
2841
+			throw new EE_Error(
2842
+				sprintf(
2843
+					__(
2844
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2845
+						"event_espresso"
2846
+					),
2847
+					get_class($this),
2848
+					$obj_or_fields_array
2849
+				)
2850
+			);
2851
+		}
2852
+		$query_params = array();
2853
+		if ($this->has_primary_key_field()
2854
+			&& ($include_primary_key
2855
+				|| $this->get_primary_key_field()
2856
+				   instanceof
2857
+				   EE_Primary_Key_String_Field)
2858
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2859
+		) {
2860
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2861
+		}
2862
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2863
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2864
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2865
+		}
2866
+		// if there is nothing to base this search on, then we shouldn't find anything
2867
+		if (empty($query_params)) {
2868
+			return array();
2869
+		}
2870
+		return $this->get_one($query_params);
2871
+	}
2872
+
2873
+
2874
+
2875
+	/**
2876
+	 * Like count, but is optimized and returns a boolean instead of an int
2877
+	 *
2878
+	 * @param array $query_params
2879
+	 * @return boolean
2880
+	 * @throws EE_Error
2881
+	 */
2882
+	public function exists($query_params)
2883
+	{
2884
+		$query_params['limit'] = 1;
2885
+		return $this->count($query_params) > 0;
2886
+	}
2887
+
2888
+
2889
+
2890
+	/**
2891
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2892
+	 *
2893
+	 * @param int|string $id
2894
+	 * @return boolean
2895
+	 * @throws EE_Error
2896
+	 */
2897
+	public function exists_by_ID($id)
2898
+	{
2899
+		return $this->exists(
2900
+			array(
2901
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2902
+				array(
2903
+					$this->primary_key_name() => $id,
2904
+				),
2905
+			)
2906
+		);
2907
+	}
2908
+
2909
+
2910
+
2911
+	/**
2912
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2913
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2914
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2915
+	 * on the main table)
2916
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2917
+	 * cases where we want to call it directly rather than via insert().
2918
+	 *
2919
+	 * @access   protected
2920
+	 * @param EE_Table_Base $table
2921
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2922
+	 *                                       float
2923
+	 * @param int           $new_id          for now we assume only int keys
2924
+	 * @throws EE_Error
2925
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2926
+	 * @return int ID of new row inserted, or FALSE on failure
2927
+	 */
2928
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2929
+	{
2930
+		global $wpdb;
2931
+		$insertion_col_n_values = array();
2932
+		$format_for_insertion = array();
2933
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2934
+		foreach ($fields_on_table as $field_name => $field_obj) {
2935
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2936
+			if ($field_obj->is_auto_increment()) {
2937
+				continue;
2938
+			}
2939
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2940
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2941
+			if ($prepared_value !== null) {
2942
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2943
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2944
+			}
2945
+		}
2946
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2947
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2948
+			// so add the fk to the main table as a column
2949
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2950
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2951
+		}
2952
+		// insert the new entry
2953
+		$result = $this->_do_wpdb_query(
2954
+			'insert',
2955
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
2956
+		);
2957
+		if ($result === false) {
2958
+			return false;
2959
+		}
2960
+		// ok, now what do we return for the ID of the newly-inserted thing?
2961
+		if ($this->has_primary_key_field()) {
2962
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2963
+				return $wpdb->insert_id;
2964
+			}
2965
+			// it's not an auto-increment primary key, so
2966
+			// it must have been supplied
2967
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
2968
+		}
2969
+		// we can't return a  primary key because there is none. instead return
2970
+		// a unique string indicating this model
2971
+		return $this->get_index_primary_key_string($fields_n_values);
2972
+	}
2973
+
2974
+
2975
+
2976
+	/**
2977
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2978
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2979
+	 * and there is no default, we pass it along. WPDB will take care of it)
2980
+	 *
2981
+	 * @param EE_Model_Field_Base $field_obj
2982
+	 * @param array               $fields_n_values
2983
+	 * @return mixed string|int|float depending on what the table column will be expecting
2984
+	 * @throws EE_Error
2985
+	 */
2986
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2987
+	{
2988
+		// if this field doesn't allow nullable, don't allow it
2989
+		if (! $field_obj->is_nullable()
2990
+			&& (
2991
+				! isset($fields_n_values[ $field_obj->get_name() ])
2992
+				|| $fields_n_values[ $field_obj->get_name() ] === null
2993
+			)
2994
+		) {
2995
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2996
+		}
2997
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
2998
+			? $fields_n_values[ $field_obj->get_name() ]
2999
+			: null;
3000
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3001
+	}
3002
+
3003
+
3004
+
3005
+	/**
3006
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3007
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3008
+	 * the field's prepare_for_set() method.
3009
+	 *
3010
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3011
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3012
+	 *                                   top of file)
3013
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3014
+	 *                                   $value is a custom selection
3015
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3016
+	 */
3017
+	private function _prepare_value_for_use_in_db($value, $field)
3018
+	{
3019
+		if ($field && $field instanceof EE_Model_Field_Base) {
3020
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3021
+			switch ($this->_values_already_prepared_by_model_object) {
3022
+				/** @noinspection PhpMissingBreakStatementInspection */
3023
+				case self::not_prepared_by_model_object:
3024
+					$value = $field->prepare_for_set($value);
3025
+				// purposefully left out "return"
3026
+				case self::prepared_by_model_object:
3027
+					/** @noinspection SuspiciousAssignmentsInspection */
3028
+					$value = $field->prepare_for_use_in_db($value);
3029
+				case self::prepared_for_use_in_db:
3030
+					// leave the value alone
3031
+			}
3032
+			return $value;
3033
+			// phpcs:enable
3034
+		}
3035
+		return $value;
3036
+	}
3037
+
3038
+
3039
+
3040
+	/**
3041
+	 * Returns the main table on this model
3042
+	 *
3043
+	 * @return EE_Primary_Table
3044
+	 * @throws EE_Error
3045
+	 */
3046
+	protected function _get_main_table()
3047
+	{
3048
+		foreach ($this->_tables as $table) {
3049
+			if ($table instanceof EE_Primary_Table) {
3050
+				return $table;
3051
+			}
3052
+		}
3053
+		throw new EE_Error(sprintf(__(
3054
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3055
+			'event_espresso'
3056
+		), get_class($this)));
3057
+	}
3058
+
3059
+
3060
+
3061
+	/**
3062
+	 * table
3063
+	 * returns EE_Primary_Table table name
3064
+	 *
3065
+	 * @return string
3066
+	 * @throws EE_Error
3067
+	 */
3068
+	public function table()
3069
+	{
3070
+		return $this->_get_main_table()->get_table_name();
3071
+	}
3072
+
3073
+
3074
+
3075
+	/**
3076
+	 * table
3077
+	 * returns first EE_Secondary_Table table name
3078
+	 *
3079
+	 * @return string
3080
+	 */
3081
+	public function second_table()
3082
+	{
3083
+		// grab second table from tables array
3084
+		$second_table = end($this->_tables);
3085
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3086
+	}
3087
+
3088
+
3089
+
3090
+	/**
3091
+	 * get_table_obj_by_alias
3092
+	 * returns table name given it's alias
3093
+	 *
3094
+	 * @param string $table_alias
3095
+	 * @return EE_Primary_Table | EE_Secondary_Table
3096
+	 */
3097
+	public function get_table_obj_by_alias($table_alias = '')
3098
+	{
3099
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3100
+	}
3101
+
3102
+
3103
+
3104
+	/**
3105
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3106
+	 *
3107
+	 * @return EE_Secondary_Table[]
3108
+	 */
3109
+	protected function _get_other_tables()
3110
+	{
3111
+		$other_tables = array();
3112
+		foreach ($this->_tables as $table_alias => $table) {
3113
+			if ($table instanceof EE_Secondary_Table) {
3114
+				$other_tables[ $table_alias ] = $table;
3115
+			}
3116
+		}
3117
+		return $other_tables;
3118
+	}
3119
+
3120
+
3121
+
3122
+	/**
3123
+	 * Finds all the fields that correspond to the given table
3124
+	 *
3125
+	 * @param string $table_alias , array key in EEM_Base::_tables
3126
+	 * @return EE_Model_Field_Base[]
3127
+	 */
3128
+	public function _get_fields_for_table($table_alias)
3129
+	{
3130
+		return $this->_fields[ $table_alias ];
3131
+	}
3132
+
3133
+
3134
+
3135
+	/**
3136
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3137
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3138
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3139
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3140
+	 * related Registration, Transaction, and Payment models.
3141
+	 *
3142
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3143
+	 * @return EE_Model_Query_Info_Carrier
3144
+	 * @throws EE_Error
3145
+	 */
3146
+	public function _extract_related_models_from_query($query_params)
3147
+	{
3148
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3149
+		if (array_key_exists(0, $query_params)) {
3150
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3151
+		}
3152
+		if (array_key_exists('group_by', $query_params)) {
3153
+			if (is_array($query_params['group_by'])) {
3154
+				$this->_extract_related_models_from_sub_params_array_values(
3155
+					$query_params['group_by'],
3156
+					$query_info_carrier,
3157
+					'group_by'
3158
+				);
3159
+			} elseif (! empty($query_params['group_by'])) {
3160
+				$this->_extract_related_model_info_from_query_param(
3161
+					$query_params['group_by'],
3162
+					$query_info_carrier,
3163
+					'group_by'
3164
+				);
3165
+			}
3166
+		}
3167
+		if (array_key_exists('having', $query_params)) {
3168
+			$this->_extract_related_models_from_sub_params_array_keys(
3169
+				$query_params[0],
3170
+				$query_info_carrier,
3171
+				'having'
3172
+			);
3173
+		}
3174
+		if (array_key_exists('order_by', $query_params)) {
3175
+			if (is_array($query_params['order_by'])) {
3176
+				$this->_extract_related_models_from_sub_params_array_keys(
3177
+					$query_params['order_by'],
3178
+					$query_info_carrier,
3179
+					'order_by'
3180
+				);
3181
+			} elseif (! empty($query_params['order_by'])) {
3182
+				$this->_extract_related_model_info_from_query_param(
3183
+					$query_params['order_by'],
3184
+					$query_info_carrier,
3185
+					'order_by'
3186
+				);
3187
+			}
3188
+		}
3189
+		if (array_key_exists('force_join', $query_params)) {
3190
+			$this->_extract_related_models_from_sub_params_array_values(
3191
+				$query_params['force_join'],
3192
+				$query_info_carrier,
3193
+				'force_join'
3194
+			);
3195
+		}
3196
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3197
+		return $query_info_carrier;
3198
+	}
3199
+
3200
+
3201
+
3202
+	/**
3203
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3204
+	 *
3205
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3206
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3207
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3208
+	 * @throws EE_Error
3209
+	 * @return \EE_Model_Query_Info_Carrier
3210
+	 */
3211
+	private function _extract_related_models_from_sub_params_array_keys(
3212
+		$sub_query_params,
3213
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3214
+		$query_param_type
3215
+	) {
3216
+		if (! empty($sub_query_params)) {
3217
+			$sub_query_params = (array) $sub_query_params;
3218
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3219
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3220
+				$this->_extract_related_model_info_from_query_param(
3221
+					$param,
3222
+					$model_query_info_carrier,
3223
+					$query_param_type
3224
+				);
3225
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3226
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3227
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3228
+				// of array('Registration.TXN_ID'=>23)
3229
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3230
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3231
+					if (! is_array($possibly_array_of_params)) {
3232
+						throw new EE_Error(sprintf(
3233
+							__(
3234
+								"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3235
+								"event_espresso"
3236
+							),
3237
+							$param,
3238
+							$possibly_array_of_params
3239
+						));
3240
+					}
3241
+					$this->_extract_related_models_from_sub_params_array_keys(
3242
+						$possibly_array_of_params,
3243
+						$model_query_info_carrier,
3244
+						$query_param_type
3245
+					);
3246
+				} elseif ($query_param_type === 0 // ie WHERE
3247
+						  && is_array($possibly_array_of_params)
3248
+						  && isset($possibly_array_of_params[2])
3249
+						  && $possibly_array_of_params[2] == true
3250
+				) {
3251
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3252
+					// indicating that $possible_array_of_params[1] is actually a field name,
3253
+					// from which we should extract query parameters!
3254
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3255
+						throw new EE_Error(sprintf(__(
3256
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3257
+							"event_espresso"
3258
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3259
+					}
3260
+					$this->_extract_related_model_info_from_query_param(
3261
+						$possibly_array_of_params[1],
3262
+						$model_query_info_carrier,
3263
+						$query_param_type
3264
+					);
3265
+				}
3266
+			}
3267
+		}
3268
+		return $model_query_info_carrier;
3269
+	}
3270
+
3271
+
3272
+
3273
+	/**
3274
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3275
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3276
+	 *
3277
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3278
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3279
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3280
+	 * @throws EE_Error
3281
+	 * @return \EE_Model_Query_Info_Carrier
3282
+	 */
3283
+	private function _extract_related_models_from_sub_params_array_values(
3284
+		$sub_query_params,
3285
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3286
+		$query_param_type
3287
+	) {
3288
+		if (! empty($sub_query_params)) {
3289
+			if (! is_array($sub_query_params)) {
3290
+				throw new EE_Error(sprintf(
3291
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3292
+					$sub_query_params
3293
+				));
3294
+			}
3295
+			foreach ($sub_query_params as $param) {
3296
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3297
+				$this->_extract_related_model_info_from_query_param(
3298
+					$param,
3299
+					$model_query_info_carrier,
3300
+					$query_param_type
3301
+				);
3302
+			}
3303
+		}
3304
+		return $model_query_info_carrier;
3305
+	}
3306
+
3307
+
3308
+
3309
+	/**
3310
+	 * Extract all the query parts from  model query params
3311
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3312
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3313
+	 * but use them in a different order. Eg, we need to know what models we are querying
3314
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3315
+	 * other models before we can finalize the where clause SQL.
3316
+	 *
3317
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3318
+	 * @throws EE_Error
3319
+	 * @return EE_Model_Query_Info_Carrier
3320
+	 */
3321
+	public function _create_model_query_info_carrier($query_params)
3322
+	{
3323
+		if (! is_array($query_params)) {
3324
+			EE_Error::doing_it_wrong(
3325
+				'EEM_Base::_create_model_query_info_carrier',
3326
+				sprintf(
3327
+					__(
3328
+						'$query_params should be an array, you passed a variable of type %s',
3329
+						'event_espresso'
3330
+					),
3331
+					gettype($query_params)
3332
+				),
3333
+				'4.6.0'
3334
+			);
3335
+			$query_params = array();
3336
+		}
3337
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3338
+		// first check if we should alter the query to account for caps or not
3339
+		// because the caps might require us to do extra joins
3340
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3341
+			$query_params[0] = $where_query_params = array_replace_recursive(
3342
+				$where_query_params,
3343
+				$this->caps_where_conditions(
3344
+					$query_params['caps']
3345
+				)
3346
+			);
3347
+		}
3348
+		$query_object = $this->_extract_related_models_from_query($query_params);
3349
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3350
+		foreach ($where_query_params as $key => $value) {
3351
+			if (is_int($key)) {
3352
+				throw new EE_Error(
3353
+					sprintf(
3354
+						__(
3355
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3356
+							"event_espresso"
3357
+						),
3358
+						$key,
3359
+						var_export($value, true),
3360
+						var_export($query_params, true),
3361
+						get_class($this)
3362
+					)
3363
+				);
3364
+			}
3365
+		}
3366
+		if (array_key_exists('default_where_conditions', $query_params)
3367
+			&& ! empty($query_params['default_where_conditions'])
3368
+		) {
3369
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3370
+		} else {
3371
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3372
+		}
3373
+		$where_query_params = array_merge(
3374
+			$this->_get_default_where_conditions_for_models_in_query(
3375
+				$query_object,
3376
+				$use_default_where_conditions,
3377
+				$where_query_params
3378
+			),
3379
+			$where_query_params
3380
+		);
3381
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3382
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3383
+		// So we need to setup a subquery and use that for the main join.
3384
+		// Note for now this only works on the primary table for the model.
3385
+		// So for instance, you could set the limit array like this:
3386
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3387
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3388
+			$query_object->set_main_model_join_sql(
3389
+				$this->_construct_limit_join_select(
3390
+					$query_params['on_join_limit'][0],
3391
+					$query_params['on_join_limit'][1]
3392
+				)
3393
+			);
3394
+		}
3395
+		// set limit
3396
+		if (array_key_exists('limit', $query_params)) {
3397
+			if (is_array($query_params['limit'])) {
3398
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3399
+					$e = sprintf(
3400
+						__(
3401
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3402
+							"event_espresso"
3403
+						),
3404
+						http_build_query($query_params['limit'])
3405
+					);
3406
+					throw new EE_Error($e . "|" . $e);
3407
+				}
3408
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3409
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3410
+			} elseif (! empty($query_params['limit'])) {
3411
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3412
+			}
3413
+		}
3414
+		// set order by
3415
+		if (array_key_exists('order_by', $query_params)) {
3416
+			if (is_array($query_params['order_by'])) {
3417
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3418
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3419
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3420
+				if (array_key_exists('order', $query_params)) {
3421
+					throw new EE_Error(
3422
+						sprintf(
3423
+							__(
3424
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3425
+								"event_espresso"
3426
+							),
3427
+							get_class($this),
3428
+							implode(", ", array_keys($query_params['order_by'])),
3429
+							implode(", ", $query_params['order_by']),
3430
+							$query_params['order']
3431
+						)
3432
+					);
3433
+				}
3434
+				$this->_extract_related_models_from_sub_params_array_keys(
3435
+					$query_params['order_by'],
3436
+					$query_object,
3437
+					'order_by'
3438
+				);
3439
+				// assume it's an array of fields to order by
3440
+				$order_array = array();
3441
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3442
+					$order = $this->_extract_order($order);
3443
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3444
+				}
3445
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3446
+			} elseif (! empty($query_params['order_by'])) {
3447
+				$this->_extract_related_model_info_from_query_param(
3448
+					$query_params['order_by'],
3449
+					$query_object,
3450
+					'order',
3451
+					$query_params['order_by']
3452
+				);
3453
+				$order = isset($query_params['order'])
3454
+					? $this->_extract_order($query_params['order'])
3455
+					: 'DESC';
3456
+				$query_object->set_order_by_sql(
3457
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3458
+				);
3459
+			}
3460
+		}
3461
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3462
+		if (! array_key_exists('order_by', $query_params)
3463
+			&& array_key_exists('order', $query_params)
3464
+			&& ! empty($query_params['order'])
3465
+		) {
3466
+			$pk_field = $this->get_primary_key_field();
3467
+			$order = $this->_extract_order($query_params['order']);
3468
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3469
+		}
3470
+		// set group by
3471
+		if (array_key_exists('group_by', $query_params)) {
3472
+			if (is_array($query_params['group_by'])) {
3473
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3474
+				$group_by_array = array();
3475
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3476
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3477
+				}
3478
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3479
+			} elseif (! empty($query_params['group_by'])) {
3480
+				$query_object->set_group_by_sql(
3481
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3482
+				);
3483
+			}
3484
+		}
3485
+		// set having
3486
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3487
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3488
+		}
3489
+		// now, just verify they didn't pass anything wack
3490
+		foreach ($query_params as $query_key => $query_value) {
3491
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3492
+				throw new EE_Error(
3493
+					sprintf(
3494
+						__(
3495
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3496
+							'event_espresso'
3497
+						),
3498
+						$query_key,
3499
+						get_class($this),
3500
+						//                      print_r( $this->_allowed_query_params, TRUE )
3501
+						implode(',', $this->_allowed_query_params)
3502
+					)
3503
+				);
3504
+			}
3505
+		}
3506
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3507
+		if (empty($main_model_join_sql)) {
3508
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3509
+		}
3510
+		return $query_object;
3511
+	}
3512
+
3513
+
3514
+
3515
+	/**
3516
+	 * Gets the where conditions that should be imposed on the query based on the
3517
+	 * context (eg reading frontend, backend, edit or delete).
3518
+	 *
3519
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3520
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3521
+	 * @throws EE_Error
3522
+	 */
3523
+	public function caps_where_conditions($context = self::caps_read)
3524
+	{
3525
+		EEM_Base::verify_is_valid_cap_context($context);
3526
+		$cap_where_conditions = array();
3527
+		$cap_restrictions = $this->caps_missing($context);
3528
+		/**
3529
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3530
+		 */
3531
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3532
+			$cap_where_conditions = array_replace_recursive(
3533
+				$cap_where_conditions,
3534
+				$restriction_if_no_cap->get_default_where_conditions()
3535
+			);
3536
+		}
3537
+		return apply_filters(
3538
+			'FHEE__EEM_Base__caps_where_conditions__return',
3539
+			$cap_where_conditions,
3540
+			$this,
3541
+			$context,
3542
+			$cap_restrictions
3543
+		);
3544
+	}
3545
+
3546
+
3547
+
3548
+	/**
3549
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3550
+	 * otherwise throws an exception
3551
+	 *
3552
+	 * @param string $should_be_order_string
3553
+	 * @return string either ASC, asc, DESC or desc
3554
+	 * @throws EE_Error
3555
+	 */
3556
+	private function _extract_order($should_be_order_string)
3557
+	{
3558
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3559
+			return $should_be_order_string;
3560
+		}
3561
+		throw new EE_Error(
3562
+			sprintf(
3563
+				__(
3564
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3565
+					"event_espresso"
3566
+				),
3567
+				get_class($this),
3568
+				$should_be_order_string
3569
+			)
3570
+		);
3571
+	}
3572
+
3573
+
3574
+
3575
+	/**
3576
+	 * Looks at all the models which are included in this query, and asks each
3577
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3578
+	 * so they can be merged
3579
+	 *
3580
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3581
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3582
+	 *                                                                  'none' means NO default where conditions will
3583
+	 *                                                                  be used AT ALL during this query.
3584
+	 *                                                                  'other_models_only' means default where
3585
+	 *                                                                  conditions from other models will be used, but
3586
+	 *                                                                  not for this primary model. 'all', the default,
3587
+	 *                                                                  means default where conditions will apply as
3588
+	 *                                                                  normal
3589
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3590
+	 * @throws EE_Error
3591
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3592
+	 */
3593
+	private function _get_default_where_conditions_for_models_in_query(
3594
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3595
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3596
+		$where_query_params = array()
3597
+	) {
3598
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3599
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3600
+			throw new EE_Error(sprintf(
3601
+				__(
3602
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3603
+					"event_espresso"
3604
+				),
3605
+				$use_default_where_conditions,
3606
+				implode(", ", $allowed_used_default_where_conditions_values)
3607
+			));
3608
+		}
3609
+		$universal_query_params = array();
3610
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3611
+			$universal_query_params = $this->_get_default_where_conditions();
3612
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3613
+			$universal_query_params = $this->_get_minimum_where_conditions();
3614
+		}
3615
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3616
+			$related_model = $this->get_related_model_obj($model_name);
3617
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3618
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3619
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3620
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3621
+			} else {
3622
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3623
+				continue;
3624
+			}
3625
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3626
+				$related_model_universal_where_params,
3627
+				$where_query_params,
3628
+				$related_model,
3629
+				$model_relation_path
3630
+			);
3631
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3632
+				$universal_query_params,
3633
+				$overrides
3634
+			);
3635
+		}
3636
+		return $universal_query_params;
3637
+	}
3638
+
3639
+
3640
+
3641
+	/**
3642
+	 * Determines whether or not we should use default where conditions for the model in question
3643
+	 * (this model, or other related models).
3644
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3645
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3646
+	 * We should use default where conditions on related models when they requested to use default where conditions
3647
+	 * on all models, or specifically just on other related models
3648
+	 * @param      $default_where_conditions_value
3649
+	 * @param bool $for_this_model false means this is for OTHER related models
3650
+	 * @return bool
3651
+	 */
3652
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3653
+	{
3654
+		return (
3655
+				   $for_this_model
3656
+				   && in_array(
3657
+					   $default_where_conditions_value,
3658
+					   array(
3659
+						   EEM_Base::default_where_conditions_all,
3660
+						   EEM_Base::default_where_conditions_this_only,
3661
+						   EEM_Base::default_where_conditions_minimum_others,
3662
+					   ),
3663
+					   true
3664
+				   )
3665
+			   )
3666
+			   || (
3667
+				   ! $for_this_model
3668
+				   && in_array(
3669
+					   $default_where_conditions_value,
3670
+					   array(
3671
+						   EEM_Base::default_where_conditions_all,
3672
+						   EEM_Base::default_where_conditions_others_only,
3673
+					   ),
3674
+					   true
3675
+				   )
3676
+			   );
3677
+	}
3678
+
3679
+	/**
3680
+	 * Determines whether or not we should use default minimum conditions for the model in question
3681
+	 * (this model, or other related models).
3682
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3683
+	 * where conditions.
3684
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3685
+	 * on this model or others
3686
+	 * @param      $default_where_conditions_value
3687
+	 * @param bool $for_this_model false means this is for OTHER related models
3688
+	 * @return bool
3689
+	 */
3690
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3691
+	{
3692
+		return (
3693
+				   $for_this_model
3694
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3695
+			   )
3696
+			   || (
3697
+				   ! $for_this_model
3698
+				   && in_array(
3699
+					   $default_where_conditions_value,
3700
+					   array(
3701
+						   EEM_Base::default_where_conditions_minimum_others,
3702
+						   EEM_Base::default_where_conditions_minimum_all,
3703
+					   ),
3704
+					   true
3705
+				   )
3706
+			   );
3707
+	}
3708
+
3709
+
3710
+	/**
3711
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3712
+	 * then we also add a special where condition which allows for that model's primary key
3713
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3714
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3715
+	 *
3716
+	 * @param array    $default_where_conditions
3717
+	 * @param array    $provided_where_conditions
3718
+	 * @param EEM_Base $model
3719
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3720
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3721
+	 * @throws EE_Error
3722
+	 */
3723
+	private function _override_defaults_or_make_null_friendly(
3724
+		$default_where_conditions,
3725
+		$provided_where_conditions,
3726
+		$model,
3727
+		$model_relation_path
3728
+	) {
3729
+		$null_friendly_where_conditions = array();
3730
+		$none_overridden = true;
3731
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3732
+		foreach ($default_where_conditions as $key => $val) {
3733
+			if (isset($provided_where_conditions[ $key ])) {
3734
+				$none_overridden = false;
3735
+			} else {
3736
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3737
+			}
3738
+		}
3739
+		if ($none_overridden && $default_where_conditions) {
3740
+			if ($model->has_primary_key_field()) {
3741
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3742
+																				. "."
3743
+																				. $model->primary_key_name() ] = array('IS NULL');
3744
+			}/*else{
3745 3745
                 //@todo NO PK, use other defaults
3746 3746
             }*/
3747
-        }
3748
-        return $null_friendly_where_conditions;
3749
-    }
3750
-
3751
-
3752
-
3753
-    /**
3754
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3755
-     * default where conditions on all get_all, update, and delete queries done by this model.
3756
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3757
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3758
-     *
3759
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3760
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3761
-     */
3762
-    private function _get_default_where_conditions($model_relation_path = null)
3763
-    {
3764
-        if ($this->_ignore_where_strategy) {
3765
-            return array();
3766
-        }
3767
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3768
-    }
3769
-
3770
-
3771
-
3772
-    /**
3773
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3774
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3775
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3776
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3777
-     * Similar to _get_default_where_conditions
3778
-     *
3779
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3780
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3781
-     */
3782
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3783
-    {
3784
-        if ($this->_ignore_where_strategy) {
3785
-            return array();
3786
-        }
3787
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3788
-    }
3789
-
3790
-
3791
-
3792
-    /**
3793
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3794
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3795
-     *
3796
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3797
-     * @return string
3798
-     * @throws EE_Error
3799
-     */
3800
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3801
-    {
3802
-        $selects = $this->_get_columns_to_select_for_this_model();
3803
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3804
-            $name_of_other_model_included) {
3805
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3806
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3807
-            foreach ($other_model_selects as $key => $value) {
3808
-                $selects[] = $value;
3809
-            }
3810
-        }
3811
-        return implode(", ", $selects);
3812
-    }
3813
-
3814
-
3815
-
3816
-    /**
3817
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3818
-     * So that's going to be the columns for all the fields on the model
3819
-     *
3820
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3821
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3822
-     */
3823
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3824
-    {
3825
-        $fields = $this->field_settings();
3826
-        $selects = array();
3827
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3828
-            $model_relation_chain,
3829
-            $this->get_this_model_name()
3830
-        );
3831
-        foreach ($fields as $field_obj) {
3832
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3833
-                         . $field_obj->get_table_alias()
3834
-                         . "."
3835
-                         . $field_obj->get_table_column()
3836
-                         . " AS '"
3837
-                         . $table_alias_with_model_relation_chain_prefix
3838
-                         . $field_obj->get_table_alias()
3839
-                         . "."
3840
-                         . $field_obj->get_table_column()
3841
-                         . "'";
3842
-        }
3843
-        // make sure we are also getting the PKs of each table
3844
-        $tables = $this->get_tables();
3845
-        if (count($tables) > 1) {
3846
-            foreach ($tables as $table_obj) {
3847
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3848
-                                       . $table_obj->get_fully_qualified_pk_column();
3849
-                if (! in_array($qualified_pk_column, $selects)) {
3850
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3851
-                }
3852
-            }
3853
-        }
3854
-        return $selects;
3855
-    }
3856
-
3857
-
3858
-
3859
-    /**
3860
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3861
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3862
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3863
-     * SQL for joining, and the data types
3864
-     *
3865
-     * @param null|string                 $original_query_param
3866
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3867
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3868
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3869
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3870
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3871
-     *                                                          or 'Registration's
3872
-     * @param string                      $original_query_param what it originally was (eg
3873
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3874
-     *                                                          matches $query_param
3875
-     * @throws EE_Error
3876
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3877
-     */
3878
-    private function _extract_related_model_info_from_query_param(
3879
-        $query_param,
3880
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3881
-        $query_param_type,
3882
-        $original_query_param = null
3883
-    ) {
3884
-        if ($original_query_param === null) {
3885
-            $original_query_param = $query_param;
3886
-        }
3887
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3888
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3889
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3890
-        $allow_fields = in_array(
3891
-            $query_param_type,
3892
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3893
-            true
3894
-        );
3895
-        // check to see if we have a field on this model
3896
-        $this_model_fields = $this->field_settings(true);
3897
-        if (array_key_exists($query_param, $this_model_fields)) {
3898
-            if ($allow_fields) {
3899
-                return;
3900
-            }
3901
-            throw new EE_Error(
3902
-                sprintf(
3903
-                    __(
3904
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3905
-                        "event_espresso"
3906
-                    ),
3907
-                    $query_param,
3908
-                    get_class($this),
3909
-                    $query_param_type,
3910
-                    $original_query_param
3911
-                )
3912
-            );
3913
-        }
3914
-        // check if this is a special logic query param
3915
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3916
-            if ($allow_logic_query_params) {
3917
-                return;
3918
-            }
3919
-            throw new EE_Error(
3920
-                sprintf(
3921
-                    __(
3922
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3923
-                        'event_espresso'
3924
-                    ),
3925
-                    implode('", "', $this->_logic_query_param_keys),
3926
-                    $query_param,
3927
-                    get_class($this),
3928
-                    '<br />',
3929
-                    "\t"
3930
-                    . ' $passed_in_query_info = <pre>'
3931
-                    . print_r($passed_in_query_info, true)
3932
-                    . '</pre>'
3933
-                    . "\n\t"
3934
-                    . ' $query_param_type = '
3935
-                    . $query_param_type
3936
-                    . "\n\t"
3937
-                    . ' $original_query_param = '
3938
-                    . $original_query_param
3939
-                )
3940
-            );
3941
-        }
3942
-        // check if it's a custom selection
3943
-        if ($this->_custom_selections instanceof CustomSelects
3944
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3945
-        ) {
3946
-            return;
3947
-        }
3948
-        // check if has a model name at the beginning
3949
-        // and
3950
-        // check if it's a field on a related model
3951
-        if ($this->extractJoinModelFromQueryParams(
3952
-            $passed_in_query_info,
3953
-            $query_param,
3954
-            $original_query_param,
3955
-            $query_param_type
3956
-        )) {
3957
-            return;
3958
-        }
3959
-
3960
-        // ok so $query_param didn't start with a model name
3961
-        // and we previously confirmed it wasn't a logic query param or field on the current model
3962
-        // it's wack, that's what it is
3963
-        throw new EE_Error(
3964
-            sprintf(
3965
-                esc_html__(
3966
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3967
-                    "event_espresso"
3968
-                ),
3969
-                $query_param,
3970
-                get_class($this),
3971
-                $query_param_type,
3972
-                $original_query_param
3973
-            )
3974
-        );
3975
-    }
3976
-
3977
-
3978
-    /**
3979
-     * Extracts any possible join model information from the provided possible_join_string.
3980
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
3981
-     * parts that should be added to the query.
3982
-     *
3983
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3984
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
3985
-     * @param null|string                 $original_query_param
3986
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
3987
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
3988
-     * @return bool  returns true if a join was added and false if not.
3989
-     * @throws EE_Error
3990
-     */
3991
-    private function extractJoinModelFromQueryParams(
3992
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3993
-        $possible_join_string,
3994
-        $original_query_param,
3995
-        $query_parameter_type
3996
-    ) {
3997
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3998
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
3999
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4000
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4001
-                if ($possible_join_string === '') {
4002
-                    // nothing left to $query_param
4003
-                    // we should actually end in a field name, not a model like this!
4004
-                    throw new EE_Error(
4005
-                        sprintf(
4006
-                            esc_html__(
4007
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4008
-                                "event_espresso"
4009
-                            ),
4010
-                            $possible_join_string,
4011
-                            $query_parameter_type,
4012
-                            get_class($this),
4013
-                            $valid_related_model_name
4014
-                        )
4015
-                    );
4016
-                }
4017
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4018
-                $related_model_obj->_extract_related_model_info_from_query_param(
4019
-                    $possible_join_string,
4020
-                    $query_info_carrier,
4021
-                    $query_parameter_type,
4022
-                    $original_query_param
4023
-                );
4024
-                return true;
4025
-            }
4026
-            if ($possible_join_string === $valid_related_model_name) {
4027
-                $this->_add_join_to_model(
4028
-                    $valid_related_model_name,
4029
-                    $query_info_carrier,
4030
-                    $original_query_param
4031
-                );
4032
-                return true;
4033
-            }
4034
-        }
4035
-        return false;
4036
-    }
4037
-
4038
-
4039
-    /**
4040
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4041
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4042
-     * @throws EE_Error
4043
-     */
4044
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4045
-    {
4046
-        if ($this->_custom_selections instanceof CustomSelects
4047
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4048
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4049
-            )
4050
-        ) {
4051
-            $original_selects = $this->_custom_selections->originalSelects();
4052
-            foreach ($original_selects as $alias => $select_configuration) {
4053
-                $this->extractJoinModelFromQueryParams(
4054
-                    $query_info_carrier,
4055
-                    $select_configuration[0],
4056
-                    $select_configuration[0],
4057
-                    'custom_selects'
4058
-                );
4059
-            }
4060
-        }
4061
-    }
4062
-
4063
-
4064
-
4065
-    /**
4066
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4067
-     * and store it on $passed_in_query_info
4068
-     *
4069
-     * @param string                      $model_name
4070
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4071
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4072
-     *                                                          model and $model_name. Eg, if we are querying Event,
4073
-     *                                                          and are adding a join to 'Payment' with the original
4074
-     *                                                          query param key
4075
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4076
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4077
-     *                                                          Payment wants to add default query params so that it
4078
-     *                                                          will know what models to prepend onto its default query
4079
-     *                                                          params or in case it wants to rename tables (in case
4080
-     *                                                          there are multiple joins to the same table)
4081
-     * @return void
4082
-     * @throws EE_Error
4083
-     */
4084
-    private function _add_join_to_model(
4085
-        $model_name,
4086
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4087
-        $original_query_param
4088
-    ) {
4089
-        $relation_obj = $this->related_settings_for($model_name);
4090
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4091
-        // check if the relation is HABTM, because then we're essentially doing two joins
4092
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4093
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4094
-            $join_model_obj = $relation_obj->get_join_model();
4095
-            // replace the model specified with the join model for this relation chain, whi
4096
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4097
-                $model_name,
4098
-                $join_model_obj->get_this_model_name(),
4099
-                $model_relation_chain
4100
-            );
4101
-            $passed_in_query_info->merge(
4102
-                new EE_Model_Query_Info_Carrier(
4103
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4104
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4105
-                )
4106
-            );
4107
-        }
4108
-        // now just join to the other table pointed to by the relation object, and add its data types
4109
-        $passed_in_query_info->merge(
4110
-            new EE_Model_Query_Info_Carrier(
4111
-                array($model_relation_chain => $model_name),
4112
-                $relation_obj->get_join_statement($model_relation_chain)
4113
-            )
4114
-        );
4115
-    }
4116
-
4117
-
4118
-
4119
-    /**
4120
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4121
-     *
4122
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4123
-     * @return string of SQL
4124
-     * @throws EE_Error
4125
-     */
4126
-    private function _construct_where_clause($where_params)
4127
-    {
4128
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4129
-        if ($SQL) {
4130
-            return " WHERE " . $SQL;
4131
-        }
4132
-        return '';
4133
-    }
4134
-
4135
-
4136
-
4137
-    /**
4138
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4139
-     * and should be passed HAVING parameters, not WHERE parameters
4140
-     *
4141
-     * @param array $having_params
4142
-     * @return string
4143
-     * @throws EE_Error
4144
-     */
4145
-    private function _construct_having_clause($having_params)
4146
-    {
4147
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4148
-        if ($SQL) {
4149
-            return " HAVING " . $SQL;
4150
-        }
4151
-        return '';
4152
-    }
4153
-
4154
-
4155
-    /**
4156
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4157
-     * Event_Meta.meta_value = 'foo'))"
4158
-     *
4159
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4160
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4161
-     * @throws EE_Error
4162
-     * @return string of SQL
4163
-     */
4164
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4165
-    {
4166
-        $where_clauses = array();
4167
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4168
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4169
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4170
-                switch ($query_param) {
4171
-                    case 'not':
4172
-                    case 'NOT':
4173
-                        $where_clauses[] = "! ("
4174
-                                           . $this->_construct_condition_clause_recursive(
4175
-                                               $op_and_value_or_sub_condition,
4176
-                                               $glue
4177
-                                           )
4178
-                                           . ")";
4179
-                        break;
4180
-                    case 'and':
4181
-                    case 'AND':
4182
-                        $where_clauses[] = " ("
4183
-                                           . $this->_construct_condition_clause_recursive(
4184
-                                               $op_and_value_or_sub_condition,
4185
-                                               ' AND '
4186
-                                           )
4187
-                                           . ")";
4188
-                        break;
4189
-                    case 'or':
4190
-                    case 'OR':
4191
-                        $where_clauses[] = " ("
4192
-                                           . $this->_construct_condition_clause_recursive(
4193
-                                               $op_and_value_or_sub_condition,
4194
-                                               ' OR '
4195
-                                           )
4196
-                                           . ")";
4197
-                        break;
4198
-                }
4199
-            } else {
4200
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4201
-                // if it's not a normal field, maybe it's a custom selection?
4202
-                if (! $field_obj) {
4203
-                    if ($this->_custom_selections instanceof CustomSelects) {
4204
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4205
-                    } else {
4206
-                        throw new EE_Error(sprintf(__(
4207
-                            "%s is neither a valid model field name, nor a custom selection",
4208
-                            "event_espresso"
4209
-                        ), $query_param));
4210
-                    }
4211
-                }
4212
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4213
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4214
-            }
4215
-        }
4216
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4217
-    }
4218
-
4219
-
4220
-
4221
-    /**
4222
-     * Takes the input parameter and extract the table name (alias) and column name
4223
-     *
4224
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4225
-     * @throws EE_Error
4226
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4227
-     */
4228
-    private function _deduce_column_name_from_query_param($query_param)
4229
-    {
4230
-        $field = $this->_deduce_field_from_query_param($query_param);
4231
-        if ($field) {
4232
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4233
-                $field->get_model_name(),
4234
-                $query_param
4235
-            );
4236
-            return $table_alias_prefix . $field->get_qualified_column();
4237
-        }
4238
-        if ($this->_custom_selections instanceof CustomSelects
4239
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4240
-        ) {
4241
-            // maybe it's custom selection item?
4242
-            // if so, just use it as the "column name"
4243
-            return $query_param;
4244
-        }
4245
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4246
-            ? implode(',', $this->_custom_selections->columnAliases())
4247
-            : '';
4248
-        throw new EE_Error(
4249
-            sprintf(
4250
-                __(
4251
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4252
-                    "event_espresso"
4253
-                ),
4254
-                $query_param,
4255
-                $custom_select_aliases
4256
-            )
4257
-        );
4258
-    }
4259
-
4260
-
4261
-
4262
-    /**
4263
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4264
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4265
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4266
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4267
-     *
4268
-     * @param string $condition_query_param_key
4269
-     * @return string
4270
-     */
4271
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4272
-    {
4273
-        $pos_of_star = strpos($condition_query_param_key, '*');
4274
-        if ($pos_of_star === false) {
4275
-            return $condition_query_param_key;
4276
-        }
4277
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4278
-        return $condition_query_param_sans_star;
4279
-    }
4280
-
4281
-
4282
-
4283
-    /**
4284
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4285
-     *
4286
-     * @param                            mixed      array | string    $op_and_value
4287
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4288
-     * @throws EE_Error
4289
-     * @return string
4290
-     */
4291
-    private function _construct_op_and_value($op_and_value, $field_obj)
4292
-    {
4293
-        if (is_array($op_and_value)) {
4294
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4295
-            if (! $operator) {
4296
-                $php_array_like_string = array();
4297
-                foreach ($op_and_value as $key => $value) {
4298
-                    $php_array_like_string[] = "$key=>$value";
4299
-                }
4300
-                throw new EE_Error(
4301
-                    sprintf(
4302
-                        __(
4303
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4304
-                            "event_espresso"
4305
-                        ),
4306
-                        implode(",", $php_array_like_string)
4307
-                    )
4308
-                );
4309
-            }
4310
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4311
-        } else {
4312
-            $operator = '=';
4313
-            $value = $op_and_value;
4314
-        }
4315
-        // check to see if the value is actually another field
4316
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4317
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4318
-        }
4319
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4320
-            // in this case, the value should be an array, or at least a comma-separated list
4321
-            // it will need to handle a little differently
4322
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4323
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4324
-            return $operator . SP . $cleaned_value;
4325
-        }
4326
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4327
-            // the value should be an array with count of two.
4328
-            if (count($value) !== 2) {
4329
-                throw new EE_Error(
4330
-                    sprintf(
4331
-                        __(
4332
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4333
-                            'event_espresso'
4334
-                        ),
4335
-                        "BETWEEN"
4336
-                    )
4337
-                );
4338
-            }
4339
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4340
-            return $operator . SP . $cleaned_value;
4341
-        }
4342
-        if (in_array($operator, $this->valid_null_style_operators())) {
4343
-            if ($value !== null) {
4344
-                throw new EE_Error(
4345
-                    sprintf(
4346
-                        __(
4347
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4348
-                            "event_espresso"
4349
-                        ),
4350
-                        $value,
4351
-                        $operator
4352
-                    )
4353
-                );
4354
-            }
4355
-            return $operator;
4356
-        }
4357
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4358
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4359
-            // remove other junk. So just treat it as a string.
4360
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4361
-        }
4362
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4363
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4364
-        }
4365
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4366
-            throw new EE_Error(
4367
-                sprintf(
4368
-                    __(
4369
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4370
-                        'event_espresso'
4371
-                    ),
4372
-                    $operator,
4373
-                    $operator
4374
-                )
4375
-            );
4376
-        }
4377
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4378
-            throw new EE_Error(
4379
-                sprintf(
4380
-                    __(
4381
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4382
-                        'event_espresso'
4383
-                    ),
4384
-                    $operator,
4385
-                    $operator
4386
-                )
4387
-            );
4388
-        }
4389
-        throw new EE_Error(
4390
-            sprintf(
4391
-                __(
4392
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4393
-                    "event_espresso"
4394
-                ),
4395
-                http_build_query($op_and_value)
4396
-            )
4397
-        );
4398
-    }
4399
-
4400
-
4401
-
4402
-    /**
4403
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4404
-     *
4405
-     * @param array                      $values
4406
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4407
-     *                                              '%s'
4408
-     * @return string
4409
-     * @throws EE_Error
4410
-     */
4411
-    public function _construct_between_value($values, $field_obj)
4412
-    {
4413
-        $cleaned_values = array();
4414
-        foreach ($values as $value) {
4415
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4416
-        }
4417
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4418
-    }
4419
-
4420
-
4421
-
4422
-    /**
4423
-     * Takes an array or a comma-separated list of $values and cleans them
4424
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4425
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4426
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4427
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4428
-     *
4429
-     * @param mixed                      $values    array or comma-separated string
4430
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4431
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4432
-     * @throws EE_Error
4433
-     */
4434
-    public function _construct_in_value($values, $field_obj)
4435
-    {
4436
-        // check if the value is a CSV list
4437
-        if (is_string($values)) {
4438
-            // in which case, turn it into an array
4439
-            $values = explode(",", $values);
4440
-        }
4441
-        $cleaned_values = array();
4442
-        foreach ($values as $value) {
4443
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4444
-        }
4445
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4446
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4447
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4448
-        if (empty($cleaned_values)) {
4449
-            $all_fields = $this->field_settings();
4450
-            $a_field = array_shift($all_fields);
4451
-            $main_table = $this->_get_main_table();
4452
-            $cleaned_values[] = "SELECT "
4453
-                                . $a_field->get_table_column()
4454
-                                . " FROM "
4455
-                                . $main_table->get_table_name()
4456
-                                . " WHERE FALSE";
4457
-        }
4458
-        return "(" . implode(",", $cleaned_values) . ")";
4459
-    }
4460
-
4461
-
4462
-
4463
-    /**
4464
-     * @param mixed                      $value
4465
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4466
-     * @throws EE_Error
4467
-     * @return false|null|string
4468
-     */
4469
-    private function _wpdb_prepare_using_field($value, $field_obj)
4470
-    {
4471
-        /** @type WPDB $wpdb */
4472
-        global $wpdb;
4473
-        if ($field_obj instanceof EE_Model_Field_Base) {
4474
-            return $wpdb->prepare(
4475
-                $field_obj->get_wpdb_data_type(),
4476
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4477
-            );
4478
-        } //$field_obj should really just be a data type
4479
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4480
-            throw new EE_Error(
4481
-                sprintf(
4482
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4483
-                    $field_obj,
4484
-                    implode(",", $this->_valid_wpdb_data_types)
4485
-                )
4486
-            );
4487
-        }
4488
-        return $wpdb->prepare($field_obj, $value);
4489
-    }
4490
-
4491
-
4492
-
4493
-    /**
4494
-     * Takes the input parameter and finds the model field that it indicates.
4495
-     *
4496
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4497
-     * @throws EE_Error
4498
-     * @return EE_Model_Field_Base
4499
-     */
4500
-    protected function _deduce_field_from_query_param($query_param_name)
4501
-    {
4502
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4503
-        // which will help us find the database table and column
4504
-        $query_param_parts = explode(".", $query_param_name);
4505
-        if (empty($query_param_parts)) {
4506
-            throw new EE_Error(sprintf(__(
4507
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4508
-                'event_espresso'
4509
-            ), $query_param_name));
4510
-        }
4511
-        $number_of_parts = count($query_param_parts);
4512
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4513
-        if ($number_of_parts === 1) {
4514
-            $field_name = $last_query_param_part;
4515
-            $model_obj = $this;
4516
-        } else {// $number_of_parts >= 2
4517
-            // the last part is the column name, and there are only 2parts. therefore...
4518
-            $field_name = $last_query_param_part;
4519
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4520
-        }
4521
-        try {
4522
-            return $model_obj->field_settings_for($field_name);
4523
-        } catch (EE_Error $e) {
4524
-            return null;
4525
-        }
4526
-    }
4527
-
4528
-
4529
-
4530
-    /**
4531
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4532
-     * alias and column which corresponds to it
4533
-     *
4534
-     * @param string $field_name
4535
-     * @throws EE_Error
4536
-     * @return string
4537
-     */
4538
-    public function _get_qualified_column_for_field($field_name)
4539
-    {
4540
-        $all_fields = $this->field_settings();
4541
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4542
-        if ($field) {
4543
-            return $field->get_qualified_column();
4544
-        }
4545
-        throw new EE_Error(
4546
-            sprintf(
4547
-                __(
4548
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4549
-                    'event_espresso'
4550
-                ),
4551
-                $field_name,
4552
-                get_class($this)
4553
-            )
4554
-        );
4555
-    }
4556
-
4557
-
4558
-
4559
-    /**
4560
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4561
-     * Example usage:
4562
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4563
-     *      array(),
4564
-     *      ARRAY_A,
4565
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4566
-     *  );
4567
-     * is equivalent to
4568
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4569
-     * and
4570
-     *  EEM_Event::instance()->get_all_wpdb_results(
4571
-     *      array(
4572
-     *          array(
4573
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4574
-     *          ),
4575
-     *          ARRAY_A,
4576
-     *          implode(
4577
-     *              ', ',
4578
-     *              array_merge(
4579
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4580
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4581
-     *              )
4582
-     *          )
4583
-     *      )
4584
-     *  );
4585
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4586
-     *
4587
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4588
-     *                                            and the one whose fields you are selecting for example: when querying
4589
-     *                                            tickets model and selecting fields from the tickets model you would
4590
-     *                                            leave this parameter empty, because no models are needed to join
4591
-     *                                            between the queried model and the selected one. Likewise when
4592
-     *                                            querying the datetime model and selecting fields from the tickets
4593
-     *                                            model, it would also be left empty, because there is a direct
4594
-     *                                            relation from datetimes to tickets, so no model is needed to join
4595
-     *                                            them together. However, when querying from the event model and
4596
-     *                                            selecting fields from the ticket model, you should provide the string
4597
-     *                                            'Datetime', indicating that the event model must first join to the
4598
-     *                                            datetime model in order to find its relation to ticket model.
4599
-     *                                            Also, when querying from the venue model and selecting fields from
4600
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4601
-     *                                            indicating you need to join the venue model to the event model,
4602
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4603
-     *                                            This string is used to deduce the prefix that gets added onto the
4604
-     *                                            models' tables qualified columns
4605
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4606
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4607
-     *                                            qualified column names
4608
-     * @return array|string
4609
-     */
4610
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4611
-    {
4612
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4613
-        $qualified_columns = array();
4614
-        foreach ($this->field_settings() as $field_name => $field) {
4615
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4616
-        }
4617
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4618
-    }
4619
-
4620
-
4621
-
4622
-    /**
4623
-     * constructs the select use on special limit joins
4624
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4625
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4626
-     * (as that is typically where the limits would be set).
4627
-     *
4628
-     * @param  string       $table_alias The table the select is being built for
4629
-     * @param  mixed|string $limit       The limit for this select
4630
-     * @return string                The final select join element for the query.
4631
-     */
4632
-    public function _construct_limit_join_select($table_alias, $limit)
4633
-    {
4634
-        $SQL = '';
4635
-        foreach ($this->_tables as $table_obj) {
4636
-            if ($table_obj instanceof EE_Primary_Table) {
4637
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4638
-                    ? $table_obj->get_select_join_limit($limit)
4639
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4640
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4641
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4642
-                    ? $table_obj->get_select_join_limit_join($limit)
4643
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4644
-            }
4645
-        }
4646
-        return $SQL;
4647
-    }
4648
-
4649
-
4650
-
4651
-    /**
4652
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4653
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4654
-     *
4655
-     * @return string SQL
4656
-     * @throws EE_Error
4657
-     */
4658
-    public function _construct_internal_join()
4659
-    {
4660
-        $SQL = $this->_get_main_table()->get_table_sql();
4661
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4662
-        return $SQL;
4663
-    }
4664
-
4665
-
4666
-
4667
-    /**
4668
-     * Constructs the SQL for joining all the tables on this model.
4669
-     * Normally $alias should be the primary table's alias, but in cases where
4670
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4671
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4672
-     * alias, this will construct SQL like:
4673
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4674
-     * With $alias being a secondary table's alias, this will construct SQL like:
4675
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4676
-     *
4677
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4678
-     * @return string
4679
-     */
4680
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4681
-    {
4682
-        $SQL = '';
4683
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4684
-        foreach ($this->_tables as $table_obj) {
4685
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4686
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4687
-                    // so we're joining to this table, meaning the table is already in
4688
-                    // the FROM statement, BUT the primary table isn't. So we want
4689
-                    // to add the inverse join sql
4690
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4691
-                } else {
4692
-                    // just add a regular JOIN to this table from the primary table
4693
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4694
-                }
4695
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4696
-        }
4697
-        return $SQL;
4698
-    }
4699
-
4700
-
4701
-
4702
-    /**
4703
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4704
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4705
-     * their data type (eg, '%s', '%d', etc)
4706
-     *
4707
-     * @return array
4708
-     */
4709
-    public function _get_data_types()
4710
-    {
4711
-        $data_types = array();
4712
-        foreach ($this->field_settings() as $field_obj) {
4713
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4714
-            /** @var $field_obj EE_Model_Field_Base */
4715
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4716
-        }
4717
-        return $data_types;
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4724
-     *
4725
-     * @param string $model_name
4726
-     * @throws EE_Error
4727
-     * @return EEM_Base
4728
-     */
4729
-    public function get_related_model_obj($model_name)
4730
-    {
4731
-        $model_classname = "EEM_" . $model_name;
4732
-        if (! class_exists($model_classname)) {
4733
-            throw new EE_Error(sprintf(__(
4734
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4735
-                'event_espresso'
4736
-            ), $model_name, $model_classname));
4737
-        }
4738
-        return call_user_func($model_classname . "::instance");
4739
-    }
4740
-
4741
-
4742
-
4743
-    /**
4744
-     * Returns the array of EE_ModelRelations for this model.
4745
-     *
4746
-     * @return EE_Model_Relation_Base[]
4747
-     */
4748
-    public function relation_settings()
4749
-    {
4750
-        return $this->_model_relations;
4751
-    }
4752
-
4753
-
4754
-
4755
-    /**
4756
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4757
-     * because without THOSE models, this model probably doesn't have much purpose.
4758
-     * (Eg, without an event, datetimes have little purpose.)
4759
-     *
4760
-     * @return EE_Belongs_To_Relation[]
4761
-     */
4762
-    public function belongs_to_relations()
4763
-    {
4764
-        $belongs_to_relations = array();
4765
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4766
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4767
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4768
-            }
4769
-        }
4770
-        return $belongs_to_relations;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Returns the specified EE_Model_Relation, or throws an exception
4777
-     *
4778
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4779
-     * @throws EE_Error
4780
-     * @return EE_Model_Relation_Base
4781
-     */
4782
-    public function related_settings_for($relation_name)
4783
-    {
4784
-        $relatedModels = $this->relation_settings();
4785
-        if (! array_key_exists($relation_name, $relatedModels)) {
4786
-            throw new EE_Error(
4787
-                sprintf(
4788
-                    __(
4789
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4790
-                        'event_espresso'
4791
-                    ),
4792
-                    $relation_name,
4793
-                    $this->_get_class_name(),
4794
-                    implode(', ', array_keys($relatedModels))
4795
-                )
4796
-            );
4797
-        }
4798
-        return $relatedModels[ $relation_name ];
4799
-    }
4800
-
4801
-
4802
-
4803
-    /**
4804
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4805
-     * fields
4806
-     *
4807
-     * @param string $fieldName
4808
-     * @param boolean $include_db_only_fields
4809
-     * @throws EE_Error
4810
-     * @return EE_Model_Field_Base
4811
-     */
4812
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4813
-    {
4814
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4815
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4816
-            throw new EE_Error(sprintf(
4817
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4818
-                $fieldName,
4819
-                get_class($this)
4820
-            ));
4821
-        }
4822
-        return $fieldSettings[ $fieldName ];
4823
-    }
4824
-
4825
-
4826
-
4827
-    /**
4828
-     * Checks if this field exists on this model
4829
-     *
4830
-     * @param string $fieldName a key in the model's _field_settings array
4831
-     * @return boolean
4832
-     */
4833
-    public function has_field($fieldName)
4834
-    {
4835
-        $fieldSettings = $this->field_settings(true);
4836
-        if (isset($fieldSettings[ $fieldName ])) {
4837
-            return true;
4838
-        }
4839
-        return false;
4840
-    }
4841
-
4842
-
4843
-
4844
-    /**
4845
-     * Returns whether or not this model has a relation to the specified model
4846
-     *
4847
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4848
-     * @return boolean
4849
-     */
4850
-    public function has_relation($relation_name)
4851
-    {
4852
-        $relations = $this->relation_settings();
4853
-        if (isset($relations[ $relation_name ])) {
4854
-            return true;
4855
-        }
4856
-        return false;
4857
-    }
4858
-
4859
-
4860
-
4861
-    /**
4862
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4863
-     * Eg, on EE_Answer that would be ANS_ID field object
4864
-     *
4865
-     * @param $field_obj
4866
-     * @return boolean
4867
-     */
4868
-    public function is_primary_key_field($field_obj)
4869
-    {
4870
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4871
-    }
4872
-
4873
-
4874
-
4875
-    /**
4876
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4877
-     * Eg, on EE_Answer that would be ANS_ID field object
4878
-     *
4879
-     * @return EE_Model_Field_Base
4880
-     * @throws EE_Error
4881
-     */
4882
-    public function get_primary_key_field()
4883
-    {
4884
-        if ($this->_primary_key_field === null) {
4885
-            foreach ($this->field_settings(true) as $field_obj) {
4886
-                if ($this->is_primary_key_field($field_obj)) {
4887
-                    $this->_primary_key_field = $field_obj;
4888
-                    break;
4889
-                }
4890
-            }
4891
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4892
-                throw new EE_Error(sprintf(
4893
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4894
-                    get_class($this)
4895
-                ));
4896
-            }
4897
-        }
4898
-        return $this->_primary_key_field;
4899
-    }
4900
-
4901
-
4902
-
4903
-    /**
4904
-     * Returns whether or not not there is a primary key on this model.
4905
-     * Internally does some caching.
4906
-     *
4907
-     * @return boolean
4908
-     */
4909
-    public function has_primary_key_field()
4910
-    {
4911
-        if ($this->_has_primary_key_field === null) {
4912
-            try {
4913
-                $this->get_primary_key_field();
4914
-                $this->_has_primary_key_field = true;
4915
-            } catch (EE_Error $e) {
4916
-                $this->_has_primary_key_field = false;
4917
-            }
4918
-        }
4919
-        return $this->_has_primary_key_field;
4920
-    }
4921
-
4922
-
4923
-
4924
-    /**
4925
-     * Finds the first field of type $field_class_name.
4926
-     *
4927
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4928
-     *                                 EE_Foreign_Key_Field, etc
4929
-     * @return EE_Model_Field_Base or null if none is found
4930
-     */
4931
-    public function get_a_field_of_type($field_class_name)
4932
-    {
4933
-        foreach ($this->field_settings() as $field) {
4934
-            if ($field instanceof $field_class_name) {
4935
-                return $field;
4936
-            }
4937
-        }
4938
-        return null;
4939
-    }
4940
-
4941
-
4942
-
4943
-    /**
4944
-     * Gets a foreign key field pointing to model.
4945
-     *
4946
-     * @param string $model_name eg Event, Registration, not EEM_Event
4947
-     * @return EE_Foreign_Key_Field_Base
4948
-     * @throws EE_Error
4949
-     */
4950
-    public function get_foreign_key_to($model_name)
4951
-    {
4952
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4953
-            foreach ($this->field_settings() as $field) {
4954
-                if ($field instanceof EE_Foreign_Key_Field_Base
4955
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4956
-                ) {
4957
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
4958
-                    break;
4959
-                }
4960
-            }
4961
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4962
-                throw new EE_Error(sprintf(__(
4963
-                    "There is no foreign key field pointing to model %s on model %s",
4964
-                    'event_espresso'
4965
-                ), $model_name, get_class($this)));
4966
-            }
4967
-        }
4968
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
4969
-    }
4970
-
4971
-
4972
-
4973
-    /**
4974
-     * Gets the table name (including $wpdb->prefix) for the table alias
4975
-     *
4976
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4977
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4978
-     *                            Either one works
4979
-     * @return string
4980
-     */
4981
-    public function get_table_for_alias($table_alias)
4982
-    {
4983
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4984
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
4985
-    }
4986
-
4987
-
4988
-
4989
-    /**
4990
-     * Returns a flat array of all field son this model, instead of organizing them
4991
-     * by table_alias as they are in the constructor.
4992
-     *
4993
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4994
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4995
-     */
4996
-    public function field_settings($include_db_only_fields = false)
4997
-    {
4998
-        if ($include_db_only_fields) {
4999
-            if ($this->_cached_fields === null) {
5000
-                $this->_cached_fields = array();
5001
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5002
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5003
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5004
-                    }
5005
-                }
5006
-            }
5007
-            return $this->_cached_fields;
5008
-        }
5009
-        if ($this->_cached_fields_non_db_only === null) {
5010
-            $this->_cached_fields_non_db_only = array();
5011
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5012
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5013
-                    /** @var $field_obj EE_Model_Field_Base */
5014
-                    if (! $field_obj->is_db_only_field()) {
5015
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5016
-                    }
5017
-                }
5018
-            }
5019
-        }
5020
-        return $this->_cached_fields_non_db_only;
5021
-    }
5022
-
5023
-
5024
-
5025
-    /**
5026
-     *        cycle though array of attendees and create objects out of each item
5027
-     *
5028
-     * @access        private
5029
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5030
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5031
-     *                           numerically indexed)
5032
-     * @throws EE_Error
5033
-     */
5034
-    protected function _create_objects($rows = array())
5035
-    {
5036
-        $array_of_objects = array();
5037
-        if (empty($rows)) {
5038
-            return array();
5039
-        }
5040
-        $count_if_model_has_no_primary_key = 0;
5041
-        $has_primary_key = $this->has_primary_key_field();
5042
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5043
-        foreach ((array) $rows as $row) {
5044
-            if (empty($row)) {
5045
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5046
-                return array();
5047
-            }
5048
-            // check if we've already set this object in the results array,
5049
-            // in which case there's no need to process it further (again)
5050
-            if ($has_primary_key) {
5051
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5052
-                    $row,
5053
-                    $primary_key_field->get_qualified_column(),
5054
-                    $primary_key_field->get_table_column()
5055
-                );
5056
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5057
-                    continue;
5058
-                }
5059
-            }
5060
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5061
-            if (! $classInstance) {
5062
-                throw new EE_Error(
5063
-                    sprintf(
5064
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5065
-                        $this->get_this_model_name(),
5066
-                        http_build_query($row)
5067
-                    )
5068
-                );
5069
-            }
5070
-            // set the timezone on the instantiated objects
5071
-            $classInstance->set_timezone($this->_timezone);
5072
-            // make sure if there is any timezone setting present that we set the timezone for the object
5073
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5074
-            $array_of_objects[ $key ] = $classInstance;
5075
-            // also, for all the relations of type BelongsTo, see if we can cache
5076
-            // those related models
5077
-            // (we could do this for other relations too, but if there are conditions
5078
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5079
-            // so it requires a little more thought than just caching them immediately...)
5080
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5081
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5082
-                    // check if this model's INFO is present. If so, cache it on the model
5083
-                    $other_model = $relation_obj->get_other_model();
5084
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5085
-                    // if we managed to make a model object from the results, cache it on the main model object
5086
-                    if ($other_model_obj_maybe) {
5087
-                        // set timezone on these other model objects if they are present
5088
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5089
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5090
-                    }
5091
-                }
5092
-            }
5093
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5094
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5095
-            // the field in the CustomSelects object
5096
-            if ($this->_custom_selections instanceof CustomSelects) {
5097
-                $classInstance->setCustomSelectsValues(
5098
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5099
-                );
5100
-            }
5101
-        }
5102
-        return $array_of_objects;
5103
-    }
5104
-
5105
-
5106
-    /**
5107
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5108
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5109
-     *
5110
-     * @param array $db_results_row
5111
-     * @return array
5112
-     */
5113
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5114
-    {
5115
-        $results = array();
5116
-        if ($this->_custom_selections instanceof CustomSelects) {
5117
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5118
-                if (isset($db_results_row[ $alias ])) {
5119
-                    $results[ $alias ] = $this->convertValueToDataType(
5120
-                        $db_results_row[ $alias ],
5121
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5122
-                    );
5123
-                }
5124
-            }
5125
-        }
5126
-        return $results;
5127
-    }
5128
-
5129
-
5130
-    /**
5131
-     * This will set the value for the given alias
5132
-     * @param string $value
5133
-     * @param string $datatype (one of %d, %s, %f)
5134
-     * @return int|string|float (int for %d, string for %s, float for %f)
5135
-     */
5136
-    protected function convertValueToDataType($value, $datatype)
5137
-    {
5138
-        switch ($datatype) {
5139
-            case '%f':
5140
-                return (float) $value;
5141
-            case '%d':
5142
-                return (int) $value;
5143
-            default:
5144
-                return (string) $value;
5145
-        }
5146
-    }
5147
-
5148
-
5149
-    /**
5150
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5151
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5152
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5153
-     * object (as set in the model_field!).
5154
-     *
5155
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5156
-     */
5157
-    public function create_default_object()
5158
-    {
5159
-        $this_model_fields_and_values = array();
5160
-        // setup the row using default values;
5161
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5162
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5163
-        }
5164
-        $className = $this->_get_class_name();
5165
-        $classInstance = EE_Registry::instance()
5166
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5167
-        return $classInstance;
5168
-    }
5169
-
5170
-
5171
-
5172
-    /**
5173
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5174
-     *                             or an stdClass where each property is the name of a column,
5175
-     * @return EE_Base_Class
5176
-     * @throws EE_Error
5177
-     */
5178
-    public function instantiate_class_from_array_or_object($cols_n_values)
5179
-    {
5180
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5181
-            $cols_n_values = get_object_vars($cols_n_values);
5182
-        }
5183
-        $primary_key = null;
5184
-        // make sure the array only has keys that are fields/columns on this model
5185
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5186
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5187
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5188
-        }
5189
-        $className = $this->_get_class_name();
5190
-        // check we actually found results that we can use to build our model object
5191
-        // if not, return null
5192
-        if ($this->has_primary_key_field()) {
5193
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5194
-                return null;
5195
-            }
5196
-        } elseif ($this->unique_indexes()) {
5197
-            $first_column = reset($this_model_fields_n_values);
5198
-            if (empty($first_column)) {
5199
-                return null;
5200
-            }
5201
-        }
5202
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5203
-        if ($primary_key) {
5204
-            $classInstance = $this->get_from_entity_map($primary_key);
5205
-            if (! $classInstance) {
5206
-                $classInstance = EE_Registry::instance()
5207
-                                            ->load_class(
5208
-                                                $className,
5209
-                                                array($this_model_fields_n_values, $this->_timezone),
5210
-                                                true,
5211
-                                                false
5212
-                                            );
5213
-                // add this new object to the entity map
5214
-                $classInstance = $this->add_to_entity_map($classInstance);
5215
-            }
5216
-        } else {
5217
-            $classInstance = EE_Registry::instance()
5218
-                                        ->load_class(
5219
-                                            $className,
5220
-                                            array($this_model_fields_n_values, $this->_timezone),
5221
-                                            true,
5222
-                                            false
5223
-                                        );
5224
-        }
5225
-        return $classInstance;
5226
-    }
5227
-
5228
-
5229
-
5230
-    /**
5231
-     * Gets the model object from the  entity map if it exists
5232
-     *
5233
-     * @param int|string $id the ID of the model object
5234
-     * @return EE_Base_Class
5235
-     */
5236
-    public function get_from_entity_map($id)
5237
-    {
5238
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5239
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5240
-    }
5241
-
5242
-
5243
-
5244
-    /**
5245
-     * add_to_entity_map
5246
-     * Adds the object to the model's entity mappings
5247
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5248
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5249
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5250
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5251
-     *        then this method should be called immediately after the update query
5252
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5253
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5254
-     *
5255
-     * @param    EE_Base_Class $object
5256
-     * @throws EE_Error
5257
-     * @return \EE_Base_Class
5258
-     */
5259
-    public function add_to_entity_map(EE_Base_Class $object)
5260
-    {
5261
-        $className = $this->_get_class_name();
5262
-        if (! $object instanceof $className) {
5263
-            throw new EE_Error(sprintf(
5264
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5265
-                is_object($object) ? get_class($object) : $object,
5266
-                $className
5267
-            ));
5268
-        }
5269
-        /** @var $object EE_Base_Class */
5270
-        if (! $object->ID()) {
5271
-            throw new EE_Error(sprintf(__(
5272
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5273
-                "event_espresso"
5274
-            ), get_class($this)));
5275
-        }
5276
-        // double check it's not already there
5277
-        $classInstance = $this->get_from_entity_map($object->ID());
5278
-        if ($classInstance) {
5279
-            return $classInstance;
5280
-        }
5281
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5282
-        return $object;
5283
-    }
5284
-
5285
-
5286
-
5287
-    /**
5288
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5289
-     * if no identifier is provided, then the entire entity map is emptied
5290
-     *
5291
-     * @param int|string $id the ID of the model object
5292
-     * @return boolean
5293
-     */
5294
-    public function clear_entity_map($id = null)
5295
-    {
5296
-        if (empty($id)) {
5297
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5298
-            return true;
5299
-        }
5300
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5301
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5302
-            return true;
5303
-        }
5304
-        return false;
5305
-    }
5306
-
5307
-
5308
-
5309
-    /**
5310
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5311
-     * Given an array where keys are column (or column alias) names and values,
5312
-     * returns an array of their corresponding field names and database values
5313
-     *
5314
-     * @param array $cols_n_values
5315
-     * @return array
5316
-     */
5317
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5318
-    {
5319
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5320
-    }
5321
-
5322
-
5323
-
5324
-    /**
5325
-     * _deduce_fields_n_values_from_cols_n_values
5326
-     * Given an array where keys are column (or column alias) names and values,
5327
-     * returns an array of their corresponding field names and database values
5328
-     *
5329
-     * @param string $cols_n_values
5330
-     * @return array
5331
-     */
5332
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5333
-    {
5334
-        $this_model_fields_n_values = array();
5335
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5336
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5337
-                $cols_n_values,
5338
-                $table_obj->get_fully_qualified_pk_column(),
5339
-                $table_obj->get_pk_column()
5340
-            );
5341
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5342
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5343
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5344
-                    if (! $field_obj->is_db_only_field()) {
5345
-                        // prepare field as if its coming from db
5346
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5347
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5348
-                    }
5349
-                }
5350
-            } else {
5351
-                // the table's rows existed. Use their values
5352
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5353
-                    if (! $field_obj->is_db_only_field()) {
5354
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5355
-                            $cols_n_values,
5356
-                            $field_obj->get_qualified_column(),
5357
-                            $field_obj->get_table_column()
5358
-                        );
5359
-                    }
5360
-                }
5361
-            }
5362
-        }
5363
-        return $this_model_fields_n_values;
5364
-    }
5365
-
5366
-
5367
-
5368
-    /**
5369
-     * @param $cols_n_values
5370
-     * @param $qualified_column
5371
-     * @param $regular_column
5372
-     * @return null
5373
-     */
5374
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5375
-    {
5376
-        $value = null;
5377
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5378
-        // does the field on the model relate to this column retrieved from the db?
5379
-        // or is it a db-only field? (not relating to the model)
5380
-        if (isset($cols_n_values[ $qualified_column ])) {
5381
-            $value = $cols_n_values[ $qualified_column ];
5382
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5383
-            $value = $cols_n_values[ $regular_column ];
5384
-        }
5385
-        return $value;
5386
-    }
5387
-
5388
-
5389
-
5390
-    /**
5391
-     * refresh_entity_map_from_db
5392
-     * Makes sure the model object in the entity map at $id assumes the values
5393
-     * of the database (opposite of EE_base_Class::save())
5394
-     *
5395
-     * @param int|string $id
5396
-     * @return EE_Base_Class
5397
-     * @throws EE_Error
5398
-     */
5399
-    public function refresh_entity_map_from_db($id)
5400
-    {
5401
-        $obj_in_map = $this->get_from_entity_map($id);
5402
-        if ($obj_in_map) {
5403
-            $wpdb_results = $this->_get_all_wpdb_results(
5404
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5405
-            );
5406
-            if ($wpdb_results && is_array($wpdb_results)) {
5407
-                $one_row = reset($wpdb_results);
5408
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5409
-                    $obj_in_map->set_from_db($field_name, $db_value);
5410
-                }
5411
-                // clear the cache of related model objects
5412
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5413
-                    $obj_in_map->clear_cache($relation_name, null, true);
5414
-                }
5415
-            }
5416
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5417
-            return $obj_in_map;
5418
-        }
5419
-        return $this->get_one_by_ID($id);
5420
-    }
5421
-
5422
-
5423
-
5424
-    /**
5425
-     * refresh_entity_map_with
5426
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5427
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5428
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5429
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5430
-     *
5431
-     * @param int|string    $id
5432
-     * @param EE_Base_Class $replacing_model_obj
5433
-     * @return \EE_Base_Class
5434
-     * @throws EE_Error
5435
-     */
5436
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5437
-    {
5438
-        $obj_in_map = $this->get_from_entity_map($id);
5439
-        if ($obj_in_map) {
5440
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5441
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5442
-                    $obj_in_map->set($field_name, $value);
5443
-                }
5444
-                // make the model object in the entity map's cache match the $replacing_model_obj
5445
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5446
-                    $obj_in_map->clear_cache($relation_name, null, true);
5447
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5448
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5449
-                    }
5450
-                }
5451
-            }
5452
-            return $obj_in_map;
5453
-        }
5454
-        $this->add_to_entity_map($replacing_model_obj);
5455
-        return $replacing_model_obj;
5456
-    }
5457
-
5458
-
5459
-
5460
-    /**
5461
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5462
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5463
-     * require_once($this->_getClassName().".class.php");
5464
-     *
5465
-     * @return string
5466
-     */
5467
-    private function _get_class_name()
5468
-    {
5469
-        return "EE_" . $this->get_this_model_name();
5470
-    }
5471
-
5472
-
5473
-
5474
-    /**
5475
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5476
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5477
-     * it would be 'Events'.
5478
-     *
5479
-     * @param int $quantity
5480
-     * @return string
5481
-     */
5482
-    public function item_name($quantity = 1)
5483
-    {
5484
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5485
-    }
5486
-
5487
-
5488
-
5489
-    /**
5490
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5491
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5492
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5493
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5494
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5495
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5496
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5497
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5498
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5499
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5500
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5501
-     *        return $previousReturnValue.$returnString;
5502
-     * }
5503
-     * require('EEM_Answer.model.php');
5504
-     * $answer=EEM_Answer::instance();
5505
-     * echo $answer->my_callback('monkeys',100);
5506
-     * //will output "you called my_callback! and passed args:monkeys,100"
5507
-     *
5508
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5509
-     * @param array  $args       array of original arguments passed to the function
5510
-     * @throws EE_Error
5511
-     * @return mixed whatever the plugin which calls add_filter decides
5512
-     */
5513
-    public function __call($methodName, $args)
5514
-    {
5515
-        $className = get_class($this);
5516
-        $tagName = "FHEE__{$className}__{$methodName}";
5517
-        if (! has_filter($tagName)) {
5518
-            throw new EE_Error(
5519
-                sprintf(
5520
-                    __(
5521
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5522
-                        'event_espresso'
5523
-                    ),
5524
-                    $methodName,
5525
-                    $className,
5526
-                    $tagName,
5527
-                    '<br />'
5528
-                )
5529
-            );
5530
-        }
5531
-        return apply_filters($tagName, null, $this, $args);
5532
-    }
5533
-
5534
-
5535
-
5536
-    /**
5537
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5538
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5539
-     *
5540
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5541
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5542
-     *                                                       the object's class name
5543
-     *                                                       or object's ID
5544
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5545
-     *                                                       exists in the database. If it does not, we add it
5546
-     * @throws EE_Error
5547
-     * @return EE_Base_Class
5548
-     */
5549
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5550
-    {
5551
-        $className = $this->_get_class_name();
5552
-        if ($base_class_obj_or_id instanceof $className) {
5553
-            $model_object = $base_class_obj_or_id;
5554
-        } else {
5555
-            $primary_key_field = $this->get_primary_key_field();
5556
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5557
-                && (
5558
-                    is_int($base_class_obj_or_id)
5559
-                    || is_string($base_class_obj_or_id)
5560
-                )
5561
-            ) {
5562
-                // assume it's an ID.
5563
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5564
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5565
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5566
-                && is_string($base_class_obj_or_id)
5567
-            ) {
5568
-                // assume its a string representation of the object
5569
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5570
-            } else {
5571
-                throw new EE_Error(
5572
-                    sprintf(
5573
-                        __(
5574
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5575
-                            'event_espresso'
5576
-                        ),
5577
-                        $base_class_obj_or_id,
5578
-                        $this->_get_class_name(),
5579
-                        print_r($base_class_obj_or_id, true)
5580
-                    )
5581
-                );
5582
-            }
5583
-        }
5584
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5585
-            $model_object->save();
5586
-        }
5587
-        return $model_object;
5588
-    }
5589
-
5590
-
5591
-
5592
-    /**
5593
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5594
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5595
-     * returns it ID.
5596
-     *
5597
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5598
-     * @return int|string depending on the type of this model object's ID
5599
-     * @throws EE_Error
5600
-     */
5601
-    public function ensure_is_ID($base_class_obj_or_id)
5602
-    {
5603
-        $className = $this->_get_class_name();
5604
-        if ($base_class_obj_or_id instanceof $className) {
5605
-            /** @var $base_class_obj_or_id EE_Base_Class */
5606
-            $id = $base_class_obj_or_id->ID();
5607
-        } elseif (is_int($base_class_obj_or_id)) {
5608
-            // assume it's an ID
5609
-            $id = $base_class_obj_or_id;
5610
-        } elseif (is_string($base_class_obj_or_id)) {
5611
-            // assume its a string representation of the object
5612
-            $id = $base_class_obj_or_id;
5613
-        } else {
5614
-            throw new EE_Error(sprintf(
5615
-                __(
5616
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5617
-                    'event_espresso'
5618
-                ),
5619
-                $base_class_obj_or_id,
5620
-                $this->_get_class_name(),
5621
-                print_r($base_class_obj_or_id, true)
5622
-            ));
5623
-        }
5624
-        return $id;
5625
-    }
5626
-
5627
-
5628
-
5629
-    /**
5630
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5631
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5632
-     * been sanitized and converted into the appropriate domain.
5633
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5634
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5635
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5636
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5637
-     * $EVT = EEM_Event::instance(); $old_setting =
5638
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5639
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5640
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5641
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5642
-     *
5643
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5644
-     * @return void
5645
-     */
5646
-    public function assume_values_already_prepared_by_model_object(
5647
-        $values_already_prepared = self::not_prepared_by_model_object
5648
-    ) {
5649
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5650
-    }
5651
-
5652
-
5653
-
5654
-    /**
5655
-     * Read comments for assume_values_already_prepared_by_model_object()
5656
-     *
5657
-     * @return int
5658
-     */
5659
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5660
-    {
5661
-        return $this->_values_already_prepared_by_model_object;
5662
-    }
5663
-
5664
-
5665
-
5666
-    /**
5667
-     * Gets all the indexes on this model
5668
-     *
5669
-     * @return EE_Index[]
5670
-     */
5671
-    public function indexes()
5672
-    {
5673
-        return $this->_indexes;
5674
-    }
5675
-
5676
-
5677
-
5678
-    /**
5679
-     * Gets all the Unique Indexes on this model
5680
-     *
5681
-     * @return EE_Unique_Index[]
5682
-     */
5683
-    public function unique_indexes()
5684
-    {
5685
-        $unique_indexes = array();
5686
-        foreach ($this->_indexes as $name => $index) {
5687
-            if ($index instanceof EE_Unique_Index) {
5688
-                $unique_indexes [ $name ] = $index;
5689
-            }
5690
-        }
5691
-        return $unique_indexes;
5692
-    }
5693
-
5694
-
5695
-
5696
-    /**
5697
-     * Gets all the fields which, when combined, make the primary key.
5698
-     * This is usually just an array with 1 element (the primary key), but in cases
5699
-     * where there is no primary key, it's a combination of fields as defined
5700
-     * on a primary index
5701
-     *
5702
-     * @return EE_Model_Field_Base[] indexed by the field's name
5703
-     * @throws EE_Error
5704
-     */
5705
-    public function get_combined_primary_key_fields()
5706
-    {
5707
-        foreach ($this->indexes() as $index) {
5708
-            if ($index instanceof EE_Primary_Key_Index) {
5709
-                return $index->fields();
5710
-            }
5711
-        }
5712
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5713
-    }
5714
-
5715
-
5716
-
5717
-    /**
5718
-     * Used to build a primary key string (when the model has no primary key),
5719
-     * which can be used a unique string to identify this model object.
5720
-     *
5721
-     * @param array $cols_n_values keys are field names, values are their values
5722
-     * @return string
5723
-     * @throws EE_Error
5724
-     */
5725
-    public function get_index_primary_key_string($cols_n_values)
5726
-    {
5727
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5728
-            $cols_n_values,
5729
-            $this->get_combined_primary_key_fields()
5730
-        );
5731
-        return http_build_query($cols_n_values_for_primary_key_index);
5732
-    }
5733
-
5734
-
5735
-
5736
-    /**
5737
-     * Gets the field values from the primary key string
5738
-     *
5739
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5740
-     * @param string $index_primary_key_string
5741
-     * @return null|array
5742
-     * @throws EE_Error
5743
-     */
5744
-    public function parse_index_primary_key_string($index_primary_key_string)
5745
-    {
5746
-        $key_fields = $this->get_combined_primary_key_fields();
5747
-        // check all of them are in the $id
5748
-        $key_vals_in_combined_pk = array();
5749
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5750
-        foreach ($key_fields as $key_field_name => $field_obj) {
5751
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5752
-                return null;
5753
-            }
5754
-        }
5755
-        return $key_vals_in_combined_pk;
5756
-    }
5757
-
5758
-
5759
-
5760
-    /**
5761
-     * verifies that an array of key-value pairs for model fields has a key
5762
-     * for each field comprising the primary key index
5763
-     *
5764
-     * @param array $key_vals
5765
-     * @return boolean
5766
-     * @throws EE_Error
5767
-     */
5768
-    public function has_all_combined_primary_key_fields($key_vals)
5769
-    {
5770
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5771
-        foreach ($keys_it_should_have as $key) {
5772
-            if (! isset($key_vals[ $key ])) {
5773
-                return false;
5774
-            }
5775
-        }
5776
-        return true;
5777
-    }
5778
-
5779
-
5780
-
5781
-    /**
5782
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5783
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5784
-     *
5785
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5786
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5787
-     * @throws EE_Error
5788
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5789
-     *                                                              indexed)
5790
-     */
5791
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5792
-    {
5793
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5794
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5795
-        } elseif (is_array($model_object_or_attributes_array)) {
5796
-            $attributes_array = $model_object_or_attributes_array;
5797
-        } else {
5798
-            throw new EE_Error(sprintf(__(
5799
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5800
-                "event_espresso"
5801
-            ), $model_object_or_attributes_array));
5802
-        }
5803
-        // even copies obviously won't have the same ID, so remove the primary key
5804
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5805
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5806
-            unset($attributes_array[ $this->primary_key_name() ]);
5807
-        }
5808
-        if (isset($query_params[0])) {
5809
-            $query_params[0] = array_merge($attributes_array, $query_params);
5810
-        } else {
5811
-            $query_params[0] = $attributes_array;
5812
-        }
5813
-        return $this->get_all($query_params);
5814
-    }
5815
-
5816
-
5817
-
5818
-    /**
5819
-     * Gets the first copy we find. See get_all_copies for more details
5820
-     *
5821
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5822
-     * @param array $query_params
5823
-     * @return EE_Base_Class
5824
-     * @throws EE_Error
5825
-     */
5826
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5827
-    {
5828
-        if (! is_array($query_params)) {
5829
-            EE_Error::doing_it_wrong(
5830
-                'EEM_Base::get_one_copy',
5831
-                sprintf(
5832
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5833
-                    gettype($query_params)
5834
-                ),
5835
-                '4.6.0'
5836
-            );
5837
-            $query_params = array();
5838
-        }
5839
-        $query_params['limit'] = 1;
5840
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5841
-        if (is_array($copies)) {
5842
-            return array_shift($copies);
5843
-        }
5844
-        return null;
5845
-    }
5846
-
5847
-
5848
-
5849
-    /**
5850
-     * Updates the item with the specified id. Ignores default query parameters because
5851
-     * we have specified the ID, and its assumed we KNOW what we're doing
5852
-     *
5853
-     * @param array      $fields_n_values keys are field names, values are their new values
5854
-     * @param int|string $id              the value of the primary key to update
5855
-     * @return int number of rows updated
5856
-     * @throws EE_Error
5857
-     */
5858
-    public function update_by_ID($fields_n_values, $id)
5859
-    {
5860
-        $query_params = array(
5861
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5862
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5863
-        );
5864
-        return $this->update($fields_n_values, $query_params);
5865
-    }
5866
-
5867
-
5868
-
5869
-    /**
5870
-     * Changes an operator which was supplied to the models into one usable in SQL
5871
-     *
5872
-     * @param string $operator_supplied
5873
-     * @return string an operator which can be used in SQL
5874
-     * @throws EE_Error
5875
-     */
5876
-    private function _prepare_operator_for_sql($operator_supplied)
5877
-    {
5878
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5879
-            : null;
5880
-        if ($sql_operator) {
5881
-            return $sql_operator;
5882
-        }
5883
-        throw new EE_Error(
5884
-            sprintf(
5885
-                __(
5886
-                    "The operator '%s' is not in the list of valid operators: %s",
5887
-                    "event_espresso"
5888
-                ),
5889
-                $operator_supplied,
5890
-                implode(",", array_keys($this->_valid_operators))
5891
-            )
5892
-        );
5893
-    }
5894
-
5895
-
5896
-
5897
-    /**
5898
-     * Gets the valid operators
5899
-     * @return array keys are accepted strings, values are the SQL they are converted to
5900
-     */
5901
-    public function valid_operators()
5902
-    {
5903
-        return $this->_valid_operators;
5904
-    }
5905
-
5906
-
5907
-
5908
-    /**
5909
-     * Gets the between-style operators (take 2 arguments).
5910
-     * @return array keys are accepted strings, values are the SQL they are converted to
5911
-     */
5912
-    public function valid_between_style_operators()
5913
-    {
5914
-        return array_intersect(
5915
-            $this->valid_operators(),
5916
-            $this->_between_style_operators
5917
-        );
5918
-    }
5919
-
5920
-    /**
5921
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5922
-     * @return array keys are accepted strings, values are the SQL they are converted to
5923
-     */
5924
-    public function valid_like_style_operators()
5925
-    {
5926
-        return array_intersect(
5927
-            $this->valid_operators(),
5928
-            $this->_like_style_operators
5929
-        );
5930
-    }
5931
-
5932
-    /**
5933
-     * Gets the "in"-style operators
5934
-     * @return array keys are accepted strings, values are the SQL they are converted to
5935
-     */
5936
-    public function valid_in_style_operators()
5937
-    {
5938
-        return array_intersect(
5939
-            $this->valid_operators(),
5940
-            $this->_in_style_operators
5941
-        );
5942
-    }
5943
-
5944
-    /**
5945
-     * Gets the "null"-style operators (accept no arguments)
5946
-     * @return array keys are accepted strings, values are the SQL they are converted to
5947
-     */
5948
-    public function valid_null_style_operators()
5949
-    {
5950
-        return array_intersect(
5951
-            $this->valid_operators(),
5952
-            $this->_null_style_operators
5953
-        );
5954
-    }
5955
-
5956
-    /**
5957
-     * Gets an array where keys are the primary keys and values are their 'names'
5958
-     * (as determined by the model object's name() function, which is often overridden)
5959
-     *
5960
-     * @param array $query_params like get_all's
5961
-     * @return string[]
5962
-     * @throws EE_Error
5963
-     */
5964
-    public function get_all_names($query_params = array())
5965
-    {
5966
-        $objs = $this->get_all($query_params);
5967
-        $names = array();
5968
-        foreach ($objs as $obj) {
5969
-            $names[ $obj->ID() ] = $obj->name();
5970
-        }
5971
-        return $names;
5972
-    }
5973
-
5974
-
5975
-
5976
-    /**
5977
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5978
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5979
-     * this is duplicated effort and reduces efficiency) you would be better to use
5980
-     * array_keys() on $model_objects.
5981
-     *
5982
-     * @param \EE_Base_Class[] $model_objects
5983
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5984
-     *                                               in the returned array
5985
-     * @return array
5986
-     * @throws EE_Error
5987
-     */
5988
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5989
-    {
5990
-        if (! $this->has_primary_key_field()) {
5991
-            if (WP_DEBUG) {
5992
-                EE_Error::add_error(
5993
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5994
-                    __FILE__,
5995
-                    __FUNCTION__,
5996
-                    __LINE__
5997
-                );
5998
-            }
5999
-        }
6000
-        $IDs = array();
6001
-        foreach ($model_objects as $model_object) {
6002
-            $id = $model_object->ID();
6003
-            if (! $id) {
6004
-                if ($filter_out_empty_ids) {
6005
-                    continue;
6006
-                }
6007
-                if (WP_DEBUG) {
6008
-                    EE_Error::add_error(
6009
-                        __(
6010
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6011
-                            'event_espresso'
6012
-                        ),
6013
-                        __FILE__,
6014
-                        __FUNCTION__,
6015
-                        __LINE__
6016
-                    );
6017
-                }
6018
-            }
6019
-            $IDs[] = $id;
6020
-        }
6021
-        return $IDs;
6022
-    }
6023
-
6024
-
6025
-
6026
-    /**
6027
-     * Returns the string used in capabilities relating to this model. If there
6028
-     * are no capabilities that relate to this model returns false
6029
-     *
6030
-     * @return string|false
6031
-     */
6032
-    public function cap_slug()
6033
-    {
6034
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6035
-    }
6036
-
6037
-
6038
-
6039
-    /**
6040
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6041
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6042
-     * only returns the cap restrictions array in that context (ie, the array
6043
-     * at that key)
6044
-     *
6045
-     * @param string $context
6046
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6047
-     * @throws EE_Error
6048
-     */
6049
-    public function cap_restrictions($context = EEM_Base::caps_read)
6050
-    {
6051
-        EEM_Base::verify_is_valid_cap_context($context);
6052
-        // check if we ought to run the restriction generator first
6053
-        if (isset($this->_cap_restriction_generators[ $context ])
6054
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6055
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6056
-        ) {
6057
-            $this->_cap_restrictions[ $context ] = array_merge(
6058
-                $this->_cap_restrictions[ $context ],
6059
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6060
-            );
6061
-        }
6062
-        // and make sure we've finalized the construction of each restriction
6063
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6064
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6065
-                $where_conditions_obj->_finalize_construct($this);
6066
-            }
6067
-        }
6068
-        return $this->_cap_restrictions[ $context ];
6069
-    }
6070
-
6071
-
6072
-
6073
-    /**
6074
-     * Indicating whether or not this model thinks its a wp core model
6075
-     *
6076
-     * @return boolean
6077
-     */
6078
-    public function is_wp_core_model()
6079
-    {
6080
-        return $this->_wp_core_model;
6081
-    }
6082
-
6083
-
6084
-
6085
-    /**
6086
-     * Gets all the caps that are missing which impose a restriction on
6087
-     * queries made in this context
6088
-     *
6089
-     * @param string $context one of EEM_Base::caps_ constants
6090
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6091
-     * @throws EE_Error
6092
-     */
6093
-    public function caps_missing($context = EEM_Base::caps_read)
6094
-    {
6095
-        $missing_caps = array();
6096
-        $cap_restrictions = $this->cap_restrictions($context);
6097
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6098
-            if (! EE_Capabilities::instance()
6099
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6100
-            ) {
6101
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6102
-            }
6103
-        }
6104
-        return $missing_caps;
6105
-    }
6106
-
6107
-
6108
-
6109
-    /**
6110
-     * Gets the mapping from capability contexts to action strings used in capability names
6111
-     *
6112
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6113
-     * one of 'read', 'edit', or 'delete'
6114
-     */
6115
-    public function cap_contexts_to_cap_action_map()
6116
-    {
6117
-        return apply_filters(
6118
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6119
-            $this->_cap_contexts_to_cap_action_map,
6120
-            $this
6121
-        );
6122
-    }
6123
-
6124
-
6125
-
6126
-    /**
6127
-     * Gets the action string for the specified capability context
6128
-     *
6129
-     * @param string $context
6130
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6131
-     * @throws EE_Error
6132
-     */
6133
-    public function cap_action_for_context($context)
6134
-    {
6135
-        $mapping = $this->cap_contexts_to_cap_action_map();
6136
-        if (isset($mapping[ $context ])) {
6137
-            return $mapping[ $context ];
6138
-        }
6139
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6140
-            return $action;
6141
-        }
6142
-        throw new EE_Error(
6143
-            sprintf(
6144
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6145
-                $context,
6146
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6147
-            )
6148
-        );
6149
-    }
6150
-
6151
-
6152
-
6153
-    /**
6154
-     * Returns all the capability contexts which are valid when querying models
6155
-     *
6156
-     * @return array
6157
-     */
6158
-    public static function valid_cap_contexts()
6159
-    {
6160
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6161
-            self::caps_read,
6162
-            self::caps_read_admin,
6163
-            self::caps_edit,
6164
-            self::caps_delete,
6165
-        ));
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Returns all valid options for 'default_where_conditions'
6172
-     *
6173
-     * @return array
6174
-     */
6175
-    public static function valid_default_where_conditions()
6176
-    {
6177
-        return array(
6178
-            EEM_Base::default_where_conditions_all,
6179
-            EEM_Base::default_where_conditions_this_only,
6180
-            EEM_Base::default_where_conditions_others_only,
6181
-            EEM_Base::default_where_conditions_minimum_all,
6182
-            EEM_Base::default_where_conditions_minimum_others,
6183
-            EEM_Base::default_where_conditions_none
6184
-        );
6185
-    }
6186
-
6187
-    // public static function default_where_conditions_full
6188
-    /**
6189
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6190
-     *
6191
-     * @param string $context
6192
-     * @return bool
6193
-     * @throws EE_Error
6194
-     */
6195
-    public static function verify_is_valid_cap_context($context)
6196
-    {
6197
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6198
-        if (in_array($context, $valid_cap_contexts)) {
6199
-            return true;
6200
-        }
6201
-        throw new EE_Error(
6202
-            sprintf(
6203
-                __(
6204
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6205
-                    'event_espresso'
6206
-                ),
6207
-                $context,
6208
-                'EEM_Base',
6209
-                implode(',', $valid_cap_contexts)
6210
-            )
6211
-        );
6212
-    }
6213
-
6214
-
6215
-
6216
-    /**
6217
-     * Clears all the models field caches. This is only useful when a sub-class
6218
-     * might have added a field or something and these caches might be invalidated
6219
-     */
6220
-    protected function _invalidate_field_caches()
6221
-    {
6222
-        $this->_cache_foreign_key_to_fields = array();
6223
-        $this->_cached_fields = null;
6224
-        $this->_cached_fields_non_db_only = null;
6225
-    }
6226
-
6227
-
6228
-
6229
-    /**
6230
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6231
-     * (eg "and", "or", "not").
6232
-     *
6233
-     * @return array
6234
-     */
6235
-    public function logic_query_param_keys()
6236
-    {
6237
-        return $this->_logic_query_param_keys;
6238
-    }
6239
-
6240
-
6241
-
6242
-    /**
6243
-     * Determines whether or not the where query param array key is for a logic query param.
6244
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6245
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6246
-     *
6247
-     * @param $query_param_key
6248
-     * @return bool
6249
-     */
6250
-    public function is_logic_query_param_key($query_param_key)
6251
-    {
6252
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6253
-            if ($query_param_key === $logic_query_param_key
6254
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6255
-            ) {
6256
-                return true;
6257
-            }
6258
-        }
6259
-        return false;
6260
-    }
3747
+		}
3748
+		return $null_friendly_where_conditions;
3749
+	}
3750
+
3751
+
3752
+
3753
+	/**
3754
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3755
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3756
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3757
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3758
+	 *
3759
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3760
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3761
+	 */
3762
+	private function _get_default_where_conditions($model_relation_path = null)
3763
+	{
3764
+		if ($this->_ignore_where_strategy) {
3765
+			return array();
3766
+		}
3767
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3768
+	}
3769
+
3770
+
3771
+
3772
+	/**
3773
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3774
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3775
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3776
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3777
+	 * Similar to _get_default_where_conditions
3778
+	 *
3779
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3780
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3781
+	 */
3782
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3783
+	{
3784
+		if ($this->_ignore_where_strategy) {
3785
+			return array();
3786
+		}
3787
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3788
+	}
3789
+
3790
+
3791
+
3792
+	/**
3793
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3794
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3795
+	 *
3796
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3797
+	 * @return string
3798
+	 * @throws EE_Error
3799
+	 */
3800
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3801
+	{
3802
+		$selects = $this->_get_columns_to_select_for_this_model();
3803
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3804
+			$name_of_other_model_included) {
3805
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3806
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3807
+			foreach ($other_model_selects as $key => $value) {
3808
+				$selects[] = $value;
3809
+			}
3810
+		}
3811
+		return implode(", ", $selects);
3812
+	}
3813
+
3814
+
3815
+
3816
+	/**
3817
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3818
+	 * So that's going to be the columns for all the fields on the model
3819
+	 *
3820
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3821
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3822
+	 */
3823
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3824
+	{
3825
+		$fields = $this->field_settings();
3826
+		$selects = array();
3827
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3828
+			$model_relation_chain,
3829
+			$this->get_this_model_name()
3830
+		);
3831
+		foreach ($fields as $field_obj) {
3832
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3833
+						 . $field_obj->get_table_alias()
3834
+						 . "."
3835
+						 . $field_obj->get_table_column()
3836
+						 . " AS '"
3837
+						 . $table_alias_with_model_relation_chain_prefix
3838
+						 . $field_obj->get_table_alias()
3839
+						 . "."
3840
+						 . $field_obj->get_table_column()
3841
+						 . "'";
3842
+		}
3843
+		// make sure we are also getting the PKs of each table
3844
+		$tables = $this->get_tables();
3845
+		if (count($tables) > 1) {
3846
+			foreach ($tables as $table_obj) {
3847
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3848
+									   . $table_obj->get_fully_qualified_pk_column();
3849
+				if (! in_array($qualified_pk_column, $selects)) {
3850
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3851
+				}
3852
+			}
3853
+		}
3854
+		return $selects;
3855
+	}
3856
+
3857
+
3858
+
3859
+	/**
3860
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3861
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3862
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3863
+	 * SQL for joining, and the data types
3864
+	 *
3865
+	 * @param null|string                 $original_query_param
3866
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3867
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3868
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3869
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3870
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3871
+	 *                                                          or 'Registration's
3872
+	 * @param string                      $original_query_param what it originally was (eg
3873
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3874
+	 *                                                          matches $query_param
3875
+	 * @throws EE_Error
3876
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3877
+	 */
3878
+	private function _extract_related_model_info_from_query_param(
3879
+		$query_param,
3880
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3881
+		$query_param_type,
3882
+		$original_query_param = null
3883
+	) {
3884
+		if ($original_query_param === null) {
3885
+			$original_query_param = $query_param;
3886
+		}
3887
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3888
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3889
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3890
+		$allow_fields = in_array(
3891
+			$query_param_type,
3892
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3893
+			true
3894
+		);
3895
+		// check to see if we have a field on this model
3896
+		$this_model_fields = $this->field_settings(true);
3897
+		if (array_key_exists($query_param, $this_model_fields)) {
3898
+			if ($allow_fields) {
3899
+				return;
3900
+			}
3901
+			throw new EE_Error(
3902
+				sprintf(
3903
+					__(
3904
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3905
+						"event_espresso"
3906
+					),
3907
+					$query_param,
3908
+					get_class($this),
3909
+					$query_param_type,
3910
+					$original_query_param
3911
+				)
3912
+			);
3913
+		}
3914
+		// check if this is a special logic query param
3915
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3916
+			if ($allow_logic_query_params) {
3917
+				return;
3918
+			}
3919
+			throw new EE_Error(
3920
+				sprintf(
3921
+					__(
3922
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3923
+						'event_espresso'
3924
+					),
3925
+					implode('", "', $this->_logic_query_param_keys),
3926
+					$query_param,
3927
+					get_class($this),
3928
+					'<br />',
3929
+					"\t"
3930
+					. ' $passed_in_query_info = <pre>'
3931
+					. print_r($passed_in_query_info, true)
3932
+					. '</pre>'
3933
+					. "\n\t"
3934
+					. ' $query_param_type = '
3935
+					. $query_param_type
3936
+					. "\n\t"
3937
+					. ' $original_query_param = '
3938
+					. $original_query_param
3939
+				)
3940
+			);
3941
+		}
3942
+		// check if it's a custom selection
3943
+		if ($this->_custom_selections instanceof CustomSelects
3944
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3945
+		) {
3946
+			return;
3947
+		}
3948
+		// check if has a model name at the beginning
3949
+		// and
3950
+		// check if it's a field on a related model
3951
+		if ($this->extractJoinModelFromQueryParams(
3952
+			$passed_in_query_info,
3953
+			$query_param,
3954
+			$original_query_param,
3955
+			$query_param_type
3956
+		)) {
3957
+			return;
3958
+		}
3959
+
3960
+		// ok so $query_param didn't start with a model name
3961
+		// and we previously confirmed it wasn't a logic query param or field on the current model
3962
+		// it's wack, that's what it is
3963
+		throw new EE_Error(
3964
+			sprintf(
3965
+				esc_html__(
3966
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3967
+					"event_espresso"
3968
+				),
3969
+				$query_param,
3970
+				get_class($this),
3971
+				$query_param_type,
3972
+				$original_query_param
3973
+			)
3974
+		);
3975
+	}
3976
+
3977
+
3978
+	/**
3979
+	 * Extracts any possible join model information from the provided possible_join_string.
3980
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
3981
+	 * parts that should be added to the query.
3982
+	 *
3983
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3984
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
3985
+	 * @param null|string                 $original_query_param
3986
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
3987
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
3988
+	 * @return bool  returns true if a join was added and false if not.
3989
+	 * @throws EE_Error
3990
+	 */
3991
+	private function extractJoinModelFromQueryParams(
3992
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3993
+		$possible_join_string,
3994
+		$original_query_param,
3995
+		$query_parameter_type
3996
+	) {
3997
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3998
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
3999
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4000
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4001
+				if ($possible_join_string === '') {
4002
+					// nothing left to $query_param
4003
+					// we should actually end in a field name, not a model like this!
4004
+					throw new EE_Error(
4005
+						sprintf(
4006
+							esc_html__(
4007
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4008
+								"event_espresso"
4009
+							),
4010
+							$possible_join_string,
4011
+							$query_parameter_type,
4012
+							get_class($this),
4013
+							$valid_related_model_name
4014
+						)
4015
+					);
4016
+				}
4017
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4018
+				$related_model_obj->_extract_related_model_info_from_query_param(
4019
+					$possible_join_string,
4020
+					$query_info_carrier,
4021
+					$query_parameter_type,
4022
+					$original_query_param
4023
+				);
4024
+				return true;
4025
+			}
4026
+			if ($possible_join_string === $valid_related_model_name) {
4027
+				$this->_add_join_to_model(
4028
+					$valid_related_model_name,
4029
+					$query_info_carrier,
4030
+					$original_query_param
4031
+				);
4032
+				return true;
4033
+			}
4034
+		}
4035
+		return false;
4036
+	}
4037
+
4038
+
4039
+	/**
4040
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4041
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4042
+	 * @throws EE_Error
4043
+	 */
4044
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4045
+	{
4046
+		if ($this->_custom_selections instanceof CustomSelects
4047
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4048
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4049
+			)
4050
+		) {
4051
+			$original_selects = $this->_custom_selections->originalSelects();
4052
+			foreach ($original_selects as $alias => $select_configuration) {
4053
+				$this->extractJoinModelFromQueryParams(
4054
+					$query_info_carrier,
4055
+					$select_configuration[0],
4056
+					$select_configuration[0],
4057
+					'custom_selects'
4058
+				);
4059
+			}
4060
+		}
4061
+	}
4062
+
4063
+
4064
+
4065
+	/**
4066
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4067
+	 * and store it on $passed_in_query_info
4068
+	 *
4069
+	 * @param string                      $model_name
4070
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4071
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4072
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4073
+	 *                                                          and are adding a join to 'Payment' with the original
4074
+	 *                                                          query param key
4075
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4076
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4077
+	 *                                                          Payment wants to add default query params so that it
4078
+	 *                                                          will know what models to prepend onto its default query
4079
+	 *                                                          params or in case it wants to rename tables (in case
4080
+	 *                                                          there are multiple joins to the same table)
4081
+	 * @return void
4082
+	 * @throws EE_Error
4083
+	 */
4084
+	private function _add_join_to_model(
4085
+		$model_name,
4086
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4087
+		$original_query_param
4088
+	) {
4089
+		$relation_obj = $this->related_settings_for($model_name);
4090
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4091
+		// check if the relation is HABTM, because then we're essentially doing two joins
4092
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4093
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4094
+			$join_model_obj = $relation_obj->get_join_model();
4095
+			// replace the model specified with the join model for this relation chain, whi
4096
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4097
+				$model_name,
4098
+				$join_model_obj->get_this_model_name(),
4099
+				$model_relation_chain
4100
+			);
4101
+			$passed_in_query_info->merge(
4102
+				new EE_Model_Query_Info_Carrier(
4103
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4104
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4105
+				)
4106
+			);
4107
+		}
4108
+		// now just join to the other table pointed to by the relation object, and add its data types
4109
+		$passed_in_query_info->merge(
4110
+			new EE_Model_Query_Info_Carrier(
4111
+				array($model_relation_chain => $model_name),
4112
+				$relation_obj->get_join_statement($model_relation_chain)
4113
+			)
4114
+		);
4115
+	}
4116
+
4117
+
4118
+
4119
+	/**
4120
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4121
+	 *
4122
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4123
+	 * @return string of SQL
4124
+	 * @throws EE_Error
4125
+	 */
4126
+	private function _construct_where_clause($where_params)
4127
+	{
4128
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4129
+		if ($SQL) {
4130
+			return " WHERE " . $SQL;
4131
+		}
4132
+		return '';
4133
+	}
4134
+
4135
+
4136
+
4137
+	/**
4138
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4139
+	 * and should be passed HAVING parameters, not WHERE parameters
4140
+	 *
4141
+	 * @param array $having_params
4142
+	 * @return string
4143
+	 * @throws EE_Error
4144
+	 */
4145
+	private function _construct_having_clause($having_params)
4146
+	{
4147
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4148
+		if ($SQL) {
4149
+			return " HAVING " . $SQL;
4150
+		}
4151
+		return '';
4152
+	}
4153
+
4154
+
4155
+	/**
4156
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4157
+	 * Event_Meta.meta_value = 'foo'))"
4158
+	 *
4159
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4160
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4161
+	 * @throws EE_Error
4162
+	 * @return string of SQL
4163
+	 */
4164
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4165
+	{
4166
+		$where_clauses = array();
4167
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4168
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4169
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4170
+				switch ($query_param) {
4171
+					case 'not':
4172
+					case 'NOT':
4173
+						$where_clauses[] = "! ("
4174
+										   . $this->_construct_condition_clause_recursive(
4175
+											   $op_and_value_or_sub_condition,
4176
+											   $glue
4177
+										   )
4178
+										   . ")";
4179
+						break;
4180
+					case 'and':
4181
+					case 'AND':
4182
+						$where_clauses[] = " ("
4183
+										   . $this->_construct_condition_clause_recursive(
4184
+											   $op_and_value_or_sub_condition,
4185
+											   ' AND '
4186
+										   )
4187
+										   . ")";
4188
+						break;
4189
+					case 'or':
4190
+					case 'OR':
4191
+						$where_clauses[] = " ("
4192
+										   . $this->_construct_condition_clause_recursive(
4193
+											   $op_and_value_or_sub_condition,
4194
+											   ' OR '
4195
+										   )
4196
+										   . ")";
4197
+						break;
4198
+				}
4199
+			} else {
4200
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4201
+				// if it's not a normal field, maybe it's a custom selection?
4202
+				if (! $field_obj) {
4203
+					if ($this->_custom_selections instanceof CustomSelects) {
4204
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4205
+					} else {
4206
+						throw new EE_Error(sprintf(__(
4207
+							"%s is neither a valid model field name, nor a custom selection",
4208
+							"event_espresso"
4209
+						), $query_param));
4210
+					}
4211
+				}
4212
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4213
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4214
+			}
4215
+		}
4216
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4217
+	}
4218
+
4219
+
4220
+
4221
+	/**
4222
+	 * Takes the input parameter and extract the table name (alias) and column name
4223
+	 *
4224
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4225
+	 * @throws EE_Error
4226
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4227
+	 */
4228
+	private function _deduce_column_name_from_query_param($query_param)
4229
+	{
4230
+		$field = $this->_deduce_field_from_query_param($query_param);
4231
+		if ($field) {
4232
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4233
+				$field->get_model_name(),
4234
+				$query_param
4235
+			);
4236
+			return $table_alias_prefix . $field->get_qualified_column();
4237
+		}
4238
+		if ($this->_custom_selections instanceof CustomSelects
4239
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4240
+		) {
4241
+			// maybe it's custom selection item?
4242
+			// if so, just use it as the "column name"
4243
+			return $query_param;
4244
+		}
4245
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4246
+			? implode(',', $this->_custom_selections->columnAliases())
4247
+			: '';
4248
+		throw new EE_Error(
4249
+			sprintf(
4250
+				__(
4251
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4252
+					"event_espresso"
4253
+				),
4254
+				$query_param,
4255
+				$custom_select_aliases
4256
+			)
4257
+		);
4258
+	}
4259
+
4260
+
4261
+
4262
+	/**
4263
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4264
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4265
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4266
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4267
+	 *
4268
+	 * @param string $condition_query_param_key
4269
+	 * @return string
4270
+	 */
4271
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4272
+	{
4273
+		$pos_of_star = strpos($condition_query_param_key, '*');
4274
+		if ($pos_of_star === false) {
4275
+			return $condition_query_param_key;
4276
+		}
4277
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4278
+		return $condition_query_param_sans_star;
4279
+	}
4280
+
4281
+
4282
+
4283
+	/**
4284
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4285
+	 *
4286
+	 * @param                            mixed      array | string    $op_and_value
4287
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4288
+	 * @throws EE_Error
4289
+	 * @return string
4290
+	 */
4291
+	private function _construct_op_and_value($op_and_value, $field_obj)
4292
+	{
4293
+		if (is_array($op_and_value)) {
4294
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4295
+			if (! $operator) {
4296
+				$php_array_like_string = array();
4297
+				foreach ($op_and_value as $key => $value) {
4298
+					$php_array_like_string[] = "$key=>$value";
4299
+				}
4300
+				throw new EE_Error(
4301
+					sprintf(
4302
+						__(
4303
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4304
+							"event_espresso"
4305
+						),
4306
+						implode(",", $php_array_like_string)
4307
+					)
4308
+				);
4309
+			}
4310
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4311
+		} else {
4312
+			$operator = '=';
4313
+			$value = $op_and_value;
4314
+		}
4315
+		// check to see if the value is actually another field
4316
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4317
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4318
+		}
4319
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4320
+			// in this case, the value should be an array, or at least a comma-separated list
4321
+			// it will need to handle a little differently
4322
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4323
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4324
+			return $operator . SP . $cleaned_value;
4325
+		}
4326
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4327
+			// the value should be an array with count of two.
4328
+			if (count($value) !== 2) {
4329
+				throw new EE_Error(
4330
+					sprintf(
4331
+						__(
4332
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4333
+							'event_espresso'
4334
+						),
4335
+						"BETWEEN"
4336
+					)
4337
+				);
4338
+			}
4339
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4340
+			return $operator . SP . $cleaned_value;
4341
+		}
4342
+		if (in_array($operator, $this->valid_null_style_operators())) {
4343
+			if ($value !== null) {
4344
+				throw new EE_Error(
4345
+					sprintf(
4346
+						__(
4347
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4348
+							"event_espresso"
4349
+						),
4350
+						$value,
4351
+						$operator
4352
+					)
4353
+				);
4354
+			}
4355
+			return $operator;
4356
+		}
4357
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4358
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4359
+			// remove other junk. So just treat it as a string.
4360
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4361
+		}
4362
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4363
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4364
+		}
4365
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4366
+			throw new EE_Error(
4367
+				sprintf(
4368
+					__(
4369
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4370
+						'event_espresso'
4371
+					),
4372
+					$operator,
4373
+					$operator
4374
+				)
4375
+			);
4376
+		}
4377
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4378
+			throw new EE_Error(
4379
+				sprintf(
4380
+					__(
4381
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4382
+						'event_espresso'
4383
+					),
4384
+					$operator,
4385
+					$operator
4386
+				)
4387
+			);
4388
+		}
4389
+		throw new EE_Error(
4390
+			sprintf(
4391
+				__(
4392
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4393
+					"event_espresso"
4394
+				),
4395
+				http_build_query($op_and_value)
4396
+			)
4397
+		);
4398
+	}
4399
+
4400
+
4401
+
4402
+	/**
4403
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4404
+	 *
4405
+	 * @param array                      $values
4406
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4407
+	 *                                              '%s'
4408
+	 * @return string
4409
+	 * @throws EE_Error
4410
+	 */
4411
+	public function _construct_between_value($values, $field_obj)
4412
+	{
4413
+		$cleaned_values = array();
4414
+		foreach ($values as $value) {
4415
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4416
+		}
4417
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4418
+	}
4419
+
4420
+
4421
+
4422
+	/**
4423
+	 * Takes an array or a comma-separated list of $values and cleans them
4424
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4425
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4426
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4427
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4428
+	 *
4429
+	 * @param mixed                      $values    array or comma-separated string
4430
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4431
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4432
+	 * @throws EE_Error
4433
+	 */
4434
+	public function _construct_in_value($values, $field_obj)
4435
+	{
4436
+		// check if the value is a CSV list
4437
+		if (is_string($values)) {
4438
+			// in which case, turn it into an array
4439
+			$values = explode(",", $values);
4440
+		}
4441
+		$cleaned_values = array();
4442
+		foreach ($values as $value) {
4443
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4444
+		}
4445
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4446
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4447
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4448
+		if (empty($cleaned_values)) {
4449
+			$all_fields = $this->field_settings();
4450
+			$a_field = array_shift($all_fields);
4451
+			$main_table = $this->_get_main_table();
4452
+			$cleaned_values[] = "SELECT "
4453
+								. $a_field->get_table_column()
4454
+								. " FROM "
4455
+								. $main_table->get_table_name()
4456
+								. " WHERE FALSE";
4457
+		}
4458
+		return "(" . implode(",", $cleaned_values) . ")";
4459
+	}
4460
+
4461
+
4462
+
4463
+	/**
4464
+	 * @param mixed                      $value
4465
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4466
+	 * @throws EE_Error
4467
+	 * @return false|null|string
4468
+	 */
4469
+	private function _wpdb_prepare_using_field($value, $field_obj)
4470
+	{
4471
+		/** @type WPDB $wpdb */
4472
+		global $wpdb;
4473
+		if ($field_obj instanceof EE_Model_Field_Base) {
4474
+			return $wpdb->prepare(
4475
+				$field_obj->get_wpdb_data_type(),
4476
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4477
+			);
4478
+		} //$field_obj should really just be a data type
4479
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4480
+			throw new EE_Error(
4481
+				sprintf(
4482
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4483
+					$field_obj,
4484
+					implode(",", $this->_valid_wpdb_data_types)
4485
+				)
4486
+			);
4487
+		}
4488
+		return $wpdb->prepare($field_obj, $value);
4489
+	}
4490
+
4491
+
4492
+
4493
+	/**
4494
+	 * Takes the input parameter and finds the model field that it indicates.
4495
+	 *
4496
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4497
+	 * @throws EE_Error
4498
+	 * @return EE_Model_Field_Base
4499
+	 */
4500
+	protected function _deduce_field_from_query_param($query_param_name)
4501
+	{
4502
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4503
+		// which will help us find the database table and column
4504
+		$query_param_parts = explode(".", $query_param_name);
4505
+		if (empty($query_param_parts)) {
4506
+			throw new EE_Error(sprintf(__(
4507
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4508
+				'event_espresso'
4509
+			), $query_param_name));
4510
+		}
4511
+		$number_of_parts = count($query_param_parts);
4512
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4513
+		if ($number_of_parts === 1) {
4514
+			$field_name = $last_query_param_part;
4515
+			$model_obj = $this;
4516
+		} else {// $number_of_parts >= 2
4517
+			// the last part is the column name, and there are only 2parts. therefore...
4518
+			$field_name = $last_query_param_part;
4519
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4520
+		}
4521
+		try {
4522
+			return $model_obj->field_settings_for($field_name);
4523
+		} catch (EE_Error $e) {
4524
+			return null;
4525
+		}
4526
+	}
4527
+
4528
+
4529
+
4530
+	/**
4531
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4532
+	 * alias and column which corresponds to it
4533
+	 *
4534
+	 * @param string $field_name
4535
+	 * @throws EE_Error
4536
+	 * @return string
4537
+	 */
4538
+	public function _get_qualified_column_for_field($field_name)
4539
+	{
4540
+		$all_fields = $this->field_settings();
4541
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4542
+		if ($field) {
4543
+			return $field->get_qualified_column();
4544
+		}
4545
+		throw new EE_Error(
4546
+			sprintf(
4547
+				__(
4548
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4549
+					'event_espresso'
4550
+				),
4551
+				$field_name,
4552
+				get_class($this)
4553
+			)
4554
+		);
4555
+	}
4556
+
4557
+
4558
+
4559
+	/**
4560
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4561
+	 * Example usage:
4562
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4563
+	 *      array(),
4564
+	 *      ARRAY_A,
4565
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4566
+	 *  );
4567
+	 * is equivalent to
4568
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4569
+	 * and
4570
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4571
+	 *      array(
4572
+	 *          array(
4573
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4574
+	 *          ),
4575
+	 *          ARRAY_A,
4576
+	 *          implode(
4577
+	 *              ', ',
4578
+	 *              array_merge(
4579
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4580
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4581
+	 *              )
4582
+	 *          )
4583
+	 *      )
4584
+	 *  );
4585
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4586
+	 *
4587
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4588
+	 *                                            and the one whose fields you are selecting for example: when querying
4589
+	 *                                            tickets model and selecting fields from the tickets model you would
4590
+	 *                                            leave this parameter empty, because no models are needed to join
4591
+	 *                                            between the queried model and the selected one. Likewise when
4592
+	 *                                            querying the datetime model and selecting fields from the tickets
4593
+	 *                                            model, it would also be left empty, because there is a direct
4594
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4595
+	 *                                            them together. However, when querying from the event model and
4596
+	 *                                            selecting fields from the ticket model, you should provide the string
4597
+	 *                                            'Datetime', indicating that the event model must first join to the
4598
+	 *                                            datetime model in order to find its relation to ticket model.
4599
+	 *                                            Also, when querying from the venue model and selecting fields from
4600
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4601
+	 *                                            indicating you need to join the venue model to the event model,
4602
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4603
+	 *                                            This string is used to deduce the prefix that gets added onto the
4604
+	 *                                            models' tables qualified columns
4605
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4606
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4607
+	 *                                            qualified column names
4608
+	 * @return array|string
4609
+	 */
4610
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4611
+	{
4612
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4613
+		$qualified_columns = array();
4614
+		foreach ($this->field_settings() as $field_name => $field) {
4615
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4616
+		}
4617
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4618
+	}
4619
+
4620
+
4621
+
4622
+	/**
4623
+	 * constructs the select use on special limit joins
4624
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4625
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4626
+	 * (as that is typically where the limits would be set).
4627
+	 *
4628
+	 * @param  string       $table_alias The table the select is being built for
4629
+	 * @param  mixed|string $limit       The limit for this select
4630
+	 * @return string                The final select join element for the query.
4631
+	 */
4632
+	public function _construct_limit_join_select($table_alias, $limit)
4633
+	{
4634
+		$SQL = '';
4635
+		foreach ($this->_tables as $table_obj) {
4636
+			if ($table_obj instanceof EE_Primary_Table) {
4637
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4638
+					? $table_obj->get_select_join_limit($limit)
4639
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4640
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4641
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4642
+					? $table_obj->get_select_join_limit_join($limit)
4643
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4644
+			}
4645
+		}
4646
+		return $SQL;
4647
+	}
4648
+
4649
+
4650
+
4651
+	/**
4652
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4653
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4654
+	 *
4655
+	 * @return string SQL
4656
+	 * @throws EE_Error
4657
+	 */
4658
+	public function _construct_internal_join()
4659
+	{
4660
+		$SQL = $this->_get_main_table()->get_table_sql();
4661
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4662
+		return $SQL;
4663
+	}
4664
+
4665
+
4666
+
4667
+	/**
4668
+	 * Constructs the SQL for joining all the tables on this model.
4669
+	 * Normally $alias should be the primary table's alias, but in cases where
4670
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4671
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4672
+	 * alias, this will construct SQL like:
4673
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4674
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4675
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4676
+	 *
4677
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4678
+	 * @return string
4679
+	 */
4680
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4681
+	{
4682
+		$SQL = '';
4683
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4684
+		foreach ($this->_tables as $table_obj) {
4685
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4686
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4687
+					// so we're joining to this table, meaning the table is already in
4688
+					// the FROM statement, BUT the primary table isn't. So we want
4689
+					// to add the inverse join sql
4690
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4691
+				} else {
4692
+					// just add a regular JOIN to this table from the primary table
4693
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4694
+				}
4695
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4696
+		}
4697
+		return $SQL;
4698
+	}
4699
+
4700
+
4701
+
4702
+	/**
4703
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4704
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4705
+	 * their data type (eg, '%s', '%d', etc)
4706
+	 *
4707
+	 * @return array
4708
+	 */
4709
+	public function _get_data_types()
4710
+	{
4711
+		$data_types = array();
4712
+		foreach ($this->field_settings() as $field_obj) {
4713
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4714
+			/** @var $field_obj EE_Model_Field_Base */
4715
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4716
+		}
4717
+		return $data_types;
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4724
+	 *
4725
+	 * @param string $model_name
4726
+	 * @throws EE_Error
4727
+	 * @return EEM_Base
4728
+	 */
4729
+	public function get_related_model_obj($model_name)
4730
+	{
4731
+		$model_classname = "EEM_" . $model_name;
4732
+		if (! class_exists($model_classname)) {
4733
+			throw new EE_Error(sprintf(__(
4734
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4735
+				'event_espresso'
4736
+			), $model_name, $model_classname));
4737
+		}
4738
+		return call_user_func($model_classname . "::instance");
4739
+	}
4740
+
4741
+
4742
+
4743
+	/**
4744
+	 * Returns the array of EE_ModelRelations for this model.
4745
+	 *
4746
+	 * @return EE_Model_Relation_Base[]
4747
+	 */
4748
+	public function relation_settings()
4749
+	{
4750
+		return $this->_model_relations;
4751
+	}
4752
+
4753
+
4754
+
4755
+	/**
4756
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4757
+	 * because without THOSE models, this model probably doesn't have much purpose.
4758
+	 * (Eg, without an event, datetimes have little purpose.)
4759
+	 *
4760
+	 * @return EE_Belongs_To_Relation[]
4761
+	 */
4762
+	public function belongs_to_relations()
4763
+	{
4764
+		$belongs_to_relations = array();
4765
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4766
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4767
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4768
+			}
4769
+		}
4770
+		return $belongs_to_relations;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Returns the specified EE_Model_Relation, or throws an exception
4777
+	 *
4778
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4779
+	 * @throws EE_Error
4780
+	 * @return EE_Model_Relation_Base
4781
+	 */
4782
+	public function related_settings_for($relation_name)
4783
+	{
4784
+		$relatedModels = $this->relation_settings();
4785
+		if (! array_key_exists($relation_name, $relatedModels)) {
4786
+			throw new EE_Error(
4787
+				sprintf(
4788
+					__(
4789
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4790
+						'event_espresso'
4791
+					),
4792
+					$relation_name,
4793
+					$this->_get_class_name(),
4794
+					implode(', ', array_keys($relatedModels))
4795
+				)
4796
+			);
4797
+		}
4798
+		return $relatedModels[ $relation_name ];
4799
+	}
4800
+
4801
+
4802
+
4803
+	/**
4804
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4805
+	 * fields
4806
+	 *
4807
+	 * @param string $fieldName
4808
+	 * @param boolean $include_db_only_fields
4809
+	 * @throws EE_Error
4810
+	 * @return EE_Model_Field_Base
4811
+	 */
4812
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4813
+	{
4814
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4815
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4816
+			throw new EE_Error(sprintf(
4817
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4818
+				$fieldName,
4819
+				get_class($this)
4820
+			));
4821
+		}
4822
+		return $fieldSettings[ $fieldName ];
4823
+	}
4824
+
4825
+
4826
+
4827
+	/**
4828
+	 * Checks if this field exists on this model
4829
+	 *
4830
+	 * @param string $fieldName a key in the model's _field_settings array
4831
+	 * @return boolean
4832
+	 */
4833
+	public function has_field($fieldName)
4834
+	{
4835
+		$fieldSettings = $this->field_settings(true);
4836
+		if (isset($fieldSettings[ $fieldName ])) {
4837
+			return true;
4838
+		}
4839
+		return false;
4840
+	}
4841
+
4842
+
4843
+
4844
+	/**
4845
+	 * Returns whether or not this model has a relation to the specified model
4846
+	 *
4847
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4848
+	 * @return boolean
4849
+	 */
4850
+	public function has_relation($relation_name)
4851
+	{
4852
+		$relations = $this->relation_settings();
4853
+		if (isset($relations[ $relation_name ])) {
4854
+			return true;
4855
+		}
4856
+		return false;
4857
+	}
4858
+
4859
+
4860
+
4861
+	/**
4862
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4863
+	 * Eg, on EE_Answer that would be ANS_ID field object
4864
+	 *
4865
+	 * @param $field_obj
4866
+	 * @return boolean
4867
+	 */
4868
+	public function is_primary_key_field($field_obj)
4869
+	{
4870
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4871
+	}
4872
+
4873
+
4874
+
4875
+	/**
4876
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4877
+	 * Eg, on EE_Answer that would be ANS_ID field object
4878
+	 *
4879
+	 * @return EE_Model_Field_Base
4880
+	 * @throws EE_Error
4881
+	 */
4882
+	public function get_primary_key_field()
4883
+	{
4884
+		if ($this->_primary_key_field === null) {
4885
+			foreach ($this->field_settings(true) as $field_obj) {
4886
+				if ($this->is_primary_key_field($field_obj)) {
4887
+					$this->_primary_key_field = $field_obj;
4888
+					break;
4889
+				}
4890
+			}
4891
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4892
+				throw new EE_Error(sprintf(
4893
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4894
+					get_class($this)
4895
+				));
4896
+			}
4897
+		}
4898
+		return $this->_primary_key_field;
4899
+	}
4900
+
4901
+
4902
+
4903
+	/**
4904
+	 * Returns whether or not not there is a primary key on this model.
4905
+	 * Internally does some caching.
4906
+	 *
4907
+	 * @return boolean
4908
+	 */
4909
+	public function has_primary_key_field()
4910
+	{
4911
+		if ($this->_has_primary_key_field === null) {
4912
+			try {
4913
+				$this->get_primary_key_field();
4914
+				$this->_has_primary_key_field = true;
4915
+			} catch (EE_Error $e) {
4916
+				$this->_has_primary_key_field = false;
4917
+			}
4918
+		}
4919
+		return $this->_has_primary_key_field;
4920
+	}
4921
+
4922
+
4923
+
4924
+	/**
4925
+	 * Finds the first field of type $field_class_name.
4926
+	 *
4927
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4928
+	 *                                 EE_Foreign_Key_Field, etc
4929
+	 * @return EE_Model_Field_Base or null if none is found
4930
+	 */
4931
+	public function get_a_field_of_type($field_class_name)
4932
+	{
4933
+		foreach ($this->field_settings() as $field) {
4934
+			if ($field instanceof $field_class_name) {
4935
+				return $field;
4936
+			}
4937
+		}
4938
+		return null;
4939
+	}
4940
+
4941
+
4942
+
4943
+	/**
4944
+	 * Gets a foreign key field pointing to model.
4945
+	 *
4946
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4947
+	 * @return EE_Foreign_Key_Field_Base
4948
+	 * @throws EE_Error
4949
+	 */
4950
+	public function get_foreign_key_to($model_name)
4951
+	{
4952
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4953
+			foreach ($this->field_settings() as $field) {
4954
+				if ($field instanceof EE_Foreign_Key_Field_Base
4955
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4956
+				) {
4957
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
4958
+					break;
4959
+				}
4960
+			}
4961
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
4962
+				throw new EE_Error(sprintf(__(
4963
+					"There is no foreign key field pointing to model %s on model %s",
4964
+					'event_espresso'
4965
+				), $model_name, get_class($this)));
4966
+			}
4967
+		}
4968
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
4969
+	}
4970
+
4971
+
4972
+
4973
+	/**
4974
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4975
+	 *
4976
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4977
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4978
+	 *                            Either one works
4979
+	 * @return string
4980
+	 */
4981
+	public function get_table_for_alias($table_alias)
4982
+	{
4983
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4984
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
4985
+	}
4986
+
4987
+
4988
+
4989
+	/**
4990
+	 * Returns a flat array of all field son this model, instead of organizing them
4991
+	 * by table_alias as they are in the constructor.
4992
+	 *
4993
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4994
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4995
+	 */
4996
+	public function field_settings($include_db_only_fields = false)
4997
+	{
4998
+		if ($include_db_only_fields) {
4999
+			if ($this->_cached_fields === null) {
5000
+				$this->_cached_fields = array();
5001
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5002
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5003
+						$this->_cached_fields[ $field_name ] = $field_obj;
5004
+					}
5005
+				}
5006
+			}
5007
+			return $this->_cached_fields;
5008
+		}
5009
+		if ($this->_cached_fields_non_db_only === null) {
5010
+			$this->_cached_fields_non_db_only = array();
5011
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5012
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5013
+					/** @var $field_obj EE_Model_Field_Base */
5014
+					if (! $field_obj->is_db_only_field()) {
5015
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5016
+					}
5017
+				}
5018
+			}
5019
+		}
5020
+		return $this->_cached_fields_non_db_only;
5021
+	}
5022
+
5023
+
5024
+
5025
+	/**
5026
+	 *        cycle though array of attendees and create objects out of each item
5027
+	 *
5028
+	 * @access        private
5029
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5030
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5031
+	 *                           numerically indexed)
5032
+	 * @throws EE_Error
5033
+	 */
5034
+	protected function _create_objects($rows = array())
5035
+	{
5036
+		$array_of_objects = array();
5037
+		if (empty($rows)) {
5038
+			return array();
5039
+		}
5040
+		$count_if_model_has_no_primary_key = 0;
5041
+		$has_primary_key = $this->has_primary_key_field();
5042
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5043
+		foreach ((array) $rows as $row) {
5044
+			if (empty($row)) {
5045
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5046
+				return array();
5047
+			}
5048
+			// check if we've already set this object in the results array,
5049
+			// in which case there's no need to process it further (again)
5050
+			if ($has_primary_key) {
5051
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5052
+					$row,
5053
+					$primary_key_field->get_qualified_column(),
5054
+					$primary_key_field->get_table_column()
5055
+				);
5056
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5057
+					continue;
5058
+				}
5059
+			}
5060
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5061
+			if (! $classInstance) {
5062
+				throw new EE_Error(
5063
+					sprintf(
5064
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5065
+						$this->get_this_model_name(),
5066
+						http_build_query($row)
5067
+					)
5068
+				);
5069
+			}
5070
+			// set the timezone on the instantiated objects
5071
+			$classInstance->set_timezone($this->_timezone);
5072
+			// make sure if there is any timezone setting present that we set the timezone for the object
5073
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5074
+			$array_of_objects[ $key ] = $classInstance;
5075
+			// also, for all the relations of type BelongsTo, see if we can cache
5076
+			// those related models
5077
+			// (we could do this for other relations too, but if there are conditions
5078
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5079
+			// so it requires a little more thought than just caching them immediately...)
5080
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5081
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5082
+					// check if this model's INFO is present. If so, cache it on the model
5083
+					$other_model = $relation_obj->get_other_model();
5084
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5085
+					// if we managed to make a model object from the results, cache it on the main model object
5086
+					if ($other_model_obj_maybe) {
5087
+						// set timezone on these other model objects if they are present
5088
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5089
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5090
+					}
5091
+				}
5092
+			}
5093
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5094
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5095
+			// the field in the CustomSelects object
5096
+			if ($this->_custom_selections instanceof CustomSelects) {
5097
+				$classInstance->setCustomSelectsValues(
5098
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5099
+				);
5100
+			}
5101
+		}
5102
+		return $array_of_objects;
5103
+	}
5104
+
5105
+
5106
+	/**
5107
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5108
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5109
+	 *
5110
+	 * @param array $db_results_row
5111
+	 * @return array
5112
+	 */
5113
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5114
+	{
5115
+		$results = array();
5116
+		if ($this->_custom_selections instanceof CustomSelects) {
5117
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5118
+				if (isset($db_results_row[ $alias ])) {
5119
+					$results[ $alias ] = $this->convertValueToDataType(
5120
+						$db_results_row[ $alias ],
5121
+						$this->_custom_selections->getDataTypeForAlias($alias)
5122
+					);
5123
+				}
5124
+			}
5125
+		}
5126
+		return $results;
5127
+	}
5128
+
5129
+
5130
+	/**
5131
+	 * This will set the value for the given alias
5132
+	 * @param string $value
5133
+	 * @param string $datatype (one of %d, %s, %f)
5134
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5135
+	 */
5136
+	protected function convertValueToDataType($value, $datatype)
5137
+	{
5138
+		switch ($datatype) {
5139
+			case '%f':
5140
+				return (float) $value;
5141
+			case '%d':
5142
+				return (int) $value;
5143
+			default:
5144
+				return (string) $value;
5145
+		}
5146
+	}
5147
+
5148
+
5149
+	/**
5150
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5151
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5152
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5153
+	 * object (as set in the model_field!).
5154
+	 *
5155
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5156
+	 */
5157
+	public function create_default_object()
5158
+	{
5159
+		$this_model_fields_and_values = array();
5160
+		// setup the row using default values;
5161
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5162
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5163
+		}
5164
+		$className = $this->_get_class_name();
5165
+		$classInstance = EE_Registry::instance()
5166
+									->load_class($className, array($this_model_fields_and_values), false, false);
5167
+		return $classInstance;
5168
+	}
5169
+
5170
+
5171
+
5172
+	/**
5173
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5174
+	 *                             or an stdClass where each property is the name of a column,
5175
+	 * @return EE_Base_Class
5176
+	 * @throws EE_Error
5177
+	 */
5178
+	public function instantiate_class_from_array_or_object($cols_n_values)
5179
+	{
5180
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5181
+			$cols_n_values = get_object_vars($cols_n_values);
5182
+		}
5183
+		$primary_key = null;
5184
+		// make sure the array only has keys that are fields/columns on this model
5185
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5186
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5187
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5188
+		}
5189
+		$className = $this->_get_class_name();
5190
+		// check we actually found results that we can use to build our model object
5191
+		// if not, return null
5192
+		if ($this->has_primary_key_field()) {
5193
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5194
+				return null;
5195
+			}
5196
+		} elseif ($this->unique_indexes()) {
5197
+			$first_column = reset($this_model_fields_n_values);
5198
+			if (empty($first_column)) {
5199
+				return null;
5200
+			}
5201
+		}
5202
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5203
+		if ($primary_key) {
5204
+			$classInstance = $this->get_from_entity_map($primary_key);
5205
+			if (! $classInstance) {
5206
+				$classInstance = EE_Registry::instance()
5207
+											->load_class(
5208
+												$className,
5209
+												array($this_model_fields_n_values, $this->_timezone),
5210
+												true,
5211
+												false
5212
+											);
5213
+				// add this new object to the entity map
5214
+				$classInstance = $this->add_to_entity_map($classInstance);
5215
+			}
5216
+		} else {
5217
+			$classInstance = EE_Registry::instance()
5218
+										->load_class(
5219
+											$className,
5220
+											array($this_model_fields_n_values, $this->_timezone),
5221
+											true,
5222
+											false
5223
+										);
5224
+		}
5225
+		return $classInstance;
5226
+	}
5227
+
5228
+
5229
+
5230
+	/**
5231
+	 * Gets the model object from the  entity map if it exists
5232
+	 *
5233
+	 * @param int|string $id the ID of the model object
5234
+	 * @return EE_Base_Class
5235
+	 */
5236
+	public function get_from_entity_map($id)
5237
+	{
5238
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5239
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5240
+	}
5241
+
5242
+
5243
+
5244
+	/**
5245
+	 * add_to_entity_map
5246
+	 * Adds the object to the model's entity mappings
5247
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5248
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5249
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5250
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5251
+	 *        then this method should be called immediately after the update query
5252
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5253
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5254
+	 *
5255
+	 * @param    EE_Base_Class $object
5256
+	 * @throws EE_Error
5257
+	 * @return \EE_Base_Class
5258
+	 */
5259
+	public function add_to_entity_map(EE_Base_Class $object)
5260
+	{
5261
+		$className = $this->_get_class_name();
5262
+		if (! $object instanceof $className) {
5263
+			throw new EE_Error(sprintf(
5264
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5265
+				is_object($object) ? get_class($object) : $object,
5266
+				$className
5267
+			));
5268
+		}
5269
+		/** @var $object EE_Base_Class */
5270
+		if (! $object->ID()) {
5271
+			throw new EE_Error(sprintf(__(
5272
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5273
+				"event_espresso"
5274
+			), get_class($this)));
5275
+		}
5276
+		// double check it's not already there
5277
+		$classInstance = $this->get_from_entity_map($object->ID());
5278
+		if ($classInstance) {
5279
+			return $classInstance;
5280
+		}
5281
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5282
+		return $object;
5283
+	}
5284
+
5285
+
5286
+
5287
+	/**
5288
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5289
+	 * if no identifier is provided, then the entire entity map is emptied
5290
+	 *
5291
+	 * @param int|string $id the ID of the model object
5292
+	 * @return boolean
5293
+	 */
5294
+	public function clear_entity_map($id = null)
5295
+	{
5296
+		if (empty($id)) {
5297
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5298
+			return true;
5299
+		}
5300
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5301
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5302
+			return true;
5303
+		}
5304
+		return false;
5305
+	}
5306
+
5307
+
5308
+
5309
+	/**
5310
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5311
+	 * Given an array where keys are column (or column alias) names and values,
5312
+	 * returns an array of their corresponding field names and database values
5313
+	 *
5314
+	 * @param array $cols_n_values
5315
+	 * @return array
5316
+	 */
5317
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5318
+	{
5319
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5320
+	}
5321
+
5322
+
5323
+
5324
+	/**
5325
+	 * _deduce_fields_n_values_from_cols_n_values
5326
+	 * Given an array where keys are column (or column alias) names and values,
5327
+	 * returns an array of their corresponding field names and database values
5328
+	 *
5329
+	 * @param string $cols_n_values
5330
+	 * @return array
5331
+	 */
5332
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5333
+	{
5334
+		$this_model_fields_n_values = array();
5335
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5336
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5337
+				$cols_n_values,
5338
+				$table_obj->get_fully_qualified_pk_column(),
5339
+				$table_obj->get_pk_column()
5340
+			);
5341
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5342
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5343
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5344
+					if (! $field_obj->is_db_only_field()) {
5345
+						// prepare field as if its coming from db
5346
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5347
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5348
+					}
5349
+				}
5350
+			} else {
5351
+				// the table's rows existed. Use their values
5352
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5353
+					if (! $field_obj->is_db_only_field()) {
5354
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5355
+							$cols_n_values,
5356
+							$field_obj->get_qualified_column(),
5357
+							$field_obj->get_table_column()
5358
+						);
5359
+					}
5360
+				}
5361
+			}
5362
+		}
5363
+		return $this_model_fields_n_values;
5364
+	}
5365
+
5366
+
5367
+
5368
+	/**
5369
+	 * @param $cols_n_values
5370
+	 * @param $qualified_column
5371
+	 * @param $regular_column
5372
+	 * @return null
5373
+	 */
5374
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5375
+	{
5376
+		$value = null;
5377
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5378
+		// does the field on the model relate to this column retrieved from the db?
5379
+		// or is it a db-only field? (not relating to the model)
5380
+		if (isset($cols_n_values[ $qualified_column ])) {
5381
+			$value = $cols_n_values[ $qualified_column ];
5382
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5383
+			$value = $cols_n_values[ $regular_column ];
5384
+		}
5385
+		return $value;
5386
+	}
5387
+
5388
+
5389
+
5390
+	/**
5391
+	 * refresh_entity_map_from_db
5392
+	 * Makes sure the model object in the entity map at $id assumes the values
5393
+	 * of the database (opposite of EE_base_Class::save())
5394
+	 *
5395
+	 * @param int|string $id
5396
+	 * @return EE_Base_Class
5397
+	 * @throws EE_Error
5398
+	 */
5399
+	public function refresh_entity_map_from_db($id)
5400
+	{
5401
+		$obj_in_map = $this->get_from_entity_map($id);
5402
+		if ($obj_in_map) {
5403
+			$wpdb_results = $this->_get_all_wpdb_results(
5404
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5405
+			);
5406
+			if ($wpdb_results && is_array($wpdb_results)) {
5407
+				$one_row = reset($wpdb_results);
5408
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5409
+					$obj_in_map->set_from_db($field_name, $db_value);
5410
+				}
5411
+				// clear the cache of related model objects
5412
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5413
+					$obj_in_map->clear_cache($relation_name, null, true);
5414
+				}
5415
+			}
5416
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5417
+			return $obj_in_map;
5418
+		}
5419
+		return $this->get_one_by_ID($id);
5420
+	}
5421
+
5422
+
5423
+
5424
+	/**
5425
+	 * refresh_entity_map_with
5426
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5427
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5428
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5429
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5430
+	 *
5431
+	 * @param int|string    $id
5432
+	 * @param EE_Base_Class $replacing_model_obj
5433
+	 * @return \EE_Base_Class
5434
+	 * @throws EE_Error
5435
+	 */
5436
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5437
+	{
5438
+		$obj_in_map = $this->get_from_entity_map($id);
5439
+		if ($obj_in_map) {
5440
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5441
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5442
+					$obj_in_map->set($field_name, $value);
5443
+				}
5444
+				// make the model object in the entity map's cache match the $replacing_model_obj
5445
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5446
+					$obj_in_map->clear_cache($relation_name, null, true);
5447
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5448
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5449
+					}
5450
+				}
5451
+			}
5452
+			return $obj_in_map;
5453
+		}
5454
+		$this->add_to_entity_map($replacing_model_obj);
5455
+		return $replacing_model_obj;
5456
+	}
5457
+
5458
+
5459
+
5460
+	/**
5461
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5462
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5463
+	 * require_once($this->_getClassName().".class.php");
5464
+	 *
5465
+	 * @return string
5466
+	 */
5467
+	private function _get_class_name()
5468
+	{
5469
+		return "EE_" . $this->get_this_model_name();
5470
+	}
5471
+
5472
+
5473
+
5474
+	/**
5475
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5476
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5477
+	 * it would be 'Events'.
5478
+	 *
5479
+	 * @param int $quantity
5480
+	 * @return string
5481
+	 */
5482
+	public function item_name($quantity = 1)
5483
+	{
5484
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5485
+	}
5486
+
5487
+
5488
+
5489
+	/**
5490
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5491
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5492
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5493
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5494
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5495
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5496
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5497
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5498
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5499
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5500
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5501
+	 *        return $previousReturnValue.$returnString;
5502
+	 * }
5503
+	 * require('EEM_Answer.model.php');
5504
+	 * $answer=EEM_Answer::instance();
5505
+	 * echo $answer->my_callback('monkeys',100);
5506
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5507
+	 *
5508
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5509
+	 * @param array  $args       array of original arguments passed to the function
5510
+	 * @throws EE_Error
5511
+	 * @return mixed whatever the plugin which calls add_filter decides
5512
+	 */
5513
+	public function __call($methodName, $args)
5514
+	{
5515
+		$className = get_class($this);
5516
+		$tagName = "FHEE__{$className}__{$methodName}";
5517
+		if (! has_filter($tagName)) {
5518
+			throw new EE_Error(
5519
+				sprintf(
5520
+					__(
5521
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5522
+						'event_espresso'
5523
+					),
5524
+					$methodName,
5525
+					$className,
5526
+					$tagName,
5527
+					'<br />'
5528
+				)
5529
+			);
5530
+		}
5531
+		return apply_filters($tagName, null, $this, $args);
5532
+	}
5533
+
5534
+
5535
+
5536
+	/**
5537
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5538
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5539
+	 *
5540
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5541
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5542
+	 *                                                       the object's class name
5543
+	 *                                                       or object's ID
5544
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5545
+	 *                                                       exists in the database. If it does not, we add it
5546
+	 * @throws EE_Error
5547
+	 * @return EE_Base_Class
5548
+	 */
5549
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5550
+	{
5551
+		$className = $this->_get_class_name();
5552
+		if ($base_class_obj_or_id instanceof $className) {
5553
+			$model_object = $base_class_obj_or_id;
5554
+		} else {
5555
+			$primary_key_field = $this->get_primary_key_field();
5556
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5557
+				&& (
5558
+					is_int($base_class_obj_or_id)
5559
+					|| is_string($base_class_obj_or_id)
5560
+				)
5561
+			) {
5562
+				// assume it's an ID.
5563
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5564
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5565
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5566
+				&& is_string($base_class_obj_or_id)
5567
+			) {
5568
+				// assume its a string representation of the object
5569
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5570
+			} else {
5571
+				throw new EE_Error(
5572
+					sprintf(
5573
+						__(
5574
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5575
+							'event_espresso'
5576
+						),
5577
+						$base_class_obj_or_id,
5578
+						$this->_get_class_name(),
5579
+						print_r($base_class_obj_or_id, true)
5580
+					)
5581
+				);
5582
+			}
5583
+		}
5584
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5585
+			$model_object->save();
5586
+		}
5587
+		return $model_object;
5588
+	}
5589
+
5590
+
5591
+
5592
+	/**
5593
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5594
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5595
+	 * returns it ID.
5596
+	 *
5597
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5598
+	 * @return int|string depending on the type of this model object's ID
5599
+	 * @throws EE_Error
5600
+	 */
5601
+	public function ensure_is_ID($base_class_obj_or_id)
5602
+	{
5603
+		$className = $this->_get_class_name();
5604
+		if ($base_class_obj_or_id instanceof $className) {
5605
+			/** @var $base_class_obj_or_id EE_Base_Class */
5606
+			$id = $base_class_obj_or_id->ID();
5607
+		} elseif (is_int($base_class_obj_or_id)) {
5608
+			// assume it's an ID
5609
+			$id = $base_class_obj_or_id;
5610
+		} elseif (is_string($base_class_obj_or_id)) {
5611
+			// assume its a string representation of the object
5612
+			$id = $base_class_obj_or_id;
5613
+		} else {
5614
+			throw new EE_Error(sprintf(
5615
+				__(
5616
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5617
+					'event_espresso'
5618
+				),
5619
+				$base_class_obj_or_id,
5620
+				$this->_get_class_name(),
5621
+				print_r($base_class_obj_or_id, true)
5622
+			));
5623
+		}
5624
+		return $id;
5625
+	}
5626
+
5627
+
5628
+
5629
+	/**
5630
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5631
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5632
+	 * been sanitized and converted into the appropriate domain.
5633
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5634
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5635
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5636
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5637
+	 * $EVT = EEM_Event::instance(); $old_setting =
5638
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5639
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5640
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5641
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5642
+	 *
5643
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5644
+	 * @return void
5645
+	 */
5646
+	public function assume_values_already_prepared_by_model_object(
5647
+		$values_already_prepared = self::not_prepared_by_model_object
5648
+	) {
5649
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5650
+	}
5651
+
5652
+
5653
+
5654
+	/**
5655
+	 * Read comments for assume_values_already_prepared_by_model_object()
5656
+	 *
5657
+	 * @return int
5658
+	 */
5659
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5660
+	{
5661
+		return $this->_values_already_prepared_by_model_object;
5662
+	}
5663
+
5664
+
5665
+
5666
+	/**
5667
+	 * Gets all the indexes on this model
5668
+	 *
5669
+	 * @return EE_Index[]
5670
+	 */
5671
+	public function indexes()
5672
+	{
5673
+		return $this->_indexes;
5674
+	}
5675
+
5676
+
5677
+
5678
+	/**
5679
+	 * Gets all the Unique Indexes on this model
5680
+	 *
5681
+	 * @return EE_Unique_Index[]
5682
+	 */
5683
+	public function unique_indexes()
5684
+	{
5685
+		$unique_indexes = array();
5686
+		foreach ($this->_indexes as $name => $index) {
5687
+			if ($index instanceof EE_Unique_Index) {
5688
+				$unique_indexes [ $name ] = $index;
5689
+			}
5690
+		}
5691
+		return $unique_indexes;
5692
+	}
5693
+
5694
+
5695
+
5696
+	/**
5697
+	 * Gets all the fields which, when combined, make the primary key.
5698
+	 * This is usually just an array with 1 element (the primary key), but in cases
5699
+	 * where there is no primary key, it's a combination of fields as defined
5700
+	 * on a primary index
5701
+	 *
5702
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5703
+	 * @throws EE_Error
5704
+	 */
5705
+	public function get_combined_primary_key_fields()
5706
+	{
5707
+		foreach ($this->indexes() as $index) {
5708
+			if ($index instanceof EE_Primary_Key_Index) {
5709
+				return $index->fields();
5710
+			}
5711
+		}
5712
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5713
+	}
5714
+
5715
+
5716
+
5717
+	/**
5718
+	 * Used to build a primary key string (when the model has no primary key),
5719
+	 * which can be used a unique string to identify this model object.
5720
+	 *
5721
+	 * @param array $cols_n_values keys are field names, values are their values
5722
+	 * @return string
5723
+	 * @throws EE_Error
5724
+	 */
5725
+	public function get_index_primary_key_string($cols_n_values)
5726
+	{
5727
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5728
+			$cols_n_values,
5729
+			$this->get_combined_primary_key_fields()
5730
+		);
5731
+		return http_build_query($cols_n_values_for_primary_key_index);
5732
+	}
5733
+
5734
+
5735
+
5736
+	/**
5737
+	 * Gets the field values from the primary key string
5738
+	 *
5739
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5740
+	 * @param string $index_primary_key_string
5741
+	 * @return null|array
5742
+	 * @throws EE_Error
5743
+	 */
5744
+	public function parse_index_primary_key_string($index_primary_key_string)
5745
+	{
5746
+		$key_fields = $this->get_combined_primary_key_fields();
5747
+		// check all of them are in the $id
5748
+		$key_vals_in_combined_pk = array();
5749
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5750
+		foreach ($key_fields as $key_field_name => $field_obj) {
5751
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5752
+				return null;
5753
+			}
5754
+		}
5755
+		return $key_vals_in_combined_pk;
5756
+	}
5757
+
5758
+
5759
+
5760
+	/**
5761
+	 * verifies that an array of key-value pairs for model fields has a key
5762
+	 * for each field comprising the primary key index
5763
+	 *
5764
+	 * @param array $key_vals
5765
+	 * @return boolean
5766
+	 * @throws EE_Error
5767
+	 */
5768
+	public function has_all_combined_primary_key_fields($key_vals)
5769
+	{
5770
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5771
+		foreach ($keys_it_should_have as $key) {
5772
+			if (! isset($key_vals[ $key ])) {
5773
+				return false;
5774
+			}
5775
+		}
5776
+		return true;
5777
+	}
5778
+
5779
+
5780
+
5781
+	/**
5782
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5783
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5784
+	 *
5785
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5786
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5787
+	 * @throws EE_Error
5788
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5789
+	 *                                                              indexed)
5790
+	 */
5791
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5792
+	{
5793
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5794
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5795
+		} elseif (is_array($model_object_or_attributes_array)) {
5796
+			$attributes_array = $model_object_or_attributes_array;
5797
+		} else {
5798
+			throw new EE_Error(sprintf(__(
5799
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5800
+				"event_espresso"
5801
+			), $model_object_or_attributes_array));
5802
+		}
5803
+		// even copies obviously won't have the same ID, so remove the primary key
5804
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5805
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5806
+			unset($attributes_array[ $this->primary_key_name() ]);
5807
+		}
5808
+		if (isset($query_params[0])) {
5809
+			$query_params[0] = array_merge($attributes_array, $query_params);
5810
+		} else {
5811
+			$query_params[0] = $attributes_array;
5812
+		}
5813
+		return $this->get_all($query_params);
5814
+	}
5815
+
5816
+
5817
+
5818
+	/**
5819
+	 * Gets the first copy we find. See get_all_copies for more details
5820
+	 *
5821
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5822
+	 * @param array $query_params
5823
+	 * @return EE_Base_Class
5824
+	 * @throws EE_Error
5825
+	 */
5826
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5827
+	{
5828
+		if (! is_array($query_params)) {
5829
+			EE_Error::doing_it_wrong(
5830
+				'EEM_Base::get_one_copy',
5831
+				sprintf(
5832
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5833
+					gettype($query_params)
5834
+				),
5835
+				'4.6.0'
5836
+			);
5837
+			$query_params = array();
5838
+		}
5839
+		$query_params['limit'] = 1;
5840
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5841
+		if (is_array($copies)) {
5842
+			return array_shift($copies);
5843
+		}
5844
+		return null;
5845
+	}
5846
+
5847
+
5848
+
5849
+	/**
5850
+	 * Updates the item with the specified id. Ignores default query parameters because
5851
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5852
+	 *
5853
+	 * @param array      $fields_n_values keys are field names, values are their new values
5854
+	 * @param int|string $id              the value of the primary key to update
5855
+	 * @return int number of rows updated
5856
+	 * @throws EE_Error
5857
+	 */
5858
+	public function update_by_ID($fields_n_values, $id)
5859
+	{
5860
+		$query_params = array(
5861
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5862
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5863
+		);
5864
+		return $this->update($fields_n_values, $query_params);
5865
+	}
5866
+
5867
+
5868
+
5869
+	/**
5870
+	 * Changes an operator which was supplied to the models into one usable in SQL
5871
+	 *
5872
+	 * @param string $operator_supplied
5873
+	 * @return string an operator which can be used in SQL
5874
+	 * @throws EE_Error
5875
+	 */
5876
+	private function _prepare_operator_for_sql($operator_supplied)
5877
+	{
5878
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5879
+			: null;
5880
+		if ($sql_operator) {
5881
+			return $sql_operator;
5882
+		}
5883
+		throw new EE_Error(
5884
+			sprintf(
5885
+				__(
5886
+					"The operator '%s' is not in the list of valid operators: %s",
5887
+					"event_espresso"
5888
+				),
5889
+				$operator_supplied,
5890
+				implode(",", array_keys($this->_valid_operators))
5891
+			)
5892
+		);
5893
+	}
5894
+
5895
+
5896
+
5897
+	/**
5898
+	 * Gets the valid operators
5899
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5900
+	 */
5901
+	public function valid_operators()
5902
+	{
5903
+		return $this->_valid_operators;
5904
+	}
5905
+
5906
+
5907
+
5908
+	/**
5909
+	 * Gets the between-style operators (take 2 arguments).
5910
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5911
+	 */
5912
+	public function valid_between_style_operators()
5913
+	{
5914
+		return array_intersect(
5915
+			$this->valid_operators(),
5916
+			$this->_between_style_operators
5917
+		);
5918
+	}
5919
+
5920
+	/**
5921
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5922
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5923
+	 */
5924
+	public function valid_like_style_operators()
5925
+	{
5926
+		return array_intersect(
5927
+			$this->valid_operators(),
5928
+			$this->_like_style_operators
5929
+		);
5930
+	}
5931
+
5932
+	/**
5933
+	 * Gets the "in"-style operators
5934
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5935
+	 */
5936
+	public function valid_in_style_operators()
5937
+	{
5938
+		return array_intersect(
5939
+			$this->valid_operators(),
5940
+			$this->_in_style_operators
5941
+		);
5942
+	}
5943
+
5944
+	/**
5945
+	 * Gets the "null"-style operators (accept no arguments)
5946
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5947
+	 */
5948
+	public function valid_null_style_operators()
5949
+	{
5950
+		return array_intersect(
5951
+			$this->valid_operators(),
5952
+			$this->_null_style_operators
5953
+		);
5954
+	}
5955
+
5956
+	/**
5957
+	 * Gets an array where keys are the primary keys and values are their 'names'
5958
+	 * (as determined by the model object's name() function, which is often overridden)
5959
+	 *
5960
+	 * @param array $query_params like get_all's
5961
+	 * @return string[]
5962
+	 * @throws EE_Error
5963
+	 */
5964
+	public function get_all_names($query_params = array())
5965
+	{
5966
+		$objs = $this->get_all($query_params);
5967
+		$names = array();
5968
+		foreach ($objs as $obj) {
5969
+			$names[ $obj->ID() ] = $obj->name();
5970
+		}
5971
+		return $names;
5972
+	}
5973
+
5974
+
5975
+
5976
+	/**
5977
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5978
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5979
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5980
+	 * array_keys() on $model_objects.
5981
+	 *
5982
+	 * @param \EE_Base_Class[] $model_objects
5983
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5984
+	 *                                               in the returned array
5985
+	 * @return array
5986
+	 * @throws EE_Error
5987
+	 */
5988
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5989
+	{
5990
+		if (! $this->has_primary_key_field()) {
5991
+			if (WP_DEBUG) {
5992
+				EE_Error::add_error(
5993
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5994
+					__FILE__,
5995
+					__FUNCTION__,
5996
+					__LINE__
5997
+				);
5998
+			}
5999
+		}
6000
+		$IDs = array();
6001
+		foreach ($model_objects as $model_object) {
6002
+			$id = $model_object->ID();
6003
+			if (! $id) {
6004
+				if ($filter_out_empty_ids) {
6005
+					continue;
6006
+				}
6007
+				if (WP_DEBUG) {
6008
+					EE_Error::add_error(
6009
+						__(
6010
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6011
+							'event_espresso'
6012
+						),
6013
+						__FILE__,
6014
+						__FUNCTION__,
6015
+						__LINE__
6016
+					);
6017
+				}
6018
+			}
6019
+			$IDs[] = $id;
6020
+		}
6021
+		return $IDs;
6022
+	}
6023
+
6024
+
6025
+
6026
+	/**
6027
+	 * Returns the string used in capabilities relating to this model. If there
6028
+	 * are no capabilities that relate to this model returns false
6029
+	 *
6030
+	 * @return string|false
6031
+	 */
6032
+	public function cap_slug()
6033
+	{
6034
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6035
+	}
6036
+
6037
+
6038
+
6039
+	/**
6040
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6041
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6042
+	 * only returns the cap restrictions array in that context (ie, the array
6043
+	 * at that key)
6044
+	 *
6045
+	 * @param string $context
6046
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6047
+	 * @throws EE_Error
6048
+	 */
6049
+	public function cap_restrictions($context = EEM_Base::caps_read)
6050
+	{
6051
+		EEM_Base::verify_is_valid_cap_context($context);
6052
+		// check if we ought to run the restriction generator first
6053
+		if (isset($this->_cap_restriction_generators[ $context ])
6054
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6055
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6056
+		) {
6057
+			$this->_cap_restrictions[ $context ] = array_merge(
6058
+				$this->_cap_restrictions[ $context ],
6059
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6060
+			);
6061
+		}
6062
+		// and make sure we've finalized the construction of each restriction
6063
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6064
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6065
+				$where_conditions_obj->_finalize_construct($this);
6066
+			}
6067
+		}
6068
+		return $this->_cap_restrictions[ $context ];
6069
+	}
6070
+
6071
+
6072
+
6073
+	/**
6074
+	 * Indicating whether or not this model thinks its a wp core model
6075
+	 *
6076
+	 * @return boolean
6077
+	 */
6078
+	public function is_wp_core_model()
6079
+	{
6080
+		return $this->_wp_core_model;
6081
+	}
6082
+
6083
+
6084
+
6085
+	/**
6086
+	 * Gets all the caps that are missing which impose a restriction on
6087
+	 * queries made in this context
6088
+	 *
6089
+	 * @param string $context one of EEM_Base::caps_ constants
6090
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6091
+	 * @throws EE_Error
6092
+	 */
6093
+	public function caps_missing($context = EEM_Base::caps_read)
6094
+	{
6095
+		$missing_caps = array();
6096
+		$cap_restrictions = $this->cap_restrictions($context);
6097
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6098
+			if (! EE_Capabilities::instance()
6099
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6100
+			) {
6101
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6102
+			}
6103
+		}
6104
+		return $missing_caps;
6105
+	}
6106
+
6107
+
6108
+
6109
+	/**
6110
+	 * Gets the mapping from capability contexts to action strings used in capability names
6111
+	 *
6112
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6113
+	 * one of 'read', 'edit', or 'delete'
6114
+	 */
6115
+	public function cap_contexts_to_cap_action_map()
6116
+	{
6117
+		return apply_filters(
6118
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6119
+			$this->_cap_contexts_to_cap_action_map,
6120
+			$this
6121
+		);
6122
+	}
6123
+
6124
+
6125
+
6126
+	/**
6127
+	 * Gets the action string for the specified capability context
6128
+	 *
6129
+	 * @param string $context
6130
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6131
+	 * @throws EE_Error
6132
+	 */
6133
+	public function cap_action_for_context($context)
6134
+	{
6135
+		$mapping = $this->cap_contexts_to_cap_action_map();
6136
+		if (isset($mapping[ $context ])) {
6137
+			return $mapping[ $context ];
6138
+		}
6139
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6140
+			return $action;
6141
+		}
6142
+		throw new EE_Error(
6143
+			sprintf(
6144
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6145
+				$context,
6146
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6147
+			)
6148
+		);
6149
+	}
6150
+
6151
+
6152
+
6153
+	/**
6154
+	 * Returns all the capability contexts which are valid when querying models
6155
+	 *
6156
+	 * @return array
6157
+	 */
6158
+	public static function valid_cap_contexts()
6159
+	{
6160
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6161
+			self::caps_read,
6162
+			self::caps_read_admin,
6163
+			self::caps_edit,
6164
+			self::caps_delete,
6165
+		));
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Returns all valid options for 'default_where_conditions'
6172
+	 *
6173
+	 * @return array
6174
+	 */
6175
+	public static function valid_default_where_conditions()
6176
+	{
6177
+		return array(
6178
+			EEM_Base::default_where_conditions_all,
6179
+			EEM_Base::default_where_conditions_this_only,
6180
+			EEM_Base::default_where_conditions_others_only,
6181
+			EEM_Base::default_where_conditions_minimum_all,
6182
+			EEM_Base::default_where_conditions_minimum_others,
6183
+			EEM_Base::default_where_conditions_none
6184
+		);
6185
+	}
6186
+
6187
+	// public static function default_where_conditions_full
6188
+	/**
6189
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6190
+	 *
6191
+	 * @param string $context
6192
+	 * @return bool
6193
+	 * @throws EE_Error
6194
+	 */
6195
+	public static function verify_is_valid_cap_context($context)
6196
+	{
6197
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6198
+		if (in_array($context, $valid_cap_contexts)) {
6199
+			return true;
6200
+		}
6201
+		throw new EE_Error(
6202
+			sprintf(
6203
+				__(
6204
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6205
+					'event_espresso'
6206
+				),
6207
+				$context,
6208
+				'EEM_Base',
6209
+				implode(',', $valid_cap_contexts)
6210
+			)
6211
+		);
6212
+	}
6213
+
6214
+
6215
+
6216
+	/**
6217
+	 * Clears all the models field caches. This is only useful when a sub-class
6218
+	 * might have added a field or something and these caches might be invalidated
6219
+	 */
6220
+	protected function _invalidate_field_caches()
6221
+	{
6222
+		$this->_cache_foreign_key_to_fields = array();
6223
+		$this->_cached_fields = null;
6224
+		$this->_cached_fields_non_db_only = null;
6225
+	}
6226
+
6227
+
6228
+
6229
+	/**
6230
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6231
+	 * (eg "and", "or", "not").
6232
+	 *
6233
+	 * @return array
6234
+	 */
6235
+	public function logic_query_param_keys()
6236
+	{
6237
+		return $this->_logic_query_param_keys;
6238
+	}
6239
+
6240
+
6241
+
6242
+	/**
6243
+	 * Determines whether or not the where query param array key is for a logic query param.
6244
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6245
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6246
+	 *
6247
+	 * @param $query_param_key
6248
+	 * @return bool
6249
+	 */
6250
+	public function is_logic_query_param_key($query_param_key)
6251
+	{
6252
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6253
+			if ($query_param_key === $logic_query_param_key
6254
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6255
+			) {
6256
+				return true;
6257
+			}
6258
+		}
6259
+		return false;
6260
+	}
6261 6261
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Soft_Delete_Base.model.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
      *
202 202
      * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
203 203
      * @param string $field_to_sum
204
-     * @return int
204
+     * @return double
205 205
      */
206 206
     public function sum_deleted($query_params = null, $field_to_sum = null)
207 207
     {
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
      * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
267 267
      *                                that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
268 268
      *                                which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
269
-     * @return boolean success
269
+     * @return integer success
270 270
      */
271 271
     public function delete_permanently($query_params = array(), $allow_blocking = true)
272 272
     {
Please login to merge, or discard this patch.
Indentation   +359 added lines, -359 removed lines patch added patch discarded remove patch
@@ -26,363 +26,363 @@
 block discarded – undo
26 26
 abstract class EEM_Soft_Delete_Base extends EEM_Base
27 27
 {
28 28
 
29
-    /**
30
-     * @param null $timezone
31
-     */
32
-    protected function __construct($timezone = null)
33
-    {
34
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
35
-            $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
36
-        }
37
-        parent::__construct($timezone);
38
-    }
39
-
40
-
41
-
42
-    /**
43
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
44
-     * returns it's name.
45
-     *
46
-     * @return string
47
-     * @throws EE_Error
48
-     */
49
-    public function deleted_field_name()
50
-    {
51
-        $field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
52
-        if ($field) {
53
-            return $field->get_name();
54
-        } else {
55
-            throw new EE_Error(sprintf(__(
56
-                'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
57
-                'event_espresso'
58
-            ), get_class($this), get_class($this)));
59
-        }
60
-    }
61
-
62
-
63
-
64
-    /**
65
-     * Gets one item that's been deleted, according to $query_params
66
-     *
67
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
68
-     * @return EE_Soft_Delete_Base_Class
69
-     */
70
-    public function get_one_deleted($query_params = array())
71
-    {
72
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
73
-        return parent::get_one($query_params);
74
-    }
75
-
76
-
77
-
78
-    /**
79
-     * Gets one item from the DB, regardless of whether it's been soft-deleted or not
80
-     *
81
-     * @param array $query_params like EEM_base::get_all's $query_params
82
-     * @return EE_Soft_Delete_Base_Class
83
-     */
84
-    public function get_one_deleted_or_undeleted($query_params = array())
85
-    {
86
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
87
-        return parent::get_one($query_params);
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
94
-     *
95
-     * @param int|string $id
96
-     * @return EE_Soft_Delete_Base_Class
97
-     */
98
-    public function get_one_by_ID_but_ignore_deleted($id)
99
-    {
100
-        return $this->get_one(
101
-            $this->alter_query_params_to_restrict_by_ID(
102
-                $id,
103
-                array('default_where_conditions' => 'default')
104
-            )
105
-        );
106
-    }
107
-
108
-
109
-
110
-    /**
111
-     * Counts all the deleted/trashed items
112
-     *
113
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
114
-     * @param string $field_to_count
115
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
116
-     * @return int
117
-     */
118
-    public function count_deleted($query_params = null, $field_to_count = null, $distinct = false)
119
-    {
120
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
121
-        return parent::count($query_params, $field_to_count, $distinct);
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * Alters the query params so that only trashed/soft-deleted items are considered
128
-     *
129
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
130
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
131
-     */
132
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
133
-    {
134
-        $deletedFlagFieldName = $this->deleted_field_name();
135
-        $query_params[0][ $deletedFlagFieldName ] = true;
136
-        return $query_params;
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * Alters the query params so that only trashed/soft-deleted items are considered
143
-     *
144
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
145
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
146
-     */
147
-    public function alter_query_params_so_only_trashed_items_included($query_params)
148
-    {
149
-        return $this->_alter_query_params_so_only_trashed_items_included($query_params);
150
-    }
151
-
152
-
153
-
154
-    /**
155
-     * Alters the query params so each item's deleted status is ignored.
156
-     *
157
-     * @param array $query_params
158
-     * @return array
159
-     */
160
-    public function alter_query_params_so_deleted_and_undeleted_items_included($query_params = array())
161
-    {
162
-        return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * Alters the query params so each item's deleted status is ignored.
169
-     *
170
-     * @param array $query_params
171
-     * @return array
172
-     */
173
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
174
-    {
175
-        if (! isset($query_params['default_where_conditions'])) {
176
-            $query_params['default_where_conditions'] = 'minimum';
177
-        }
178
-        return $query_params;
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     * Counts all deleted and undeleted items
185
-     *
186
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
187
-     * @param string $field_to_count
188
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
189
-     * @return int
190
-     */
191
-    public function count_deleted_and_undeleted($query_params = null, $field_to_count = null, $distinct = false)
192
-    {
193
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
194
-        return parent::count($query_params, $field_to_count, $distinct);
195
-    }
196
-
197
-
198
-
199
-    /**
200
-     * Sum all the deleted items.
201
-     *
202
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
203
-     * @param string $field_to_sum
204
-     * @return int
205
-     */
206
-    public function sum_deleted($query_params = null, $field_to_sum = null)
207
-    {
208
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
209
-        return parent::sum($query_params, $field_to_sum);
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     * Sums all the deleted and undeleted items.
216
-     *
217
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
218
-     * @param string $field_to_sum
219
-     * @return int
220
-     */
221
-    public function sum_deleted_and_undeleted($query_params = null, $field_to_sum = null)
222
-    {
223
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
224
-        parent::sum($query_params, $field_to_sum);
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
231
-     * whether they've been soft-deleted or not
232
-     *
233
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
234
-     * @return EE_Soft_Delete_Base_Class[]
235
-     */
236
-    public function get_all_deleted_and_undeleted($query_params = array())
237
-    {
238
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
239
-        return parent::get_all($query_params);
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
246
-     *
247
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
248
-     * @return EE_Soft_Delete_Base_Class[]
249
-     */
250
-    public function get_all_deleted($query_params = array())
251
-    {
252
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
253
-        return parent::get_all($query_params);
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     * Permanently deletes the selected rows. When selecting rows for deletion, ignores
260
-     * whether they've been soft-deleted or not. (ie, you don't have to soft-delete objects
261
-     * before you can permanently delete them).
262
-     * Because this will cause a real deletion, related models may block this deletion (ie, add an error
263
-     * and abort the delete)
264
-     *
265
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
266
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
267
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
268
-     *                                which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
269
-     * @return boolean success
270
-     */
271
-    public function delete_permanently($query_params = array(), $allow_blocking = true)
272
-    {
273
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
274
-        return parent::delete_permanently($query_params, $allow_blocking);
275
-    }
276
-
277
-
278
-
279
-    /**
280
-     * Restores a particular item by its ID (primary key). Ignores the fact whether the item
281
-     * has been soft-deleted or not.
282
-     *
283
-     * @param mixed $ID int if primary key is an int, string otherwise
284
-     * @return boolean success
285
-     */
286
-    public function restore_by_ID($ID = false)
287
-    {
288
-        return $this->delete_or_restore_by_ID(false, $ID);
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
295
-     * this function will ignore whether the items have been soft-deleted or not.
296
-     *
297
-     * @param boolean $delete true for delete, false for restore
298
-     * @param mixed   $ID     int if primary key is an int, string otherwise
299
-     * @return boolean
300
-     */
301
-    public function delete_or_restore_by_ID($delete = true, $ID = false)
302
-    {
303
-        if (! $ID) {
304
-            return false;
305
-        }
306
-        if ($this->delete_or_restore(
307
-            $delete,
308
-            $this->alter_query_params_to_restrict_by_ID($ID)
309
-        )
310
-        ) {
311
-            return true;
312
-        } else {
313
-            return false;
314
-        }
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * Overrides parent's 'delete' method to instead do a soft delete on all rows that
321
-     * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been soft-deleted or not.
322
-     * Note: because this item will be soft-deleted only,
323
-     * doesn't block because of model dependencies
324
-     *
325
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
-     * @param bool  $block_deletes
327
-     * @return boolean
328
-     */
329
-    public function delete($query_params = array(), $block_deletes = false)
330
-    {
331
-        // no matter what, we WON'T block soft deletes.
332
-        return $this->delete_or_restore(true, $query_params);
333
-    }
334
-
335
-
336
-
337
-    /**
338
-     * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default, trashed/soft-deleted
339
-     * items are ignored in queries. However, this particular function ignores whether the items have been soft-deleted or not.
340
-     *
341
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
342
-     * @return boolean
343
-     */
344
-    public function restore($query_params = array())
345
-    {
346
-        return $this->delete_or_restore(false, $query_params);
347
-    }
348
-
349
-
350
-
351
-    /**
352
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
353
-     *
354
-     * @param boolean $delete       true to indicate deletion, false to indicate restoration
355
-     * @param array   $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
356
-     * @return boolean
357
-     */
358
-    public function delete_or_restore($delete = true, $query_params = array())
359
-    {
360
-        $deletedFlagFieldName = $this->deleted_field_name();
361
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
362
-        if ($this->update(array($deletedFlagFieldName => $delete), $query_params)) {
363
-            return true;
364
-        } else {
365
-            return false;
366
-        }
367
-    }
368
-
369
-
370
-
371
-    /**
372
-     * Updates all the items of this model which match the $query params, regardless of whether
373
-     * they've been soft-deleted or not
374
-     *
375
-     * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
376
-     * @param array   $query_params            like EEM_base::get_all's $query_params
377
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
378
-     *                                         in this model's entity map according to $fields_n_values that match $query_params. This
379
-     *                                         obviously has some overhead, so you can disable it by setting this to FALSE, but
380
-     *                                         be aware that model objects being used could get out-of-sync with the database
381
-     * @return int number of items updated
382
-     */
383
-    public function update_deleted_and_undeleted($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
384
-    {
385
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
386
-        return $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
387
-    }
29
+	/**
30
+	 * @param null $timezone
31
+	 */
32
+	protected function __construct($timezone = null)
33
+	{
34
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
35
+			$this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
36
+		}
37
+		parent::__construct($timezone);
38
+	}
39
+
40
+
41
+
42
+	/**
43
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
44
+	 * returns it's name.
45
+	 *
46
+	 * @return string
47
+	 * @throws EE_Error
48
+	 */
49
+	public function deleted_field_name()
50
+	{
51
+		$field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
52
+		if ($field) {
53
+			return $field->get_name();
54
+		} else {
55
+			throw new EE_Error(sprintf(__(
56
+				'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
57
+				'event_espresso'
58
+			), get_class($this), get_class($this)));
59
+		}
60
+	}
61
+
62
+
63
+
64
+	/**
65
+	 * Gets one item that's been deleted, according to $query_params
66
+	 *
67
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
68
+	 * @return EE_Soft_Delete_Base_Class
69
+	 */
70
+	public function get_one_deleted($query_params = array())
71
+	{
72
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
73
+		return parent::get_one($query_params);
74
+	}
75
+
76
+
77
+
78
+	/**
79
+	 * Gets one item from the DB, regardless of whether it's been soft-deleted or not
80
+	 *
81
+	 * @param array $query_params like EEM_base::get_all's $query_params
82
+	 * @return EE_Soft_Delete_Base_Class
83
+	 */
84
+	public function get_one_deleted_or_undeleted($query_params = array())
85
+	{
86
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
87
+		return parent::get_one($query_params);
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
94
+	 *
95
+	 * @param int|string $id
96
+	 * @return EE_Soft_Delete_Base_Class
97
+	 */
98
+	public function get_one_by_ID_but_ignore_deleted($id)
99
+	{
100
+		return $this->get_one(
101
+			$this->alter_query_params_to_restrict_by_ID(
102
+				$id,
103
+				array('default_where_conditions' => 'default')
104
+			)
105
+		);
106
+	}
107
+
108
+
109
+
110
+	/**
111
+	 * Counts all the deleted/trashed items
112
+	 *
113
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
114
+	 * @param string $field_to_count
115
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
116
+	 * @return int
117
+	 */
118
+	public function count_deleted($query_params = null, $field_to_count = null, $distinct = false)
119
+	{
120
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
121
+		return parent::count($query_params, $field_to_count, $distinct);
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * Alters the query params so that only trashed/soft-deleted items are considered
128
+	 *
129
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
130
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
131
+	 */
132
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
133
+	{
134
+		$deletedFlagFieldName = $this->deleted_field_name();
135
+		$query_params[0][ $deletedFlagFieldName ] = true;
136
+		return $query_params;
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * Alters the query params so that only trashed/soft-deleted items are considered
143
+	 *
144
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
145
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
146
+	 */
147
+	public function alter_query_params_so_only_trashed_items_included($query_params)
148
+	{
149
+		return $this->_alter_query_params_so_only_trashed_items_included($query_params);
150
+	}
151
+
152
+
153
+
154
+	/**
155
+	 * Alters the query params so each item's deleted status is ignored.
156
+	 *
157
+	 * @param array $query_params
158
+	 * @return array
159
+	 */
160
+	public function alter_query_params_so_deleted_and_undeleted_items_included($query_params = array())
161
+	{
162
+		return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * Alters the query params so each item's deleted status is ignored.
169
+	 *
170
+	 * @param array $query_params
171
+	 * @return array
172
+	 */
173
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
174
+	{
175
+		if (! isset($query_params['default_where_conditions'])) {
176
+			$query_params['default_where_conditions'] = 'minimum';
177
+		}
178
+		return $query_params;
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 * Counts all deleted and undeleted items
185
+	 *
186
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
187
+	 * @param string $field_to_count
188
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
189
+	 * @return int
190
+	 */
191
+	public function count_deleted_and_undeleted($query_params = null, $field_to_count = null, $distinct = false)
192
+	{
193
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
194
+		return parent::count($query_params, $field_to_count, $distinct);
195
+	}
196
+
197
+
198
+
199
+	/**
200
+	 * Sum all the deleted items.
201
+	 *
202
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
203
+	 * @param string $field_to_sum
204
+	 * @return int
205
+	 */
206
+	public function sum_deleted($query_params = null, $field_to_sum = null)
207
+	{
208
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
209
+		return parent::sum($query_params, $field_to_sum);
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 * Sums all the deleted and undeleted items.
216
+	 *
217
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
218
+	 * @param string $field_to_sum
219
+	 * @return int
220
+	 */
221
+	public function sum_deleted_and_undeleted($query_params = null, $field_to_sum = null)
222
+	{
223
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
224
+		parent::sum($query_params, $field_to_sum);
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
231
+	 * whether they've been soft-deleted or not
232
+	 *
233
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
234
+	 * @return EE_Soft_Delete_Base_Class[]
235
+	 */
236
+	public function get_all_deleted_and_undeleted($query_params = array())
237
+	{
238
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
239
+		return parent::get_all($query_params);
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
246
+	 *
247
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
248
+	 * @return EE_Soft_Delete_Base_Class[]
249
+	 */
250
+	public function get_all_deleted($query_params = array())
251
+	{
252
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
253
+		return parent::get_all($query_params);
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 * Permanently deletes the selected rows. When selecting rows for deletion, ignores
260
+	 * whether they've been soft-deleted or not. (ie, you don't have to soft-delete objects
261
+	 * before you can permanently delete them).
262
+	 * Because this will cause a real deletion, related models may block this deletion (ie, add an error
263
+	 * and abort the delete)
264
+	 *
265
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
266
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
267
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
268
+	 *                                which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
269
+	 * @return boolean success
270
+	 */
271
+	public function delete_permanently($query_params = array(), $allow_blocking = true)
272
+	{
273
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
274
+		return parent::delete_permanently($query_params, $allow_blocking);
275
+	}
276
+
277
+
278
+
279
+	/**
280
+	 * Restores a particular item by its ID (primary key). Ignores the fact whether the item
281
+	 * has been soft-deleted or not.
282
+	 *
283
+	 * @param mixed $ID int if primary key is an int, string otherwise
284
+	 * @return boolean success
285
+	 */
286
+	public function restore_by_ID($ID = false)
287
+	{
288
+		return $this->delete_or_restore_by_ID(false, $ID);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
295
+	 * this function will ignore whether the items have been soft-deleted or not.
296
+	 *
297
+	 * @param boolean $delete true for delete, false for restore
298
+	 * @param mixed   $ID     int if primary key is an int, string otherwise
299
+	 * @return boolean
300
+	 */
301
+	public function delete_or_restore_by_ID($delete = true, $ID = false)
302
+	{
303
+		if (! $ID) {
304
+			return false;
305
+		}
306
+		if ($this->delete_or_restore(
307
+			$delete,
308
+			$this->alter_query_params_to_restrict_by_ID($ID)
309
+		)
310
+		) {
311
+			return true;
312
+		} else {
313
+			return false;
314
+		}
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * Overrides parent's 'delete' method to instead do a soft delete on all rows that
321
+	 * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been soft-deleted or not.
322
+	 * Note: because this item will be soft-deleted only,
323
+	 * doesn't block because of model dependencies
324
+	 *
325
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
+	 * @param bool  $block_deletes
327
+	 * @return boolean
328
+	 */
329
+	public function delete($query_params = array(), $block_deletes = false)
330
+	{
331
+		// no matter what, we WON'T block soft deletes.
332
+		return $this->delete_or_restore(true, $query_params);
333
+	}
334
+
335
+
336
+
337
+	/**
338
+	 * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default, trashed/soft-deleted
339
+	 * items are ignored in queries. However, this particular function ignores whether the items have been soft-deleted or not.
340
+	 *
341
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
342
+	 * @return boolean
343
+	 */
344
+	public function restore($query_params = array())
345
+	{
346
+		return $this->delete_or_restore(false, $query_params);
347
+	}
348
+
349
+
350
+
351
+	/**
352
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
353
+	 *
354
+	 * @param boolean $delete       true to indicate deletion, false to indicate restoration
355
+	 * @param array   $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
356
+	 * @return boolean
357
+	 */
358
+	public function delete_or_restore($delete = true, $query_params = array())
359
+	{
360
+		$deletedFlagFieldName = $this->deleted_field_name();
361
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
362
+		if ($this->update(array($deletedFlagFieldName => $delete), $query_params)) {
363
+			return true;
364
+		} else {
365
+			return false;
366
+		}
367
+	}
368
+
369
+
370
+
371
+	/**
372
+	 * Updates all the items of this model which match the $query params, regardless of whether
373
+	 * they've been soft-deleted or not
374
+	 *
375
+	 * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
376
+	 * @param array   $query_params            like EEM_base::get_all's $query_params
377
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
378
+	 *                                         in this model's entity map according to $fields_n_values that match $query_params. This
379
+	 *                                         obviously has some overhead, so you can disable it by setting this to FALSE, but
380
+	 *                                         be aware that model objects being used could get out-of-sync with the database
381
+	 * @return int number of items updated
382
+	 */
383
+	public function update_deleted_and_undeleted($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
384
+	{
385
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
386
+		return $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
387
+	}
388 388
 }
Please login to merge, or discard this patch.
core/db_models/strategies/EE_CPT_Minimum_Where_Conditions.strategy.php 2 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -18,6 +18,10 @@  discard block
 block discarded – undo
18 18
 
19 19
     protected $_post_type;
20 20
     protected $_meta_field;
21
+
22
+    /**
23
+     * @param string $post_type
24
+     */
21 25
     public function __construct($post_type, $meta_field_to_chk = '')
22 26
     {
23 27
         $this->_post_type = $post_type;
@@ -40,7 +44,6 @@  discard block
 block discarded – undo
40 44
     }
41 45
     /**
42 46
      * Gets the where default where conditions for a custom post type model
43
-     * @param string $model_relation_path. Eg, from Event to Payment, this should be "Registration.Transaction.Payment"
44 47
      * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
45 48
      */
46 49
     protected function _get_default_where_conditions()
Please login to merge, or discard this patch.
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 /**
4 4
  *
5 5
  * Class EE_CPT_Minimum_Where_Conditions
6
-  *
6
+ *
7 7
  * Strategy specifically for adding where conditions specific to CPT models.
8 8
  * But only sets the minimum, so any row of the right type will get used
9 9
  *
@@ -16,39 +16,39 @@  discard block
 block discarded – undo
16 16
 class EE_CPT_Minimum_Where_Conditions extends EE_Default_Where_Conditions
17 17
 {
18 18
 
19
-    protected $_post_type;
20
-    protected $_meta_field;
21
-    public function __construct($post_type, $meta_field_to_chk = '')
22
-    {
23
-        $this->_post_type = $post_type;
24
-        $this->_meta_field = $meta_field_to_chk;
25
-    }
26
-    /**
27
-     * Gets the field with the specified column. Note, this function might not work
28
-     * properly if two fields refer to columns with the same name on different tables
29
-     * @param string $column column name
30
-     * @return EE_Model_Field_Base
31
-     */
32
-    protected function _get_field_on_column($column)
33
-    {
34
-        $all_fields = $this->_model->field_settings(true);
35
-        foreach ($all_fields as $field_name => $field_obj) {
36
-            if ($column == $field_obj->get_table_column()) {
37
-                return $field_obj;
38
-            }
39
-        }
40
-    }
41
-    /**
42
-     * Gets the where default where conditions for a custom post type model
43
-     * @param string $model_relation_path. Eg, from Event to Payment, this should be "Registration.Transaction.Payment"
44
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
45
-     */
46
-    protected function _get_default_where_conditions()
47
-    {
48
-        // find post_type field
49
-        $post_type_field = $this->_get_field_on_column('post_type');
50
-        return array(
51
-            $post_type_field->get_name() => $this->_post_type
52
-        );
53
-    }
19
+	protected $_post_type;
20
+	protected $_meta_field;
21
+	public function __construct($post_type, $meta_field_to_chk = '')
22
+	{
23
+		$this->_post_type = $post_type;
24
+		$this->_meta_field = $meta_field_to_chk;
25
+	}
26
+	/**
27
+	 * Gets the field with the specified column. Note, this function might not work
28
+	 * properly if two fields refer to columns with the same name on different tables
29
+	 * @param string $column column name
30
+	 * @return EE_Model_Field_Base
31
+	 */
32
+	protected function _get_field_on_column($column)
33
+	{
34
+		$all_fields = $this->_model->field_settings(true);
35
+		foreach ($all_fields as $field_name => $field_obj) {
36
+			if ($column == $field_obj->get_table_column()) {
37
+				return $field_obj;
38
+			}
39
+		}
40
+	}
41
+	/**
42
+	 * Gets the where default where conditions for a custom post type model
43
+	 * @param string $model_relation_path. Eg, from Event to Payment, this should be "Registration.Transaction.Payment"
44
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
45
+	 */
46
+	protected function _get_default_where_conditions()
47
+	{
48
+		// find post_type field
49
+		$post_type_field = $this->_get_field_on_column('post_type');
50
+		return array(
51
+			$post_type_field->get_name() => $this->_post_type
52
+		);
53
+	}
54 54
 }
Please login to merge, or discard this patch.
core/db_models/strategies/EE_CPT_Where_Conditions.strategy.php 2 patches
Doc Comments   -1 removed lines patch added patch discarded remove patch
@@ -16,7 +16,6 @@
 block discarded – undo
16 16
 {
17 17
     /**
18 18
      * Gets the where default where conditions for a custom post type model
19
-     * @param string $model_relation_path. Eg, from Event to Payment, this should be "Registration.Transaction.Payment"
20 19
      * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
21 20
      */
22 21
     protected function _get_default_where_conditions()
Please login to merge, or discard this patch.
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 /**
4 4
  *
5 5
  * Class EE_Default_Where_Conditions
6
-  *
6
+ *
7 7
  * Strategy specifically for adding where conditions specific to CPT models.
8 8
  *
9 9
  * @package         Event Espresso
@@ -14,19 +14,19 @@  discard block
 block discarded – undo
14 14
  */
15 15
 class EE_CPT_Where_Conditions extends EE_CPT_Minimum_Where_Conditions
16 16
 {
17
-    /**
18
-     * Gets the where default where conditions for a custom post type model
19
-     * @param string $model_relation_path. Eg, from Event to Payment, this should be "Registration.Transaction.Payment"
20
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
21
-     */
22
-    protected function _get_default_where_conditions()
23
-    {
24
-        $status_field = $this->_get_field_on_column('post_status');
25
-        return array_merge(
26
-            parent::_get_default_where_conditions(),
27
-            array(
28
-                $status_field->get_name() => array('NOT IN',array('auto-draft','trash') )
29
-            )
30
-        );
31
-    }
17
+	/**
18
+	 * Gets the where default where conditions for a custom post type model
19
+	 * @param string $model_relation_path. Eg, from Event to Payment, this should be "Registration.Transaction.Payment"
20
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
21
+	 */
22
+	protected function _get_default_where_conditions()
23
+	{
24
+		$status_field = $this->_get_field_on_column('post_status');
25
+		return array_merge(
26
+			parent::_get_default_where_conditions(),
27
+			array(
28
+				$status_field->get_name() => array('NOT IN',array('auto-draft','trash') )
29
+			)
30
+		);
31
+	}
32 32
 }
Please login to merge, or discard this patch.
admin/extend/registrations/Extend_Registrations_Admin_Page.core.php 1 patch
Indentation   +1201 added lines, -1201 removed lines patch added patch discarded remove patch
@@ -16,1258 +16,1258 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * This is used to hold the reports template data which is setup early in the request.
21
-     *
22
-     * @type array
23
-     */
24
-    protected $_reports_template_data = array();
19
+	/**
20
+	 * This is used to hold the reports template data which is setup early in the request.
21
+	 *
22
+	 * @type array
23
+	 */
24
+	protected $_reports_template_data = array();
25 25
 
26 26
 
27
-    /**
28
-     * Extend_Registrations_Admin_Page constructor.
29
-     *
30
-     * @param bool $routing
31
-     */
32
-    public function __construct($routing = true)
33
-    {
34
-        parent::__construct($routing);
35
-        if (! defined('REG_CAF_TEMPLATE_PATH')) {
36
-            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
37
-            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
38
-            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
39
-        }
40
-    }
27
+	/**
28
+	 * Extend_Registrations_Admin_Page constructor.
29
+	 *
30
+	 * @param bool $routing
31
+	 */
32
+	public function __construct($routing = true)
33
+	{
34
+		parent::__construct($routing);
35
+		if (! defined('REG_CAF_TEMPLATE_PATH')) {
36
+			define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
37
+			define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
38
+			define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
39
+		}
40
+	}
41 41
 
42 42
 
43
-    /**
44
-     * Extending page configuration.
45
-     */
46
-    protected function _extend_page_config()
47
-    {
48
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
49
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50
-            ? $this->_req_data['_REG_ID']
51
-            : 0;
52
-        $new_page_routes = array(
53
-            'reports'                      => array(
54
-                'func'       => '_registration_reports',
55
-                'capability' => 'ee_read_registrations',
56
-            ),
57
-            'registration_checkins'        => array(
58
-                'func'       => '_registration_checkin_list_table',
59
-                'capability' => 'ee_read_checkins',
60
-            ),
61
-            'newsletter_selected_send'     => array(
62
-                'func'       => '_newsletter_selected_send',
63
-                'noheader'   => true,
64
-                'capability' => 'ee_send_message',
65
-            ),
66
-            'delete_checkin_rows'          => array(
67
-                'func'       => '_delete_checkin_rows',
68
-                'noheader'   => true,
69
-                'capability' => 'ee_delete_checkins',
70
-            ),
71
-            'delete_checkin_row'           => array(
72
-                'func'       => '_delete_checkin_row',
73
-                'noheader'   => true,
74
-                'capability' => 'ee_delete_checkin',
75
-                'obj_id'     => $reg_id,
76
-            ),
77
-            'toggle_checkin_status'        => array(
78
-                'func'       => '_toggle_checkin_status',
79
-                'noheader'   => true,
80
-                'capability' => 'ee_edit_checkin',
81
-                'obj_id'     => $reg_id,
82
-            ),
83
-            'toggle_checkin_status_bulk'   => array(
84
-                'func'       => '_toggle_checkin_status',
85
-                'noheader'   => true,
86
-                'capability' => 'ee_edit_checkins',
87
-            ),
88
-            'event_registrations'          => array(
89
-                'func'       => '_event_registrations_list_table',
90
-                'capability' => 'ee_read_checkins',
91
-            ),
92
-            'registrations_checkin_report' => array(
93
-                'func'       => '_registrations_checkin_report',
94
-                'noheader'   => true,
95
-                'capability' => 'ee_read_registrations',
96
-            ),
97
-        );
98
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
99
-        $new_page_config = array(
100
-            'reports'               => array(
101
-                'nav'           => array(
102
-                    'label' => esc_html__('Reports', 'event_espresso'),
103
-                    'order' => 30,
104
-                ),
105
-                'help_tabs'     => array(
106
-                    'registrations_reports_help_tab' => array(
107
-                        'title'    => esc_html__('Registration Reports', 'event_espresso'),
108
-                        'filename' => 'registrations_reports',
109
-                    ),
110
-                ),
111
-                /*'help_tour' => array( 'Registration_Reports_Help_Tour' ),*/
112
-                'require_nonce' => false,
113
-            ),
114
-            'event_registrations'   => array(
115
-                'nav'           => array(
116
-                    'label'      => esc_html__('Event Check-In', 'event_espresso'),
117
-                    'order'      => 10,
118
-                    'persistent' => true,
119
-                ),
120
-                'help_tabs'     => array(
121
-                    'registrations_event_checkin_help_tab'                       => array(
122
-                        'title'    => esc_html__('Registrations Event Check-In', 'event_espresso'),
123
-                        'filename' => 'registrations_event_checkin',
124
-                    ),
125
-                    'registrations_event_checkin_table_column_headings_help_tab' => array(
126
-                        'title'    => esc_html__('Event Check-In Table Column Headings', 'event_espresso'),
127
-                        'filename' => 'registrations_event_checkin_table_column_headings',
128
-                    ),
129
-                    'registrations_event_checkin_filters_help_tab'               => array(
130
-                        'title'    => esc_html__('Event Check-In Filters', 'event_espresso'),
131
-                        'filename' => 'registrations_event_checkin_filters',
132
-                    ),
133
-                    'registrations_event_checkin_views_help_tab'                 => array(
134
-                        'title'    => esc_html__('Event Check-In Views', 'event_espresso'),
135
-                        'filename' => 'registrations_event_checkin_views',
136
-                    ),
137
-                    'registrations_event_checkin_other_help_tab'                 => array(
138
-                        'title'    => esc_html__('Event Check-In Other', 'event_espresso'),
139
-                        'filename' => 'registrations_event_checkin_other',
140
-                    ),
141
-                ),
142
-                'help_tour'     => array('Event_Checkin_Help_Tour'),
143
-                'qtips'         => array('Registration_List_Table_Tips'),
144
-                'list_table'    => 'EE_Event_Registrations_List_Table',
145
-                'metaboxes'     => array(),
146
-                'require_nonce' => false,
147
-            ),
148
-            'registration_checkins' => array(
149
-                'nav'           => array(
150
-                    'label'      => esc_html__('Check-In Records', 'event_espresso'),
151
-                    'order'      => 15,
152
-                    'persistent' => false,
153
-                ),
154
-                'list_table'    => 'EE_Registration_CheckIn_List_Table',
155
-                // 'help_tour' => array( 'Checkin_Toggle_View_Help_Tour' ),
156
-                'metaboxes'     => array(),
157
-                'require_nonce' => false,
158
-            ),
159
-        );
160
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
161
-        $this->_page_config['contact_list']['list_table'] = 'Extend_EE_Attendee_Contact_List_Table';
162
-        $this->_page_config['default']['list_table'] = 'Extend_EE_Registrations_List_Table';
163
-    }
43
+	/**
44
+	 * Extending page configuration.
45
+	 */
46
+	protected function _extend_page_config()
47
+	{
48
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
49
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50
+			? $this->_req_data['_REG_ID']
51
+			: 0;
52
+		$new_page_routes = array(
53
+			'reports'                      => array(
54
+				'func'       => '_registration_reports',
55
+				'capability' => 'ee_read_registrations',
56
+			),
57
+			'registration_checkins'        => array(
58
+				'func'       => '_registration_checkin_list_table',
59
+				'capability' => 'ee_read_checkins',
60
+			),
61
+			'newsletter_selected_send'     => array(
62
+				'func'       => '_newsletter_selected_send',
63
+				'noheader'   => true,
64
+				'capability' => 'ee_send_message',
65
+			),
66
+			'delete_checkin_rows'          => array(
67
+				'func'       => '_delete_checkin_rows',
68
+				'noheader'   => true,
69
+				'capability' => 'ee_delete_checkins',
70
+			),
71
+			'delete_checkin_row'           => array(
72
+				'func'       => '_delete_checkin_row',
73
+				'noheader'   => true,
74
+				'capability' => 'ee_delete_checkin',
75
+				'obj_id'     => $reg_id,
76
+			),
77
+			'toggle_checkin_status'        => array(
78
+				'func'       => '_toggle_checkin_status',
79
+				'noheader'   => true,
80
+				'capability' => 'ee_edit_checkin',
81
+				'obj_id'     => $reg_id,
82
+			),
83
+			'toggle_checkin_status_bulk'   => array(
84
+				'func'       => '_toggle_checkin_status',
85
+				'noheader'   => true,
86
+				'capability' => 'ee_edit_checkins',
87
+			),
88
+			'event_registrations'          => array(
89
+				'func'       => '_event_registrations_list_table',
90
+				'capability' => 'ee_read_checkins',
91
+			),
92
+			'registrations_checkin_report' => array(
93
+				'func'       => '_registrations_checkin_report',
94
+				'noheader'   => true,
95
+				'capability' => 'ee_read_registrations',
96
+			),
97
+		);
98
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
99
+		$new_page_config = array(
100
+			'reports'               => array(
101
+				'nav'           => array(
102
+					'label' => esc_html__('Reports', 'event_espresso'),
103
+					'order' => 30,
104
+				),
105
+				'help_tabs'     => array(
106
+					'registrations_reports_help_tab' => array(
107
+						'title'    => esc_html__('Registration Reports', 'event_espresso'),
108
+						'filename' => 'registrations_reports',
109
+					),
110
+				),
111
+				/*'help_tour' => array( 'Registration_Reports_Help_Tour' ),*/
112
+				'require_nonce' => false,
113
+			),
114
+			'event_registrations'   => array(
115
+				'nav'           => array(
116
+					'label'      => esc_html__('Event Check-In', 'event_espresso'),
117
+					'order'      => 10,
118
+					'persistent' => true,
119
+				),
120
+				'help_tabs'     => array(
121
+					'registrations_event_checkin_help_tab'                       => array(
122
+						'title'    => esc_html__('Registrations Event Check-In', 'event_espresso'),
123
+						'filename' => 'registrations_event_checkin',
124
+					),
125
+					'registrations_event_checkin_table_column_headings_help_tab' => array(
126
+						'title'    => esc_html__('Event Check-In Table Column Headings', 'event_espresso'),
127
+						'filename' => 'registrations_event_checkin_table_column_headings',
128
+					),
129
+					'registrations_event_checkin_filters_help_tab'               => array(
130
+						'title'    => esc_html__('Event Check-In Filters', 'event_espresso'),
131
+						'filename' => 'registrations_event_checkin_filters',
132
+					),
133
+					'registrations_event_checkin_views_help_tab'                 => array(
134
+						'title'    => esc_html__('Event Check-In Views', 'event_espresso'),
135
+						'filename' => 'registrations_event_checkin_views',
136
+					),
137
+					'registrations_event_checkin_other_help_tab'                 => array(
138
+						'title'    => esc_html__('Event Check-In Other', 'event_espresso'),
139
+						'filename' => 'registrations_event_checkin_other',
140
+					),
141
+				),
142
+				'help_tour'     => array('Event_Checkin_Help_Tour'),
143
+				'qtips'         => array('Registration_List_Table_Tips'),
144
+				'list_table'    => 'EE_Event_Registrations_List_Table',
145
+				'metaboxes'     => array(),
146
+				'require_nonce' => false,
147
+			),
148
+			'registration_checkins' => array(
149
+				'nav'           => array(
150
+					'label'      => esc_html__('Check-In Records', 'event_espresso'),
151
+					'order'      => 15,
152
+					'persistent' => false,
153
+				),
154
+				'list_table'    => 'EE_Registration_CheckIn_List_Table',
155
+				// 'help_tour' => array( 'Checkin_Toggle_View_Help_Tour' ),
156
+				'metaboxes'     => array(),
157
+				'require_nonce' => false,
158
+			),
159
+		);
160
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
161
+		$this->_page_config['contact_list']['list_table'] = 'Extend_EE_Attendee_Contact_List_Table';
162
+		$this->_page_config['default']['list_table'] = 'Extend_EE_Registrations_List_Table';
163
+	}
164 164
 
165 165
 
166
-    /**
167
-     * Ajax hooks for all routes in this page.
168
-     */
169
-    protected function _ajax_hooks()
170
-    {
171
-        parent::_ajax_hooks();
172
-        add_action('wp_ajax_get_newsletter_form_content', array($this, 'get_newsletter_form_content'));
173
-    }
166
+	/**
167
+	 * Ajax hooks for all routes in this page.
168
+	 */
169
+	protected function _ajax_hooks()
170
+	{
171
+		parent::_ajax_hooks();
172
+		add_action('wp_ajax_get_newsletter_form_content', array($this, 'get_newsletter_form_content'));
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * Global scripts for all routes in this page.
178
-     */
179
-    public function load_scripts_styles()
180
-    {
181
-        parent::load_scripts_styles();
182
-        // if newsletter message type is active then let's add filter and load js for it.
183
-        if (EEH_MSG_Template::is_mt_active('newsletter')) {
184
-            // enqueue newsletter js
185
-            wp_enqueue_script(
186
-                'ee-newsletter-trigger',
187
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
188
-                array('ee-dialog'),
189
-                EVENT_ESPRESSO_VERSION,
190
-                true
191
-            );
192
-            wp_enqueue_style(
193
-                'ee-newsletter-trigger-css',
194
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
195
-                array(),
196
-                EVENT_ESPRESSO_VERSION
197
-            );
198
-            // hook in buttons for newsletter message type trigger.
199
-            add_action(
200
-                'AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons',
201
-                array($this, 'add_newsletter_action_buttons'),
202
-                10
203
-            );
204
-        }
205
-    }
176
+	/**
177
+	 * Global scripts for all routes in this page.
178
+	 */
179
+	public function load_scripts_styles()
180
+	{
181
+		parent::load_scripts_styles();
182
+		// if newsletter message type is active then let's add filter and load js for it.
183
+		if (EEH_MSG_Template::is_mt_active('newsletter')) {
184
+			// enqueue newsletter js
185
+			wp_enqueue_script(
186
+				'ee-newsletter-trigger',
187
+				REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
188
+				array('ee-dialog'),
189
+				EVENT_ESPRESSO_VERSION,
190
+				true
191
+			);
192
+			wp_enqueue_style(
193
+				'ee-newsletter-trigger-css',
194
+				REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
195
+				array(),
196
+				EVENT_ESPRESSO_VERSION
197
+			);
198
+			// hook in buttons for newsletter message type trigger.
199
+			add_action(
200
+				'AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons',
201
+				array($this, 'add_newsletter_action_buttons'),
202
+				10
203
+			);
204
+		}
205
+	}
206 206
 
207 207
 
208
-    /**
209
-     * Scripts and styles for just the reports route.
210
-     */
211
-    public function load_scripts_styles_reports()
212
-    {
213
-        wp_register_script(
214
-            'ee-reg-reports-js',
215
-            REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
216
-            array('google-charts'),
217
-            EVENT_ESPRESSO_VERSION,
218
-            true
219
-        );
220
-        wp_enqueue_script('ee-reg-reports-js');
221
-        $this->_registration_reports_js_setup();
222
-    }
208
+	/**
209
+	 * Scripts and styles for just the reports route.
210
+	 */
211
+	public function load_scripts_styles_reports()
212
+	{
213
+		wp_register_script(
214
+			'ee-reg-reports-js',
215
+			REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
216
+			array('google-charts'),
217
+			EVENT_ESPRESSO_VERSION,
218
+			true
219
+		);
220
+		wp_enqueue_script('ee-reg-reports-js');
221
+		$this->_registration_reports_js_setup();
222
+	}
223 223
 
224 224
 
225
-    /**
226
-     * Register screen options for event_registrations route.
227
-     */
228
-    protected function _add_screen_options_event_registrations()
229
-    {
230
-        $this->_per_page_screen_option();
231
-    }
225
+	/**
226
+	 * Register screen options for event_registrations route.
227
+	 */
228
+	protected function _add_screen_options_event_registrations()
229
+	{
230
+		$this->_per_page_screen_option();
231
+	}
232 232
 
233 233
 
234
-    /**
235
-     * Register screen options for registration_checkins route
236
-     */
237
-    protected function _add_screen_options_registration_checkins()
238
-    {
239
-        $page_title = $this->_admin_page_title;
240
-        $this->_admin_page_title = esc_html__('Check-In Records', 'event_espresso');
241
-        $this->_per_page_screen_option();
242
-        $this->_admin_page_title = $page_title;
243
-    }
234
+	/**
235
+	 * Register screen options for registration_checkins route
236
+	 */
237
+	protected function _add_screen_options_registration_checkins()
238
+	{
239
+		$page_title = $this->_admin_page_title;
240
+		$this->_admin_page_title = esc_html__('Check-In Records', 'event_espresso');
241
+		$this->_per_page_screen_option();
242
+		$this->_admin_page_title = $page_title;
243
+	}
244 244
 
245 245
 
246
-    /**
247
-     * Set views property for event_registrations route.
248
-     */
249
-    protected function _set_list_table_views_event_registrations()
250
-    {
251
-        $this->_views = array(
252
-            'all' => array(
253
-                'slug'        => 'all',
254
-                'label'       => esc_html__('All', 'event_espresso'),
255
-                'count'       => 0,
256
-                'bulk_action' => ! isset($this->_req_data['event_id'])
257
-                    ? array()
258
-                    : array(
259
-                        'toggle_checkin_status_bulk' => esc_html__('Toggle Check-In', 'event_espresso'),
260
-                    ),
261
-            ),
262
-        );
263
-    }
246
+	/**
247
+	 * Set views property for event_registrations route.
248
+	 */
249
+	protected function _set_list_table_views_event_registrations()
250
+	{
251
+		$this->_views = array(
252
+			'all' => array(
253
+				'slug'        => 'all',
254
+				'label'       => esc_html__('All', 'event_espresso'),
255
+				'count'       => 0,
256
+				'bulk_action' => ! isset($this->_req_data['event_id'])
257
+					? array()
258
+					: array(
259
+						'toggle_checkin_status_bulk' => esc_html__('Toggle Check-In', 'event_espresso'),
260
+					),
261
+			),
262
+		);
263
+	}
264 264
 
265 265
 
266
-    /**
267
-     * Set views property for registration_checkins route.
268
-     */
269
-    protected function _set_list_table_views_registration_checkins()
270
-    {
271
-        $this->_views = array(
272
-            'all' => array(
273
-                'slug'        => 'all',
274
-                'label'       => esc_html__('All', 'event_espresso'),
275
-                'count'       => 0,
276
-                'bulk_action' => array('delete_checkin_rows' => esc_html__('Delete Check-In Rows', 'event_espresso')),
277
-            ),
278
-        );
279
-    }
266
+	/**
267
+	 * Set views property for registration_checkins route.
268
+	 */
269
+	protected function _set_list_table_views_registration_checkins()
270
+	{
271
+		$this->_views = array(
272
+			'all' => array(
273
+				'slug'        => 'all',
274
+				'label'       => esc_html__('All', 'event_espresso'),
275
+				'count'       => 0,
276
+				'bulk_action' => array('delete_checkin_rows' => esc_html__('Delete Check-In Rows', 'event_espresso')),
277
+			),
278
+		);
279
+	}
280 280
 
281 281
 
282
-    /**
283
-     * callback for ajax action.
284
-     *
285
-     * @since 4.3.0
286
-     * @return void (JSON)
287
-     * @throws EE_Error
288
-     * @throws InvalidArgumentException
289
-     * @throws InvalidDataTypeException
290
-     * @throws InvalidInterfaceException
291
-     */
292
-    public function get_newsletter_form_content()
293
-    {
294
-        // do a nonce check cause we're not coming in from an normal route here.
295
-        $nonce = isset($this->_req_data['get_newsletter_form_content_nonce']) ? sanitize_text_field(
296
-            $this->_req_data['get_newsletter_form_content_nonce']
297
-        ) : '';
298
-        $nonce_ref = 'get_newsletter_form_content_nonce';
299
-        $this->_verify_nonce($nonce, $nonce_ref);
300
-        // let's get the mtp for the incoming MTP_ ID
301
-        if (! isset($this->_req_data['GRP_ID'])) {
302
-            EE_Error::add_error(
303
-                esc_html__(
304
-                    'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
305
-                    'event_espresso'
306
-                ),
307
-                __FILE__,
308
-                __FUNCTION__,
309
-                __LINE__
310
-            );
311
-            $this->_template_args['success'] = false;
312
-            $this->_template_args['error'] = true;
313
-            $this->_return_json();
314
-        }
315
-        $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
316
-        if (! $MTPG instanceof EE_Message_Template_Group) {
317
-            EE_Error::add_error(
318
-                sprintf(
319
-                    esc_html__(
320
-                        'The GRP_ID given (%d) does not appear to have a corresponding row in the database.',
321
-                        'event_espresso'
322
-                    ),
323
-                    $this->_req_data['GRP_ID']
324
-                ),
325
-                __FILE__,
326
-                __FUNCTION__,
327
-                __LINE__
328
-            );
329
-            $this->_template_args['success'] = false;
330
-            $this->_template_args['error'] = true;
331
-            $this->_return_json();
332
-        }
333
-        $MTPs = $MTPG->context_templates();
334
-        $MTPs = $MTPs['attendee'];
335
-        $template_fields = array();
336
-        /** @var EE_Message_Template $MTP */
337
-        foreach ($MTPs as $MTP) {
338
-            $field = $MTP->get('MTP_template_field');
339
-            if ($field === 'content') {
340
-                $content = $MTP->get('MTP_content');
341
-                if (! empty($content['newsletter_content'])) {
342
-                    $template_fields['newsletter_content'] = $content['newsletter_content'];
343
-                }
344
-                continue;
345
-            }
346
-            $template_fields[ $MTP->get('MTP_template_field') ] = $MTP->get('MTP_content');
347
-        }
348
-        $this->_template_args['success'] = true;
349
-        $this->_template_args['error'] = false;
350
-        $this->_template_args['data'] = array(
351
-            'batch_message_from'    => isset($template_fields['from'])
352
-                ? $template_fields['from']
353
-                : '',
354
-            'batch_message_subject' => isset($template_fields['subject'])
355
-                ? $template_fields['subject']
356
-                : '',
357
-            'batch_message_content' => isset($template_fields['newsletter_content'])
358
-                ? $template_fields['newsletter_content']
359
-                : '',
360
-        );
361
-        $this->_return_json();
362
-    }
282
+	/**
283
+	 * callback for ajax action.
284
+	 *
285
+	 * @since 4.3.0
286
+	 * @return void (JSON)
287
+	 * @throws EE_Error
288
+	 * @throws InvalidArgumentException
289
+	 * @throws InvalidDataTypeException
290
+	 * @throws InvalidInterfaceException
291
+	 */
292
+	public function get_newsletter_form_content()
293
+	{
294
+		// do a nonce check cause we're not coming in from an normal route here.
295
+		$nonce = isset($this->_req_data['get_newsletter_form_content_nonce']) ? sanitize_text_field(
296
+			$this->_req_data['get_newsletter_form_content_nonce']
297
+		) : '';
298
+		$nonce_ref = 'get_newsletter_form_content_nonce';
299
+		$this->_verify_nonce($nonce, $nonce_ref);
300
+		// let's get the mtp for the incoming MTP_ ID
301
+		if (! isset($this->_req_data['GRP_ID'])) {
302
+			EE_Error::add_error(
303
+				esc_html__(
304
+					'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
305
+					'event_espresso'
306
+				),
307
+				__FILE__,
308
+				__FUNCTION__,
309
+				__LINE__
310
+			);
311
+			$this->_template_args['success'] = false;
312
+			$this->_template_args['error'] = true;
313
+			$this->_return_json();
314
+		}
315
+		$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
316
+		if (! $MTPG instanceof EE_Message_Template_Group) {
317
+			EE_Error::add_error(
318
+				sprintf(
319
+					esc_html__(
320
+						'The GRP_ID given (%d) does not appear to have a corresponding row in the database.',
321
+						'event_espresso'
322
+					),
323
+					$this->_req_data['GRP_ID']
324
+				),
325
+				__FILE__,
326
+				__FUNCTION__,
327
+				__LINE__
328
+			);
329
+			$this->_template_args['success'] = false;
330
+			$this->_template_args['error'] = true;
331
+			$this->_return_json();
332
+		}
333
+		$MTPs = $MTPG->context_templates();
334
+		$MTPs = $MTPs['attendee'];
335
+		$template_fields = array();
336
+		/** @var EE_Message_Template $MTP */
337
+		foreach ($MTPs as $MTP) {
338
+			$field = $MTP->get('MTP_template_field');
339
+			if ($field === 'content') {
340
+				$content = $MTP->get('MTP_content');
341
+				if (! empty($content['newsletter_content'])) {
342
+					$template_fields['newsletter_content'] = $content['newsletter_content'];
343
+				}
344
+				continue;
345
+			}
346
+			$template_fields[ $MTP->get('MTP_template_field') ] = $MTP->get('MTP_content');
347
+		}
348
+		$this->_template_args['success'] = true;
349
+		$this->_template_args['error'] = false;
350
+		$this->_template_args['data'] = array(
351
+			'batch_message_from'    => isset($template_fields['from'])
352
+				? $template_fields['from']
353
+				: '',
354
+			'batch_message_subject' => isset($template_fields['subject'])
355
+				? $template_fields['subject']
356
+				: '',
357
+			'batch_message_content' => isset($template_fields['newsletter_content'])
358
+				? $template_fields['newsletter_content']
359
+				: '',
360
+		);
361
+		$this->_return_json();
362
+	}
363 363
 
364 364
 
365
-    /**
366
-     * callback for AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons action
367
-     *
368
-     * @since 4.3.0
369
-     * @param EE_Admin_List_Table $list_table
370
-     * @return void
371
-     * @throws InvalidArgumentException
372
-     * @throws InvalidDataTypeException
373
-     * @throws InvalidInterfaceException
374
-     */
375
-    public function add_newsletter_action_buttons(EE_Admin_List_Table $list_table)
376
-    {
377
-        if (! EE_Registry::instance()->CAP->current_user_can(
378
-            'ee_send_message',
379
-            'espresso_registrations_newsletter_selected_send'
380
-        )
381
-        ) {
382
-            return;
383
-        }
384
-        $routes_to_add_to = array(
385
-            'contact_list',
386
-            'event_registrations',
387
-            'default',
388
-        );
389
-        if ($this->_current_page === 'espresso_registrations' && in_array($this->_req_action, $routes_to_add_to)) {
390
-            if (($this->_req_action === 'event_registrations' && empty($this->_req_data['event_id']))
391
-                || (isset($this->_req_data['status']) && $this->_req_data['status'] === 'trash')
392
-            ) {
393
-                echo '';
394
-            } else {
395
-                $button_text = sprintf(
396
-                    esc_html__('Send Batch Message (%s selected)', 'event_espresso'),
397
-                    '<span class="send-selected-newsletter-count">0</span>'
398
-                );
399
-                echo '<button id="selected-batch-send-trigger" class="button secondary-button">'
400
-                     . '<span class="dashicons dashicons-email "></span>'
401
-                     . $button_text
402
-                     . '</button>';
403
-                add_action('admin_footer', array($this, 'newsletter_send_form_skeleton'));
404
-            }
405
-        }
406
-    }
365
+	/**
366
+	 * callback for AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons action
367
+	 *
368
+	 * @since 4.3.0
369
+	 * @param EE_Admin_List_Table $list_table
370
+	 * @return void
371
+	 * @throws InvalidArgumentException
372
+	 * @throws InvalidDataTypeException
373
+	 * @throws InvalidInterfaceException
374
+	 */
375
+	public function add_newsletter_action_buttons(EE_Admin_List_Table $list_table)
376
+	{
377
+		if (! EE_Registry::instance()->CAP->current_user_can(
378
+			'ee_send_message',
379
+			'espresso_registrations_newsletter_selected_send'
380
+		)
381
+		) {
382
+			return;
383
+		}
384
+		$routes_to_add_to = array(
385
+			'contact_list',
386
+			'event_registrations',
387
+			'default',
388
+		);
389
+		if ($this->_current_page === 'espresso_registrations' && in_array($this->_req_action, $routes_to_add_to)) {
390
+			if (($this->_req_action === 'event_registrations' && empty($this->_req_data['event_id']))
391
+				|| (isset($this->_req_data['status']) && $this->_req_data['status'] === 'trash')
392
+			) {
393
+				echo '';
394
+			} else {
395
+				$button_text = sprintf(
396
+					esc_html__('Send Batch Message (%s selected)', 'event_espresso'),
397
+					'<span class="send-selected-newsletter-count">0</span>'
398
+				);
399
+				echo '<button id="selected-batch-send-trigger" class="button secondary-button">'
400
+					 . '<span class="dashicons dashicons-email "></span>'
401
+					 . $button_text
402
+					 . '</button>';
403
+				add_action('admin_footer', array($this, 'newsletter_send_form_skeleton'));
404
+			}
405
+		}
406
+	}
407 407
 
408 408
 
409
-    /**
410
-     * @throws DomainException
411
-     * @throws EE_Error
412
-     * @throws InvalidArgumentException
413
-     * @throws InvalidDataTypeException
414
-     * @throws InvalidInterfaceException
415
-     */
416
-    public function newsletter_send_form_skeleton()
417
-    {
418
-        $list_table = $this->_list_table_object;
419
-        $codes = array();
420
-        // need to templates for the newsletter message type for the template selector.
421
-        $values[] = array('text' => esc_html__('Select Template to Use', 'event_espresso'), 'id' => 0);
422
-        $mtps = EEM_Message_Template_Group::instance()->get_all(
423
-            array(array('MTP_message_type' => 'newsletter', 'MTP_messenger' => 'email'))
424
-        );
425
-        foreach ($mtps as $mtp) {
426
-            $name = $mtp->name();
427
-            $values[] = array(
428
-                'text' => empty($name) ? esc_html__('Global', 'event_espresso') : $name,
429
-                'id'   => $mtp->ID(),
430
-            );
431
-        }
432
-        // need to get a list of shortcodes that are available for the newsletter message type.
433
-        $shortcodes = EEH_MSG_Template::get_shortcodes(
434
-            'newsletter',
435
-            'email',
436
-            array(),
437
-            'attendee',
438
-            false
439
-        );
440
-        foreach ($shortcodes as $field => $shortcode_array) {
441
-            $available_shortcodes = array();
442
-            foreach ($shortcode_array as $shortcode => $shortcode_details) {
443
-                $field_id = $field === '[NEWSLETTER_CONTENT]'
444
-                    ? 'content'
445
-                    : $field;
446
-                $field_id = 'batch-message-' . strtolower($field_id);
447
-                $available_shortcodes[] = '<span class="js-shortcode-selection" data-value="'
448
-                                          . $shortcode
449
-                                          . '" data-linked-input-id="' . $field_id . '">'
450
-                                          . $shortcode
451
-                                          . '</span>';
452
-            }
453
-            $codes[ $field ] = implode(', ', $available_shortcodes);
454
-        }
455
-        $shortcodes = $codes;
456
-        $form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
457
-        $form_template_args = array(
458
-            'form_action'       => admin_url('admin.php?page=espresso_registrations'),
459
-            'form_route'        => 'newsletter_selected_send',
460
-            'form_nonce_name'   => 'newsletter_selected_send_nonce',
461
-            'form_nonce'        => wp_create_nonce('newsletter_selected_send_nonce'),
462
-            'redirect_back_to'  => $this->_req_action,
463
-            'ajax_nonce'        => wp_create_nonce('get_newsletter_form_content_nonce'),
464
-            'template_selector' => EEH_Form_Fields::select_input('newsletter_mtp_selected', $values),
465
-            'shortcodes'        => $shortcodes,
466
-            'id_type'           => $list_table instanceof EE_Attendee_Contact_List_Table ? 'contact' : 'registration',
467
-        );
468
-        EEH_Template::display_template($form_template, $form_template_args);
469
-    }
409
+	/**
410
+	 * @throws DomainException
411
+	 * @throws EE_Error
412
+	 * @throws InvalidArgumentException
413
+	 * @throws InvalidDataTypeException
414
+	 * @throws InvalidInterfaceException
415
+	 */
416
+	public function newsletter_send_form_skeleton()
417
+	{
418
+		$list_table = $this->_list_table_object;
419
+		$codes = array();
420
+		// need to templates for the newsletter message type for the template selector.
421
+		$values[] = array('text' => esc_html__('Select Template to Use', 'event_espresso'), 'id' => 0);
422
+		$mtps = EEM_Message_Template_Group::instance()->get_all(
423
+			array(array('MTP_message_type' => 'newsletter', 'MTP_messenger' => 'email'))
424
+		);
425
+		foreach ($mtps as $mtp) {
426
+			$name = $mtp->name();
427
+			$values[] = array(
428
+				'text' => empty($name) ? esc_html__('Global', 'event_espresso') : $name,
429
+				'id'   => $mtp->ID(),
430
+			);
431
+		}
432
+		// need to get a list of shortcodes that are available for the newsletter message type.
433
+		$shortcodes = EEH_MSG_Template::get_shortcodes(
434
+			'newsletter',
435
+			'email',
436
+			array(),
437
+			'attendee',
438
+			false
439
+		);
440
+		foreach ($shortcodes as $field => $shortcode_array) {
441
+			$available_shortcodes = array();
442
+			foreach ($shortcode_array as $shortcode => $shortcode_details) {
443
+				$field_id = $field === '[NEWSLETTER_CONTENT]'
444
+					? 'content'
445
+					: $field;
446
+				$field_id = 'batch-message-' . strtolower($field_id);
447
+				$available_shortcodes[] = '<span class="js-shortcode-selection" data-value="'
448
+										  . $shortcode
449
+										  . '" data-linked-input-id="' . $field_id . '">'
450
+										  . $shortcode
451
+										  . '</span>';
452
+			}
453
+			$codes[ $field ] = implode(', ', $available_shortcodes);
454
+		}
455
+		$shortcodes = $codes;
456
+		$form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
457
+		$form_template_args = array(
458
+			'form_action'       => admin_url('admin.php?page=espresso_registrations'),
459
+			'form_route'        => 'newsletter_selected_send',
460
+			'form_nonce_name'   => 'newsletter_selected_send_nonce',
461
+			'form_nonce'        => wp_create_nonce('newsletter_selected_send_nonce'),
462
+			'redirect_back_to'  => $this->_req_action,
463
+			'ajax_nonce'        => wp_create_nonce('get_newsletter_form_content_nonce'),
464
+			'template_selector' => EEH_Form_Fields::select_input('newsletter_mtp_selected', $values),
465
+			'shortcodes'        => $shortcodes,
466
+			'id_type'           => $list_table instanceof EE_Attendee_Contact_List_Table ? 'contact' : 'registration',
467
+		);
468
+		EEH_Template::display_template($form_template, $form_template_args);
469
+	}
470 470
 
471 471
 
472
-    /**
473
-     * Handles sending selected registrations/contacts a newsletter.
474
-     *
475
-     * @since  4.3.0
476
-     * @return void
477
-     * @throws EE_Error
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidDataTypeException
480
-     * @throws InvalidInterfaceException
481
-     */
482
-    protected function _newsletter_selected_send()
483
-    {
484
-        $success = true;
485
-        // first we need to make sure we have a GRP_ID so we know what template we're sending and updating!
486
-        if (empty($this->_req_data['newsletter_mtp_selected'])) {
487
-            EE_Error::add_error(
488
-                esc_html__(
489
-                    'In order to send a message, a Message Template GRP_ID is needed. It was not provided so messages were not sent.',
490
-                    'event_espresso'
491
-                ),
492
-                __FILE__,
493
-                __FUNCTION__,
494
-                __LINE__
495
-            );
496
-            $success = false;
497
-        }
498
-        if ($success) {
499
-            // update Message template in case there are any changes
500
-            $Message_Template_Group = EEM_Message_Template_Group::instance()->get_one_by_ID(
501
-                $this->_req_data['newsletter_mtp_selected']
502
-            );
503
-            $Message_Templates = $Message_Template_Group instanceof EE_Message_Template_Group
504
-                ? $Message_Template_Group->context_templates()
505
-                : array();
506
-            if (empty($Message_Templates)) {
507
-                EE_Error::add_error(
508
-                    esc_html__(
509
-                        'Unable to retrieve message template fields from the db. Messages not sent.',
510
-                        'event_espresso'
511
-                    ),
512
-                    __FILE__,
513
-                    __FUNCTION__,
514
-                    __LINE__
515
-                );
516
-            }
517
-            // let's just update the specific fields
518
-            foreach ($Message_Templates['attendee'] as $Message_Template) {
519
-                if ($Message_Template instanceof EE_Message_Template) {
520
-                    $field = $Message_Template->get('MTP_template_field');
521
-                    $content = $Message_Template->get('MTP_content');
522
-                    $new_content = $content;
523
-                    switch ($field) {
524
-                        case 'from':
525
-                            $new_content = ! empty($this->_req_data['batch_message']['from'])
526
-                                ? $this->_req_data['batch_message']['from']
527
-                                : $content;
528
-                            break;
529
-                        case 'subject':
530
-                            $new_content = ! empty($this->_req_data['batch_message']['subject'])
531
-                                ? $this->_req_data['batch_message']['subject']
532
-                                : $content;
533
-                            break;
534
-                        case 'content':
535
-                            $new_content = $content;
536
-                            $new_content['newsletter_content'] = ! empty($this->_req_data['batch_message']['content'])
537
-                                ? $this->_req_data['batch_message']['content']
538
-                                : $content['newsletter_content'];
539
-                            break;
540
-                        default:
541
-                            // continue the foreach loop, we don't want to set $new_content nor save.
542
-                            continue 2;
543
-                    }
544
-                    $Message_Template->set('MTP_content', $new_content);
545
-                    $Message_Template->save();
546
-                }
547
-            }
548
-            // great fields are updated!  now let's make sure we just have contact objects (EE_Attendee).
549
-            $id_type = ! empty($this->_req_data['batch_message']['id_type'])
550
-                ? $this->_req_data['batch_message']['id_type']
551
-                : 'registration';
552
-            // id_type will affect how we assemble the ids.
553
-            $ids = ! empty($this->_req_data['batch_message']['ids'])
554
-                ? json_decode(stripslashes($this->_req_data['batch_message']['ids']))
555
-                : array();
556
-            $registrations_used_for_contact_data = array();
557
-            // using switch because eventually we'll have other contexts that will be used for generating messages.
558
-            switch ($id_type) {
559
-                case 'registration':
560
-                    $registrations_used_for_contact_data = EEM_Registration::instance()->get_all(
561
-                        array(
562
-                            array(
563
-                                'REG_ID' => array('IN', $ids),
564
-                            ),
565
-                        )
566
-                    );
567
-                    break;
568
-                case 'contact':
569
-                    $registrations_used_for_contact_data = EEM_Registration::instance()
570
-                                                                           ->get_latest_registration_for_each_of_given_contacts(
571
-                                                                               $ids
572
-                                                                           );
573
-                    break;
574
-            }
575
-            do_action_ref_array(
576
-                'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
577
-                array(
578
-                    $registrations_used_for_contact_data,
579
-                    $Message_Template_Group->ID(),
580
-                )
581
-            );
582
-            // kept for backward compat, internally we no longer use this action.
583
-            // @deprecated 4.8.36.rc.002
584
-            $contacts = $id_type === 'registration'
585
-                ? EEM_Attendee::instance()->get_array_of_contacts_from_reg_ids($ids)
586
-                : EEM_Attendee::instance()->get_all(array(array('ATT_ID' => array('in', $ids))));
587
-            do_action_ref_array(
588
-                'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send',
589
-                array(
590
-                    $contacts,
591
-                    $Message_Template_Group->ID(),
592
-                )
593
-            );
594
-        }
595
-        $query_args = array(
596
-            'action' => ! empty($this->_req_data['redirect_back_to'])
597
-                ? $this->_req_data['redirect_back_to']
598
-                : 'default',
599
-        );
600
-        $this->_redirect_after_action(false, '', '', $query_args, true);
601
-    }
472
+	/**
473
+	 * Handles sending selected registrations/contacts a newsletter.
474
+	 *
475
+	 * @since  4.3.0
476
+	 * @return void
477
+	 * @throws EE_Error
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws InvalidInterfaceException
481
+	 */
482
+	protected function _newsletter_selected_send()
483
+	{
484
+		$success = true;
485
+		// first we need to make sure we have a GRP_ID so we know what template we're sending and updating!
486
+		if (empty($this->_req_data['newsletter_mtp_selected'])) {
487
+			EE_Error::add_error(
488
+				esc_html__(
489
+					'In order to send a message, a Message Template GRP_ID is needed. It was not provided so messages were not sent.',
490
+					'event_espresso'
491
+				),
492
+				__FILE__,
493
+				__FUNCTION__,
494
+				__LINE__
495
+			);
496
+			$success = false;
497
+		}
498
+		if ($success) {
499
+			// update Message template in case there are any changes
500
+			$Message_Template_Group = EEM_Message_Template_Group::instance()->get_one_by_ID(
501
+				$this->_req_data['newsletter_mtp_selected']
502
+			);
503
+			$Message_Templates = $Message_Template_Group instanceof EE_Message_Template_Group
504
+				? $Message_Template_Group->context_templates()
505
+				: array();
506
+			if (empty($Message_Templates)) {
507
+				EE_Error::add_error(
508
+					esc_html__(
509
+						'Unable to retrieve message template fields from the db. Messages not sent.',
510
+						'event_espresso'
511
+					),
512
+					__FILE__,
513
+					__FUNCTION__,
514
+					__LINE__
515
+				);
516
+			}
517
+			// let's just update the specific fields
518
+			foreach ($Message_Templates['attendee'] as $Message_Template) {
519
+				if ($Message_Template instanceof EE_Message_Template) {
520
+					$field = $Message_Template->get('MTP_template_field');
521
+					$content = $Message_Template->get('MTP_content');
522
+					$new_content = $content;
523
+					switch ($field) {
524
+						case 'from':
525
+							$new_content = ! empty($this->_req_data['batch_message']['from'])
526
+								? $this->_req_data['batch_message']['from']
527
+								: $content;
528
+							break;
529
+						case 'subject':
530
+							$new_content = ! empty($this->_req_data['batch_message']['subject'])
531
+								? $this->_req_data['batch_message']['subject']
532
+								: $content;
533
+							break;
534
+						case 'content':
535
+							$new_content = $content;
536
+							$new_content['newsletter_content'] = ! empty($this->_req_data['batch_message']['content'])
537
+								? $this->_req_data['batch_message']['content']
538
+								: $content['newsletter_content'];
539
+							break;
540
+						default:
541
+							// continue the foreach loop, we don't want to set $new_content nor save.
542
+							continue 2;
543
+					}
544
+					$Message_Template->set('MTP_content', $new_content);
545
+					$Message_Template->save();
546
+				}
547
+			}
548
+			// great fields are updated!  now let's make sure we just have contact objects (EE_Attendee).
549
+			$id_type = ! empty($this->_req_data['batch_message']['id_type'])
550
+				? $this->_req_data['batch_message']['id_type']
551
+				: 'registration';
552
+			// id_type will affect how we assemble the ids.
553
+			$ids = ! empty($this->_req_data['batch_message']['ids'])
554
+				? json_decode(stripslashes($this->_req_data['batch_message']['ids']))
555
+				: array();
556
+			$registrations_used_for_contact_data = array();
557
+			// using switch because eventually we'll have other contexts that will be used for generating messages.
558
+			switch ($id_type) {
559
+				case 'registration':
560
+					$registrations_used_for_contact_data = EEM_Registration::instance()->get_all(
561
+						array(
562
+							array(
563
+								'REG_ID' => array('IN', $ids),
564
+							),
565
+						)
566
+					);
567
+					break;
568
+				case 'contact':
569
+					$registrations_used_for_contact_data = EEM_Registration::instance()
570
+																		   ->get_latest_registration_for_each_of_given_contacts(
571
+																			   $ids
572
+																		   );
573
+					break;
574
+			}
575
+			do_action_ref_array(
576
+				'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
577
+				array(
578
+					$registrations_used_for_contact_data,
579
+					$Message_Template_Group->ID(),
580
+				)
581
+			);
582
+			// kept for backward compat, internally we no longer use this action.
583
+			// @deprecated 4.8.36.rc.002
584
+			$contacts = $id_type === 'registration'
585
+				? EEM_Attendee::instance()->get_array_of_contacts_from_reg_ids($ids)
586
+				: EEM_Attendee::instance()->get_all(array(array('ATT_ID' => array('in', $ids))));
587
+			do_action_ref_array(
588
+				'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send',
589
+				array(
590
+					$contacts,
591
+					$Message_Template_Group->ID(),
592
+				)
593
+			);
594
+		}
595
+		$query_args = array(
596
+			'action' => ! empty($this->_req_data['redirect_back_to'])
597
+				? $this->_req_data['redirect_back_to']
598
+				: 'default',
599
+		);
600
+		$this->_redirect_after_action(false, '', '', $query_args, true);
601
+	}
602 602
 
603 603
 
604
-    /**
605
-     * This is called when javascript is being enqueued to setup the various data needed for the reports js.
606
-     * Also $this->{$_reports_template_data} property is set for later usage by the _registration_reports method.
607
-     */
608
-    protected function _registration_reports_js_setup()
609
-    {
610
-        $this->_reports_template_data['admin_reports'][] = $this->_registrations_per_day_report();
611
-        $this->_reports_template_data['admin_reports'][] = $this->_registrations_per_event_report();
612
-    }
604
+	/**
605
+	 * This is called when javascript is being enqueued to setup the various data needed for the reports js.
606
+	 * Also $this->{$_reports_template_data} property is set for later usage by the _registration_reports method.
607
+	 */
608
+	protected function _registration_reports_js_setup()
609
+	{
610
+		$this->_reports_template_data['admin_reports'][] = $this->_registrations_per_day_report();
611
+		$this->_reports_template_data['admin_reports'][] = $this->_registrations_per_event_report();
612
+	}
613 613
 
614 614
 
615
-    /**
616
-     *        generates Business Reports regarding Registrations
617
-     *
618
-     * @access protected
619
-     * @return void
620
-     * @throws DomainException
621
-     */
622
-    protected function _registration_reports()
623
-    {
624
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
625
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
626
-            $template_path,
627
-            $this->_reports_template_data,
628
-            true
629
-        );
630
-        // the final template wrapper
631
-        $this->display_admin_page_with_no_sidebar();
632
-    }
615
+	/**
616
+	 *        generates Business Reports regarding Registrations
617
+	 *
618
+	 * @access protected
619
+	 * @return void
620
+	 * @throws DomainException
621
+	 */
622
+	protected function _registration_reports()
623
+	{
624
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
625
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
626
+			$template_path,
627
+			$this->_reports_template_data,
628
+			true
629
+		);
630
+		// the final template wrapper
631
+		$this->display_admin_page_with_no_sidebar();
632
+	}
633 633
 
634 634
 
635
-    /**
636
-     * Generates Business Report showing total registrations per day.
637
-     *
638
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
639
-     * @return string
640
-     * @throws EE_Error
641
-     * @throws InvalidArgumentException
642
-     * @throws InvalidDataTypeException
643
-     * @throws InvalidInterfaceException
644
-     */
645
-    private function _registrations_per_day_report($period = '-1 month')
646
-    {
647
-        $report_ID = 'reg-admin-registrations-per-day-report-dv';
648
-        $results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
649
-        $results = (array) $results;
650
-        $regs = array();
651
-        $subtitle = '';
652
-        if ($results) {
653
-            $column_titles = array();
654
-            $tracker = 0;
655
-            foreach ($results as $result) {
656
-                $report_column_values = array();
657
-                foreach ($result as $property_name => $property_value) {
658
-                    $property_value = $property_name === 'Registration_REG_date' ? $property_value
659
-                        : (int) $property_value;
660
-                    $report_column_values[] = $property_value;
661
-                    if ($tracker === 0) {
662
-                        if ($property_name === 'Registration_REG_date') {
663
-                            $column_titles[] = esc_html__(
664
-                                'Date (only days with registrations are shown)',
665
-                                'event_espresso'
666
-                            );
667
-                        } else {
668
-                            $column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
669
-                        }
670
-                    }
671
-                }
672
-                $tracker++;
673
-                $regs[] = $report_column_values;
674
-            }
675
-            // make sure the column_titles is pushed to the beginning of the array
676
-            array_unshift($regs, $column_titles);
677
-            // setup the date range.
678
-            $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
679
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
680
-            $ending_date = new DateTime("now", $DateTimeZone);
681
-            $subtitle = sprintf(
682
-                _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
683
-                $beginning_date->format('Y-m-d'),
684
-                $ending_date->format('Y-m-d')
685
-            );
686
-        }
687
-        $report_title = esc_html__('Total Registrations per Day', 'event_espresso');
688
-        $report_params = array(
689
-            'title'     => $report_title,
690
-            'subtitle'  => $subtitle,
691
-            'id'        => $report_ID,
692
-            'regs'      => $regs,
693
-            'noResults' => empty($regs),
694
-            'noRegsMsg' => sprintf(
695
-                esc_html__(
696
-                    '%sThere are currently no registration records in the last month for this report.%s',
697
-                    'event_espresso'
698
-                ),
699
-                '<h2>' . $report_title . '</h2><p>',
700
-                '</p>'
701
-            ),
702
-        );
703
-        wp_localize_script('ee-reg-reports-js', 'regPerDay', $report_params);
704
-        return $report_ID;
705
-    }
635
+	/**
636
+	 * Generates Business Report showing total registrations per day.
637
+	 *
638
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
639
+	 * @return string
640
+	 * @throws EE_Error
641
+	 * @throws InvalidArgumentException
642
+	 * @throws InvalidDataTypeException
643
+	 * @throws InvalidInterfaceException
644
+	 */
645
+	private function _registrations_per_day_report($period = '-1 month')
646
+	{
647
+		$report_ID = 'reg-admin-registrations-per-day-report-dv';
648
+		$results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
649
+		$results = (array) $results;
650
+		$regs = array();
651
+		$subtitle = '';
652
+		if ($results) {
653
+			$column_titles = array();
654
+			$tracker = 0;
655
+			foreach ($results as $result) {
656
+				$report_column_values = array();
657
+				foreach ($result as $property_name => $property_value) {
658
+					$property_value = $property_name === 'Registration_REG_date' ? $property_value
659
+						: (int) $property_value;
660
+					$report_column_values[] = $property_value;
661
+					if ($tracker === 0) {
662
+						if ($property_name === 'Registration_REG_date') {
663
+							$column_titles[] = esc_html__(
664
+								'Date (only days with registrations are shown)',
665
+								'event_espresso'
666
+							);
667
+						} else {
668
+							$column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
669
+						}
670
+					}
671
+				}
672
+				$tracker++;
673
+				$regs[] = $report_column_values;
674
+			}
675
+			// make sure the column_titles is pushed to the beginning of the array
676
+			array_unshift($regs, $column_titles);
677
+			// setup the date range.
678
+			$DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
679
+			$beginning_date = new DateTime("now " . $period, $DateTimeZone);
680
+			$ending_date = new DateTime("now", $DateTimeZone);
681
+			$subtitle = sprintf(
682
+				_x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
683
+				$beginning_date->format('Y-m-d'),
684
+				$ending_date->format('Y-m-d')
685
+			);
686
+		}
687
+		$report_title = esc_html__('Total Registrations per Day', 'event_espresso');
688
+		$report_params = array(
689
+			'title'     => $report_title,
690
+			'subtitle'  => $subtitle,
691
+			'id'        => $report_ID,
692
+			'regs'      => $regs,
693
+			'noResults' => empty($regs),
694
+			'noRegsMsg' => sprintf(
695
+				esc_html__(
696
+					'%sThere are currently no registration records in the last month for this report.%s',
697
+					'event_espresso'
698
+				),
699
+				'<h2>' . $report_title . '</h2><p>',
700
+				'</p>'
701
+			),
702
+		);
703
+		wp_localize_script('ee-reg-reports-js', 'regPerDay', $report_params);
704
+		return $report_ID;
705
+	}
706 706
 
707 707
 
708
-    /**
709
-     * Generates Business Report showing total registrations per event.
710
-     *
711
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
712
-     * @return string
713
-     * @throws EE_Error
714
-     * @throws InvalidArgumentException
715
-     * @throws InvalidDataTypeException
716
-     * @throws InvalidInterfaceException
717
-     */
718
-    private function _registrations_per_event_report($period = '-1 month')
719
-    {
720
-        $report_ID = 'reg-admin-registrations-per-event-report-dv';
721
-        $results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
722
-        $results = (array) $results;
723
-        $regs = array();
724
-        $subtitle = '';
725
-        if ($results) {
726
-            $column_titles = array();
727
-            $tracker = 0;
728
-            foreach ($results as $result) {
729
-                $report_column_values = array();
730
-                foreach ($result as $property_name => $property_value) {
731
-                    $property_value = $property_name === 'Registration_Event' ? wp_trim_words(
732
-                        $property_value,
733
-                        4,
734
-                        '...'
735
-                    ) : (int) $property_value;
736
-                    $report_column_values[] = $property_value;
737
-                    if ($tracker === 0) {
738
-                        if ($property_name === 'Registration_Event') {
739
-                            $column_titles[] = esc_html__('Event', 'event_espresso');
740
-                        } else {
741
-                            $column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
742
-                        }
743
-                    }
744
-                }
745
-                $tracker++;
746
-                $regs[] = $report_column_values;
747
-            }
748
-            // make sure the column_titles is pushed to the beginning of the array
749
-            array_unshift($regs, $column_titles);
750
-            // setup the date range.
751
-            $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
752
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
753
-            $ending_date = new DateTime("now", $DateTimeZone);
754
-            $subtitle = sprintf(
755
-                _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
756
-                $beginning_date->format('Y-m-d'),
757
-                $ending_date->format('Y-m-d')
758
-            );
759
-        }
760
-        $report_title = esc_html__('Total Registrations per Event', 'event_espresso');
761
-        $report_params = array(
762
-            'title'     => $report_title,
763
-            'subtitle'  => $subtitle,
764
-            'id'        => $report_ID,
765
-            'regs'      => $regs,
766
-            'noResults' => empty($regs),
767
-            'noRegsMsg' => sprintf(
768
-                esc_html__(
769
-                    '%sThere are currently no registration records in the last month for this report.%s',
770
-                    'event_espresso'
771
-                ),
772
-                '<h2>' . $report_title . '</h2><p>',
773
-                '</p>'
774
-            ),
775
-        );
776
-        wp_localize_script('ee-reg-reports-js', 'regPerEvent', $report_params);
777
-        return $report_ID;
778
-    }
708
+	/**
709
+	 * Generates Business Report showing total registrations per event.
710
+	 *
711
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
712
+	 * @return string
713
+	 * @throws EE_Error
714
+	 * @throws InvalidArgumentException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws InvalidInterfaceException
717
+	 */
718
+	private function _registrations_per_event_report($period = '-1 month')
719
+	{
720
+		$report_ID = 'reg-admin-registrations-per-event-report-dv';
721
+		$results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
722
+		$results = (array) $results;
723
+		$regs = array();
724
+		$subtitle = '';
725
+		if ($results) {
726
+			$column_titles = array();
727
+			$tracker = 0;
728
+			foreach ($results as $result) {
729
+				$report_column_values = array();
730
+				foreach ($result as $property_name => $property_value) {
731
+					$property_value = $property_name === 'Registration_Event' ? wp_trim_words(
732
+						$property_value,
733
+						4,
734
+						'...'
735
+					) : (int) $property_value;
736
+					$report_column_values[] = $property_value;
737
+					if ($tracker === 0) {
738
+						if ($property_name === 'Registration_Event') {
739
+							$column_titles[] = esc_html__('Event', 'event_espresso');
740
+						} else {
741
+							$column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
742
+						}
743
+					}
744
+				}
745
+				$tracker++;
746
+				$regs[] = $report_column_values;
747
+			}
748
+			// make sure the column_titles is pushed to the beginning of the array
749
+			array_unshift($regs, $column_titles);
750
+			// setup the date range.
751
+			$DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
752
+			$beginning_date = new DateTime("now " . $period, $DateTimeZone);
753
+			$ending_date = new DateTime("now", $DateTimeZone);
754
+			$subtitle = sprintf(
755
+				_x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
756
+				$beginning_date->format('Y-m-d'),
757
+				$ending_date->format('Y-m-d')
758
+			);
759
+		}
760
+		$report_title = esc_html__('Total Registrations per Event', 'event_espresso');
761
+		$report_params = array(
762
+			'title'     => $report_title,
763
+			'subtitle'  => $subtitle,
764
+			'id'        => $report_ID,
765
+			'regs'      => $regs,
766
+			'noResults' => empty($regs),
767
+			'noRegsMsg' => sprintf(
768
+				esc_html__(
769
+					'%sThere are currently no registration records in the last month for this report.%s',
770
+					'event_espresso'
771
+				),
772
+				'<h2>' . $report_title . '</h2><p>',
773
+				'</p>'
774
+			),
775
+		);
776
+		wp_localize_script('ee-reg-reports-js', 'regPerEvent', $report_params);
777
+		return $report_ID;
778
+	}
779 779
 
780 780
 
781
-    /**
782
-     * generates HTML for the Registration Check-in list table (showing all Check-ins for a specific registration)
783
-     *
784
-     * @access protected
785
-     * @return void
786
-     * @throws EE_Error
787
-     * @throws InvalidArgumentException
788
-     * @throws InvalidDataTypeException
789
-     * @throws InvalidInterfaceException
790
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
791
-     */
792
-    protected function _registration_checkin_list_table()
793
-    {
794
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
795
-        $reg_id = isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : null;
796
-        /** @var EE_Registration $registration */
797
-        $registration = EEM_Registration::instance()->get_one_by_ID($reg_id);
798
-        $attendee = $registration->attendee();
799
-        $this->_admin_page_title .= $this->get_action_link_or_button(
800
-            'new_registration',
801
-            'add-registrant',
802
-            array('event_id' => $registration->event_ID()),
803
-            'add-new-h2'
804
-        );
805
-        $checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
806
-        $checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
807
-        $legend_items = array(
808
-            'checkin'  => array(
809
-                'class' => $checked_in->cssClasses(),
810
-                'desc'  => $checked_in->legendLabel(),
811
-            ),
812
-            'checkout' => array(
813
-                'class' => $checked_out->cssClasses(),
814
-                'desc'  => $checked_out->legendLabel(),
815
-            ),
816
-        );
817
-        $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
818
-        $dtt_id = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
819
-        /** @var EE_Datetime $datetime */
820
-        $datetime = EEM_Datetime::instance()->get_one_by_ID($dtt_id);
821
-        $datetime_label = '';
822
-        if ($datetime instanceof EE_Datetime) {
823
-            $datetime_label = $datetime->get_dtt_display_name(true);
824
-            $datetime_label .= ! empty($datetime_label)
825
-                ? ' (' . $datetime->get_dtt_display_name() . ')'
826
-                : $datetime->get_dtt_display_name();
827
-        }
828
-        $datetime_link = ! empty($dtt_id) && $registration instanceof EE_Registration
829
-            ? EE_Admin_Page::add_query_args_and_nonce(
830
-                array(
831
-                    'action'   => 'event_registrations',
832
-                    'event_id' => $registration->event_ID(),
833
-                    'DTT_ID'   => $dtt_id,
834
-                ),
835
-                $this->_admin_base_url
836
-            )
837
-            : '';
838
-        $datetime_link = ! empty($datetime_link)
839
-            ? '<a href="' . $datetime_link . '">'
840
-              . '<span id="checkin-dtt">'
841
-              . $datetime_label
842
-              . '</span></a>'
843
-            : $datetime_label;
844
-        $attendee_name = $attendee instanceof EE_Attendee
845
-            ? $attendee->full_name()
846
-            : '';
847
-        $attendee_link = $attendee instanceof EE_Attendee
848
-            ? $attendee->get_admin_details_link()
849
-            : '';
850
-        $attendee_link = ! empty($attendee_link)
851
-            ? '<a href="' . $attendee->get_admin_details_link() . '"'
852
-              . ' title="' . esc_html__('Click for attendee details', 'event_espresso') . '">'
853
-              . '<span id="checkin-attendee-name">'
854
-              . $attendee_name
855
-              . '</span></a>'
856
-            : '';
857
-        $event_link = $registration->event() instanceof EE_Event
858
-            ? $registration->event()->get_admin_details_link()
859
-            : '';
860
-        $event_link = ! empty($event_link)
861
-            ? '<a href="' . $event_link . '"'
862
-              . ' title="' . esc_html__('Click here to edit event.', 'event_espresso') . '">'
863
-              . '<span id="checkin-event-name">'
864
-              . $registration->event_name()
865
-              . '</span>'
866
-              . '</a>'
867
-            : '';
868
-        $this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
869
-            ? '<h2>' . sprintf(
870
-                esc_html__('Displaying check in records for %1$s for %2$s at the event, %3$s', 'event_espresso'),
871
-                $attendee_link,
872
-                $datetime_link,
873
-                $event_link
874
-            ) . '</h2>'
875
-            : '';
876
-        $this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
877
-            ? '<input type="hidden" name="_REG_ID" value="' . $reg_id . '">' : '';
878
-        $this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
879
-            ? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
880
-        $this->display_admin_list_table_page_with_no_sidebar();
881
-    }
781
+	/**
782
+	 * generates HTML for the Registration Check-in list table (showing all Check-ins for a specific registration)
783
+	 *
784
+	 * @access protected
785
+	 * @return void
786
+	 * @throws EE_Error
787
+	 * @throws InvalidArgumentException
788
+	 * @throws InvalidDataTypeException
789
+	 * @throws InvalidInterfaceException
790
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
791
+	 */
792
+	protected function _registration_checkin_list_table()
793
+	{
794
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
795
+		$reg_id = isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : null;
796
+		/** @var EE_Registration $registration */
797
+		$registration = EEM_Registration::instance()->get_one_by_ID($reg_id);
798
+		$attendee = $registration->attendee();
799
+		$this->_admin_page_title .= $this->get_action_link_or_button(
800
+			'new_registration',
801
+			'add-registrant',
802
+			array('event_id' => $registration->event_ID()),
803
+			'add-new-h2'
804
+		);
805
+		$checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
806
+		$checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
807
+		$legend_items = array(
808
+			'checkin'  => array(
809
+				'class' => $checked_in->cssClasses(),
810
+				'desc'  => $checked_in->legendLabel(),
811
+			),
812
+			'checkout' => array(
813
+				'class' => $checked_out->cssClasses(),
814
+				'desc'  => $checked_out->legendLabel(),
815
+			),
816
+		);
817
+		$this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
818
+		$dtt_id = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
819
+		/** @var EE_Datetime $datetime */
820
+		$datetime = EEM_Datetime::instance()->get_one_by_ID($dtt_id);
821
+		$datetime_label = '';
822
+		if ($datetime instanceof EE_Datetime) {
823
+			$datetime_label = $datetime->get_dtt_display_name(true);
824
+			$datetime_label .= ! empty($datetime_label)
825
+				? ' (' . $datetime->get_dtt_display_name() . ')'
826
+				: $datetime->get_dtt_display_name();
827
+		}
828
+		$datetime_link = ! empty($dtt_id) && $registration instanceof EE_Registration
829
+			? EE_Admin_Page::add_query_args_and_nonce(
830
+				array(
831
+					'action'   => 'event_registrations',
832
+					'event_id' => $registration->event_ID(),
833
+					'DTT_ID'   => $dtt_id,
834
+				),
835
+				$this->_admin_base_url
836
+			)
837
+			: '';
838
+		$datetime_link = ! empty($datetime_link)
839
+			? '<a href="' . $datetime_link . '">'
840
+			  . '<span id="checkin-dtt">'
841
+			  . $datetime_label
842
+			  . '</span></a>'
843
+			: $datetime_label;
844
+		$attendee_name = $attendee instanceof EE_Attendee
845
+			? $attendee->full_name()
846
+			: '';
847
+		$attendee_link = $attendee instanceof EE_Attendee
848
+			? $attendee->get_admin_details_link()
849
+			: '';
850
+		$attendee_link = ! empty($attendee_link)
851
+			? '<a href="' . $attendee->get_admin_details_link() . '"'
852
+			  . ' title="' . esc_html__('Click for attendee details', 'event_espresso') . '">'
853
+			  . '<span id="checkin-attendee-name">'
854
+			  . $attendee_name
855
+			  . '</span></a>'
856
+			: '';
857
+		$event_link = $registration->event() instanceof EE_Event
858
+			? $registration->event()->get_admin_details_link()
859
+			: '';
860
+		$event_link = ! empty($event_link)
861
+			? '<a href="' . $event_link . '"'
862
+			  . ' title="' . esc_html__('Click here to edit event.', 'event_espresso') . '">'
863
+			  . '<span id="checkin-event-name">'
864
+			  . $registration->event_name()
865
+			  . '</span>'
866
+			  . '</a>'
867
+			: '';
868
+		$this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
869
+			? '<h2>' . sprintf(
870
+				esc_html__('Displaying check in records for %1$s for %2$s at the event, %3$s', 'event_espresso'),
871
+				$attendee_link,
872
+				$datetime_link,
873
+				$event_link
874
+			) . '</h2>'
875
+			: '';
876
+		$this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
877
+			? '<input type="hidden" name="_REG_ID" value="' . $reg_id . '">' : '';
878
+		$this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
879
+			? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
880
+		$this->display_admin_list_table_page_with_no_sidebar();
881
+	}
882 882
 
883 883
 
884
-    /**
885
-     * toggle the Check-in status for the given registration (coming from ajax)
886
-     *
887
-     * @return void (JSON)
888
-     * @throws EE_Error
889
-     * @throws InvalidArgumentException
890
-     * @throws InvalidDataTypeException
891
-     * @throws InvalidInterfaceException
892
-     */
893
-    public function toggle_checkin_status()
894
-    {
895
-        // first make sure we have the necessary data
896
-        if (! isset($this->_req_data['_regid'])) {
897
-            EE_Error::add_error(
898
-                esc_html__(
899
-                    'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
900
-                    'event_espresso'
901
-                ),
902
-                __FILE__,
903
-                __FUNCTION__,
904
-                __LINE__
905
-            );
906
-            $this->_template_args['success'] = false;
907
-            $this->_template_args['error'] = true;
908
-            $this->_return_json();
909
-        };
910
-        // do a nonce check cause we're not coming in from an normal route here.
911
-        $nonce = isset($this->_req_data['checkinnonce']) ? sanitize_text_field($this->_req_data['checkinnonce'])
912
-            : '';
913
-        $nonce_ref = 'checkin_nonce';
914
-        $this->_verify_nonce($nonce, $nonce_ref);
915
-        // beautiful! Made it this far so let's get the status.
916
-        $new_status = new CheckinStatusDashicon($this->_toggle_checkin_status());
917
-        // setup new class to return via ajax
918
-        $this->_template_args['admin_page_content'] = 'clickable trigger-checkin ' . $new_status->cssClasses();
919
-        $this->_template_args['success'] = true;
920
-        $this->_return_json();
921
-    }
884
+	/**
885
+	 * toggle the Check-in status for the given registration (coming from ajax)
886
+	 *
887
+	 * @return void (JSON)
888
+	 * @throws EE_Error
889
+	 * @throws InvalidArgumentException
890
+	 * @throws InvalidDataTypeException
891
+	 * @throws InvalidInterfaceException
892
+	 */
893
+	public function toggle_checkin_status()
894
+	{
895
+		// first make sure we have the necessary data
896
+		if (! isset($this->_req_data['_regid'])) {
897
+			EE_Error::add_error(
898
+				esc_html__(
899
+					'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
900
+					'event_espresso'
901
+				),
902
+				__FILE__,
903
+				__FUNCTION__,
904
+				__LINE__
905
+			);
906
+			$this->_template_args['success'] = false;
907
+			$this->_template_args['error'] = true;
908
+			$this->_return_json();
909
+		};
910
+		// do a nonce check cause we're not coming in from an normal route here.
911
+		$nonce = isset($this->_req_data['checkinnonce']) ? sanitize_text_field($this->_req_data['checkinnonce'])
912
+			: '';
913
+		$nonce_ref = 'checkin_nonce';
914
+		$this->_verify_nonce($nonce, $nonce_ref);
915
+		// beautiful! Made it this far so let's get the status.
916
+		$new_status = new CheckinStatusDashicon($this->_toggle_checkin_status());
917
+		// setup new class to return via ajax
918
+		$this->_template_args['admin_page_content'] = 'clickable trigger-checkin ' . $new_status->cssClasses();
919
+		$this->_template_args['success'] = true;
920
+		$this->_return_json();
921
+	}
922 922
 
923 923
 
924
-    /**
925
-     * handles toggling the checkin status for the registration,
926
-     *
927
-     * @access protected
928
-     * @return int|void
929
-     * @throws EE_Error
930
-     * @throws InvalidArgumentException
931
-     * @throws InvalidDataTypeException
932
-     * @throws InvalidInterfaceException
933
-     */
934
-    protected function _toggle_checkin_status()
935
-    {
936
-        // first let's get the query args out of the way for the redirect
937
-        $query_args = array(
938
-            'action'   => 'event_registrations',
939
-            'event_id' => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
940
-            'DTT_ID'   => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null,
941
-        );
942
-        $new_status = false;
943
-        // bulk action check in toggle
944
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
945
-            // cycle thru checkboxes
946
-            while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
947
-                $DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
948
-                $new_status = $this->_toggle_checkin($REG_ID, $DTT_ID);
949
-            }
950
-        } elseif (isset($this->_req_data['_regid'])) {
951
-            // coming from ajax request
952
-            $DTT_ID = isset($this->_req_data['dttid']) ? $this->_req_data['dttid'] : null;
953
-            $query_args['DTT_ID'] = $DTT_ID;
954
-            $new_status = $this->_toggle_checkin($this->_req_data['_regid'], $DTT_ID);
955
-        } else {
956
-            EE_Error::add_error(
957
-                esc_html__('Missing some required data to toggle the Check-in', 'event_espresso'),
958
-                __FILE__,
959
-                __FUNCTION__,
960
-                __LINE__
961
-            );
962
-        }
963
-        if (defined('DOING_AJAX')) {
964
-            return $new_status;
965
-        }
966
-        $this->_redirect_after_action(false, '', '', $query_args, true);
967
-    }
924
+	/**
925
+	 * handles toggling the checkin status for the registration,
926
+	 *
927
+	 * @access protected
928
+	 * @return int|void
929
+	 * @throws EE_Error
930
+	 * @throws InvalidArgumentException
931
+	 * @throws InvalidDataTypeException
932
+	 * @throws InvalidInterfaceException
933
+	 */
934
+	protected function _toggle_checkin_status()
935
+	{
936
+		// first let's get the query args out of the way for the redirect
937
+		$query_args = array(
938
+			'action'   => 'event_registrations',
939
+			'event_id' => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
940
+			'DTT_ID'   => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null,
941
+		);
942
+		$new_status = false;
943
+		// bulk action check in toggle
944
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
945
+			// cycle thru checkboxes
946
+			while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
947
+				$DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
948
+				$new_status = $this->_toggle_checkin($REG_ID, $DTT_ID);
949
+			}
950
+		} elseif (isset($this->_req_data['_regid'])) {
951
+			// coming from ajax request
952
+			$DTT_ID = isset($this->_req_data['dttid']) ? $this->_req_data['dttid'] : null;
953
+			$query_args['DTT_ID'] = $DTT_ID;
954
+			$new_status = $this->_toggle_checkin($this->_req_data['_regid'], $DTT_ID);
955
+		} else {
956
+			EE_Error::add_error(
957
+				esc_html__('Missing some required data to toggle the Check-in', 'event_espresso'),
958
+				__FILE__,
959
+				__FUNCTION__,
960
+				__LINE__
961
+			);
962
+		}
963
+		if (defined('DOING_AJAX')) {
964
+			return $new_status;
965
+		}
966
+		$this->_redirect_after_action(false, '', '', $query_args, true);
967
+	}
968 968
 
969 969
 
970
-    /**
971
-     * This is toggles a single Check-in for the given registration and datetime.
972
-     *
973
-     * @param  int $REG_ID The registration we're toggling
974
-     * @param  int $DTT_ID The datetime we're toggling
975
-     * @return int The new status toggled to.
976
-     * @throws EE_Error
977
-     * @throws InvalidArgumentException
978
-     * @throws InvalidDataTypeException
979
-     * @throws InvalidInterfaceException
980
-     */
981
-    private function _toggle_checkin($REG_ID, $DTT_ID)
982
-    {
983
-        /** @var EE_Registration $REG */
984
-        $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
985
-        $new_status = $REG->toggle_checkin_status($DTT_ID);
986
-        if ($new_status !== false) {
987
-            EE_Error::add_success($REG->get_checkin_msg($DTT_ID));
988
-        } else {
989
-            EE_Error::add_error($REG->get_checkin_msg($DTT_ID, true), __FILE__, __FUNCTION__, __LINE__);
990
-            $new_status = false;
991
-        }
992
-        return $new_status;
993
-    }
970
+	/**
971
+	 * This is toggles a single Check-in for the given registration and datetime.
972
+	 *
973
+	 * @param  int $REG_ID The registration we're toggling
974
+	 * @param  int $DTT_ID The datetime we're toggling
975
+	 * @return int The new status toggled to.
976
+	 * @throws EE_Error
977
+	 * @throws InvalidArgumentException
978
+	 * @throws InvalidDataTypeException
979
+	 * @throws InvalidInterfaceException
980
+	 */
981
+	private function _toggle_checkin($REG_ID, $DTT_ID)
982
+	{
983
+		/** @var EE_Registration $REG */
984
+		$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
985
+		$new_status = $REG->toggle_checkin_status($DTT_ID);
986
+		if ($new_status !== false) {
987
+			EE_Error::add_success($REG->get_checkin_msg($DTT_ID));
988
+		} else {
989
+			EE_Error::add_error($REG->get_checkin_msg($DTT_ID, true), __FILE__, __FUNCTION__, __LINE__);
990
+			$new_status = false;
991
+		}
992
+		return $new_status;
993
+	}
994 994
 
995 995
 
996
-    /**
997
-     * Takes care of deleting multiple EE_Checkin table rows
998
-     *
999
-     * @access protected
1000
-     * @return void
1001
-     * @throws EE_Error
1002
-     * @throws InvalidArgumentException
1003
-     * @throws InvalidDataTypeException
1004
-     * @throws InvalidInterfaceException
1005
-     */
1006
-    protected function _delete_checkin_rows()
1007
-    {
1008
-        $query_args = array(
1009
-            'action'  => 'registration_checkins',
1010
-            'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1011
-            '_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1012
-        );
1013
-        $errors = 0;
1014
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1015
-            while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
1016
-                if (! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
1017
-                    $errors++;
1018
-                }
1019
-            }
1020
-        } else {
1021
-            EE_Error::add_error(
1022
-                esc_html__(
1023
-                    'So, something went wrong with the bulk delete because there was no data received for instructions on WHAT to delete!',
1024
-                    'event_espresso'
1025
-                ),
1026
-                __FILE__,
1027
-                __FUNCTION__,
1028
-                __LINE__
1029
-            );
1030
-            $this->_redirect_after_action(false, '', '', $query_args, true);
1031
-        }
1032
-        if ($errors > 0) {
1033
-            EE_Error::add_error(
1034
-                sprintf(__('There were %d records that did not delete successfully', 'event_espresso'), $errors),
1035
-                __FILE__,
1036
-                __FUNCTION__,
1037
-                __LINE__
1038
-            );
1039
-        } else {
1040
-            EE_Error::add_success(__('Records were successfully deleted', 'event_espresso'));
1041
-        }
1042
-        $this->_redirect_after_action(false, '', '', $query_args, true);
1043
-    }
996
+	/**
997
+	 * Takes care of deleting multiple EE_Checkin table rows
998
+	 *
999
+	 * @access protected
1000
+	 * @return void
1001
+	 * @throws EE_Error
1002
+	 * @throws InvalidArgumentException
1003
+	 * @throws InvalidDataTypeException
1004
+	 * @throws InvalidInterfaceException
1005
+	 */
1006
+	protected function _delete_checkin_rows()
1007
+	{
1008
+		$query_args = array(
1009
+			'action'  => 'registration_checkins',
1010
+			'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1011
+			'_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1012
+		);
1013
+		$errors = 0;
1014
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1015
+			while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
1016
+				if (! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
1017
+					$errors++;
1018
+				}
1019
+			}
1020
+		} else {
1021
+			EE_Error::add_error(
1022
+				esc_html__(
1023
+					'So, something went wrong with the bulk delete because there was no data received for instructions on WHAT to delete!',
1024
+					'event_espresso'
1025
+				),
1026
+				__FILE__,
1027
+				__FUNCTION__,
1028
+				__LINE__
1029
+			);
1030
+			$this->_redirect_after_action(false, '', '', $query_args, true);
1031
+		}
1032
+		if ($errors > 0) {
1033
+			EE_Error::add_error(
1034
+				sprintf(__('There were %d records that did not delete successfully', 'event_espresso'), $errors),
1035
+				__FILE__,
1036
+				__FUNCTION__,
1037
+				__LINE__
1038
+			);
1039
+		} else {
1040
+			EE_Error::add_success(__('Records were successfully deleted', 'event_espresso'));
1041
+		}
1042
+		$this->_redirect_after_action(false, '', '', $query_args, true);
1043
+	}
1044 1044
 
1045 1045
 
1046
-    /**
1047
-     * Deletes a single EE_Checkin row
1048
-     *
1049
-     * @return void
1050
-     * @throws EE_Error
1051
-     * @throws InvalidArgumentException
1052
-     * @throws InvalidDataTypeException
1053
-     * @throws InvalidInterfaceException
1054
-     */
1055
-    protected function _delete_checkin_row()
1056
-    {
1057
-        $query_args = array(
1058
-            'action'  => 'registration_checkins',
1059
-            'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1060
-            '_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1061
-        );
1062
-        if (! empty($this->_req_data['CHK_ID'])) {
1063
-            if (! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
1064
-                EE_Error::add_error(
1065
-                    esc_html__('Something went wrong and this check-in record was not deleted', 'event_espresso'),
1066
-                    __FILE__,
1067
-                    __FUNCTION__,
1068
-                    __LINE__
1069
-                );
1070
-            } else {
1071
-                EE_Error::add_success(__('Check-In record successfully deleted', 'event_espresso'));
1072
-            }
1073
-        } else {
1074
-            EE_Error::add_error(
1075
-                esc_html__(
1076
-                    'In order to delete a Check-in record, there must be a Check-In ID available. There is not. It is not your fault, there is just a gremlin living in the code',
1077
-                    'event_espresso'
1078
-                ),
1079
-                __FILE__,
1080
-                __FUNCTION__,
1081
-                __LINE__
1082
-            );
1083
-        }
1084
-        $this->_redirect_after_action(false, '', '', $query_args, true);
1085
-    }
1046
+	/**
1047
+	 * Deletes a single EE_Checkin row
1048
+	 *
1049
+	 * @return void
1050
+	 * @throws EE_Error
1051
+	 * @throws InvalidArgumentException
1052
+	 * @throws InvalidDataTypeException
1053
+	 * @throws InvalidInterfaceException
1054
+	 */
1055
+	protected function _delete_checkin_row()
1056
+	{
1057
+		$query_args = array(
1058
+			'action'  => 'registration_checkins',
1059
+			'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1060
+			'_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1061
+		);
1062
+		if (! empty($this->_req_data['CHK_ID'])) {
1063
+			if (! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
1064
+				EE_Error::add_error(
1065
+					esc_html__('Something went wrong and this check-in record was not deleted', 'event_espresso'),
1066
+					__FILE__,
1067
+					__FUNCTION__,
1068
+					__LINE__
1069
+				);
1070
+			} else {
1071
+				EE_Error::add_success(__('Check-In record successfully deleted', 'event_espresso'));
1072
+			}
1073
+		} else {
1074
+			EE_Error::add_error(
1075
+				esc_html__(
1076
+					'In order to delete a Check-in record, there must be a Check-In ID available. There is not. It is not your fault, there is just a gremlin living in the code',
1077
+					'event_espresso'
1078
+				),
1079
+				__FILE__,
1080
+				__FUNCTION__,
1081
+				__LINE__
1082
+			);
1083
+		}
1084
+		$this->_redirect_after_action(false, '', '', $query_args, true);
1085
+	}
1086 1086
 
1087 1087
 
1088
-    /**
1089
-     *        generates HTML for the Event Registrations List Table
1090
-     *
1091
-     * @access protected
1092
-     * @return void
1093
-     * @throws EE_Error
1094
-     * @throws InvalidArgumentException
1095
-     * @throws InvalidDataTypeException
1096
-     * @throws InvalidInterfaceException
1097
-     */
1098
-    protected function _event_registrations_list_table()
1099
-    {
1100
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1101
-        $this->_admin_page_title .= isset($this->_req_data['event_id'])
1102
-            ? $this->get_action_link_or_button(
1103
-                'new_registration',
1104
-                'add-registrant',
1105
-                array('event_id' => $this->_req_data['event_id']),
1106
-                'add-new-h2',
1107
-                '',
1108
-                false
1109
-            )
1110
-            : '';
1111
-        $checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
1112
-        $checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
1113
-        $checked_never = new CheckinStatusDashicon(EE_Checkin::status_checked_never);
1114
-        $legend_items = array(
1115
-            'star-icon'        => array(
1116
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
1117
-                'desc'  => esc_html__('This Registrant is the Primary Registrant', 'event_espresso'),
1118
-            ),
1119
-            'checkin'          => array(
1120
-                'class' => $checked_in->cssClasses(),
1121
-                'desc'  => $checked_in->legendLabel(),
1122
-            ),
1123
-            'checkout'         => array(
1124
-                'class' => $checked_out->cssClasses(),
1125
-                'desc'  => $checked_out->legendLabel(),
1126
-            ),
1127
-            'nocheckinrecord'  => array(
1128
-                'class' => $checked_never->cssClasses(),
1129
-                'desc'  => $checked_never->legendLabel(),
1130
-            ),
1131
-            'approved_status'  => array(
1132
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1133
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1134
-            ),
1135
-            'cancelled_status' => array(
1136
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1137
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1138
-            ),
1139
-            'declined_status'  => array(
1140
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1141
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1142
-            ),
1143
-            'not_approved'     => array(
1144
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1145
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1146
-            ),
1147
-            'pending_status'   => array(
1148
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1149
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1150
-            ),
1151
-            'wait_list'        => array(
1152
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1153
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1154
-            ),
1155
-        );
1156
-        $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1157
-        $event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1158
-        $this->_template_args['before_list_table'] = ! empty($event_id)
1159
-            ? '<h2>' . sprintf(
1160
-                esc_html__('Viewing Registrations for Event: %s', 'event_espresso'),
1161
-                EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1162
-            ) . '</h2>'
1163
-            : '';
1164
-        // need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on
1165
-        // the event.
1166
-        /** @var EE_Event $event */
1167
-        $event = EEM_Event::instance()->get_one_by_ID($event_id);
1168
-        $DTT_ID = ! empty($this->_req_data['DTT_ID']) ? absint($this->_req_data['DTT_ID']) : 0;
1169
-        $datetime = null;
1170
-        if ($event instanceof EE_Event) {
1171
-            $datetimes_on_event = $event->datetimes();
1172
-            if (count($datetimes_on_event) === 1) {
1173
-                $datetime = reset($datetimes_on_event);
1174
-            }
1175
-        }
1176
-        $datetime = $datetime instanceof EE_Datetime ? $datetime : EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1177
-        if ($datetime instanceof EE_Datetime && $this->_template_args['before_list_table'] !== '') {
1178
-            $this->_template_args['before_list_table'] = substr($this->_template_args['before_list_table'], 0, -5);
1179
-            $this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1180
-            $this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1181
-            $this->_template_args['before_list_table'] .= $datetime->name();
1182
-            $this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1183
-            $this->_template_args['before_list_table'] .= '</span></h2>';
1184
-        }
1185
-        // if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status
1186
-        // column represents
1187
-        if (! $datetime instanceof EE_Datetime) {
1188
-            $this->_template_args['before_list_table'] .= '<br><p class="description">'
1189
-                                                          . esc_html__(
1190
-                                                              'In this view, the check-in status represents the latest check-in record for the registration in that row.',
1191
-                                                              'event_espresso'
1192
-                                                          )
1193
-                                                          . '</p>';
1194
-        }
1195
-        $this->display_admin_list_table_page_with_no_sidebar();
1196
-    }
1088
+	/**
1089
+	 *        generates HTML for the Event Registrations List Table
1090
+	 *
1091
+	 * @access protected
1092
+	 * @return void
1093
+	 * @throws EE_Error
1094
+	 * @throws InvalidArgumentException
1095
+	 * @throws InvalidDataTypeException
1096
+	 * @throws InvalidInterfaceException
1097
+	 */
1098
+	protected function _event_registrations_list_table()
1099
+	{
1100
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1101
+		$this->_admin_page_title .= isset($this->_req_data['event_id'])
1102
+			? $this->get_action_link_or_button(
1103
+				'new_registration',
1104
+				'add-registrant',
1105
+				array('event_id' => $this->_req_data['event_id']),
1106
+				'add-new-h2',
1107
+				'',
1108
+				false
1109
+			)
1110
+			: '';
1111
+		$checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
1112
+		$checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
1113
+		$checked_never = new CheckinStatusDashicon(EE_Checkin::status_checked_never);
1114
+		$legend_items = array(
1115
+			'star-icon'        => array(
1116
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
1117
+				'desc'  => esc_html__('This Registrant is the Primary Registrant', 'event_espresso'),
1118
+			),
1119
+			'checkin'          => array(
1120
+				'class' => $checked_in->cssClasses(),
1121
+				'desc'  => $checked_in->legendLabel(),
1122
+			),
1123
+			'checkout'         => array(
1124
+				'class' => $checked_out->cssClasses(),
1125
+				'desc'  => $checked_out->legendLabel(),
1126
+			),
1127
+			'nocheckinrecord'  => array(
1128
+				'class' => $checked_never->cssClasses(),
1129
+				'desc'  => $checked_never->legendLabel(),
1130
+			),
1131
+			'approved_status'  => array(
1132
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1133
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1134
+			),
1135
+			'cancelled_status' => array(
1136
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1137
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1138
+			),
1139
+			'declined_status'  => array(
1140
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1141
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1142
+			),
1143
+			'not_approved'     => array(
1144
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1145
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1146
+			),
1147
+			'pending_status'   => array(
1148
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1149
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1150
+			),
1151
+			'wait_list'        => array(
1152
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1153
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1154
+			),
1155
+		);
1156
+		$this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1157
+		$event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1158
+		$this->_template_args['before_list_table'] = ! empty($event_id)
1159
+			? '<h2>' . sprintf(
1160
+				esc_html__('Viewing Registrations for Event: %s', 'event_espresso'),
1161
+				EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1162
+			) . '</h2>'
1163
+			: '';
1164
+		// need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on
1165
+		// the event.
1166
+		/** @var EE_Event $event */
1167
+		$event = EEM_Event::instance()->get_one_by_ID($event_id);
1168
+		$DTT_ID = ! empty($this->_req_data['DTT_ID']) ? absint($this->_req_data['DTT_ID']) : 0;
1169
+		$datetime = null;
1170
+		if ($event instanceof EE_Event) {
1171
+			$datetimes_on_event = $event->datetimes();
1172
+			if (count($datetimes_on_event) === 1) {
1173
+				$datetime = reset($datetimes_on_event);
1174
+			}
1175
+		}
1176
+		$datetime = $datetime instanceof EE_Datetime ? $datetime : EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1177
+		if ($datetime instanceof EE_Datetime && $this->_template_args['before_list_table'] !== '') {
1178
+			$this->_template_args['before_list_table'] = substr($this->_template_args['before_list_table'], 0, -5);
1179
+			$this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1180
+			$this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1181
+			$this->_template_args['before_list_table'] .= $datetime->name();
1182
+			$this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1183
+			$this->_template_args['before_list_table'] .= '</span></h2>';
1184
+		}
1185
+		// if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status
1186
+		// column represents
1187
+		if (! $datetime instanceof EE_Datetime) {
1188
+			$this->_template_args['before_list_table'] .= '<br><p class="description">'
1189
+														  . esc_html__(
1190
+															  'In this view, the check-in status represents the latest check-in record for the registration in that row.',
1191
+															  'event_espresso'
1192
+														  )
1193
+														  . '</p>';
1194
+		}
1195
+		$this->display_admin_list_table_page_with_no_sidebar();
1196
+	}
1197 1197
 
1198
-    /**
1199
-     * Download the registrations check-in report (same as the normal registration report, but with different where
1200
-     * conditions)
1201
-     *
1202
-     * @return void ends the request by a redirect or download
1203
-     */
1204
-    public function _registrations_checkin_report()
1205
-    {
1206
-        $this->_registrations_report_base('_get_checkin_query_params_from_request');
1207
-    }
1198
+	/**
1199
+	 * Download the registrations check-in report (same as the normal registration report, but with different where
1200
+	 * conditions)
1201
+	 *
1202
+	 * @return void ends the request by a redirect or download
1203
+	 */
1204
+	public function _registrations_checkin_report()
1205
+	{
1206
+		$this->_registrations_report_base('_get_checkin_query_params_from_request');
1207
+	}
1208 1208
 
1209
-    /**
1210
-     * Gets the query params from the request, plus adds a where condition for the registration status,
1211
-     * because on the checkin page we only ever want to see approved and pending-approval registrations
1212
-     *
1213
-     * @param array $request
1214
-     * @param int   $per_page
1215
-     * @param bool  $count
1216
-     * @return array
1217
-     * @throws EE_Error
1218
-     */
1219
-    protected function _get_checkin_query_params_from_request(
1220
-        $request,
1221
-        $per_page = 10,
1222
-        $count = false
1223
-    ) {
1224
-        $query_params = $this->_get_registration_query_parameters($request, $per_page, $count);
1225
-        // unlike the regular registrations list table,
1226
-        $status_ids_array = apply_filters(
1227
-            'FHEE__Extend_Registrations_Admin_Page__get_event_attendees__status_ids_array',
1228
-            array(EEM_Registration::status_id_pending_payment, EEM_Registration::status_id_approved)
1229
-        );
1230
-        $query_params[0]['STS_ID'] = array('IN', $status_ids_array);
1231
-        return $query_params;
1232
-    }
1209
+	/**
1210
+	 * Gets the query params from the request, plus adds a where condition for the registration status,
1211
+	 * because on the checkin page we only ever want to see approved and pending-approval registrations
1212
+	 *
1213
+	 * @param array $request
1214
+	 * @param int   $per_page
1215
+	 * @param bool  $count
1216
+	 * @return array
1217
+	 * @throws EE_Error
1218
+	 */
1219
+	protected function _get_checkin_query_params_from_request(
1220
+		$request,
1221
+		$per_page = 10,
1222
+		$count = false
1223
+	) {
1224
+		$query_params = $this->_get_registration_query_parameters($request, $per_page, $count);
1225
+		// unlike the regular registrations list table,
1226
+		$status_ids_array = apply_filters(
1227
+			'FHEE__Extend_Registrations_Admin_Page__get_event_attendees__status_ids_array',
1228
+			array(EEM_Registration::status_id_pending_payment, EEM_Registration::status_id_approved)
1229
+		);
1230
+		$query_params[0]['STS_ID'] = array('IN', $status_ids_array);
1231
+		return $query_params;
1232
+	}
1233 1233
 
1234 1234
 
1235
-    /**
1236
-     * Gets registrations for an event
1237
-     *
1238
-     * @param int    $per_page
1239
-     * @param bool   $count whether to return count or data.
1240
-     * @param bool   $trash
1241
-     * @param string $orderby
1242
-     * @return EE_Registration[]|int
1243
-     * @throws EE_Error
1244
-     * @throws InvalidArgumentException
1245
-     * @throws InvalidDataTypeException
1246
-     * @throws InvalidInterfaceException
1247
-     */
1248
-    public function get_event_attendees($per_page = 10, $count = false, $trash = false, $orderby = 'ATT_fname')
1249
-    {
1250
-        // normalize some request params that get setup by the parent `get_registrations` method.
1251
-        $request = $this->_req_data;
1252
-        $request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1253
-        $request['order'] = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1254
-        if ($trash) {
1255
-            $request['status'] = 'trash';
1256
-        }
1257
-        $query_params = $this->_get_checkin_query_params_from_request($request, $per_page, $count);
1258
-        /**
1259
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1260
-         *
1261
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1262
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1263
-         *                             or if you have the development copy of EE you can view this at the path:
1264
-         *                             /docs/G--Model-System/model-query-params.md
1265
-         */
1266
-        $query_params['group_by'] = '';
1235
+	/**
1236
+	 * Gets registrations for an event
1237
+	 *
1238
+	 * @param int    $per_page
1239
+	 * @param bool   $count whether to return count or data.
1240
+	 * @param bool   $trash
1241
+	 * @param string $orderby
1242
+	 * @return EE_Registration[]|int
1243
+	 * @throws EE_Error
1244
+	 * @throws InvalidArgumentException
1245
+	 * @throws InvalidDataTypeException
1246
+	 * @throws InvalidInterfaceException
1247
+	 */
1248
+	public function get_event_attendees($per_page = 10, $count = false, $trash = false, $orderby = 'ATT_fname')
1249
+	{
1250
+		// normalize some request params that get setup by the parent `get_registrations` method.
1251
+		$request = $this->_req_data;
1252
+		$request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1253
+		$request['order'] = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1254
+		if ($trash) {
1255
+			$request['status'] = 'trash';
1256
+		}
1257
+		$query_params = $this->_get_checkin_query_params_from_request($request, $per_page, $count);
1258
+		/**
1259
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1260
+		 *
1261
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1262
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1263
+		 *                             or if you have the development copy of EE you can view this at the path:
1264
+		 *                             /docs/G--Model-System/model-query-params.md
1265
+		 */
1266
+		$query_params['group_by'] = '';
1267 1267
 
1268
-        return $count
1269
-            ? EEM_Registration::instance()->count($query_params)
1270
-            /** @type EE_Registration[] */
1271
-            : EEM_Registration::instance()->get_all($query_params);
1272
-    }
1268
+		return $count
1269
+			? EEM_Registration::instance()->count($query_params)
1270
+			/** @type EE_Registration[] */
1271
+			: EEM_Registration::instance()->get_all($query_params);
1272
+	}
1273 1273
 }
Please login to merge, or discard this patch.
admin_pages/registrations/Registrations_Admin_Page.core.php 1 patch
Indentation   +3831 added lines, -3831 removed lines patch added patch discarded remove patch
@@ -19,2406 +19,2406 @@  discard block
 block discarded – undo
19 19
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
20 20
 {
21 21
 
22
-    /**
23
-     * @var EE_Registration
24
-     */
25
-    private $_registration;
26
-
27
-    /**
28
-     * @var EE_Event
29
-     */
30
-    private $_reg_event;
31
-
32
-    /**
33
-     * @var EE_Session
34
-     */
35
-    private $_session;
36
-
37
-    private static $_reg_status;
38
-
39
-    /**
40
-     * Form for displaying the custom questions for this registration.
41
-     * This gets used a few times throughout the request so its best to cache it
42
-     *
43
-     * @var EE_Registration_Custom_Questions_Form
44
-     */
45
-    protected $_reg_custom_questions_form = null;
46
-
47
-
48
-    /**
49
-     *        constructor
50
-     *
51
-     * @Constructor
52
-     * @access public
53
-     * @param bool $routing
54
-     * @return Registrations_Admin_Page
55
-     */
56
-    public function __construct($routing = true)
57
-    {
58
-        parent::__construct($routing);
59
-        add_action('wp_loaded', array($this, 'wp_loaded'));
60
-    }
61
-
62
-
63
-    public function wp_loaded()
64
-    {
65
-        // when adding a new registration...
66
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67
-            EE_System::do_not_cache();
68
-            if (! isset($this->_req_data['processing_registration'])
69
-                || absint($this->_req_data['processing_registration']) !== 1
70
-            ) {
71
-                // and it's NOT the attendee information reg step
72
-                // force cookie expiration by setting time to last week
73
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
74
-                // and update the global
75
-                $_COOKIE['ee_registration_added'] = 0;
76
-            }
77
-        }
78
-    }
79
-
80
-
81
-    protected function _init_page_props()
82
-    {
83
-        $this->page_slug = REG_PG_SLUG;
84
-        $this->_admin_base_url = REG_ADMIN_URL;
85
-        $this->_admin_base_path = REG_ADMIN;
86
-        $this->page_label = esc_html__('Registrations', 'event_espresso');
87
-        $this->_cpt_routes = array(
88
-            'add_new_attendee' => 'espresso_attendees',
89
-            'edit_attendee'    => 'espresso_attendees',
90
-            'insert_attendee'  => 'espresso_attendees',
91
-            'update_attendee'  => 'espresso_attendees',
92
-        );
93
-        $this->_cpt_model_names = array(
94
-            'add_new_attendee' => 'EEM_Attendee',
95
-            'edit_attendee'    => 'EEM_Attendee',
96
-        );
97
-        $this->_cpt_edit_routes = array(
98
-            'espresso_attendees' => 'edit_attendee',
99
-        );
100
-        $this->_pagenow_map = array(
101
-            'add_new_attendee' => 'post-new.php',
102
-            'edit_attendee'    => 'post.php',
103
-            'trash'            => 'post.php',
104
-        );
105
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
106
-        // add filters so that the comment urls don't take users to a confusing 404 page
107
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
108
-    }
109
-
110
-
111
-    public function clear_comment_link($link, $comment, $args)
112
-    {
113
-        // gotta make sure this only happens on this route
114
-        $post_type = get_post_type($comment->comment_post_ID);
115
-        if ($post_type === 'espresso_attendees') {
116
-            return '#commentsdiv';
117
-        }
118
-        return $link;
119
-    }
120
-
121
-
122
-    protected function _ajax_hooks()
123
-    {
124
-        // todo: all hooks for registrations ajax goes in here
125
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
126
-    }
127
-
128
-
129
-    protected function _define_page_props()
130
-    {
131
-        $this->_admin_page_title = $this->page_label;
132
-        $this->_labels = array(
133
-            'buttons'                      => array(
134
-                'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
135
-                'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
136
-                'edit'                => esc_html__('Edit Contact', 'event_espresso'),
137
-                'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
138
-                'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
139
-                'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
140
-                'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
141
-                'contact_list_export' => esc_html__("Export Data", "event_espresso"),
142
-            ),
143
-            'publishbox'                   => array(
144
-                'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
145
-                'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
146
-            ),
147
-            'hide_add_button_on_cpt_route' => array(
148
-                'edit_attendee' => true,
149
-            ),
150
-        );
151
-    }
152
-
153
-
154
-    /**
155
-     *        grab url requests and route them
156
-     *
157
-     * @access private
158
-     * @return void
159
-     */
160
-    public function _set_page_routes()
161
-    {
162
-        $this->_get_registration_status_array();
163
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
164
-            ? $this->_req_data['_REG_ID'] : 0;
165
-        $reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
166
-            ? $this->_req_data['reg_status_change_form']['REG_ID']
167
-            : $reg_id;
168
-        $att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
169
-            ? $this->_req_data['ATT_ID'] : 0;
170
-        $att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
171
-            ? $this->_req_data['post']
172
-            : $att_id;
173
-        $this->_page_routes = array(
174
-            'default'                             => array(
175
-                'func'       => '_registrations_overview_list_table',
176
-                'capability' => 'ee_read_registrations',
177
-            ),
178
-            'view_registration'                   => array(
179
-                'func'       => '_registration_details',
180
-                'capability' => 'ee_read_registration',
181
-                'obj_id'     => $reg_id,
182
-            ),
183
-            'edit_registration'                   => array(
184
-                'func'               => '_update_attendee_registration_form',
185
-                'noheader'           => true,
186
-                'headers_sent_route' => 'view_registration',
187
-                'capability'         => 'ee_edit_registration',
188
-                'obj_id'             => $reg_id,
189
-                '_REG_ID'            => $reg_id,
190
-            ),
191
-            'trash_registrations'                 => array(
192
-                'func'       => '_trash_or_restore_registrations',
193
-                'args'       => array('trash' => true),
194
-                'noheader'   => true,
195
-                'capability' => 'ee_delete_registrations',
196
-            ),
197
-            'restore_registrations'               => array(
198
-                'func'       => '_trash_or_restore_registrations',
199
-                'args'       => array('trash' => false),
200
-                'noheader'   => true,
201
-                'capability' => 'ee_delete_registrations',
202
-            ),
203
-            'delete_registrations'                => array(
204
-                'func'       => '_delete_registrations',
205
-                'noheader'   => true,
206
-                'capability' => 'ee_delete_registrations',
207
-            ),
208
-            'new_registration'                    => array(
209
-                'func'       => 'new_registration',
210
-                'capability' => 'ee_edit_registrations',
211
-            ),
212
-            'process_reg_step'                    => array(
213
-                'func'       => 'process_reg_step',
214
-                'noheader'   => true,
215
-                'capability' => 'ee_edit_registrations',
216
-            ),
217
-            'redirect_to_txn'                     => array(
218
-                'func'       => 'redirect_to_txn',
219
-                'noheader'   => true,
220
-                'capability' => 'ee_edit_registrations',
221
-            ),
222
-            'change_reg_status'                   => array(
223
-                'func'       => '_change_reg_status',
224
-                'noheader'   => true,
225
-                'capability' => 'ee_edit_registration',
226
-                'obj_id'     => $reg_id,
227
-            ),
228
-            'approve_registration'                => array(
229
-                'func'       => 'approve_registration',
230
-                'noheader'   => true,
231
-                'capability' => 'ee_edit_registration',
232
-                'obj_id'     => $reg_id,
233
-            ),
234
-            'approve_and_notify_registration'     => array(
235
-                'func'       => 'approve_registration',
236
-                'noheader'   => true,
237
-                'args'       => array(true),
238
-                'capability' => 'ee_edit_registration',
239
-                'obj_id'     => $reg_id,
240
-            ),
241
-            'approve_registrations'               => array(
242
-                'func'       => 'bulk_action_on_registrations',
243
-                'noheader'   => true,
244
-                'capability' => 'ee_edit_registrations',
245
-                'args'       => array('approve'),
246
-            ),
247
-            'approve_and_notify_registrations'    => array(
248
-                'func'       => 'bulk_action_on_registrations',
249
-                'noheader'   => true,
250
-                'capability' => 'ee_edit_registrations',
251
-                'args'       => array('approve', true),
252
-            ),
253
-            'decline_registration'                => array(
254
-                'func'       => 'decline_registration',
255
-                'noheader'   => true,
256
-                'capability' => 'ee_edit_registration',
257
-                'obj_id'     => $reg_id,
258
-            ),
259
-            'decline_and_notify_registration'     => array(
260
-                'func'       => 'decline_registration',
261
-                'noheader'   => true,
262
-                'args'       => array(true),
263
-                'capability' => 'ee_edit_registration',
264
-                'obj_id'     => $reg_id,
265
-            ),
266
-            'decline_registrations'               => array(
267
-                'func'       => 'bulk_action_on_registrations',
268
-                'noheader'   => true,
269
-                'capability' => 'ee_edit_registrations',
270
-                'args'       => array('decline'),
271
-            ),
272
-            'decline_and_notify_registrations'    => array(
273
-                'func'       => 'bulk_action_on_registrations',
274
-                'noheader'   => true,
275
-                'capability' => 'ee_edit_registrations',
276
-                'args'       => array('decline', true),
277
-            ),
278
-            'pending_registration'                => array(
279
-                'func'       => 'pending_registration',
280
-                'noheader'   => true,
281
-                'capability' => 'ee_edit_registration',
282
-                'obj_id'     => $reg_id,
283
-            ),
284
-            'pending_and_notify_registration'     => array(
285
-                'func'       => 'pending_registration',
286
-                'noheader'   => true,
287
-                'args'       => array(true),
288
-                'capability' => 'ee_edit_registration',
289
-                'obj_id'     => $reg_id,
290
-            ),
291
-            'pending_registrations'               => array(
292
-                'func'       => 'bulk_action_on_registrations',
293
-                'noheader'   => true,
294
-                'capability' => 'ee_edit_registrations',
295
-                'args'       => array('pending'),
296
-            ),
297
-            'pending_and_notify_registrations'    => array(
298
-                'func'       => 'bulk_action_on_registrations',
299
-                'noheader'   => true,
300
-                'capability' => 'ee_edit_registrations',
301
-                'args'       => array('pending', true),
302
-            ),
303
-            'no_approve_registration'             => array(
304
-                'func'       => 'not_approve_registration',
305
-                'noheader'   => true,
306
-                'capability' => 'ee_edit_registration',
307
-                'obj_id'     => $reg_id,
308
-            ),
309
-            'no_approve_and_notify_registration'  => array(
310
-                'func'       => 'not_approve_registration',
311
-                'noheader'   => true,
312
-                'args'       => array(true),
313
-                'capability' => 'ee_edit_registration',
314
-                'obj_id'     => $reg_id,
315
-            ),
316
-            'no_approve_registrations'            => array(
317
-                'func'       => 'bulk_action_on_registrations',
318
-                'noheader'   => true,
319
-                'capability' => 'ee_edit_registrations',
320
-                'args'       => array('not_approve'),
321
-            ),
322
-            'no_approve_and_notify_registrations' => array(
323
-                'func'       => 'bulk_action_on_registrations',
324
-                'noheader'   => true,
325
-                'capability' => 'ee_edit_registrations',
326
-                'args'       => array('not_approve', true),
327
-            ),
328
-            'cancel_registration'                 => array(
329
-                'func'       => 'cancel_registration',
330
-                'noheader'   => true,
331
-                'capability' => 'ee_edit_registration',
332
-                'obj_id'     => $reg_id,
333
-            ),
334
-            'cancel_and_notify_registration'      => array(
335
-                'func'       => 'cancel_registration',
336
-                'noheader'   => true,
337
-                'args'       => array(true),
338
-                'capability' => 'ee_edit_registration',
339
-                'obj_id'     => $reg_id,
340
-            ),
341
-            'cancel_registrations'                => array(
342
-                'func'       => 'bulk_action_on_registrations',
343
-                'noheader'   => true,
344
-                'capability' => 'ee_edit_registrations',
345
-                'args'       => array('cancel'),
346
-            ),
347
-            'cancel_and_notify_registrations'     => array(
348
-                'func'       => 'bulk_action_on_registrations',
349
-                'noheader'   => true,
350
-                'capability' => 'ee_edit_registrations',
351
-                'args'       => array('cancel', true),
352
-            ),
353
-            'wait_list_registration'              => array(
354
-                'func'       => 'wait_list_registration',
355
-                'noheader'   => true,
356
-                'capability' => 'ee_edit_registration',
357
-                'obj_id'     => $reg_id,
358
-            ),
359
-            'wait_list_and_notify_registration'   => array(
360
-                'func'       => 'wait_list_registration',
361
-                'noheader'   => true,
362
-                'args'       => array(true),
363
-                'capability' => 'ee_edit_registration',
364
-                'obj_id'     => $reg_id,
365
-            ),
366
-            'contact_list'                        => array(
367
-                'func'       => '_attendee_contact_list_table',
368
-                'capability' => 'ee_read_contacts',
369
-            ),
370
-            'add_new_attendee'                    => array(
371
-                'func' => '_create_new_cpt_item',
372
-                'args' => array(
373
-                    'new_attendee' => true,
374
-                    'capability'   => 'ee_edit_contacts',
375
-                ),
376
-            ),
377
-            'edit_attendee'                       => array(
378
-                'func'       => '_edit_cpt_item',
379
-                'capability' => 'ee_edit_contacts',
380
-                'obj_id'     => $att_id,
381
-            ),
382
-            'duplicate_attendee'                  => array(
383
-                'func'       => '_duplicate_attendee',
384
-                'noheader'   => true,
385
-                'capability' => 'ee_edit_contacts',
386
-                'obj_id'     => $att_id,
387
-            ),
388
-            'insert_attendee'                     => array(
389
-                'func'       => '_insert_or_update_attendee',
390
-                'args'       => array(
391
-                    'new_attendee' => true,
392
-                ),
393
-                'noheader'   => true,
394
-                'capability' => 'ee_edit_contacts',
395
-            ),
396
-            'update_attendee'                     => array(
397
-                'func'       => '_insert_or_update_attendee',
398
-                'args'       => array(
399
-                    'new_attendee' => false,
400
-                ),
401
-                'noheader'   => true,
402
-                'capability' => 'ee_edit_contacts',
403
-                'obj_id'     => $att_id,
404
-            ),
405
-            'trash_attendees'                     => array(
406
-                'func'       => '_trash_or_restore_attendees',
407
-                'args'       => array(
408
-                    'trash' => 'true',
409
-                ),
410
-                'noheader'   => true,
411
-                'capability' => 'ee_delete_contacts',
412
-            ),
413
-            'trash_attendee'                      => array(
414
-                'func'       => '_trash_or_restore_attendees',
415
-                'args'       => array(
416
-                    'trash' => true,
417
-                ),
418
-                'noheader'   => true,
419
-                'capability' => 'ee_delete_contacts',
420
-                'obj_id'     => $att_id,
421
-            ),
422
-            'restore_attendees'                   => array(
423
-                'func'       => '_trash_or_restore_attendees',
424
-                'args'       => array(
425
-                    'trash' => false,
426
-                ),
427
-                'noheader'   => true,
428
-                'capability' => 'ee_delete_contacts',
429
-                'obj_id'     => $att_id,
430
-            ),
431
-            'resend_registration'                 => array(
432
-                'func'       => '_resend_registration',
433
-                'noheader'   => true,
434
-                'capability' => 'ee_send_message',
435
-            ),
436
-            'registrations_report'                => array(
437
-                'func'       => '_registrations_report',
438
-                'noheader'   => true,
439
-                'capability' => 'ee_read_registrations',
440
-            ),
441
-            'contact_list_export'                 => array(
442
-                'func'       => '_contact_list_export',
443
-                'noheader'   => true,
444
-                'capability' => 'export',
445
-            ),
446
-            'contact_list_report'                 => array(
447
-                'func'       => '_contact_list_report',
448
-                'noheader'   => true,
449
-                'capability' => 'ee_read_contacts',
450
-            ),
451
-        );
452
-    }
453
-
454
-
455
-    protected function _set_page_config()
456
-    {
457
-        $this->_page_config = array(
458
-            'default'           => array(
459
-                'nav'           => array(
460
-                    'label' => esc_html__('Overview', 'event_espresso'),
461
-                    'order' => 5,
462
-                ),
463
-                'help_tabs'     => array(
464
-                    'registrations_overview_help_tab'                       => array(
465
-                        'title'    => esc_html__('Registrations Overview', 'event_espresso'),
466
-                        'filename' => 'registrations_overview',
467
-                    ),
468
-                    'registrations_overview_table_column_headings_help_tab' => array(
469
-                        'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
470
-                        'filename' => 'registrations_overview_table_column_headings',
471
-                    ),
472
-                    'registrations_overview_filters_help_tab'               => array(
473
-                        'title'    => esc_html__('Registration Filters', 'event_espresso'),
474
-                        'filename' => 'registrations_overview_filters',
475
-                    ),
476
-                    'registrations_overview_views_help_tab'                 => array(
477
-                        'title'    => esc_html__('Registration Views', 'event_espresso'),
478
-                        'filename' => 'registrations_overview_views',
479
-                    ),
480
-                    'registrations_regoverview_other_help_tab'              => array(
481
-                        'title'    => esc_html__('Registrations Other', 'event_espresso'),
482
-                        'filename' => 'registrations_overview_other',
483
-                    ),
484
-                ),
485
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
486
-                'qtips'         => array('Registration_List_Table_Tips'),
487
-                'list_table'    => 'EE_Registrations_List_Table',
488
-                'require_nonce' => false,
489
-            ),
490
-            'view_registration' => array(
491
-                'nav'           => array(
492
-                    'label'      => esc_html__('REG Details', 'event_espresso'),
493
-                    'order'      => 15,
494
-                    'url'        => isset($this->_req_data['_REG_ID'])
495
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
496
-                        : $this->_admin_base_url,
497
-                    'persistent' => false,
498
-                ),
499
-                'help_tabs'     => array(
500
-                    'registrations_details_help_tab'                    => array(
501
-                        'title'    => esc_html__('Registration Details', 'event_espresso'),
502
-                        'filename' => 'registrations_details',
503
-                    ),
504
-                    'registrations_details_table_help_tab'              => array(
505
-                        'title'    => esc_html__('Registration Details Table', 'event_espresso'),
506
-                        'filename' => 'registrations_details_table',
507
-                    ),
508
-                    'registrations_details_form_answers_help_tab'       => array(
509
-                        'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
510
-                        'filename' => 'registrations_details_form_answers',
511
-                    ),
512
-                    'registrations_details_registrant_details_help_tab' => array(
513
-                        'title'    => esc_html__('Contact Details', 'event_espresso'),
514
-                        'filename' => 'registrations_details_registrant_details',
515
-                    ),
516
-                ),
517
-                'help_tour'     => array('Registration_Details_Help_Tour'),
518
-                'metaboxes'     => array_merge(
519
-                    $this->_default_espresso_metaboxes,
520
-                    array('_registration_details_metaboxes')
521
-                ),
522
-                'require_nonce' => false,
523
-            ),
524
-            'new_registration'  => array(
525
-                'nav'           => array(
526
-                    'label'      => esc_html__('Add New Registration', 'event_espresso'),
527
-                    'url'        => '#',
528
-                    'order'      => 15,
529
-                    'persistent' => false,
530
-                ),
531
-                'metaboxes'     => $this->_default_espresso_metaboxes,
532
-                'labels'        => array(
533
-                    'publishbox' => esc_html__('Save Registration', 'event_espresso'),
534
-                ),
535
-                'require_nonce' => false,
536
-            ),
537
-            'add_new_attendee'  => array(
538
-                'nav'           => array(
539
-                    'label'      => esc_html__('Add Contact', 'event_espresso'),
540
-                    'order'      => 15,
541
-                    'persistent' => false,
542
-                ),
543
-                'metaboxes'     => array_merge(
544
-                    $this->_default_espresso_metaboxes,
545
-                    array('_publish_post_box', 'attendee_editor_metaboxes')
546
-                ),
547
-                'require_nonce' => false,
548
-            ),
549
-            'edit_attendee'     => array(
550
-                'nav'           => array(
551
-                    'label'      => esc_html__('Edit Contact', 'event_espresso'),
552
-                    'order'      => 15,
553
-                    'persistent' => false,
554
-                    'url'        => isset($this->_req_data['ATT_ID'])
555
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
556
-                        : $this->_admin_base_url,
557
-                ),
558
-                'metaboxes'     => array('attendee_editor_metaboxes'),
559
-                'require_nonce' => false,
560
-            ),
561
-            'contact_list'      => array(
562
-                'nav'           => array(
563
-                    'label' => esc_html__('Contact List', 'event_espresso'),
564
-                    'order' => 20,
565
-                ),
566
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
567
-                'help_tabs'     => array(
568
-                    'registrations_contact_list_help_tab'                       => array(
569
-                        'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
570
-                        'filename' => 'registrations_contact_list',
571
-                    ),
572
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
573
-                        'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
574
-                        'filename' => 'registrations_contact_list_table_column_headings',
575
-                    ),
576
-                    'registrations_contact_list_views_help_tab'                 => array(
577
-                        'title'    => esc_html__('Contact List Views', 'event_espresso'),
578
-                        'filename' => 'registrations_contact_list_views',
579
-                    ),
580
-                    'registrations_contact_list_other_help_tab'                 => array(
581
-                        'title'    => esc_html__('Contact List Other', 'event_espresso'),
582
-                        'filename' => 'registrations_contact_list_other',
583
-                    ),
584
-                ),
585
-                'help_tour'     => array('Contact_List_Help_Tour'),
586
-                'metaboxes'     => array(),
587
-                'require_nonce' => false,
588
-            ),
589
-            // override default cpt routes
590
-            'create_new'        => '',
591
-            'edit'              => '',
592
-        );
593
-    }
594
-
595
-
596
-    /**
597
-     * The below methods aren't used by this class currently
598
-     */
599
-    protected function _add_screen_options()
600
-    {
601
-    }
602
-
603
-
604
-    protected function _add_feature_pointers()
605
-    {
606
-    }
607
-
608
-
609
-    public function admin_init()
610
-    {
611
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
612
-            'click "Update Registration Questions" to save your changes',
613
-            'event_espresso'
614
-        );
615
-    }
616
-
617
-
618
-    public function admin_notices()
619
-    {
620
-    }
621
-
622
-
623
-    public function admin_footer_scripts()
624
-    {
625
-    }
626
-
627
-
628
-    /**
629
-     *        get list of registration statuses
630
-     *
631
-     * @access private
632
-     * @return void
633
-     * @throws EE_Error
634
-     */
635
-    private function _get_registration_status_array()
636
-    {
637
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
638
-    }
639
-
640
-
641
-    protected function _add_screen_options_default()
642
-    {
643
-        $this->_per_page_screen_option();
644
-    }
645
-
646
-
647
-    protected function _add_screen_options_contact_list()
648
-    {
649
-        $page_title = $this->_admin_page_title;
650
-        $this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
651
-        $this->_per_page_screen_option();
652
-        $this->_admin_page_title = $page_title;
653
-    }
654
-
655
-
656
-    public function load_scripts_styles()
657
-    {
658
-        // style
659
-        wp_register_style(
660
-            'espresso_reg',
661
-            REG_ASSETS_URL . 'espresso_registrations_admin.css',
662
-            array('ee-admin-css'),
663
-            EVENT_ESPRESSO_VERSION
664
-        );
665
-        wp_enqueue_style('espresso_reg');
666
-        // script
667
-        wp_register_script(
668
-            'espresso_reg',
669
-            REG_ASSETS_URL . 'espresso_registrations_admin.js',
670
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671
-            EVENT_ESPRESSO_VERSION,
672
-            true
673
-        );
674
-        wp_enqueue_script('espresso_reg');
675
-    }
676
-
677
-
678
-    public function load_scripts_styles_edit_attendee()
679
-    {
680
-        // stuff to only show up on our attendee edit details page.
681
-        $attendee_details_translations = array(
682
-            'att_publish_text' => sprintf(
683
-                esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
684
-                $this->_cpt_model_obj->get_datetime('ATT_created')
685
-            ),
686
-        );
687
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
688
-        wp_enqueue_script('jquery-validate');
689
-    }
690
-
691
-
692
-    public function load_scripts_styles_view_registration()
693
-    {
694
-        // styles
695
-        wp_enqueue_style('espresso-ui-theme');
696
-        // scripts
697
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
698
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
699
-    }
700
-
701
-
702
-    public function load_scripts_styles_contact_list()
703
-    {
704
-        wp_dequeue_style('espresso_reg');
705
-        wp_register_style(
706
-            'espresso_att',
707
-            REG_ASSETS_URL . 'espresso_attendees_admin.css',
708
-            array('ee-admin-css'),
709
-            EVENT_ESPRESSO_VERSION
710
-        );
711
-        wp_enqueue_style('espresso_att');
712
-    }
713
-
714
-
715
-    public function load_scripts_styles_new_registration()
716
-    {
717
-        wp_register_script(
718
-            'ee-spco-for-admin',
719
-            REG_ASSETS_URL . 'spco_for_admin.js',
720
-            array('underscore', 'jquery'),
721
-            EVENT_ESPRESSO_VERSION,
722
-            true
723
-        );
724
-        wp_enqueue_script('ee-spco-for-admin');
725
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
726
-        EE_Form_Section_Proper::wp_enqueue_scripts();
727
-        EED_Ticket_Selector::load_tckt_slctr_assets();
728
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
729
-    }
730
-
731
-
732
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
733
-    {
734
-        add_filter('FHEE_load_EE_messages', '__return_true');
735
-    }
736
-
737
-
738
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
739
-    {
740
-        add_filter('FHEE_load_EE_messages', '__return_true');
741
-    }
742
-
743
-
744
-    protected function _set_list_table_views_default()
745
-    {
746
-        // for notification related bulk actions we need to make sure only active messengers have an option.
747
-        EED_Messages::set_autoloaders();
748
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
749
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
750
-        $active_mts = $message_resource_manager->list_of_active_message_types();
751
-        // key= bulk_action_slug, value= message type.
752
-        $match_array = array(
753
-            'approve_registrations'    => 'registration',
754
-            'decline_registrations'    => 'declined_registration',
755
-            'pending_registrations'    => 'pending_approval',
756
-            'no_approve_registrations' => 'not_approved_registration',
757
-            'cancel_registrations'     => 'cancelled_registration',
758
-        );
759
-        $can_send = EE_Registry::instance()->CAP->current_user_can(
760
-            'ee_send_message',
761
-            'batch_send_messages'
762
-        );
763
-        /** setup reg status bulk actions **/
764
-        $def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
765
-        if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
766
-            $def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
767
-                'Approve and Notify Registrations',
768
-                'event_espresso'
769
-            );
770
-        }
771
-        $def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
772
-        if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
773
-            $def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
774
-                'Decline and Notify Registrations',
775
-                'event_espresso'
776
-            );
777
-        }
778
-        $def_reg_status_actions['pending_registrations'] = esc_html__(
779
-            'Set Registrations to Pending Payment',
780
-            'event_espresso'
781
-        );
782
-        if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
783
-            $def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
784
-                'Set Registrations to Pending Payment and Notify',
785
-                'event_espresso'
786
-            );
787
-        }
788
-        $def_reg_status_actions['no_approve_registrations'] = esc_html__(
789
-            'Set Registrations to Not Approved',
790
-            'event_espresso'
791
-        );
792
-        if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
793
-            $def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
794
-                'Set Registrations to Not Approved and Notify',
795
-                'event_espresso'
796
-            );
797
-        }
798
-        $def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
799
-        if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
800
-            $def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
801
-                'Cancel Registrations and Notify',
802
-                'event_espresso'
803
-            );
804
-        }
805
-        $def_reg_status_actions = apply_filters(
806
-            'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
807
-            $def_reg_status_actions,
808
-            $active_mts,
809
-            $can_send
810
-        );
811
-
812
-        $this->_views = array(
813
-            'all'   => array(
814
-                'slug'        => 'all',
815
-                'label'       => esc_html__('View All Registrations', 'event_espresso'),
816
-                'count'       => 0,
817
-                'bulk_action' => array_merge(
818
-                    $def_reg_status_actions,
819
-                    array(
820
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
821
-                    )
822
-                ),
823
-            ),
824
-            'month' => array(
825
-                'slug'        => 'month',
826
-                'label'       => esc_html__('This Month', 'event_espresso'),
827
-                'count'       => 0,
828
-                'bulk_action' => array_merge(
829
-                    $def_reg_status_actions,
830
-                    array(
831
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
832
-                    )
833
-                ),
834
-            ),
835
-            'today' => array(
836
-                'slug'        => 'today',
837
-                'label'       => sprintf(
838
-                    esc_html__('Today - %s', 'event_espresso'),
839
-                    date('M d, Y', current_time('timestamp'))
840
-                ),
841
-                'count'       => 0,
842
-                'bulk_action' => array_merge(
843
-                    $def_reg_status_actions,
844
-                    array(
845
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
-                    )
847
-                ),
848
-            ),
849
-        );
850
-        if (EE_Registry::instance()->CAP->current_user_can(
851
-            'ee_delete_registrations',
852
-            'espresso_registrations_delete_registration'
853
-        )) {
854
-            $this->_views['incomplete'] = array(
855
-                'slug'        => 'incomplete',
856
-                'label'       => esc_html__('Incomplete', 'event_espresso'),
857
-                'count'       => 0,
858
-                'bulk_action' => array(
859
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
860
-                ),
861
-            );
862
-            $this->_views['trash'] = array(
863
-                'slug'        => 'trash',
864
-                'label'       => esc_html__('Trash', 'event_espresso'),
865
-                'count'       => 0,
866
-                'bulk_action' => array(
867
-                    'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
868
-                    'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
869
-                ),
870
-            );
871
-        }
872
-    }
873
-
874
-
875
-    protected function _set_list_table_views_contact_list()
876
-    {
877
-        $this->_views = array(
878
-            'in_use' => array(
879
-                'slug'        => 'in_use',
880
-                'label'       => esc_html__('In Use', 'event_espresso'),
881
-                'count'       => 0,
882
-                'bulk_action' => array(
883
-                    'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
884
-                ),
885
-            ),
886
-        );
887
-        if (EE_Registry::instance()->CAP->current_user_can(
888
-            'ee_delete_contacts',
889
-            'espresso_registrations_trash_attendees'
890
-        )
891
-        ) {
892
-            $this->_views['trash'] = array(
893
-                'slug'        => 'trash',
894
-                'label'       => esc_html__('Trash', 'event_espresso'),
895
-                'count'       => 0,
896
-                'bulk_action' => array(
897
-                    'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
898
-                ),
899
-            );
900
-        }
901
-    }
902
-
903
-
904
-    protected function _registration_legend_items()
905
-    {
906
-        $fc_items = array(
907
-            'star-icon'        => array(
908
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
909
-                'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
910
-            ),
911
-            'view_details'     => array(
912
-                'class' => 'dashicons dashicons-clipboard',
913
-                'desc'  => esc_html__('View Registration Details', 'event_espresso'),
914
-            ),
915
-            'edit_attendee'    => array(
916
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
917
-                'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
918
-            ),
919
-            'view_transaction' => array(
920
-                'class' => 'dashicons dashicons-cart',
921
-                'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
922
-            ),
923
-            'view_invoice'     => array(
924
-                'class' => 'dashicons dashicons-media-spreadsheet',
925
-                'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
926
-            ),
927
-        );
928
-        if (EE_Registry::instance()->CAP->current_user_can(
929
-            'ee_send_message',
930
-            'espresso_registrations_resend_registration'
931
-        )) {
932
-            $fc_items['resend_registration'] = array(
933
-                'class' => 'dashicons dashicons-email-alt',
934
-                'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
935
-            );
936
-        } else {
937
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
938
-        }
939
-        if (EE_Registry::instance()->CAP->current_user_can(
940
-            'ee_read_global_messages',
941
-            'view_filtered_messages'
942
-        )) {
943
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
944
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
945
-                $fc_items['view_related_messages'] = array(
946
-                    'class' => $related_for_icon['css_class'],
947
-                    'desc'  => $related_for_icon['label'],
948
-                );
949
-            }
950
-        }
951
-        $sc_items = array(
952
-            'approved_status'   => array(
953
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
954
-                'desc'  => EEH_Template::pretty_status(
955
-                    EEM_Registration::status_id_approved,
956
-                    false,
957
-                    'sentence'
958
-                ),
959
-            ),
960
-            'pending_status'    => array(
961
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
962
-                'desc'  => EEH_Template::pretty_status(
963
-                    EEM_Registration::status_id_pending_payment,
964
-                    false,
965
-                    'sentence'
966
-                ),
967
-            ),
968
-            'wait_list'         => array(
969
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
970
-                'desc'  => EEH_Template::pretty_status(
971
-                    EEM_Registration::status_id_wait_list,
972
-                    false,
973
-                    'sentence'
974
-                ),
975
-            ),
976
-            'incomplete_status' => array(
977
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
978
-                'desc'  => EEH_Template::pretty_status(
979
-                    EEM_Registration::status_id_incomplete,
980
-                    false,
981
-                    'sentence'
982
-                ),
983
-            ),
984
-            'not_approved'      => array(
985
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
986
-                'desc'  => EEH_Template::pretty_status(
987
-                    EEM_Registration::status_id_not_approved,
988
-                    false,
989
-                    'sentence'
990
-                ),
991
-            ),
992
-            'declined_status'   => array(
993
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
994
-                'desc'  => EEH_Template::pretty_status(
995
-                    EEM_Registration::status_id_declined,
996
-                    false,
997
-                    'sentence'
998
-                ),
999
-            ),
1000
-            'cancelled_status'  => array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1002
-                'desc'  => EEH_Template::pretty_status(
1003
-                    EEM_Registration::status_id_cancelled,
1004
-                    false,
1005
-                    'sentence'
1006
-                ),
1007
-            ),
1008
-        );
1009
-        return array_merge($fc_items, $sc_items);
1010
-    }
1011
-
1012
-
1013
-
1014
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
1015
-    /**
1016
-     * @throws \EE_Error
1017
-     */
1018
-    protected function _registrations_overview_list_table()
1019
-    {
1020
-        $this->_template_args['admin_page_header'] = '';
1021
-        $EVT_ID = ! empty($this->_req_data['event_id'])
1022
-            ? absint($this->_req_data['event_id'])
1023
-            : 0;
1024
-        $ATT_ID = ! empty($this->_req_data['ATT_ID'])
1025
-            ? absint($this->_req_data['ATT_ID'])
1026
-            : 0;
1027
-        if ($ATT_ID) {
1028
-            $attendee = EEM_Attendee::instance()->get_one_by_ID($ATT_ID);
1029
-            if ($attendee instanceof EE_Attendee) {
1030
-                $this->_template_args['admin_page_header'] = sprintf(
1031
-                    esc_html__(
1032
-                        '%1$s Viewing registrations for %2$s%3$s',
1033
-                        'event_espresso'
1034
-                    ),
1035
-                    '<h3 style="line-height:1.5em;">',
1036
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1037
-                        array(
1038
-                            'action' => 'edit_attendee',
1039
-                            'post'   => $ATT_ID,
1040
-                        ),
1041
-                        REG_ADMIN_URL
1042
-                    ) . '">' . $attendee->full_name() . '</a>',
1043
-                    '</h3>'
1044
-                );
1045
-            }
1046
-        }
1047
-        if ($EVT_ID) {
1048
-            if (EE_Registry::instance()->CAP->current_user_can(
1049
-                'ee_edit_registrations',
1050
-                'espresso_registrations_new_registration',
1051
-                $EVT_ID
1052
-            )) {
1053
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1054
-                    'new_registration',
1055
-                    'add-registrant',
1056
-                    array('event_id' => $EVT_ID),
1057
-                    'add-new-h2'
1058
-                );
1059
-            }
1060
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1061
-            if ($event instanceof EE_Event) {
1062
-                $this->_template_args['admin_page_header'] = sprintf(
1063
-                    esc_html__(
1064
-                        '%s Viewing registrations for the event: %s%s',
1065
-                        'event_espresso'
1066
-                    ),
1067
-                    '<h3 style="line-height:1.5em;">',
1068
-                    '<br /><a href="'
1069
-                    . EE_Admin_Page::add_query_args_and_nonce(
1070
-                        array(
1071
-                            'action' => 'edit',
1072
-                            'post'   => $event->ID(),
1073
-                        ),
1074
-                        EVENTS_ADMIN_URL
1075
-                    )
1076
-                    . '">&nbsp;'
1077
-                    . $event->get('EVT_name')
1078
-                    . '&nbsp;</a>&nbsp;',
1079
-                    '</h3>'
1080
-                );
1081
-            }
1082
-            $DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1083
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1084
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1085
-                $this->_template_args['admin_page_header'] = substr(
1086
-                    $this->_template_args['admin_page_header'],
1087
-                    0,
1088
-                    -5
1089
-                );
1090
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092
-                $this->_template_args['admin_page_header'] .= $datetime->name();
1093
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1094
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
1095
-            }
1096
-        }
1097
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1098
-        $this->display_admin_list_table_page_with_no_sidebar();
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * This sets the _registration property for the registration details screen
1104
-     *
1105
-     * @access private
1106
-     * @return bool
1107
-     * @throws EE_Error
1108
-     * @throws InvalidArgumentException
1109
-     * @throws InvalidDataTypeException
1110
-     * @throws InvalidInterfaceException
1111
-     */
1112
-    private function _set_registration_object()
1113
-    {
1114
-        // get out if we've already set the object
1115
-        if ($this->_registration instanceof EE_Registration) {
1116
-            return true;
1117
-        }
1118
-        $REG = EEM_Registration::instance();
1119
-        $REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121
-            return true;
1122
-        } else {
1123
-            $error_msg = sprintf(
1124
-                esc_html__(
1125
-                    'An error occurred and the details for Registration ID #%s could not be retrieved.',
1126
-                    'event_espresso'
1127
-                ),
1128
-                $REG_ID
1129
-            );
1130
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1131
-            $this->_registration = null;
1132
-            return false;
1133
-        }
1134
-    }
1135
-
1136
-
1137
-    /**
1138
-     * Used to retrieve registrations for the list table.
1139
-     *
1140
-     * @param int  $per_page
1141
-     * @param bool $count
1142
-     * @param bool $this_month
1143
-     * @param bool $today
1144
-     * @return EE_Registration[]|int
1145
-     * @throws EE_Error
1146
-     * @throws InvalidArgumentException
1147
-     * @throws InvalidDataTypeException
1148
-     * @throws InvalidInterfaceException
1149
-     */
1150
-    public function get_registrations(
1151
-        $per_page = 10,
1152
-        $count = false,
1153
-        $this_month = false,
1154
-        $today = false
1155
-    ) {
1156
-        if ($this_month) {
1157
-            $this->_req_data['status'] = 'month';
1158
-        }
1159
-        if ($today) {
1160
-            $this->_req_data['status'] = 'today';
1161
-        }
1162
-        $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1163
-        /**
1164
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1165
-         *
1166
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1167
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1168
-         *                             or if you have the development copy of EE you can view this at the path:
1169
-         *                             /docs/G--Model-System/model-query-params.md
1170
-         */
1171
-        $query_params['group_by'] = '';
1172
-
1173
-        return $count
1174
-            ? EEM_Registration::instance()->count($query_params)
1175
-            /** @type EE_Registration[] */
1176
-            : EEM_Registration::instance()->get_all($query_params);
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Retrieves the query parameters to be used by the Registration model for getting registrations.
1182
-     * Note: this listens to values on the request for some of the query parameters.
1183
-     *
1184
-     * @param array $request
1185
-     * @param int   $per_page
1186
-     * @param bool  $count
1187
-     * @return array
1188
-     * @throws EE_Error
1189
-     */
1190
-    protected function _get_registration_query_parameters(
1191
-        $request = array(),
1192
-        $per_page = 10,
1193
-        $count = false
1194
-    ) {
1195
-
1196
-        $query_params = array(
1197
-            0                          => $this->_get_where_conditions_for_registrations_query(
1198
-                $request
1199
-            ),
1200
-            'caps'                     => EEM_Registration::caps_read_admin,
1201
-            'default_where_conditions' => 'this_model_only',
1202
-        );
1203
-        if (! $count) {
1204
-            $query_params = array_merge(
1205
-                $query_params,
1206
-                $this->_get_orderby_for_registrations_query(),
1207
-                $this->_get_limit($per_page)
1208
-            );
1209
-        }
1210
-
1211
-        return $query_params;
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * This will add ATT_ID to the provided $where array for EE model query parameters.
1217
-     *
1218
-     * @param array $request usually the same as $this->_req_data but not necessarily
1219
-     * @return array
1220
-     */
1221
-    protected function addAttendeeIdToWhereConditions(array $request)
1222
-    {
1223
-        $where = array();
1224
-        if (! empty($request['ATT_ID'])) {
1225
-            $where['ATT_ID'] = absint($request['ATT_ID']);
1226
-        }
1227
-        return $where;
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * This will add EVT_ID to the provided $where array for EE model query parameters.
1233
-     *
1234
-     * @param array $request usually the same as $this->_req_data but not necessarily
1235
-     * @return array
1236
-     */
1237
-    protected function _add_event_id_to_where_conditions(array $request)
1238
-    {
1239
-        $where = array();
1240
-        if (! empty($request['event_id'])) {
1241
-            $where['EVT_ID'] = absint($request['event_id']);
1242
-        }
1243
-        return $where;
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Adds category ID if it exists in the request to the where conditions for the registrations query.
1249
-     *
1250
-     * @param array $request usually the same as $this->_req_data but not necessarily
1251
-     * @return array
1252
-     */
1253
-    protected function _add_category_id_to_where_conditions(array $request)
1254
-    {
1255
-        $where = array();
1256
-        if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257
-            $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258
-        }
1259
-        return $where;
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1265
-     *
1266
-     * @param array $request usually the same as $this->_req_data but not necessarily
1267
-     * @return array
1268
-     */
1269
-    protected function _add_datetime_id_to_where_conditions(array $request)
1270
-    {
1271
-        $where = array();
1272
-        if (! empty($request['datetime_id'])) {
1273
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274
-        }
1275
-        if (! empty($request['DTT_ID'])) {
1276
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277
-        }
1278
-        return $where;
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * Adds the correct registration status to the where conditions for the registrations query.
1284
-     *
1285
-     * @param array $request usually the same as $this->_req_data but not necessarily
1286
-     * @return array
1287
-     */
1288
-    protected function _add_registration_status_to_where_conditions(array $request)
1289
-    {
1290
-        $where = array();
1291
-        $view = EEH_Array::is_set($request, 'status', '');
1292
-        $registration_status = ! empty($request['_reg_status'])
1293
-            ? sanitize_text_field($request['_reg_status'])
1294
-            : '';
1295
-
1296
-        /*
22
+	/**
23
+	 * @var EE_Registration
24
+	 */
25
+	private $_registration;
26
+
27
+	/**
28
+	 * @var EE_Event
29
+	 */
30
+	private $_reg_event;
31
+
32
+	/**
33
+	 * @var EE_Session
34
+	 */
35
+	private $_session;
36
+
37
+	private static $_reg_status;
38
+
39
+	/**
40
+	 * Form for displaying the custom questions for this registration.
41
+	 * This gets used a few times throughout the request so its best to cache it
42
+	 *
43
+	 * @var EE_Registration_Custom_Questions_Form
44
+	 */
45
+	protected $_reg_custom_questions_form = null;
46
+
47
+
48
+	/**
49
+	 *        constructor
50
+	 *
51
+	 * @Constructor
52
+	 * @access public
53
+	 * @param bool $routing
54
+	 * @return Registrations_Admin_Page
55
+	 */
56
+	public function __construct($routing = true)
57
+	{
58
+		parent::__construct($routing);
59
+		add_action('wp_loaded', array($this, 'wp_loaded'));
60
+	}
61
+
62
+
63
+	public function wp_loaded()
64
+	{
65
+		// when adding a new registration...
66
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67
+			EE_System::do_not_cache();
68
+			if (! isset($this->_req_data['processing_registration'])
69
+				|| absint($this->_req_data['processing_registration']) !== 1
70
+			) {
71
+				// and it's NOT the attendee information reg step
72
+				// force cookie expiration by setting time to last week
73
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
74
+				// and update the global
75
+				$_COOKIE['ee_registration_added'] = 0;
76
+			}
77
+		}
78
+	}
79
+
80
+
81
+	protected function _init_page_props()
82
+	{
83
+		$this->page_slug = REG_PG_SLUG;
84
+		$this->_admin_base_url = REG_ADMIN_URL;
85
+		$this->_admin_base_path = REG_ADMIN;
86
+		$this->page_label = esc_html__('Registrations', 'event_espresso');
87
+		$this->_cpt_routes = array(
88
+			'add_new_attendee' => 'espresso_attendees',
89
+			'edit_attendee'    => 'espresso_attendees',
90
+			'insert_attendee'  => 'espresso_attendees',
91
+			'update_attendee'  => 'espresso_attendees',
92
+		);
93
+		$this->_cpt_model_names = array(
94
+			'add_new_attendee' => 'EEM_Attendee',
95
+			'edit_attendee'    => 'EEM_Attendee',
96
+		);
97
+		$this->_cpt_edit_routes = array(
98
+			'espresso_attendees' => 'edit_attendee',
99
+		);
100
+		$this->_pagenow_map = array(
101
+			'add_new_attendee' => 'post-new.php',
102
+			'edit_attendee'    => 'post.php',
103
+			'trash'            => 'post.php',
104
+		);
105
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
106
+		// add filters so that the comment urls don't take users to a confusing 404 page
107
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
108
+	}
109
+
110
+
111
+	public function clear_comment_link($link, $comment, $args)
112
+	{
113
+		// gotta make sure this only happens on this route
114
+		$post_type = get_post_type($comment->comment_post_ID);
115
+		if ($post_type === 'espresso_attendees') {
116
+			return '#commentsdiv';
117
+		}
118
+		return $link;
119
+	}
120
+
121
+
122
+	protected function _ajax_hooks()
123
+	{
124
+		// todo: all hooks for registrations ajax goes in here
125
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
126
+	}
127
+
128
+
129
+	protected function _define_page_props()
130
+	{
131
+		$this->_admin_page_title = $this->page_label;
132
+		$this->_labels = array(
133
+			'buttons'                      => array(
134
+				'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
135
+				'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
136
+				'edit'                => esc_html__('Edit Contact', 'event_espresso'),
137
+				'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
138
+				'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
139
+				'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
140
+				'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
141
+				'contact_list_export' => esc_html__("Export Data", "event_espresso"),
142
+			),
143
+			'publishbox'                   => array(
144
+				'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
145
+				'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
146
+			),
147
+			'hide_add_button_on_cpt_route' => array(
148
+				'edit_attendee' => true,
149
+			),
150
+		);
151
+	}
152
+
153
+
154
+	/**
155
+	 *        grab url requests and route them
156
+	 *
157
+	 * @access private
158
+	 * @return void
159
+	 */
160
+	public function _set_page_routes()
161
+	{
162
+		$this->_get_registration_status_array();
163
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
164
+			? $this->_req_data['_REG_ID'] : 0;
165
+		$reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
166
+			? $this->_req_data['reg_status_change_form']['REG_ID']
167
+			: $reg_id;
168
+		$att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
169
+			? $this->_req_data['ATT_ID'] : 0;
170
+		$att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
171
+			? $this->_req_data['post']
172
+			: $att_id;
173
+		$this->_page_routes = array(
174
+			'default'                             => array(
175
+				'func'       => '_registrations_overview_list_table',
176
+				'capability' => 'ee_read_registrations',
177
+			),
178
+			'view_registration'                   => array(
179
+				'func'       => '_registration_details',
180
+				'capability' => 'ee_read_registration',
181
+				'obj_id'     => $reg_id,
182
+			),
183
+			'edit_registration'                   => array(
184
+				'func'               => '_update_attendee_registration_form',
185
+				'noheader'           => true,
186
+				'headers_sent_route' => 'view_registration',
187
+				'capability'         => 'ee_edit_registration',
188
+				'obj_id'             => $reg_id,
189
+				'_REG_ID'            => $reg_id,
190
+			),
191
+			'trash_registrations'                 => array(
192
+				'func'       => '_trash_or_restore_registrations',
193
+				'args'       => array('trash' => true),
194
+				'noheader'   => true,
195
+				'capability' => 'ee_delete_registrations',
196
+			),
197
+			'restore_registrations'               => array(
198
+				'func'       => '_trash_or_restore_registrations',
199
+				'args'       => array('trash' => false),
200
+				'noheader'   => true,
201
+				'capability' => 'ee_delete_registrations',
202
+			),
203
+			'delete_registrations'                => array(
204
+				'func'       => '_delete_registrations',
205
+				'noheader'   => true,
206
+				'capability' => 'ee_delete_registrations',
207
+			),
208
+			'new_registration'                    => array(
209
+				'func'       => 'new_registration',
210
+				'capability' => 'ee_edit_registrations',
211
+			),
212
+			'process_reg_step'                    => array(
213
+				'func'       => 'process_reg_step',
214
+				'noheader'   => true,
215
+				'capability' => 'ee_edit_registrations',
216
+			),
217
+			'redirect_to_txn'                     => array(
218
+				'func'       => 'redirect_to_txn',
219
+				'noheader'   => true,
220
+				'capability' => 'ee_edit_registrations',
221
+			),
222
+			'change_reg_status'                   => array(
223
+				'func'       => '_change_reg_status',
224
+				'noheader'   => true,
225
+				'capability' => 'ee_edit_registration',
226
+				'obj_id'     => $reg_id,
227
+			),
228
+			'approve_registration'                => array(
229
+				'func'       => 'approve_registration',
230
+				'noheader'   => true,
231
+				'capability' => 'ee_edit_registration',
232
+				'obj_id'     => $reg_id,
233
+			),
234
+			'approve_and_notify_registration'     => array(
235
+				'func'       => 'approve_registration',
236
+				'noheader'   => true,
237
+				'args'       => array(true),
238
+				'capability' => 'ee_edit_registration',
239
+				'obj_id'     => $reg_id,
240
+			),
241
+			'approve_registrations'               => array(
242
+				'func'       => 'bulk_action_on_registrations',
243
+				'noheader'   => true,
244
+				'capability' => 'ee_edit_registrations',
245
+				'args'       => array('approve'),
246
+			),
247
+			'approve_and_notify_registrations'    => array(
248
+				'func'       => 'bulk_action_on_registrations',
249
+				'noheader'   => true,
250
+				'capability' => 'ee_edit_registrations',
251
+				'args'       => array('approve', true),
252
+			),
253
+			'decline_registration'                => array(
254
+				'func'       => 'decline_registration',
255
+				'noheader'   => true,
256
+				'capability' => 'ee_edit_registration',
257
+				'obj_id'     => $reg_id,
258
+			),
259
+			'decline_and_notify_registration'     => array(
260
+				'func'       => 'decline_registration',
261
+				'noheader'   => true,
262
+				'args'       => array(true),
263
+				'capability' => 'ee_edit_registration',
264
+				'obj_id'     => $reg_id,
265
+			),
266
+			'decline_registrations'               => array(
267
+				'func'       => 'bulk_action_on_registrations',
268
+				'noheader'   => true,
269
+				'capability' => 'ee_edit_registrations',
270
+				'args'       => array('decline'),
271
+			),
272
+			'decline_and_notify_registrations'    => array(
273
+				'func'       => 'bulk_action_on_registrations',
274
+				'noheader'   => true,
275
+				'capability' => 'ee_edit_registrations',
276
+				'args'       => array('decline', true),
277
+			),
278
+			'pending_registration'                => array(
279
+				'func'       => 'pending_registration',
280
+				'noheader'   => true,
281
+				'capability' => 'ee_edit_registration',
282
+				'obj_id'     => $reg_id,
283
+			),
284
+			'pending_and_notify_registration'     => array(
285
+				'func'       => 'pending_registration',
286
+				'noheader'   => true,
287
+				'args'       => array(true),
288
+				'capability' => 'ee_edit_registration',
289
+				'obj_id'     => $reg_id,
290
+			),
291
+			'pending_registrations'               => array(
292
+				'func'       => 'bulk_action_on_registrations',
293
+				'noheader'   => true,
294
+				'capability' => 'ee_edit_registrations',
295
+				'args'       => array('pending'),
296
+			),
297
+			'pending_and_notify_registrations'    => array(
298
+				'func'       => 'bulk_action_on_registrations',
299
+				'noheader'   => true,
300
+				'capability' => 'ee_edit_registrations',
301
+				'args'       => array('pending', true),
302
+			),
303
+			'no_approve_registration'             => array(
304
+				'func'       => 'not_approve_registration',
305
+				'noheader'   => true,
306
+				'capability' => 'ee_edit_registration',
307
+				'obj_id'     => $reg_id,
308
+			),
309
+			'no_approve_and_notify_registration'  => array(
310
+				'func'       => 'not_approve_registration',
311
+				'noheader'   => true,
312
+				'args'       => array(true),
313
+				'capability' => 'ee_edit_registration',
314
+				'obj_id'     => $reg_id,
315
+			),
316
+			'no_approve_registrations'            => array(
317
+				'func'       => 'bulk_action_on_registrations',
318
+				'noheader'   => true,
319
+				'capability' => 'ee_edit_registrations',
320
+				'args'       => array('not_approve'),
321
+			),
322
+			'no_approve_and_notify_registrations' => array(
323
+				'func'       => 'bulk_action_on_registrations',
324
+				'noheader'   => true,
325
+				'capability' => 'ee_edit_registrations',
326
+				'args'       => array('not_approve', true),
327
+			),
328
+			'cancel_registration'                 => array(
329
+				'func'       => 'cancel_registration',
330
+				'noheader'   => true,
331
+				'capability' => 'ee_edit_registration',
332
+				'obj_id'     => $reg_id,
333
+			),
334
+			'cancel_and_notify_registration'      => array(
335
+				'func'       => 'cancel_registration',
336
+				'noheader'   => true,
337
+				'args'       => array(true),
338
+				'capability' => 'ee_edit_registration',
339
+				'obj_id'     => $reg_id,
340
+			),
341
+			'cancel_registrations'                => array(
342
+				'func'       => 'bulk_action_on_registrations',
343
+				'noheader'   => true,
344
+				'capability' => 'ee_edit_registrations',
345
+				'args'       => array('cancel'),
346
+			),
347
+			'cancel_and_notify_registrations'     => array(
348
+				'func'       => 'bulk_action_on_registrations',
349
+				'noheader'   => true,
350
+				'capability' => 'ee_edit_registrations',
351
+				'args'       => array('cancel', true),
352
+			),
353
+			'wait_list_registration'              => array(
354
+				'func'       => 'wait_list_registration',
355
+				'noheader'   => true,
356
+				'capability' => 'ee_edit_registration',
357
+				'obj_id'     => $reg_id,
358
+			),
359
+			'wait_list_and_notify_registration'   => array(
360
+				'func'       => 'wait_list_registration',
361
+				'noheader'   => true,
362
+				'args'       => array(true),
363
+				'capability' => 'ee_edit_registration',
364
+				'obj_id'     => $reg_id,
365
+			),
366
+			'contact_list'                        => array(
367
+				'func'       => '_attendee_contact_list_table',
368
+				'capability' => 'ee_read_contacts',
369
+			),
370
+			'add_new_attendee'                    => array(
371
+				'func' => '_create_new_cpt_item',
372
+				'args' => array(
373
+					'new_attendee' => true,
374
+					'capability'   => 'ee_edit_contacts',
375
+				),
376
+			),
377
+			'edit_attendee'                       => array(
378
+				'func'       => '_edit_cpt_item',
379
+				'capability' => 'ee_edit_contacts',
380
+				'obj_id'     => $att_id,
381
+			),
382
+			'duplicate_attendee'                  => array(
383
+				'func'       => '_duplicate_attendee',
384
+				'noheader'   => true,
385
+				'capability' => 'ee_edit_contacts',
386
+				'obj_id'     => $att_id,
387
+			),
388
+			'insert_attendee'                     => array(
389
+				'func'       => '_insert_or_update_attendee',
390
+				'args'       => array(
391
+					'new_attendee' => true,
392
+				),
393
+				'noheader'   => true,
394
+				'capability' => 'ee_edit_contacts',
395
+			),
396
+			'update_attendee'                     => array(
397
+				'func'       => '_insert_or_update_attendee',
398
+				'args'       => array(
399
+					'new_attendee' => false,
400
+				),
401
+				'noheader'   => true,
402
+				'capability' => 'ee_edit_contacts',
403
+				'obj_id'     => $att_id,
404
+			),
405
+			'trash_attendees'                     => array(
406
+				'func'       => '_trash_or_restore_attendees',
407
+				'args'       => array(
408
+					'trash' => 'true',
409
+				),
410
+				'noheader'   => true,
411
+				'capability' => 'ee_delete_contacts',
412
+			),
413
+			'trash_attendee'                      => array(
414
+				'func'       => '_trash_or_restore_attendees',
415
+				'args'       => array(
416
+					'trash' => true,
417
+				),
418
+				'noheader'   => true,
419
+				'capability' => 'ee_delete_contacts',
420
+				'obj_id'     => $att_id,
421
+			),
422
+			'restore_attendees'                   => array(
423
+				'func'       => '_trash_or_restore_attendees',
424
+				'args'       => array(
425
+					'trash' => false,
426
+				),
427
+				'noheader'   => true,
428
+				'capability' => 'ee_delete_contacts',
429
+				'obj_id'     => $att_id,
430
+			),
431
+			'resend_registration'                 => array(
432
+				'func'       => '_resend_registration',
433
+				'noheader'   => true,
434
+				'capability' => 'ee_send_message',
435
+			),
436
+			'registrations_report'                => array(
437
+				'func'       => '_registrations_report',
438
+				'noheader'   => true,
439
+				'capability' => 'ee_read_registrations',
440
+			),
441
+			'contact_list_export'                 => array(
442
+				'func'       => '_contact_list_export',
443
+				'noheader'   => true,
444
+				'capability' => 'export',
445
+			),
446
+			'contact_list_report'                 => array(
447
+				'func'       => '_contact_list_report',
448
+				'noheader'   => true,
449
+				'capability' => 'ee_read_contacts',
450
+			),
451
+		);
452
+	}
453
+
454
+
455
+	protected function _set_page_config()
456
+	{
457
+		$this->_page_config = array(
458
+			'default'           => array(
459
+				'nav'           => array(
460
+					'label' => esc_html__('Overview', 'event_espresso'),
461
+					'order' => 5,
462
+				),
463
+				'help_tabs'     => array(
464
+					'registrations_overview_help_tab'                       => array(
465
+						'title'    => esc_html__('Registrations Overview', 'event_espresso'),
466
+						'filename' => 'registrations_overview',
467
+					),
468
+					'registrations_overview_table_column_headings_help_tab' => array(
469
+						'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
470
+						'filename' => 'registrations_overview_table_column_headings',
471
+					),
472
+					'registrations_overview_filters_help_tab'               => array(
473
+						'title'    => esc_html__('Registration Filters', 'event_espresso'),
474
+						'filename' => 'registrations_overview_filters',
475
+					),
476
+					'registrations_overview_views_help_tab'                 => array(
477
+						'title'    => esc_html__('Registration Views', 'event_espresso'),
478
+						'filename' => 'registrations_overview_views',
479
+					),
480
+					'registrations_regoverview_other_help_tab'              => array(
481
+						'title'    => esc_html__('Registrations Other', 'event_espresso'),
482
+						'filename' => 'registrations_overview_other',
483
+					),
484
+				),
485
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
486
+				'qtips'         => array('Registration_List_Table_Tips'),
487
+				'list_table'    => 'EE_Registrations_List_Table',
488
+				'require_nonce' => false,
489
+			),
490
+			'view_registration' => array(
491
+				'nav'           => array(
492
+					'label'      => esc_html__('REG Details', 'event_espresso'),
493
+					'order'      => 15,
494
+					'url'        => isset($this->_req_data['_REG_ID'])
495
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
496
+						: $this->_admin_base_url,
497
+					'persistent' => false,
498
+				),
499
+				'help_tabs'     => array(
500
+					'registrations_details_help_tab'                    => array(
501
+						'title'    => esc_html__('Registration Details', 'event_espresso'),
502
+						'filename' => 'registrations_details',
503
+					),
504
+					'registrations_details_table_help_tab'              => array(
505
+						'title'    => esc_html__('Registration Details Table', 'event_espresso'),
506
+						'filename' => 'registrations_details_table',
507
+					),
508
+					'registrations_details_form_answers_help_tab'       => array(
509
+						'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
510
+						'filename' => 'registrations_details_form_answers',
511
+					),
512
+					'registrations_details_registrant_details_help_tab' => array(
513
+						'title'    => esc_html__('Contact Details', 'event_espresso'),
514
+						'filename' => 'registrations_details_registrant_details',
515
+					),
516
+				),
517
+				'help_tour'     => array('Registration_Details_Help_Tour'),
518
+				'metaboxes'     => array_merge(
519
+					$this->_default_espresso_metaboxes,
520
+					array('_registration_details_metaboxes')
521
+				),
522
+				'require_nonce' => false,
523
+			),
524
+			'new_registration'  => array(
525
+				'nav'           => array(
526
+					'label'      => esc_html__('Add New Registration', 'event_espresso'),
527
+					'url'        => '#',
528
+					'order'      => 15,
529
+					'persistent' => false,
530
+				),
531
+				'metaboxes'     => $this->_default_espresso_metaboxes,
532
+				'labels'        => array(
533
+					'publishbox' => esc_html__('Save Registration', 'event_espresso'),
534
+				),
535
+				'require_nonce' => false,
536
+			),
537
+			'add_new_attendee'  => array(
538
+				'nav'           => array(
539
+					'label'      => esc_html__('Add Contact', 'event_espresso'),
540
+					'order'      => 15,
541
+					'persistent' => false,
542
+				),
543
+				'metaboxes'     => array_merge(
544
+					$this->_default_espresso_metaboxes,
545
+					array('_publish_post_box', 'attendee_editor_metaboxes')
546
+				),
547
+				'require_nonce' => false,
548
+			),
549
+			'edit_attendee'     => array(
550
+				'nav'           => array(
551
+					'label'      => esc_html__('Edit Contact', 'event_espresso'),
552
+					'order'      => 15,
553
+					'persistent' => false,
554
+					'url'        => isset($this->_req_data['ATT_ID'])
555
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
556
+						: $this->_admin_base_url,
557
+				),
558
+				'metaboxes'     => array('attendee_editor_metaboxes'),
559
+				'require_nonce' => false,
560
+			),
561
+			'contact_list'      => array(
562
+				'nav'           => array(
563
+					'label' => esc_html__('Contact List', 'event_espresso'),
564
+					'order' => 20,
565
+				),
566
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
567
+				'help_tabs'     => array(
568
+					'registrations_contact_list_help_tab'                       => array(
569
+						'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
570
+						'filename' => 'registrations_contact_list',
571
+					),
572
+					'registrations_contact-list_table_column_headings_help_tab' => array(
573
+						'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
574
+						'filename' => 'registrations_contact_list_table_column_headings',
575
+					),
576
+					'registrations_contact_list_views_help_tab'                 => array(
577
+						'title'    => esc_html__('Contact List Views', 'event_espresso'),
578
+						'filename' => 'registrations_contact_list_views',
579
+					),
580
+					'registrations_contact_list_other_help_tab'                 => array(
581
+						'title'    => esc_html__('Contact List Other', 'event_espresso'),
582
+						'filename' => 'registrations_contact_list_other',
583
+					),
584
+				),
585
+				'help_tour'     => array('Contact_List_Help_Tour'),
586
+				'metaboxes'     => array(),
587
+				'require_nonce' => false,
588
+			),
589
+			// override default cpt routes
590
+			'create_new'        => '',
591
+			'edit'              => '',
592
+		);
593
+	}
594
+
595
+
596
+	/**
597
+	 * The below methods aren't used by this class currently
598
+	 */
599
+	protected function _add_screen_options()
600
+	{
601
+	}
602
+
603
+
604
+	protected function _add_feature_pointers()
605
+	{
606
+	}
607
+
608
+
609
+	public function admin_init()
610
+	{
611
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
612
+			'click "Update Registration Questions" to save your changes',
613
+			'event_espresso'
614
+		);
615
+	}
616
+
617
+
618
+	public function admin_notices()
619
+	{
620
+	}
621
+
622
+
623
+	public function admin_footer_scripts()
624
+	{
625
+	}
626
+
627
+
628
+	/**
629
+	 *        get list of registration statuses
630
+	 *
631
+	 * @access private
632
+	 * @return void
633
+	 * @throws EE_Error
634
+	 */
635
+	private function _get_registration_status_array()
636
+	{
637
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
638
+	}
639
+
640
+
641
+	protected function _add_screen_options_default()
642
+	{
643
+		$this->_per_page_screen_option();
644
+	}
645
+
646
+
647
+	protected function _add_screen_options_contact_list()
648
+	{
649
+		$page_title = $this->_admin_page_title;
650
+		$this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
651
+		$this->_per_page_screen_option();
652
+		$this->_admin_page_title = $page_title;
653
+	}
654
+
655
+
656
+	public function load_scripts_styles()
657
+	{
658
+		// style
659
+		wp_register_style(
660
+			'espresso_reg',
661
+			REG_ASSETS_URL . 'espresso_registrations_admin.css',
662
+			array('ee-admin-css'),
663
+			EVENT_ESPRESSO_VERSION
664
+		);
665
+		wp_enqueue_style('espresso_reg');
666
+		// script
667
+		wp_register_script(
668
+			'espresso_reg',
669
+			REG_ASSETS_URL . 'espresso_registrations_admin.js',
670
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671
+			EVENT_ESPRESSO_VERSION,
672
+			true
673
+		);
674
+		wp_enqueue_script('espresso_reg');
675
+	}
676
+
677
+
678
+	public function load_scripts_styles_edit_attendee()
679
+	{
680
+		// stuff to only show up on our attendee edit details page.
681
+		$attendee_details_translations = array(
682
+			'att_publish_text' => sprintf(
683
+				esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
684
+				$this->_cpt_model_obj->get_datetime('ATT_created')
685
+			),
686
+		);
687
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
688
+		wp_enqueue_script('jquery-validate');
689
+	}
690
+
691
+
692
+	public function load_scripts_styles_view_registration()
693
+	{
694
+		// styles
695
+		wp_enqueue_style('espresso-ui-theme');
696
+		// scripts
697
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
698
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
699
+	}
700
+
701
+
702
+	public function load_scripts_styles_contact_list()
703
+	{
704
+		wp_dequeue_style('espresso_reg');
705
+		wp_register_style(
706
+			'espresso_att',
707
+			REG_ASSETS_URL . 'espresso_attendees_admin.css',
708
+			array('ee-admin-css'),
709
+			EVENT_ESPRESSO_VERSION
710
+		);
711
+		wp_enqueue_style('espresso_att');
712
+	}
713
+
714
+
715
+	public function load_scripts_styles_new_registration()
716
+	{
717
+		wp_register_script(
718
+			'ee-spco-for-admin',
719
+			REG_ASSETS_URL . 'spco_for_admin.js',
720
+			array('underscore', 'jquery'),
721
+			EVENT_ESPRESSO_VERSION,
722
+			true
723
+		);
724
+		wp_enqueue_script('ee-spco-for-admin');
725
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
726
+		EE_Form_Section_Proper::wp_enqueue_scripts();
727
+		EED_Ticket_Selector::load_tckt_slctr_assets();
728
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
729
+	}
730
+
731
+
732
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
733
+	{
734
+		add_filter('FHEE_load_EE_messages', '__return_true');
735
+	}
736
+
737
+
738
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
739
+	{
740
+		add_filter('FHEE_load_EE_messages', '__return_true');
741
+	}
742
+
743
+
744
+	protected function _set_list_table_views_default()
745
+	{
746
+		// for notification related bulk actions we need to make sure only active messengers have an option.
747
+		EED_Messages::set_autoloaders();
748
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
749
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
750
+		$active_mts = $message_resource_manager->list_of_active_message_types();
751
+		// key= bulk_action_slug, value= message type.
752
+		$match_array = array(
753
+			'approve_registrations'    => 'registration',
754
+			'decline_registrations'    => 'declined_registration',
755
+			'pending_registrations'    => 'pending_approval',
756
+			'no_approve_registrations' => 'not_approved_registration',
757
+			'cancel_registrations'     => 'cancelled_registration',
758
+		);
759
+		$can_send = EE_Registry::instance()->CAP->current_user_can(
760
+			'ee_send_message',
761
+			'batch_send_messages'
762
+		);
763
+		/** setup reg status bulk actions **/
764
+		$def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
765
+		if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
766
+			$def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
767
+				'Approve and Notify Registrations',
768
+				'event_espresso'
769
+			);
770
+		}
771
+		$def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
772
+		if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
773
+			$def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
774
+				'Decline and Notify Registrations',
775
+				'event_espresso'
776
+			);
777
+		}
778
+		$def_reg_status_actions['pending_registrations'] = esc_html__(
779
+			'Set Registrations to Pending Payment',
780
+			'event_espresso'
781
+		);
782
+		if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
783
+			$def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
784
+				'Set Registrations to Pending Payment and Notify',
785
+				'event_espresso'
786
+			);
787
+		}
788
+		$def_reg_status_actions['no_approve_registrations'] = esc_html__(
789
+			'Set Registrations to Not Approved',
790
+			'event_espresso'
791
+		);
792
+		if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
793
+			$def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
794
+				'Set Registrations to Not Approved and Notify',
795
+				'event_espresso'
796
+			);
797
+		}
798
+		$def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
799
+		if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
800
+			$def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
801
+				'Cancel Registrations and Notify',
802
+				'event_espresso'
803
+			);
804
+		}
805
+		$def_reg_status_actions = apply_filters(
806
+			'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
807
+			$def_reg_status_actions,
808
+			$active_mts,
809
+			$can_send
810
+		);
811
+
812
+		$this->_views = array(
813
+			'all'   => array(
814
+				'slug'        => 'all',
815
+				'label'       => esc_html__('View All Registrations', 'event_espresso'),
816
+				'count'       => 0,
817
+				'bulk_action' => array_merge(
818
+					$def_reg_status_actions,
819
+					array(
820
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
821
+					)
822
+				),
823
+			),
824
+			'month' => array(
825
+				'slug'        => 'month',
826
+				'label'       => esc_html__('This Month', 'event_espresso'),
827
+				'count'       => 0,
828
+				'bulk_action' => array_merge(
829
+					$def_reg_status_actions,
830
+					array(
831
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
832
+					)
833
+				),
834
+			),
835
+			'today' => array(
836
+				'slug'        => 'today',
837
+				'label'       => sprintf(
838
+					esc_html__('Today - %s', 'event_espresso'),
839
+					date('M d, Y', current_time('timestamp'))
840
+				),
841
+				'count'       => 0,
842
+				'bulk_action' => array_merge(
843
+					$def_reg_status_actions,
844
+					array(
845
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
+					)
847
+				),
848
+			),
849
+		);
850
+		if (EE_Registry::instance()->CAP->current_user_can(
851
+			'ee_delete_registrations',
852
+			'espresso_registrations_delete_registration'
853
+		)) {
854
+			$this->_views['incomplete'] = array(
855
+				'slug'        => 'incomplete',
856
+				'label'       => esc_html__('Incomplete', 'event_espresso'),
857
+				'count'       => 0,
858
+				'bulk_action' => array(
859
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
860
+				),
861
+			);
862
+			$this->_views['trash'] = array(
863
+				'slug'        => 'trash',
864
+				'label'       => esc_html__('Trash', 'event_espresso'),
865
+				'count'       => 0,
866
+				'bulk_action' => array(
867
+					'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
868
+					'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
869
+				),
870
+			);
871
+		}
872
+	}
873
+
874
+
875
+	protected function _set_list_table_views_contact_list()
876
+	{
877
+		$this->_views = array(
878
+			'in_use' => array(
879
+				'slug'        => 'in_use',
880
+				'label'       => esc_html__('In Use', 'event_espresso'),
881
+				'count'       => 0,
882
+				'bulk_action' => array(
883
+					'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
884
+				),
885
+			),
886
+		);
887
+		if (EE_Registry::instance()->CAP->current_user_can(
888
+			'ee_delete_contacts',
889
+			'espresso_registrations_trash_attendees'
890
+		)
891
+		) {
892
+			$this->_views['trash'] = array(
893
+				'slug'        => 'trash',
894
+				'label'       => esc_html__('Trash', 'event_espresso'),
895
+				'count'       => 0,
896
+				'bulk_action' => array(
897
+					'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
898
+				),
899
+			);
900
+		}
901
+	}
902
+
903
+
904
+	protected function _registration_legend_items()
905
+	{
906
+		$fc_items = array(
907
+			'star-icon'        => array(
908
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
909
+				'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
910
+			),
911
+			'view_details'     => array(
912
+				'class' => 'dashicons dashicons-clipboard',
913
+				'desc'  => esc_html__('View Registration Details', 'event_espresso'),
914
+			),
915
+			'edit_attendee'    => array(
916
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
917
+				'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
918
+			),
919
+			'view_transaction' => array(
920
+				'class' => 'dashicons dashicons-cart',
921
+				'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
922
+			),
923
+			'view_invoice'     => array(
924
+				'class' => 'dashicons dashicons-media-spreadsheet',
925
+				'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
926
+			),
927
+		);
928
+		if (EE_Registry::instance()->CAP->current_user_can(
929
+			'ee_send_message',
930
+			'espresso_registrations_resend_registration'
931
+		)) {
932
+			$fc_items['resend_registration'] = array(
933
+				'class' => 'dashicons dashicons-email-alt',
934
+				'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
935
+			);
936
+		} else {
937
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
938
+		}
939
+		if (EE_Registry::instance()->CAP->current_user_can(
940
+			'ee_read_global_messages',
941
+			'view_filtered_messages'
942
+		)) {
943
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
944
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
945
+				$fc_items['view_related_messages'] = array(
946
+					'class' => $related_for_icon['css_class'],
947
+					'desc'  => $related_for_icon['label'],
948
+				);
949
+			}
950
+		}
951
+		$sc_items = array(
952
+			'approved_status'   => array(
953
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
954
+				'desc'  => EEH_Template::pretty_status(
955
+					EEM_Registration::status_id_approved,
956
+					false,
957
+					'sentence'
958
+				),
959
+			),
960
+			'pending_status'    => array(
961
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
962
+				'desc'  => EEH_Template::pretty_status(
963
+					EEM_Registration::status_id_pending_payment,
964
+					false,
965
+					'sentence'
966
+				),
967
+			),
968
+			'wait_list'         => array(
969
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
970
+				'desc'  => EEH_Template::pretty_status(
971
+					EEM_Registration::status_id_wait_list,
972
+					false,
973
+					'sentence'
974
+				),
975
+			),
976
+			'incomplete_status' => array(
977
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
978
+				'desc'  => EEH_Template::pretty_status(
979
+					EEM_Registration::status_id_incomplete,
980
+					false,
981
+					'sentence'
982
+				),
983
+			),
984
+			'not_approved'      => array(
985
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
986
+				'desc'  => EEH_Template::pretty_status(
987
+					EEM_Registration::status_id_not_approved,
988
+					false,
989
+					'sentence'
990
+				),
991
+			),
992
+			'declined_status'   => array(
993
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
994
+				'desc'  => EEH_Template::pretty_status(
995
+					EEM_Registration::status_id_declined,
996
+					false,
997
+					'sentence'
998
+				),
999
+			),
1000
+			'cancelled_status'  => array(
1001
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1002
+				'desc'  => EEH_Template::pretty_status(
1003
+					EEM_Registration::status_id_cancelled,
1004
+					false,
1005
+					'sentence'
1006
+				),
1007
+			),
1008
+		);
1009
+		return array_merge($fc_items, $sc_items);
1010
+	}
1011
+
1012
+
1013
+
1014
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
1015
+	/**
1016
+	 * @throws \EE_Error
1017
+	 */
1018
+	protected function _registrations_overview_list_table()
1019
+	{
1020
+		$this->_template_args['admin_page_header'] = '';
1021
+		$EVT_ID = ! empty($this->_req_data['event_id'])
1022
+			? absint($this->_req_data['event_id'])
1023
+			: 0;
1024
+		$ATT_ID = ! empty($this->_req_data['ATT_ID'])
1025
+			? absint($this->_req_data['ATT_ID'])
1026
+			: 0;
1027
+		if ($ATT_ID) {
1028
+			$attendee = EEM_Attendee::instance()->get_one_by_ID($ATT_ID);
1029
+			if ($attendee instanceof EE_Attendee) {
1030
+				$this->_template_args['admin_page_header'] = sprintf(
1031
+					esc_html__(
1032
+						'%1$s Viewing registrations for %2$s%3$s',
1033
+						'event_espresso'
1034
+					),
1035
+					'<h3 style="line-height:1.5em;">',
1036
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1037
+						array(
1038
+							'action' => 'edit_attendee',
1039
+							'post'   => $ATT_ID,
1040
+						),
1041
+						REG_ADMIN_URL
1042
+					) . '">' . $attendee->full_name() . '</a>',
1043
+					'</h3>'
1044
+				);
1045
+			}
1046
+		}
1047
+		if ($EVT_ID) {
1048
+			if (EE_Registry::instance()->CAP->current_user_can(
1049
+				'ee_edit_registrations',
1050
+				'espresso_registrations_new_registration',
1051
+				$EVT_ID
1052
+			)) {
1053
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1054
+					'new_registration',
1055
+					'add-registrant',
1056
+					array('event_id' => $EVT_ID),
1057
+					'add-new-h2'
1058
+				);
1059
+			}
1060
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1061
+			if ($event instanceof EE_Event) {
1062
+				$this->_template_args['admin_page_header'] = sprintf(
1063
+					esc_html__(
1064
+						'%s Viewing registrations for the event: %s%s',
1065
+						'event_espresso'
1066
+					),
1067
+					'<h3 style="line-height:1.5em;">',
1068
+					'<br /><a href="'
1069
+					. EE_Admin_Page::add_query_args_and_nonce(
1070
+						array(
1071
+							'action' => 'edit',
1072
+							'post'   => $event->ID(),
1073
+						),
1074
+						EVENTS_ADMIN_URL
1075
+					)
1076
+					. '">&nbsp;'
1077
+					. $event->get('EVT_name')
1078
+					. '&nbsp;</a>&nbsp;',
1079
+					'</h3>'
1080
+				);
1081
+			}
1082
+			$DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1083
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1084
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1085
+				$this->_template_args['admin_page_header'] = substr(
1086
+					$this->_template_args['admin_page_header'],
1087
+					0,
1088
+					-5
1089
+				);
1090
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092
+				$this->_template_args['admin_page_header'] .= $datetime->name();
1093
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1094
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
1095
+			}
1096
+		}
1097
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1098
+		$this->display_admin_list_table_page_with_no_sidebar();
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * This sets the _registration property for the registration details screen
1104
+	 *
1105
+	 * @access private
1106
+	 * @return bool
1107
+	 * @throws EE_Error
1108
+	 * @throws InvalidArgumentException
1109
+	 * @throws InvalidDataTypeException
1110
+	 * @throws InvalidInterfaceException
1111
+	 */
1112
+	private function _set_registration_object()
1113
+	{
1114
+		// get out if we've already set the object
1115
+		if ($this->_registration instanceof EE_Registration) {
1116
+			return true;
1117
+		}
1118
+		$REG = EEM_Registration::instance();
1119
+		$REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121
+			return true;
1122
+		} else {
1123
+			$error_msg = sprintf(
1124
+				esc_html__(
1125
+					'An error occurred and the details for Registration ID #%s could not be retrieved.',
1126
+					'event_espresso'
1127
+				),
1128
+				$REG_ID
1129
+			);
1130
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1131
+			$this->_registration = null;
1132
+			return false;
1133
+		}
1134
+	}
1135
+
1136
+
1137
+	/**
1138
+	 * Used to retrieve registrations for the list table.
1139
+	 *
1140
+	 * @param int  $per_page
1141
+	 * @param bool $count
1142
+	 * @param bool $this_month
1143
+	 * @param bool $today
1144
+	 * @return EE_Registration[]|int
1145
+	 * @throws EE_Error
1146
+	 * @throws InvalidArgumentException
1147
+	 * @throws InvalidDataTypeException
1148
+	 * @throws InvalidInterfaceException
1149
+	 */
1150
+	public function get_registrations(
1151
+		$per_page = 10,
1152
+		$count = false,
1153
+		$this_month = false,
1154
+		$today = false
1155
+	) {
1156
+		if ($this_month) {
1157
+			$this->_req_data['status'] = 'month';
1158
+		}
1159
+		if ($today) {
1160
+			$this->_req_data['status'] = 'today';
1161
+		}
1162
+		$query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1163
+		/**
1164
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1165
+		 *
1166
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1167
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1168
+		 *                             or if you have the development copy of EE you can view this at the path:
1169
+		 *                             /docs/G--Model-System/model-query-params.md
1170
+		 */
1171
+		$query_params['group_by'] = '';
1172
+
1173
+		return $count
1174
+			? EEM_Registration::instance()->count($query_params)
1175
+			/** @type EE_Registration[] */
1176
+			: EEM_Registration::instance()->get_all($query_params);
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Retrieves the query parameters to be used by the Registration model for getting registrations.
1182
+	 * Note: this listens to values on the request for some of the query parameters.
1183
+	 *
1184
+	 * @param array $request
1185
+	 * @param int   $per_page
1186
+	 * @param bool  $count
1187
+	 * @return array
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	protected function _get_registration_query_parameters(
1191
+		$request = array(),
1192
+		$per_page = 10,
1193
+		$count = false
1194
+	) {
1195
+
1196
+		$query_params = array(
1197
+			0                          => $this->_get_where_conditions_for_registrations_query(
1198
+				$request
1199
+			),
1200
+			'caps'                     => EEM_Registration::caps_read_admin,
1201
+			'default_where_conditions' => 'this_model_only',
1202
+		);
1203
+		if (! $count) {
1204
+			$query_params = array_merge(
1205
+				$query_params,
1206
+				$this->_get_orderby_for_registrations_query(),
1207
+				$this->_get_limit($per_page)
1208
+			);
1209
+		}
1210
+
1211
+		return $query_params;
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * This will add ATT_ID to the provided $where array for EE model query parameters.
1217
+	 *
1218
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1219
+	 * @return array
1220
+	 */
1221
+	protected function addAttendeeIdToWhereConditions(array $request)
1222
+	{
1223
+		$where = array();
1224
+		if (! empty($request['ATT_ID'])) {
1225
+			$where['ATT_ID'] = absint($request['ATT_ID']);
1226
+		}
1227
+		return $where;
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * This will add EVT_ID to the provided $where array for EE model query parameters.
1233
+	 *
1234
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1235
+	 * @return array
1236
+	 */
1237
+	protected function _add_event_id_to_where_conditions(array $request)
1238
+	{
1239
+		$where = array();
1240
+		if (! empty($request['event_id'])) {
1241
+			$where['EVT_ID'] = absint($request['event_id']);
1242
+		}
1243
+		return $where;
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Adds category ID if it exists in the request to the where conditions for the registrations query.
1249
+	 *
1250
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1251
+	 * @return array
1252
+	 */
1253
+	protected function _add_category_id_to_where_conditions(array $request)
1254
+	{
1255
+		$where = array();
1256
+		if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257
+			$where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258
+		}
1259
+		return $where;
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1265
+	 *
1266
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1267
+	 * @return array
1268
+	 */
1269
+	protected function _add_datetime_id_to_where_conditions(array $request)
1270
+	{
1271
+		$where = array();
1272
+		if (! empty($request['datetime_id'])) {
1273
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274
+		}
1275
+		if (! empty($request['DTT_ID'])) {
1276
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277
+		}
1278
+		return $where;
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * Adds the correct registration status to the where conditions for the registrations query.
1284
+	 *
1285
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1286
+	 * @return array
1287
+	 */
1288
+	protected function _add_registration_status_to_where_conditions(array $request)
1289
+	{
1290
+		$where = array();
1291
+		$view = EEH_Array::is_set($request, 'status', '');
1292
+		$registration_status = ! empty($request['_reg_status'])
1293
+			? sanitize_text_field($request['_reg_status'])
1294
+			: '';
1295
+
1296
+		/*
1297 1297
          * If filtering by registration status, then we show registrations matching that status.
1298 1298
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations
1299 1299
          * UNLESS viewing trashed registrations.
1300 1300
          */
1301
-        if (! empty($registration_status)) {
1302
-            $where['STS_ID'] = $registration_status;
1303
-        } else {
1304
-            // make sure we exclude incomplete registrations, but only if not trashed.
1305
-            if ($view === 'trash') {
1306
-                $where['REG_deleted'] = true;
1307
-            } elseif ($view === 'incomplete') {
1308
-                $where['STS_ID'] = EEM_Registration::status_id_incomplete;
1309
-            } else {
1310
-                $where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1311
-            }
1312
-        }
1313
-        return $where;
1314
-    }
1315
-
1316
-
1317
-    /**
1318
-     * Adds any provided date restraints to the where conditions for the registrations query.
1319
-     *
1320
-     * @param array $request usually the same as $this->_req_data but not necessarily
1321
-     * @return array
1322
-     * @throws EE_Error
1323
-     * @throws InvalidArgumentException
1324
-     * @throws InvalidDataTypeException
1325
-     * @throws InvalidInterfaceException
1326
-     */
1327
-    protected function _add_date_to_where_conditions(array $request)
1328
-    {
1329
-        $where = array();
1330
-        $view = EEH_Array::is_set($request, 'status', '');
1331
-        $month_range = ! empty($request['month_range'])
1332
-            ? sanitize_text_field($request['month_range'])
1333
-            : '';
1334
-        $retrieve_for_today = $view === 'today';
1335
-        $retrieve_for_this_month = $view === 'month';
1336
-
1337
-        if ($retrieve_for_today) {
1338
-            $now = date('Y-m-d', current_time('timestamp'));
1339
-            $where['REG_date'] = array(
1340
-                'BETWEEN',
1341
-                array(
1342
-                    EEM_Registration::instance()->convert_datetime_for_query(
1343
-                        'REG_date',
1344
-                        $now . ' 00:00:00',
1345
-                        'Y-m-d H:i:s'
1346
-                    ),
1347
-                    EEM_Registration::instance()->convert_datetime_for_query(
1348
-                        'REG_date',
1349
-                        $now . ' 23:59:59',
1350
-                        'Y-m-d H:i:s'
1351
-                    ),
1352
-                ),
1353
-            );
1354
-        } elseif ($retrieve_for_this_month) {
1355
-            $current_year_and_month = date('Y-m', current_time('timestamp'));
1356
-            $days_this_month = date('t', current_time('timestamp'));
1357
-            $where['REG_date'] = array(
1358
-                'BETWEEN',
1359
-                array(
1360
-                    EEM_Registration::instance()->convert_datetime_for_query(
1361
-                        'REG_date',
1362
-                        $current_year_and_month . '-01 00:00:00',
1363
-                        'Y-m-d H:i:s'
1364
-                    ),
1365
-                    EEM_Registration::instance()->convert_datetime_for_query(
1366
-                        'REG_date',
1367
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1368
-                        'Y-m-d H:i:s'
1369
-                    ),
1370
-                ),
1371
-            );
1372
-        } elseif ($month_range) {
1373
-            $pieces = explode(' ', $month_range, 3);
1374
-            $month_requested = ! empty($pieces[0])
1375
-                ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1376
-                : '';
1377
-            $year_requested = ! empty($pieces[1])
1378
-                ? $pieces[1]
1379
-                : '';
1380
-            // if there is not a month or year then we can't go further
1381
-            if ($month_requested && $year_requested) {
1382
-                $days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1383
-                $where['REG_date'] = array(
1384
-                    'BETWEEN',
1385
-                    array(
1386
-                        EEM_Registration::instance()->convert_datetime_for_query(
1387
-                            'REG_date',
1388
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1389
-                            'Y-m-d H:i:s'
1390
-                        ),
1391
-                        EEM_Registration::instance()->convert_datetime_for_query(
1392
-                            'REG_date',
1393
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1394
-                            'Y-m-d H:i:s'
1395
-                        ),
1396
-                    ),
1397
-                );
1398
-            }
1399
-        }
1400
-        return $where;
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * Adds any provided search restraints to the where conditions for the registrations query
1406
-     *
1407
-     * @param array $request usually the same as $this->_req_data but not necessarily
1408
-     * @return array
1409
-     */
1410
-    protected function _add_search_to_where_conditions(array $request)
1411
-    {
1412
-        $where = array();
1413
-        if (! empty($request['s'])) {
1414
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1415
-            $where['OR*search_conditions'] = array(
1416
-                'Event.EVT_name'                          => array('LIKE', $search_string),
1417
-                'Event.EVT_desc'                          => array('LIKE', $search_string),
1418
-                'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1419
-                'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1420
-                'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1421
-                'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1422
-                'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1423
-                'Attendee.ATT_email'                      => array('LIKE', $search_string),
1424
-                'Attendee.ATT_address'                    => array('LIKE', $search_string),
1425
-                'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1426
-                'Attendee.ATT_city'                       => array('LIKE', $search_string),
1427
-                'REG_final_price'                         => array('LIKE', $search_string),
1428
-                'REG_code'                                => array('LIKE', $search_string),
1429
-                'REG_count'                               => array('LIKE', $search_string),
1430
-                'REG_group_size'                          => array('LIKE', $search_string),
1431
-                'Ticket.TKT_name'                         => array('LIKE', $search_string),
1432
-                'Ticket.TKT_description'                  => array('LIKE', $search_string),
1433
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1434
-            );
1435
-        }
1436
-        return $where;
1437
-    }
1438
-
1439
-
1440
-    /**
1441
-     * Sets up the where conditions for the registrations query.
1442
-     *
1443
-     * @param array $request
1444
-     * @return array
1445
-     * @throws EE_Error
1446
-     */
1447
-    protected function _get_where_conditions_for_registrations_query($request)
1448
-    {
1449
-        return apply_filters(
1450
-            'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1451
-            array_merge(
1452
-                $this->addAttendeeIdToWhereConditions($request),
1453
-                $this->_add_event_id_to_where_conditions($request),
1454
-                $this->_add_category_id_to_where_conditions($request),
1455
-                $this->_add_datetime_id_to_where_conditions($request),
1456
-                $this->_add_registration_status_to_where_conditions($request),
1457
-                $this->_add_date_to_where_conditions($request),
1458
-                $this->_add_search_to_where_conditions($request)
1459
-            ),
1460
-            $request
1461
-        );
1462
-    }
1463
-
1464
-
1465
-    /**
1466
-     * Sets up the orderby for the registrations query.
1467
-     *
1468
-     * @return array
1469
-     */
1470
-    protected function _get_orderby_for_registrations_query()
1471
-    {
1472
-        $orderby_field = ! empty($this->_req_data['orderby'])
1473
-            ? sanitize_text_field($this->_req_data['orderby'])
1474
-            : '_REG_date';
1475
-        switch ($orderby_field) {
1476
-            case '_REG_ID':
1477
-                $orderby = array('REG_ID');
1478
-                break;
1479
-            case '_Reg_status':
1480
-                $orderby = array('STS_ID');
1481
-                break;
1482
-            case 'ATT_fname':
1483
-                $orderby = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1484
-                break;
1485
-            case 'ATT_lname':
1486
-                $orderby = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1487
-                break;
1488
-            case 'event_name':
1489
-                $orderby = array('Event.EVT_name');
1490
-                break;
1491
-            case 'DTT_EVT_start':
1492
-                $orderby = array('Event.Datetime.DTT_EVT_start');
1493
-                break;
1494
-            case '_REG_date':
1495
-                $orderby = array('REG_date');
1496
-                break;
1497
-            default:
1498
-                $orderby = array($orderby_field);
1499
-                break;
1500
-        }
1501
-
1502
-        // order
1503
-        $order = ! empty($this->_req_data['order'])
1504
-            ? sanitize_text_field($this->_req_data['order'])
1505
-            : 'DESC';
1506
-        $orderby = array_combine(
1507
-            $orderby,
1508
-            array_fill(0, count($orderby), $order)
1509
-        );
1510
-        // because there are many registrations with the same date, define
1511
-        // a secondary way to order them, otherwise MySQL seems to be a bit random
1512
-        if (empty($orderby['REG_ID'])) {
1513
-            $orderby['REG_ID'] = $order;
1514
-        }
1515
-
1516
-        $orderby = apply_filters(
1517
-            'FHEE__Registrations_Admin_Page___get_orderby_for_registrations_query',
1518
-            $orderby,
1519
-            $this->_req_data
1520
-        );
1521
-
1522
-        return array('order_by' => $orderby);
1523
-    }
1524
-
1525
-
1526
-    /**
1527
-     * Sets up the limit for the registrations query.
1528
-     *
1529
-     * @param $per_page
1530
-     * @return array
1531
-     */
1532
-    protected function _get_limit($per_page)
1533
-    {
1534
-        $current_page = ! empty($this->_req_data['paged'])
1535
-            ? absint($this->_req_data['paged'])
1536
-            : 1;
1537
-        $per_page = ! empty($this->_req_data['perpage'])
1538
-            ? $this->_req_data['perpage']
1539
-            : $per_page;
1540
-
1541
-        // -1 means return all results so get out if that's set.
1542
-        if ((int) $per_page === -1) {
1543
-            return array();
1544
-        }
1545
-        $per_page = absint($per_page);
1546
-        $offset = ($current_page - 1) * $per_page;
1547
-        return array('limit' => array($offset, $per_page));
1548
-    }
1549
-
1550
-
1551
-    public function get_registration_status_array()
1552
-    {
1553
-        return self::$_reg_status;
1554
-    }
1555
-
1556
-
1557
-
1558
-
1559
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1560
-    /**
1561
-     *        generates HTML for the View Registration Details Admin page
1562
-     *
1563
-     * @access protected
1564
-     * @return void
1565
-     * @throws DomainException
1566
-     * @throws EE_Error
1567
-     * @throws InvalidArgumentException
1568
-     * @throws InvalidDataTypeException
1569
-     * @throws InvalidInterfaceException
1570
-     * @throws EntityNotFoundException
1571
-     */
1572
-    protected function _registration_details()
1573
-    {
1574
-        $this->_template_args = array();
1575
-        $this->_set_registration_object();
1576
-        if (is_object($this->_registration)) {
1577
-            $transaction = $this->_registration->transaction()
1578
-                ? $this->_registration->transaction()
1579
-                : EE_Transaction::new_instance();
1580
-            $this->_session = $transaction->session_data();
1581
-            $event_id = $this->_registration->event_ID();
1582
-            $this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1583
-            $this->_template_args['reg_nmbr']['label'] = esc_html__('Registration Number', 'event_espresso');
1584
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1585
-            $this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1586
-            $this->_template_args['grand_total'] = $transaction->total();
1587
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1588
-            // link back to overview
1589
-            $this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1590
-            $this->_template_args['registration'] = $this->_registration;
1591
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1592
-                array(
1593
-                    'action'   => 'default',
1594
-                    'event_id' => $event_id,
1595
-                ),
1596
-                REG_ADMIN_URL
1597
-            );
1598
-            $this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(
1599
-                array(
1600
-                    'action' => 'default',
1601
-                    'EVT_ID' => $event_id,
1602
-                    'page'   => 'espresso_transactions',
1603
-                ),
1604
-                admin_url('admin.php')
1605
-            );
1606
-            $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
1607
-                array(
1608
-                    'page'   => 'espresso_events',
1609
-                    'action' => 'edit',
1610
-                    'post'   => $event_id,
1611
-                ),
1612
-                admin_url('admin.php')
1613
-            );
1614
-            // next and previous links
1615
-            $next_reg = $this->_registration->next(
1616
-                null,
1617
-                array(),
1618
-                'REG_ID'
1619
-            );
1620
-            $this->_template_args['next_registration'] = $next_reg
1621
-                ? $this->_next_link(
1622
-                    EE_Admin_Page::add_query_args_and_nonce(
1623
-                        array(
1624
-                            'action'  => 'view_registration',
1625
-                            '_REG_ID' => $next_reg['REG_ID'],
1626
-                        ),
1627
-                        REG_ADMIN_URL
1628
-                    ),
1629
-                    'dashicons dashicons-arrow-right ee-icon-size-22'
1630
-                )
1631
-                : '';
1632
-            $previous_reg = $this->_registration->previous(
1633
-                null,
1634
-                array(),
1635
-                'REG_ID'
1636
-            );
1637
-            $this->_template_args['previous_registration'] = $previous_reg
1638
-                ? $this->_previous_link(
1639
-                    EE_Admin_Page::add_query_args_and_nonce(
1640
-                        array(
1641
-                            'action'  => 'view_registration',
1642
-                            '_REG_ID' => $previous_reg['REG_ID'],
1643
-                        ),
1644
-                        REG_ADMIN_URL
1645
-                    ),
1646
-                    'dashicons dashicons-arrow-left ee-icon-size-22'
1647
-                )
1648
-                : '';
1649
-            // grab header
1650
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1651
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
1652
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653
-                $template_path,
1654
-                $this->_template_args,
1655
-                true
1656
-            );
1657
-        } else {
1658
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1659
-        }
1660
-        // the details template wrapper
1661
-        $this->display_admin_page_with_sidebar();
1662
-    }
1663
-
1664
-
1665
-    protected function _registration_details_metaboxes()
1666
-    {
1667
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1668
-        $this->_set_registration_object();
1669
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1670
-        add_meta_box(
1671
-            'edit-reg-status-mbox',
1672
-            esc_html__('Registration Status', 'event_espresso'),
1673
-            array($this, 'set_reg_status_buttons_metabox'),
1674
-            $this->wp_page_slug,
1675
-            'normal',
1676
-            'high'
1677
-        );
1678
-        add_meta_box(
1679
-            'edit-reg-details-mbox',
1680
-            esc_html__('Registration Details', 'event_espresso'),
1681
-            array($this, '_reg_details_meta_box'),
1682
-            $this->wp_page_slug,
1683
-            'normal',
1684
-            'high'
1685
-        );
1686
-        if ($attendee instanceof EE_Attendee
1687
-            && EE_Registry::instance()->CAP->current_user_can(
1688
-                'ee_read_registration',
1689
-                'edit-reg-questions-mbox',
1690
-                $this->_registration->ID()
1691
-            )
1692
-        ) {
1693
-            add_meta_box(
1694
-                'edit-reg-questions-mbox',
1695
-                esc_html__('Registration Form Answers', 'event_espresso'),
1696
-                array($this, '_reg_questions_meta_box'),
1697
-                $this->wp_page_slug,
1698
-                'normal',
1699
-                'high'
1700
-            );
1701
-        }
1702
-        add_meta_box(
1703
-            'edit-reg-registrant-mbox',
1704
-            esc_html__('Contact Details', 'event_espresso'),
1705
-            array($this, '_reg_registrant_side_meta_box'),
1706
-            $this->wp_page_slug,
1707
-            'side',
1708
-            'high'
1709
-        );
1710
-        if ($this->_registration->group_size() > 1) {
1711
-            add_meta_box(
1712
-                'edit-reg-attendees-mbox',
1713
-                esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1714
-                array($this, '_reg_attendees_meta_box'),
1715
-                $this->wp_page_slug,
1716
-                'normal',
1717
-                'high'
1718
-            );
1719
-        }
1720
-    }
1721
-
1722
-
1723
-    /**
1724
-     * set_reg_status_buttons_metabox
1725
-     *
1726
-     * @access protected
1727
-     * @return string
1728
-     * @throws \EE_Error
1729
-     */
1730
-    public function set_reg_status_buttons_metabox()
1731
-    {
1732
-        $this->_set_registration_object();
1733
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1734
-        echo $change_reg_status_form->form_open(
1735
-            self::add_query_args_and_nonce(
1736
-                array(
1737
-                    'action' => 'change_reg_status',
1738
-                ),
1739
-                REG_ADMIN_URL
1740
-            )
1741
-        );
1742
-        echo $change_reg_status_form->get_html();
1743
-        echo $change_reg_status_form->form_close();
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * @return EE_Form_Section_Proper
1749
-     * @throws EE_Error
1750
-     * @throws InvalidArgumentException
1751
-     * @throws InvalidDataTypeException
1752
-     * @throws InvalidInterfaceException
1753
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1754
-     */
1755
-    protected function _generate_reg_status_change_form()
1756
-    {
1757
-        $reg_status_change_form_array = array(
1758
-            'name'            => 'reg_status_change_form',
1759
-            'html_id'         => 'reg-status-change-form',
1760
-            'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1761
-            'subsections'     => array(
1762
-                'return'             => new EE_Hidden_Input(
1763
-                    array(
1764
-                        'name'    => 'return',
1765
-                        'default' => 'view_registration',
1766
-                    )
1767
-                ),
1768
-                'REG_ID'             => new EE_Hidden_Input(
1769
-                    array(
1770
-                        'name'    => 'REG_ID',
1771
-                        'default' => $this->_registration->ID(),
1772
-                    )
1773
-                ),
1774
-                'current_status'     => new EE_Form_Section_HTML(
1775
-                    EEH_HTML::tr(
1776
-                        EEH_HTML::th(
1777
-                            EEH_HTML::label(
1778
-                                EEH_HTML::strong(
1779
-                                    esc_html__('Current Registration Status', 'event_espresso')
1780
-                                )
1781
-                            )
1782
-                        )
1783
-                        . EEH_HTML::td(
1784
-                            EEH_HTML::strong(
1785
-                                $this->_registration->pretty_status(),
1786
-                                '',
1787
-                                'status-' . $this->_registration->status_ID(),
1788
-                                'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789
-                            )
1790
-                        )
1791
-                    )
1792
-                )
1793
-            )
1794
-        );
1795
-        if (EE_Registry::instance()->CAP->current_user_can(
1796
-            'ee_edit_registration',
1797
-            'toggle_registration_status',
1798
-            $this->_registration->ID()
1799
-        )) {
1800
-            $reg_status_change_form_array['subsections']['reg_status'] = new EE_Select_Input(
1801
-                $this->_get_reg_statuses(),
1802
-                array(
1803
-                    'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1804
-                    'default'         => $this->_registration->status_ID(),
1805
-                )
1806
-            );
1807
-            $reg_status_change_form_array['subsections']['send_notifications'] = new EE_Yes_No_Input(
1808
-                array(
1809
-                    'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1810
-                    'default'         => false,
1811
-                    'html_help_text'  => esc_html__(
1812
-                        'If set to "Yes", then the related messages will be sent to the registrant.',
1813
-                        'event_espresso'
1814
-                    )
1815
-                )
1816
-            );
1817
-            $reg_status_change_form_array['subsections']['submit'] = new EE_Submit_Input(
1818
-                array(
1819
-                    'html_class'      => 'button-primary',
1820
-                    'html_label_text' => '&nbsp;',
1821
-                    'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1822
-                )
1823
-            );
1824
-        }
1825
-        return new EE_Form_Section_Proper($reg_status_change_form_array);
1826
-    }
1827
-
1828
-
1829
-    /**
1830
-     * Returns an array of all the buttons for the various statuses and switch status actions
1831
-     *
1832
-     * @return array
1833
-     * @throws EE_Error
1834
-     * @throws InvalidArgumentException
1835
-     * @throws InvalidDataTypeException
1836
-     * @throws InvalidInterfaceException
1837
-     * @throws EntityNotFoundException
1838
-     */
1839
-    protected function _get_reg_statuses()
1840
-    {
1841
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
-        unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1843
-        // get current reg status
1844
-        $current_status = $this->_registration->status_ID();
1845
-        // is registration for free event? This will determine whether to display the pending payment option
1846
-        if ($current_status !== EEM_Registration::status_id_pending_payment
1847
-            && EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848
-        ) {
1849
-            unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1850
-        }
1851
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852
-    }
1853
-
1854
-
1855
-    /**
1856
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1857
-     *
1858
-     * @param bool $status REG status given for changing registrations to.
1859
-     * @param bool $notify Whether to send messages notifications or not.
1860
-     * @return array (array with reg_id(s) updated and whether update was successful.
1861
-     * @throws EE_Error
1862
-     * @throws InvalidArgumentException
1863
-     * @throws InvalidDataTypeException
1864
-     * @throws InvalidInterfaceException
1865
-     * @throws ReflectionException
1866
-     * @throws RuntimeException
1867
-     * @throws EntityNotFoundException
1868
-     */
1869
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1870
-    {
1871
-        if (isset($this->_req_data['reg_status_change_form'])) {
1872
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1873
-                ? (array) $this->_req_data['reg_status_change_form']['REG_ID']
1874
-                : array();
1875
-        } else {
1876
-            $REG_IDs = isset($this->_req_data['_REG_ID'])
1877
-                ? (array) $this->_req_data['_REG_ID']
1878
-                : array();
1879
-        }
1880
-        // sanitize $REG_IDs
1881
-        $REG_IDs = array_map('absint', $REG_IDs);
1882
-        // and remove empty entries
1883
-        $REG_IDs = array_filter($REG_IDs);
1884
-
1885
-        $result = $this->_set_registration_status($REG_IDs, $status, $notify);
1886
-
1887
-        /**
1888
-         * Set and filter $_req_data['_REG_ID'] for any potential future messages notifications.
1889
-         * Currently this value is used downstream by the _process_resend_registration method.
1890
-         *
1891
-         * @param int|array                $registration_ids The registration ids that have had their status changed successfully.
1892
-         * @param bool                     $status           The status registrations were changed to.
1893
-         * @param bool                     $success          If the status was changed successfully for all registrations.
1894
-         * @param Registrations_Admin_Page $admin_page_object
1895
-         */
1896
-        $this->_req_data['_REG_ID'] = apply_filters(
1897
-            'FHEE__Registrations_Admin_Page___set_registration_status_from_request__REG_IDs',
1898
-            $result['REG_ID'],
1899
-            $status,
1900
-            $result['success'],
1901
-            $this
1902
-        );
1903
-
1904
-        // notify?
1905
-        if ($notify
1906
-            && $result['success']
1907
-            && ! empty($this->_req_data['_REG_ID'])
1908
-            && EE_Registry::instance()->CAP->current_user_can(
1909
-                'ee_send_message',
1910
-                'espresso_registrations_resend_registration'
1911
-            )
1912
-        ) {
1913
-            $this->_process_resend_registration();
1914
-        }
1915
-        return $result;
1916
-    }
1917
-
1918
-
1919
-    /**
1920
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1921
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1922
-     *
1923
-     * @param array  $REG_IDs
1924
-     * @param string $status
1925
-     * @param bool   $notify  Used to indicate whether notification was requested or not.  This determines the context
1926
-     *                        slug sent with setting the registration status.
1927
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1928
-     * @throws EE_Error
1929
-     * @throws InvalidArgumentException
1930
-     * @throws InvalidDataTypeException
1931
-     * @throws InvalidInterfaceException
1932
-     * @throws ReflectionException
1933
-     * @throws RuntimeException
1934
-     * @throws EntityNotFoundException
1935
-     */
1936
-    protected function _set_registration_status($REG_IDs = array(), $status = '', $notify = false)
1937
-    {
1938
-        $success = false;
1939
-        // typecast $REG_IDs
1940
-        $REG_IDs = (array) $REG_IDs;
1941
-        if (! empty($REG_IDs)) {
1942
-            $success = true;
1943
-            // set default status if none is passed
1944
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1945
-            $status_context = $notify
1946
-                ? Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY
1947
-                : Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN;
1948
-            // loop through REG_ID's and change status
1949
-            foreach ($REG_IDs as $REG_ID) {
1950
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1951
-                if ($registration instanceof EE_Registration) {
1952
-                    $registration->set_status(
1953
-                        $status,
1954
-                        false,
1955
-                        new Context(
1956
-                            $status_context,
1957
-                            esc_html__(
1958
-                                'Manually triggered status change on a Registration Admin Page route.',
1959
-                                'event_espresso'
1960
-                            )
1961
-                        )
1962
-                    );
1963
-                    $result = $registration->save();
1964
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1965
-                    $success = $result !== false ? $success : false;
1966
-                }
1967
-            }
1968
-        }
1969
-
1970
-        // return $success and processed registrations
1971
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * Common logic for setting up success message and redirecting to appropriate route
1977
-     *
1978
-     * @param  string $STS_ID status id for the registration changed to
1979
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1980
-     * @return void
1981
-     * @throws EE_Error
1982
-     */
1983
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1984
-    {
1985
-        $result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1986
-            : array('success' => false);
1987
-        $success = isset($result['success']) && $result['success'];
1988
-        // setup success message
1989
-        if ($success) {
1990
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1991
-                $msg = sprintf(
1992
-                    esc_html__('Registration status has been set to %s', 'event_espresso'),
1993
-                    EEH_Template::pretty_status($STS_ID, false, 'lower')
1994
-                );
1995
-            } else {
1996
-                $msg = sprintf(
1997
-                    esc_html__('Registrations have been set to %s.', 'event_espresso'),
1998
-                    EEH_Template::pretty_status($STS_ID, false, 'lower')
1999
-                );
2000
-            }
2001
-            EE_Error::add_success($msg);
2002
-        } else {
2003
-            EE_Error::add_error(
2004
-                esc_html__(
2005
-                    'Something went wrong, and the status was not changed',
2006
-                    'event_espresso'
2007
-                ),
2008
-                __FILE__,
2009
-                __LINE__,
2010
-                __FUNCTION__
2011
-            );
2012
-        }
2013
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
2014
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
2015
-        } else {
2016
-            $route = array('action' => 'default');
2017
-        }
2018
-        // unset nonces
2019
-        foreach ($this->_req_data as $ref => $value) {
2020
-            if (strpos($ref, 'nonce') !== false) {
2021
-                unset($this->_req_data[ $ref ]);
2022
-                continue;
2023
-            }
2024
-            $value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
2025
-            $this->_req_data[ $ref ] = $value;
2026
-        }
2027
-        // merge request vars so that the reloaded list table contains any existing filter query params
2028
-        $route = array_merge($this->_req_data, $route);
2029
-        $this->_redirect_after_action($success, '', '', $route, true);
2030
-    }
2031
-
2032
-
2033
-    /**
2034
-     * incoming reg status change from reg details page.
2035
-     *
2036
-     * @return void
2037
-     */
2038
-    protected function _change_reg_status()
2039
-    {
2040
-        $this->_req_data['return'] = 'view_registration';
2041
-        // set notify based on whether the send notifications toggle is set or not
2042
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
2043
-        // $notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
2044
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
2045
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
2046
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
2047
-            case EEM_Registration::status_id_approved:
2048
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'):
2049
-                $this->approve_registration($notify);
2050
-                break;
2051
-            case EEM_Registration::status_id_pending_payment:
2052
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'):
2053
-                $this->pending_registration($notify);
2054
-                break;
2055
-            case EEM_Registration::status_id_not_approved:
2056
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'):
2057
-                $this->not_approve_registration($notify);
2058
-                break;
2059
-            case EEM_Registration::status_id_declined:
2060
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'):
2061
-                $this->decline_registration($notify);
2062
-                break;
2063
-            case EEM_Registration::status_id_cancelled:
2064
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'):
2065
-                $this->cancel_registration($notify);
2066
-                break;
2067
-            case EEM_Registration::status_id_wait_list:
2068
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'):
2069
-                $this->wait_list_registration($notify);
2070
-                break;
2071
-            case EEM_Registration::status_id_incomplete:
2072
-            default:
2073
-                $result['success'] = false;
2074
-                unset($this->_req_data['return']);
2075
-                $this->_reg_status_change_return('', false);
2076
-                break;
2077
-        }
2078
-    }
2079
-
2080
-
2081
-    /**
2082
-     * Callback for bulk action routes.
2083
-     * Note: although we could just register the singular route callbacks for each bulk action route as well, this
2084
-     * method was chosen so there is one central place all the registration status bulk actions are going through.
2085
-     * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
2086
-     * when an action is happening on just a single registration).
2087
-     *
2088
-     * @param      $action
2089
-     * @param bool $notify
2090
-     */
2091
-    protected function bulk_action_on_registrations($action, $notify = false)
2092
-    {
2093
-        do_action(
2094
-            'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
2095
-            $this,
2096
-            $action,
2097
-            $notify
2098
-        );
2099
-        $method = $action . '_registration';
2100
-        if (method_exists($this, $method)) {
2101
-            $this->$method($notify);
2102
-        }
2103
-    }
2104
-
2105
-
2106
-    /**
2107
-     * approve_registration
2108
-     *
2109
-     * @access protected
2110
-     * @param bool $notify whether or not to notify the registrant about their approval.
2111
-     * @return void
2112
-     */
2113
-    protected function approve_registration($notify = false)
2114
-    {
2115
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
2116
-    }
2117
-
2118
-
2119
-    /**
2120
-     *        decline_registration
2121
-     *
2122
-     * @access protected
2123
-     * @param bool $notify whether or not to notify the registrant about their status change.
2124
-     * @return void
2125
-     */
2126
-    protected function decline_registration($notify = false)
2127
-    {
2128
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
2129
-    }
2130
-
2131
-
2132
-    /**
2133
-     *        cancel_registration
2134
-     *
2135
-     * @access protected
2136
-     * @param bool $notify whether or not to notify the registrant about their status change.
2137
-     * @return void
2138
-     */
2139
-    protected function cancel_registration($notify = false)
2140
-    {
2141
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
2142
-    }
2143
-
2144
-
2145
-    /**
2146
-     *        not_approve_registration
2147
-     *
2148
-     * @access protected
2149
-     * @param bool $notify whether or not to notify the registrant about their status change.
2150
-     * @return void
2151
-     */
2152
-    protected function not_approve_registration($notify = false)
2153
-    {
2154
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
2155
-    }
2156
-
2157
-
2158
-    /**
2159
-     *        decline_registration
2160
-     *
2161
-     * @access protected
2162
-     * @param bool $notify whether or not to notify the registrant about their status change.
2163
-     * @return void
2164
-     */
2165
-    protected function pending_registration($notify = false)
2166
-    {
2167
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
2168
-    }
2169
-
2170
-
2171
-    /**
2172
-     * waitlist_registration
2173
-     *
2174
-     * @access protected
2175
-     * @param bool $notify whether or not to notify the registrant about their status change.
2176
-     * @return void
2177
-     */
2178
-    protected function wait_list_registration($notify = false)
2179
-    {
2180
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2181
-    }
2182
-
2183
-
2184
-    /**
2185
-     *        generates HTML for the Registration main meta box
2186
-     *
2187
-     * @access public
2188
-     * @return void
2189
-     * @throws DomainException
2190
-     * @throws EE_Error
2191
-     * @throws InvalidArgumentException
2192
-     * @throws InvalidDataTypeException
2193
-     * @throws InvalidInterfaceException
2194
-     * @throws ReflectionException
2195
-     * @throws EntityNotFoundException
2196
-     */
2197
-    public function _reg_details_meta_box()
2198
-    {
2199
-        EEH_Autoloader::register_line_item_display_autoloaders();
2200
-        EEH_Autoloader::register_line_item_filter_autoloaders();
2201
-        EE_Registry::instance()->load_helper('Line_Item');
2202
-        $transaction = $this->_registration->transaction() ? $this->_registration->transaction()
2203
-            : EE_Transaction::new_instance();
2204
-        $this->_session = $transaction->session_data();
2205
-        $filters = new EE_Line_Item_Filter_Collection();
2206
-        // $filters->add( new EE_Non_Zero_Line_Item_Filter() );
2207
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2208
-        $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
2209
-            $filters,
2210
-            $transaction->total_line_item()
2211
-        );
2212
-        $filtered_line_item_tree = $line_item_filter_processor->process();
2213
-        $line_item_display = new EE_Line_Item_Display(
2214
-            'reg_admin_table',
2215
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy'
2216
-        );
2217
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2218
-            $filtered_line_item_tree,
2219
-            array('EE_Registration' => $this->_registration)
2220
-        );
2221
-        $attendee = $this->_registration->attendee();
2222
-        if (EE_Registry::instance()->CAP->current_user_can(
2223
-            'ee_read_transaction',
2224
-            'espresso_transactions_view_transaction'
2225
-        )) {
2226
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2227
-                EE_Admin_Page::add_query_args_and_nonce(
2228
-                    array(
2229
-                        'action' => 'view_transaction',
2230
-                        'TXN_ID' => $transaction->ID(),
2231
-                    ),
2232
-                    TXN_ADMIN_URL
2233
-                ),
2234
-                esc_html__(' View Transaction', 'event_espresso'),
2235
-                'button secondary-button right',
2236
-                'dashicons dashicons-cart'
2237
-            );
2238
-        } else {
2239
-            $this->_template_args['view_transaction_button'] = '';
2240
-        }
2241
-        if ($attendee instanceof EE_Attendee
2242
-            && EE_Registry::instance()->CAP->current_user_can(
2243
-                'ee_send_message',
2244
-                'espresso_registrations_resend_registration'
2245
-            )
2246
-        ) {
2247
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2248
-                EE_Admin_Page::add_query_args_and_nonce(
2249
-                    array(
2250
-                        'action'      => 'resend_registration',
2251
-                        '_REG_ID'     => $this->_registration->ID(),
2252
-                        'redirect_to' => 'view_registration',
2253
-                    ),
2254
-                    REG_ADMIN_URL
2255
-                ),
2256
-                esc_html__(' Resend Registration', 'event_espresso'),
2257
-                'button secondary-button right',
2258
-                'dashicons dashicons-email-alt'
2259
-            );
2260
-        } else {
2261
-            $this->_template_args['resend_registration_button'] = '';
2262
-        }
2263
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2264
-        $payment = $transaction->get_first_related('Payment');
2265
-        $payment = ! $payment instanceof EE_Payment
2266
-            ? EE_Payment::new_instance()
2267
-            : $payment;
2268
-        $payment_method = $payment->get_first_related('Payment_Method');
2269
-        $payment_method = ! $payment_method instanceof EE_Payment_Method
2270
-            ? EE_Payment_Method::new_instance()
2271
-            : $payment_method;
2272
-        $reg_details = array(
2273
-            'payment_method'       => $payment_method->name(),
2274
-            'response_msg'         => $payment->gateway_response(),
2275
-            'registration_id'      => $this->_registration->get('REG_code'),
2276
-            'registration_session' => $this->_registration->session_ID(),
2277
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2278
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2279
-        );
2280
-        if (isset($reg_details['registration_id'])) {
2281
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2282
-            $this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2283
-                'Registration ID',
2284
-                'event_espresso'
2285
-            );
2286
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2287
-        }
2288
-        if (isset($reg_details['payment_method'])) {
2289
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2290
-            $this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2291
-                'Most Recent Payment Method',
2292
-                'event_espresso'
2293
-            );
2294
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2295
-            $this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
2296
-            $this->_template_args['reg_details']['response_msg']['label'] = esc_html__(
2297
-                'Payment method response',
2298
-                'event_espresso'
2299
-            );
2300
-            $this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
2301
-        }
2302
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2303
-        $this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2304
-            'Registration Session',
2305
-            'event_espresso'
2306
-        );
2307
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2308
-        $this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
2309
-        $this->_template_args['reg_details']['ip_address']['label'] = esc_html__(
2310
-            'Registration placed from IP',
2311
-            'event_espresso'
2312
-        );
2313
-        $this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
2314
-        $this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
2315
-        $this->_template_args['reg_details']['user_agent']['label'] = esc_html__(
2316
-            'Registrant User Agent',
2317
-            'event_espresso'
2318
-        );
2319
-        $this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
2320
-        $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
2321
-            array(
2322
-                'action'   => 'default',
2323
-                'event_id' => $this->_registration->event_ID(),
2324
-            ),
2325
-            REG_ADMIN_URL
2326
-        );
2327
-        $this->_template_args['REG_ID'] = $this->_registration->ID();
2328
-        $this->_template_args['event_id'] = $this->_registration->event_ID();
2329
-        $template_path =
2330
-            REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2331
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2332
-    }
2333
-
2334
-
2335
-    /**
2336
-     * generates HTML for the Registration Questions meta box.
2337
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2338
-     * otherwise uses new forms system
2339
-     *
2340
-     * @access public
2341
-     * @return void
2342
-     * @throws DomainException
2343
-     * @throws EE_Error
2344
-     */
2345
-    public function _reg_questions_meta_box()
2346
-    {
2347
-        // allow someone to override this method entirely
2348
-        if (apply_filters(
2349
-            'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default',
2350
-            true,
2351
-            $this,
2352
-            $this->_registration
2353
-        )) {
2354
-            $form = $this->_get_reg_custom_questions_form(
2355
-                $this->_registration->ID()
2356
-            );
2357
-            $this->_template_args['att_questions'] = count($form->subforms()) > 0
2358
-                ? $form->get_html_and_js()
2359
-                : '';
2360
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
2361
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
2362
-            $template_path =
2363
-                REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2364
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
2365
-        }
2366
-    }
2367
-
2368
-
2369
-    /**
2370
-     * form_before_question_group
2371
-     *
2372
-     * @deprecated    as of 4.8.32.rc.000
2373
-     * @access        public
2374
-     * @param        string $output
2375
-     * @return        string
2376
-     */
2377
-    public function form_before_question_group($output)
2378
-    {
2379
-        EE_Error::doing_it_wrong(
2380
-            __CLASS__ . '::' . __FUNCTION__,
2381
-            esc_html__(
2382
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2383
-                'event_espresso'
2384
-            ),
2385
-            '4.8.32.rc.000'
2386
-        );
2387
-        return '
1301
+		if (! empty($registration_status)) {
1302
+			$where['STS_ID'] = $registration_status;
1303
+		} else {
1304
+			// make sure we exclude incomplete registrations, but only if not trashed.
1305
+			if ($view === 'trash') {
1306
+				$where['REG_deleted'] = true;
1307
+			} elseif ($view === 'incomplete') {
1308
+				$where['STS_ID'] = EEM_Registration::status_id_incomplete;
1309
+			} else {
1310
+				$where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1311
+			}
1312
+		}
1313
+		return $where;
1314
+	}
1315
+
1316
+
1317
+	/**
1318
+	 * Adds any provided date restraints to the where conditions for the registrations query.
1319
+	 *
1320
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1321
+	 * @return array
1322
+	 * @throws EE_Error
1323
+	 * @throws InvalidArgumentException
1324
+	 * @throws InvalidDataTypeException
1325
+	 * @throws InvalidInterfaceException
1326
+	 */
1327
+	protected function _add_date_to_where_conditions(array $request)
1328
+	{
1329
+		$where = array();
1330
+		$view = EEH_Array::is_set($request, 'status', '');
1331
+		$month_range = ! empty($request['month_range'])
1332
+			? sanitize_text_field($request['month_range'])
1333
+			: '';
1334
+		$retrieve_for_today = $view === 'today';
1335
+		$retrieve_for_this_month = $view === 'month';
1336
+
1337
+		if ($retrieve_for_today) {
1338
+			$now = date('Y-m-d', current_time('timestamp'));
1339
+			$where['REG_date'] = array(
1340
+				'BETWEEN',
1341
+				array(
1342
+					EEM_Registration::instance()->convert_datetime_for_query(
1343
+						'REG_date',
1344
+						$now . ' 00:00:00',
1345
+						'Y-m-d H:i:s'
1346
+					),
1347
+					EEM_Registration::instance()->convert_datetime_for_query(
1348
+						'REG_date',
1349
+						$now . ' 23:59:59',
1350
+						'Y-m-d H:i:s'
1351
+					),
1352
+				),
1353
+			);
1354
+		} elseif ($retrieve_for_this_month) {
1355
+			$current_year_and_month = date('Y-m', current_time('timestamp'));
1356
+			$days_this_month = date('t', current_time('timestamp'));
1357
+			$where['REG_date'] = array(
1358
+				'BETWEEN',
1359
+				array(
1360
+					EEM_Registration::instance()->convert_datetime_for_query(
1361
+						'REG_date',
1362
+						$current_year_and_month . '-01 00:00:00',
1363
+						'Y-m-d H:i:s'
1364
+					),
1365
+					EEM_Registration::instance()->convert_datetime_for_query(
1366
+						'REG_date',
1367
+						$current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1368
+						'Y-m-d H:i:s'
1369
+					),
1370
+				),
1371
+			);
1372
+		} elseif ($month_range) {
1373
+			$pieces = explode(' ', $month_range, 3);
1374
+			$month_requested = ! empty($pieces[0])
1375
+				? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1376
+				: '';
1377
+			$year_requested = ! empty($pieces[1])
1378
+				? $pieces[1]
1379
+				: '';
1380
+			// if there is not a month or year then we can't go further
1381
+			if ($month_requested && $year_requested) {
1382
+				$days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1383
+				$where['REG_date'] = array(
1384
+					'BETWEEN',
1385
+					array(
1386
+						EEM_Registration::instance()->convert_datetime_for_query(
1387
+							'REG_date',
1388
+							$year_requested . '-' . $month_requested . '-01 00:00:00',
1389
+							'Y-m-d H:i:s'
1390
+						),
1391
+						EEM_Registration::instance()->convert_datetime_for_query(
1392
+							'REG_date',
1393
+							$year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1394
+							'Y-m-d H:i:s'
1395
+						),
1396
+					),
1397
+				);
1398
+			}
1399
+		}
1400
+		return $where;
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * Adds any provided search restraints to the where conditions for the registrations query
1406
+	 *
1407
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1408
+	 * @return array
1409
+	 */
1410
+	protected function _add_search_to_where_conditions(array $request)
1411
+	{
1412
+		$where = array();
1413
+		if (! empty($request['s'])) {
1414
+			$search_string = '%' . sanitize_text_field($request['s']) . '%';
1415
+			$where['OR*search_conditions'] = array(
1416
+				'Event.EVT_name'                          => array('LIKE', $search_string),
1417
+				'Event.EVT_desc'                          => array('LIKE', $search_string),
1418
+				'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1419
+				'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1420
+				'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1421
+				'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1422
+				'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1423
+				'Attendee.ATT_email'                      => array('LIKE', $search_string),
1424
+				'Attendee.ATT_address'                    => array('LIKE', $search_string),
1425
+				'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1426
+				'Attendee.ATT_city'                       => array('LIKE', $search_string),
1427
+				'REG_final_price'                         => array('LIKE', $search_string),
1428
+				'REG_code'                                => array('LIKE', $search_string),
1429
+				'REG_count'                               => array('LIKE', $search_string),
1430
+				'REG_group_size'                          => array('LIKE', $search_string),
1431
+				'Ticket.TKT_name'                         => array('LIKE', $search_string),
1432
+				'Ticket.TKT_description'                  => array('LIKE', $search_string),
1433
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1434
+			);
1435
+		}
1436
+		return $where;
1437
+	}
1438
+
1439
+
1440
+	/**
1441
+	 * Sets up the where conditions for the registrations query.
1442
+	 *
1443
+	 * @param array $request
1444
+	 * @return array
1445
+	 * @throws EE_Error
1446
+	 */
1447
+	protected function _get_where_conditions_for_registrations_query($request)
1448
+	{
1449
+		return apply_filters(
1450
+			'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1451
+			array_merge(
1452
+				$this->addAttendeeIdToWhereConditions($request),
1453
+				$this->_add_event_id_to_where_conditions($request),
1454
+				$this->_add_category_id_to_where_conditions($request),
1455
+				$this->_add_datetime_id_to_where_conditions($request),
1456
+				$this->_add_registration_status_to_where_conditions($request),
1457
+				$this->_add_date_to_where_conditions($request),
1458
+				$this->_add_search_to_where_conditions($request)
1459
+			),
1460
+			$request
1461
+		);
1462
+	}
1463
+
1464
+
1465
+	/**
1466
+	 * Sets up the orderby for the registrations query.
1467
+	 *
1468
+	 * @return array
1469
+	 */
1470
+	protected function _get_orderby_for_registrations_query()
1471
+	{
1472
+		$orderby_field = ! empty($this->_req_data['orderby'])
1473
+			? sanitize_text_field($this->_req_data['orderby'])
1474
+			: '_REG_date';
1475
+		switch ($orderby_field) {
1476
+			case '_REG_ID':
1477
+				$orderby = array('REG_ID');
1478
+				break;
1479
+			case '_Reg_status':
1480
+				$orderby = array('STS_ID');
1481
+				break;
1482
+			case 'ATT_fname':
1483
+				$orderby = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1484
+				break;
1485
+			case 'ATT_lname':
1486
+				$orderby = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1487
+				break;
1488
+			case 'event_name':
1489
+				$orderby = array('Event.EVT_name');
1490
+				break;
1491
+			case 'DTT_EVT_start':
1492
+				$orderby = array('Event.Datetime.DTT_EVT_start');
1493
+				break;
1494
+			case '_REG_date':
1495
+				$orderby = array('REG_date');
1496
+				break;
1497
+			default:
1498
+				$orderby = array($orderby_field);
1499
+				break;
1500
+		}
1501
+
1502
+		// order
1503
+		$order = ! empty($this->_req_data['order'])
1504
+			? sanitize_text_field($this->_req_data['order'])
1505
+			: 'DESC';
1506
+		$orderby = array_combine(
1507
+			$orderby,
1508
+			array_fill(0, count($orderby), $order)
1509
+		);
1510
+		// because there are many registrations with the same date, define
1511
+		// a secondary way to order them, otherwise MySQL seems to be a bit random
1512
+		if (empty($orderby['REG_ID'])) {
1513
+			$orderby['REG_ID'] = $order;
1514
+		}
1515
+
1516
+		$orderby = apply_filters(
1517
+			'FHEE__Registrations_Admin_Page___get_orderby_for_registrations_query',
1518
+			$orderby,
1519
+			$this->_req_data
1520
+		);
1521
+
1522
+		return array('order_by' => $orderby);
1523
+	}
1524
+
1525
+
1526
+	/**
1527
+	 * Sets up the limit for the registrations query.
1528
+	 *
1529
+	 * @param $per_page
1530
+	 * @return array
1531
+	 */
1532
+	protected function _get_limit($per_page)
1533
+	{
1534
+		$current_page = ! empty($this->_req_data['paged'])
1535
+			? absint($this->_req_data['paged'])
1536
+			: 1;
1537
+		$per_page = ! empty($this->_req_data['perpage'])
1538
+			? $this->_req_data['perpage']
1539
+			: $per_page;
1540
+
1541
+		// -1 means return all results so get out if that's set.
1542
+		if ((int) $per_page === -1) {
1543
+			return array();
1544
+		}
1545
+		$per_page = absint($per_page);
1546
+		$offset = ($current_page - 1) * $per_page;
1547
+		return array('limit' => array($offset, $per_page));
1548
+	}
1549
+
1550
+
1551
+	public function get_registration_status_array()
1552
+	{
1553
+		return self::$_reg_status;
1554
+	}
1555
+
1556
+
1557
+
1558
+
1559
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1560
+	/**
1561
+	 *        generates HTML for the View Registration Details Admin page
1562
+	 *
1563
+	 * @access protected
1564
+	 * @return void
1565
+	 * @throws DomainException
1566
+	 * @throws EE_Error
1567
+	 * @throws InvalidArgumentException
1568
+	 * @throws InvalidDataTypeException
1569
+	 * @throws InvalidInterfaceException
1570
+	 * @throws EntityNotFoundException
1571
+	 */
1572
+	protected function _registration_details()
1573
+	{
1574
+		$this->_template_args = array();
1575
+		$this->_set_registration_object();
1576
+		if (is_object($this->_registration)) {
1577
+			$transaction = $this->_registration->transaction()
1578
+				? $this->_registration->transaction()
1579
+				: EE_Transaction::new_instance();
1580
+			$this->_session = $transaction->session_data();
1581
+			$event_id = $this->_registration->event_ID();
1582
+			$this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1583
+			$this->_template_args['reg_nmbr']['label'] = esc_html__('Registration Number', 'event_espresso');
1584
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1585
+			$this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1586
+			$this->_template_args['grand_total'] = $transaction->total();
1587
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1588
+			// link back to overview
1589
+			$this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1590
+			$this->_template_args['registration'] = $this->_registration;
1591
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1592
+				array(
1593
+					'action'   => 'default',
1594
+					'event_id' => $event_id,
1595
+				),
1596
+				REG_ADMIN_URL
1597
+			);
1598
+			$this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(
1599
+				array(
1600
+					'action' => 'default',
1601
+					'EVT_ID' => $event_id,
1602
+					'page'   => 'espresso_transactions',
1603
+				),
1604
+				admin_url('admin.php')
1605
+			);
1606
+			$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
1607
+				array(
1608
+					'page'   => 'espresso_events',
1609
+					'action' => 'edit',
1610
+					'post'   => $event_id,
1611
+				),
1612
+				admin_url('admin.php')
1613
+			);
1614
+			// next and previous links
1615
+			$next_reg = $this->_registration->next(
1616
+				null,
1617
+				array(),
1618
+				'REG_ID'
1619
+			);
1620
+			$this->_template_args['next_registration'] = $next_reg
1621
+				? $this->_next_link(
1622
+					EE_Admin_Page::add_query_args_and_nonce(
1623
+						array(
1624
+							'action'  => 'view_registration',
1625
+							'_REG_ID' => $next_reg['REG_ID'],
1626
+						),
1627
+						REG_ADMIN_URL
1628
+					),
1629
+					'dashicons dashicons-arrow-right ee-icon-size-22'
1630
+				)
1631
+				: '';
1632
+			$previous_reg = $this->_registration->previous(
1633
+				null,
1634
+				array(),
1635
+				'REG_ID'
1636
+			);
1637
+			$this->_template_args['previous_registration'] = $previous_reg
1638
+				? $this->_previous_link(
1639
+					EE_Admin_Page::add_query_args_and_nonce(
1640
+						array(
1641
+							'action'  => 'view_registration',
1642
+							'_REG_ID' => $previous_reg['REG_ID'],
1643
+						),
1644
+						REG_ADMIN_URL
1645
+					),
1646
+					'dashicons dashicons-arrow-left ee-icon-size-22'
1647
+				)
1648
+				: '';
1649
+			// grab header
1650
+			$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1651
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
1652
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653
+				$template_path,
1654
+				$this->_template_args,
1655
+				true
1656
+			);
1657
+		} else {
1658
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1659
+		}
1660
+		// the details template wrapper
1661
+		$this->display_admin_page_with_sidebar();
1662
+	}
1663
+
1664
+
1665
+	protected function _registration_details_metaboxes()
1666
+	{
1667
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1668
+		$this->_set_registration_object();
1669
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1670
+		add_meta_box(
1671
+			'edit-reg-status-mbox',
1672
+			esc_html__('Registration Status', 'event_espresso'),
1673
+			array($this, 'set_reg_status_buttons_metabox'),
1674
+			$this->wp_page_slug,
1675
+			'normal',
1676
+			'high'
1677
+		);
1678
+		add_meta_box(
1679
+			'edit-reg-details-mbox',
1680
+			esc_html__('Registration Details', 'event_espresso'),
1681
+			array($this, '_reg_details_meta_box'),
1682
+			$this->wp_page_slug,
1683
+			'normal',
1684
+			'high'
1685
+		);
1686
+		if ($attendee instanceof EE_Attendee
1687
+			&& EE_Registry::instance()->CAP->current_user_can(
1688
+				'ee_read_registration',
1689
+				'edit-reg-questions-mbox',
1690
+				$this->_registration->ID()
1691
+			)
1692
+		) {
1693
+			add_meta_box(
1694
+				'edit-reg-questions-mbox',
1695
+				esc_html__('Registration Form Answers', 'event_espresso'),
1696
+				array($this, '_reg_questions_meta_box'),
1697
+				$this->wp_page_slug,
1698
+				'normal',
1699
+				'high'
1700
+			);
1701
+		}
1702
+		add_meta_box(
1703
+			'edit-reg-registrant-mbox',
1704
+			esc_html__('Contact Details', 'event_espresso'),
1705
+			array($this, '_reg_registrant_side_meta_box'),
1706
+			$this->wp_page_slug,
1707
+			'side',
1708
+			'high'
1709
+		);
1710
+		if ($this->_registration->group_size() > 1) {
1711
+			add_meta_box(
1712
+				'edit-reg-attendees-mbox',
1713
+				esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1714
+				array($this, '_reg_attendees_meta_box'),
1715
+				$this->wp_page_slug,
1716
+				'normal',
1717
+				'high'
1718
+			);
1719
+		}
1720
+	}
1721
+
1722
+
1723
+	/**
1724
+	 * set_reg_status_buttons_metabox
1725
+	 *
1726
+	 * @access protected
1727
+	 * @return string
1728
+	 * @throws \EE_Error
1729
+	 */
1730
+	public function set_reg_status_buttons_metabox()
1731
+	{
1732
+		$this->_set_registration_object();
1733
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1734
+		echo $change_reg_status_form->form_open(
1735
+			self::add_query_args_and_nonce(
1736
+				array(
1737
+					'action' => 'change_reg_status',
1738
+				),
1739
+				REG_ADMIN_URL
1740
+			)
1741
+		);
1742
+		echo $change_reg_status_form->get_html();
1743
+		echo $change_reg_status_form->form_close();
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * @return EE_Form_Section_Proper
1749
+	 * @throws EE_Error
1750
+	 * @throws InvalidArgumentException
1751
+	 * @throws InvalidDataTypeException
1752
+	 * @throws InvalidInterfaceException
1753
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1754
+	 */
1755
+	protected function _generate_reg_status_change_form()
1756
+	{
1757
+		$reg_status_change_form_array = array(
1758
+			'name'            => 'reg_status_change_form',
1759
+			'html_id'         => 'reg-status-change-form',
1760
+			'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1761
+			'subsections'     => array(
1762
+				'return'             => new EE_Hidden_Input(
1763
+					array(
1764
+						'name'    => 'return',
1765
+						'default' => 'view_registration',
1766
+					)
1767
+				),
1768
+				'REG_ID'             => new EE_Hidden_Input(
1769
+					array(
1770
+						'name'    => 'REG_ID',
1771
+						'default' => $this->_registration->ID(),
1772
+					)
1773
+				),
1774
+				'current_status'     => new EE_Form_Section_HTML(
1775
+					EEH_HTML::tr(
1776
+						EEH_HTML::th(
1777
+							EEH_HTML::label(
1778
+								EEH_HTML::strong(
1779
+									esc_html__('Current Registration Status', 'event_espresso')
1780
+								)
1781
+							)
1782
+						)
1783
+						. EEH_HTML::td(
1784
+							EEH_HTML::strong(
1785
+								$this->_registration->pretty_status(),
1786
+								'',
1787
+								'status-' . $this->_registration->status_ID(),
1788
+								'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789
+							)
1790
+						)
1791
+					)
1792
+				)
1793
+			)
1794
+		);
1795
+		if (EE_Registry::instance()->CAP->current_user_can(
1796
+			'ee_edit_registration',
1797
+			'toggle_registration_status',
1798
+			$this->_registration->ID()
1799
+		)) {
1800
+			$reg_status_change_form_array['subsections']['reg_status'] = new EE_Select_Input(
1801
+				$this->_get_reg_statuses(),
1802
+				array(
1803
+					'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1804
+					'default'         => $this->_registration->status_ID(),
1805
+				)
1806
+			);
1807
+			$reg_status_change_form_array['subsections']['send_notifications'] = new EE_Yes_No_Input(
1808
+				array(
1809
+					'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1810
+					'default'         => false,
1811
+					'html_help_text'  => esc_html__(
1812
+						'If set to "Yes", then the related messages will be sent to the registrant.',
1813
+						'event_espresso'
1814
+					)
1815
+				)
1816
+			);
1817
+			$reg_status_change_form_array['subsections']['submit'] = new EE_Submit_Input(
1818
+				array(
1819
+					'html_class'      => 'button-primary',
1820
+					'html_label_text' => '&nbsp;',
1821
+					'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1822
+				)
1823
+			);
1824
+		}
1825
+		return new EE_Form_Section_Proper($reg_status_change_form_array);
1826
+	}
1827
+
1828
+
1829
+	/**
1830
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1831
+	 *
1832
+	 * @return array
1833
+	 * @throws EE_Error
1834
+	 * @throws InvalidArgumentException
1835
+	 * @throws InvalidDataTypeException
1836
+	 * @throws InvalidInterfaceException
1837
+	 * @throws EntityNotFoundException
1838
+	 */
1839
+	protected function _get_reg_statuses()
1840
+	{
1841
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
+		unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1843
+		// get current reg status
1844
+		$current_status = $this->_registration->status_ID();
1845
+		// is registration for free event? This will determine whether to display the pending payment option
1846
+		if ($current_status !== EEM_Registration::status_id_pending_payment
1847
+			&& EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848
+		) {
1849
+			unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1850
+		}
1851
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852
+	}
1853
+
1854
+
1855
+	/**
1856
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1857
+	 *
1858
+	 * @param bool $status REG status given for changing registrations to.
1859
+	 * @param bool $notify Whether to send messages notifications or not.
1860
+	 * @return array (array with reg_id(s) updated and whether update was successful.
1861
+	 * @throws EE_Error
1862
+	 * @throws InvalidArgumentException
1863
+	 * @throws InvalidDataTypeException
1864
+	 * @throws InvalidInterfaceException
1865
+	 * @throws ReflectionException
1866
+	 * @throws RuntimeException
1867
+	 * @throws EntityNotFoundException
1868
+	 */
1869
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1870
+	{
1871
+		if (isset($this->_req_data['reg_status_change_form'])) {
1872
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1873
+				? (array) $this->_req_data['reg_status_change_form']['REG_ID']
1874
+				: array();
1875
+		} else {
1876
+			$REG_IDs = isset($this->_req_data['_REG_ID'])
1877
+				? (array) $this->_req_data['_REG_ID']
1878
+				: array();
1879
+		}
1880
+		// sanitize $REG_IDs
1881
+		$REG_IDs = array_map('absint', $REG_IDs);
1882
+		// and remove empty entries
1883
+		$REG_IDs = array_filter($REG_IDs);
1884
+
1885
+		$result = $this->_set_registration_status($REG_IDs, $status, $notify);
1886
+
1887
+		/**
1888
+		 * Set and filter $_req_data['_REG_ID'] for any potential future messages notifications.
1889
+		 * Currently this value is used downstream by the _process_resend_registration method.
1890
+		 *
1891
+		 * @param int|array                $registration_ids The registration ids that have had their status changed successfully.
1892
+		 * @param bool                     $status           The status registrations were changed to.
1893
+		 * @param bool                     $success          If the status was changed successfully for all registrations.
1894
+		 * @param Registrations_Admin_Page $admin_page_object
1895
+		 */
1896
+		$this->_req_data['_REG_ID'] = apply_filters(
1897
+			'FHEE__Registrations_Admin_Page___set_registration_status_from_request__REG_IDs',
1898
+			$result['REG_ID'],
1899
+			$status,
1900
+			$result['success'],
1901
+			$this
1902
+		);
1903
+
1904
+		// notify?
1905
+		if ($notify
1906
+			&& $result['success']
1907
+			&& ! empty($this->_req_data['_REG_ID'])
1908
+			&& EE_Registry::instance()->CAP->current_user_can(
1909
+				'ee_send_message',
1910
+				'espresso_registrations_resend_registration'
1911
+			)
1912
+		) {
1913
+			$this->_process_resend_registration();
1914
+		}
1915
+		return $result;
1916
+	}
1917
+
1918
+
1919
+	/**
1920
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1921
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1922
+	 *
1923
+	 * @param array  $REG_IDs
1924
+	 * @param string $status
1925
+	 * @param bool   $notify  Used to indicate whether notification was requested or not.  This determines the context
1926
+	 *                        slug sent with setting the registration status.
1927
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1928
+	 * @throws EE_Error
1929
+	 * @throws InvalidArgumentException
1930
+	 * @throws InvalidDataTypeException
1931
+	 * @throws InvalidInterfaceException
1932
+	 * @throws ReflectionException
1933
+	 * @throws RuntimeException
1934
+	 * @throws EntityNotFoundException
1935
+	 */
1936
+	protected function _set_registration_status($REG_IDs = array(), $status = '', $notify = false)
1937
+	{
1938
+		$success = false;
1939
+		// typecast $REG_IDs
1940
+		$REG_IDs = (array) $REG_IDs;
1941
+		if (! empty($REG_IDs)) {
1942
+			$success = true;
1943
+			// set default status if none is passed
1944
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1945
+			$status_context = $notify
1946
+				? Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY
1947
+				: Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN;
1948
+			// loop through REG_ID's and change status
1949
+			foreach ($REG_IDs as $REG_ID) {
1950
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1951
+				if ($registration instanceof EE_Registration) {
1952
+					$registration->set_status(
1953
+						$status,
1954
+						false,
1955
+						new Context(
1956
+							$status_context,
1957
+							esc_html__(
1958
+								'Manually triggered status change on a Registration Admin Page route.',
1959
+								'event_espresso'
1960
+							)
1961
+						)
1962
+					);
1963
+					$result = $registration->save();
1964
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1965
+					$success = $result !== false ? $success : false;
1966
+				}
1967
+			}
1968
+		}
1969
+
1970
+		// return $success and processed registrations
1971
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * Common logic for setting up success message and redirecting to appropriate route
1977
+	 *
1978
+	 * @param  string $STS_ID status id for the registration changed to
1979
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1980
+	 * @return void
1981
+	 * @throws EE_Error
1982
+	 */
1983
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1984
+	{
1985
+		$result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1986
+			: array('success' => false);
1987
+		$success = isset($result['success']) && $result['success'];
1988
+		// setup success message
1989
+		if ($success) {
1990
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1991
+				$msg = sprintf(
1992
+					esc_html__('Registration status has been set to %s', 'event_espresso'),
1993
+					EEH_Template::pretty_status($STS_ID, false, 'lower')
1994
+				);
1995
+			} else {
1996
+				$msg = sprintf(
1997
+					esc_html__('Registrations have been set to %s.', 'event_espresso'),
1998
+					EEH_Template::pretty_status($STS_ID, false, 'lower')
1999
+				);
2000
+			}
2001
+			EE_Error::add_success($msg);
2002
+		} else {
2003
+			EE_Error::add_error(
2004
+				esc_html__(
2005
+					'Something went wrong, and the status was not changed',
2006
+					'event_espresso'
2007
+				),
2008
+				__FILE__,
2009
+				__LINE__,
2010
+				__FUNCTION__
2011
+			);
2012
+		}
2013
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
2014
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
2015
+		} else {
2016
+			$route = array('action' => 'default');
2017
+		}
2018
+		// unset nonces
2019
+		foreach ($this->_req_data as $ref => $value) {
2020
+			if (strpos($ref, 'nonce') !== false) {
2021
+				unset($this->_req_data[ $ref ]);
2022
+				continue;
2023
+			}
2024
+			$value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
2025
+			$this->_req_data[ $ref ] = $value;
2026
+		}
2027
+		// merge request vars so that the reloaded list table contains any existing filter query params
2028
+		$route = array_merge($this->_req_data, $route);
2029
+		$this->_redirect_after_action($success, '', '', $route, true);
2030
+	}
2031
+
2032
+
2033
+	/**
2034
+	 * incoming reg status change from reg details page.
2035
+	 *
2036
+	 * @return void
2037
+	 */
2038
+	protected function _change_reg_status()
2039
+	{
2040
+		$this->_req_data['return'] = 'view_registration';
2041
+		// set notify based on whether the send notifications toggle is set or not
2042
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
2043
+		// $notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
2044
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
2045
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
2046
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
2047
+			case EEM_Registration::status_id_approved:
2048
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'):
2049
+				$this->approve_registration($notify);
2050
+				break;
2051
+			case EEM_Registration::status_id_pending_payment:
2052
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'):
2053
+				$this->pending_registration($notify);
2054
+				break;
2055
+			case EEM_Registration::status_id_not_approved:
2056
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'):
2057
+				$this->not_approve_registration($notify);
2058
+				break;
2059
+			case EEM_Registration::status_id_declined:
2060
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'):
2061
+				$this->decline_registration($notify);
2062
+				break;
2063
+			case EEM_Registration::status_id_cancelled:
2064
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'):
2065
+				$this->cancel_registration($notify);
2066
+				break;
2067
+			case EEM_Registration::status_id_wait_list:
2068
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'):
2069
+				$this->wait_list_registration($notify);
2070
+				break;
2071
+			case EEM_Registration::status_id_incomplete:
2072
+			default:
2073
+				$result['success'] = false;
2074
+				unset($this->_req_data['return']);
2075
+				$this->_reg_status_change_return('', false);
2076
+				break;
2077
+		}
2078
+	}
2079
+
2080
+
2081
+	/**
2082
+	 * Callback for bulk action routes.
2083
+	 * Note: although we could just register the singular route callbacks for each bulk action route as well, this
2084
+	 * method was chosen so there is one central place all the registration status bulk actions are going through.
2085
+	 * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
2086
+	 * when an action is happening on just a single registration).
2087
+	 *
2088
+	 * @param      $action
2089
+	 * @param bool $notify
2090
+	 */
2091
+	protected function bulk_action_on_registrations($action, $notify = false)
2092
+	{
2093
+		do_action(
2094
+			'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
2095
+			$this,
2096
+			$action,
2097
+			$notify
2098
+		);
2099
+		$method = $action . '_registration';
2100
+		if (method_exists($this, $method)) {
2101
+			$this->$method($notify);
2102
+		}
2103
+	}
2104
+
2105
+
2106
+	/**
2107
+	 * approve_registration
2108
+	 *
2109
+	 * @access protected
2110
+	 * @param bool $notify whether or not to notify the registrant about their approval.
2111
+	 * @return void
2112
+	 */
2113
+	protected function approve_registration($notify = false)
2114
+	{
2115
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
2116
+	}
2117
+
2118
+
2119
+	/**
2120
+	 *        decline_registration
2121
+	 *
2122
+	 * @access protected
2123
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2124
+	 * @return void
2125
+	 */
2126
+	protected function decline_registration($notify = false)
2127
+	{
2128
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
2129
+	}
2130
+
2131
+
2132
+	/**
2133
+	 *        cancel_registration
2134
+	 *
2135
+	 * @access protected
2136
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2137
+	 * @return void
2138
+	 */
2139
+	protected function cancel_registration($notify = false)
2140
+	{
2141
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
2142
+	}
2143
+
2144
+
2145
+	/**
2146
+	 *        not_approve_registration
2147
+	 *
2148
+	 * @access protected
2149
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2150
+	 * @return void
2151
+	 */
2152
+	protected function not_approve_registration($notify = false)
2153
+	{
2154
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
2155
+	}
2156
+
2157
+
2158
+	/**
2159
+	 *        decline_registration
2160
+	 *
2161
+	 * @access protected
2162
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2163
+	 * @return void
2164
+	 */
2165
+	protected function pending_registration($notify = false)
2166
+	{
2167
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
2168
+	}
2169
+
2170
+
2171
+	/**
2172
+	 * waitlist_registration
2173
+	 *
2174
+	 * @access protected
2175
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2176
+	 * @return void
2177
+	 */
2178
+	protected function wait_list_registration($notify = false)
2179
+	{
2180
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2181
+	}
2182
+
2183
+
2184
+	/**
2185
+	 *        generates HTML for the Registration main meta box
2186
+	 *
2187
+	 * @access public
2188
+	 * @return void
2189
+	 * @throws DomainException
2190
+	 * @throws EE_Error
2191
+	 * @throws InvalidArgumentException
2192
+	 * @throws InvalidDataTypeException
2193
+	 * @throws InvalidInterfaceException
2194
+	 * @throws ReflectionException
2195
+	 * @throws EntityNotFoundException
2196
+	 */
2197
+	public function _reg_details_meta_box()
2198
+	{
2199
+		EEH_Autoloader::register_line_item_display_autoloaders();
2200
+		EEH_Autoloader::register_line_item_filter_autoloaders();
2201
+		EE_Registry::instance()->load_helper('Line_Item');
2202
+		$transaction = $this->_registration->transaction() ? $this->_registration->transaction()
2203
+			: EE_Transaction::new_instance();
2204
+		$this->_session = $transaction->session_data();
2205
+		$filters = new EE_Line_Item_Filter_Collection();
2206
+		// $filters->add( new EE_Non_Zero_Line_Item_Filter() );
2207
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2208
+		$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
2209
+			$filters,
2210
+			$transaction->total_line_item()
2211
+		);
2212
+		$filtered_line_item_tree = $line_item_filter_processor->process();
2213
+		$line_item_display = new EE_Line_Item_Display(
2214
+			'reg_admin_table',
2215
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy'
2216
+		);
2217
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2218
+			$filtered_line_item_tree,
2219
+			array('EE_Registration' => $this->_registration)
2220
+		);
2221
+		$attendee = $this->_registration->attendee();
2222
+		if (EE_Registry::instance()->CAP->current_user_can(
2223
+			'ee_read_transaction',
2224
+			'espresso_transactions_view_transaction'
2225
+		)) {
2226
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2227
+				EE_Admin_Page::add_query_args_and_nonce(
2228
+					array(
2229
+						'action' => 'view_transaction',
2230
+						'TXN_ID' => $transaction->ID(),
2231
+					),
2232
+					TXN_ADMIN_URL
2233
+				),
2234
+				esc_html__(' View Transaction', 'event_espresso'),
2235
+				'button secondary-button right',
2236
+				'dashicons dashicons-cart'
2237
+			);
2238
+		} else {
2239
+			$this->_template_args['view_transaction_button'] = '';
2240
+		}
2241
+		if ($attendee instanceof EE_Attendee
2242
+			&& EE_Registry::instance()->CAP->current_user_can(
2243
+				'ee_send_message',
2244
+				'espresso_registrations_resend_registration'
2245
+			)
2246
+		) {
2247
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2248
+				EE_Admin_Page::add_query_args_and_nonce(
2249
+					array(
2250
+						'action'      => 'resend_registration',
2251
+						'_REG_ID'     => $this->_registration->ID(),
2252
+						'redirect_to' => 'view_registration',
2253
+					),
2254
+					REG_ADMIN_URL
2255
+				),
2256
+				esc_html__(' Resend Registration', 'event_espresso'),
2257
+				'button secondary-button right',
2258
+				'dashicons dashicons-email-alt'
2259
+			);
2260
+		} else {
2261
+			$this->_template_args['resend_registration_button'] = '';
2262
+		}
2263
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2264
+		$payment = $transaction->get_first_related('Payment');
2265
+		$payment = ! $payment instanceof EE_Payment
2266
+			? EE_Payment::new_instance()
2267
+			: $payment;
2268
+		$payment_method = $payment->get_first_related('Payment_Method');
2269
+		$payment_method = ! $payment_method instanceof EE_Payment_Method
2270
+			? EE_Payment_Method::new_instance()
2271
+			: $payment_method;
2272
+		$reg_details = array(
2273
+			'payment_method'       => $payment_method->name(),
2274
+			'response_msg'         => $payment->gateway_response(),
2275
+			'registration_id'      => $this->_registration->get('REG_code'),
2276
+			'registration_session' => $this->_registration->session_ID(),
2277
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2278
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2279
+		);
2280
+		if (isset($reg_details['registration_id'])) {
2281
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2282
+			$this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2283
+				'Registration ID',
2284
+				'event_espresso'
2285
+			);
2286
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2287
+		}
2288
+		if (isset($reg_details['payment_method'])) {
2289
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2290
+			$this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2291
+				'Most Recent Payment Method',
2292
+				'event_espresso'
2293
+			);
2294
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2295
+			$this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
2296
+			$this->_template_args['reg_details']['response_msg']['label'] = esc_html__(
2297
+				'Payment method response',
2298
+				'event_espresso'
2299
+			);
2300
+			$this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
2301
+		}
2302
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2303
+		$this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2304
+			'Registration Session',
2305
+			'event_espresso'
2306
+		);
2307
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2308
+		$this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
2309
+		$this->_template_args['reg_details']['ip_address']['label'] = esc_html__(
2310
+			'Registration placed from IP',
2311
+			'event_espresso'
2312
+		);
2313
+		$this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
2314
+		$this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
2315
+		$this->_template_args['reg_details']['user_agent']['label'] = esc_html__(
2316
+			'Registrant User Agent',
2317
+			'event_espresso'
2318
+		);
2319
+		$this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
2320
+		$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
2321
+			array(
2322
+				'action'   => 'default',
2323
+				'event_id' => $this->_registration->event_ID(),
2324
+			),
2325
+			REG_ADMIN_URL
2326
+		);
2327
+		$this->_template_args['REG_ID'] = $this->_registration->ID();
2328
+		$this->_template_args['event_id'] = $this->_registration->event_ID();
2329
+		$template_path =
2330
+			REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2331
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2332
+	}
2333
+
2334
+
2335
+	/**
2336
+	 * generates HTML for the Registration Questions meta box.
2337
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2338
+	 * otherwise uses new forms system
2339
+	 *
2340
+	 * @access public
2341
+	 * @return void
2342
+	 * @throws DomainException
2343
+	 * @throws EE_Error
2344
+	 */
2345
+	public function _reg_questions_meta_box()
2346
+	{
2347
+		// allow someone to override this method entirely
2348
+		if (apply_filters(
2349
+			'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default',
2350
+			true,
2351
+			$this,
2352
+			$this->_registration
2353
+		)) {
2354
+			$form = $this->_get_reg_custom_questions_form(
2355
+				$this->_registration->ID()
2356
+			);
2357
+			$this->_template_args['att_questions'] = count($form->subforms()) > 0
2358
+				? $form->get_html_and_js()
2359
+				: '';
2360
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
2361
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
2362
+			$template_path =
2363
+				REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2364
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
2365
+		}
2366
+	}
2367
+
2368
+
2369
+	/**
2370
+	 * form_before_question_group
2371
+	 *
2372
+	 * @deprecated    as of 4.8.32.rc.000
2373
+	 * @access        public
2374
+	 * @param        string $output
2375
+	 * @return        string
2376
+	 */
2377
+	public function form_before_question_group($output)
2378
+	{
2379
+		EE_Error::doing_it_wrong(
2380
+			__CLASS__ . '::' . __FUNCTION__,
2381
+			esc_html__(
2382
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2383
+				'event_espresso'
2384
+			),
2385
+			'4.8.32.rc.000'
2386
+		);
2387
+		return '
2388 2388
 	<table class="form-table ee-width-100">
2389 2389
 		<tbody>
2390 2390
 			';
2391
-    }
2392
-
2393
-
2394
-    /**
2395
-     * form_after_question_group
2396
-     *
2397
-     * @deprecated    as of 4.8.32.rc.000
2398
-     * @access        public
2399
-     * @param        string $output
2400
-     * @return        string
2401
-     */
2402
-    public function form_after_question_group($output)
2403
-    {
2404
-        EE_Error::doing_it_wrong(
2405
-            __CLASS__ . '::' . __FUNCTION__,
2406
-            esc_html__(
2407
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2408
-                'event_espresso'
2409
-            ),
2410
-            '4.8.32.rc.000'
2411
-        );
2412
-        return '
2391
+	}
2392
+
2393
+
2394
+	/**
2395
+	 * form_after_question_group
2396
+	 *
2397
+	 * @deprecated    as of 4.8.32.rc.000
2398
+	 * @access        public
2399
+	 * @param        string $output
2400
+	 * @return        string
2401
+	 */
2402
+	public function form_after_question_group($output)
2403
+	{
2404
+		EE_Error::doing_it_wrong(
2405
+			__CLASS__ . '::' . __FUNCTION__,
2406
+			esc_html__(
2407
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2408
+				'event_espresso'
2409
+			),
2410
+			'4.8.32.rc.000'
2411
+		);
2412
+		return '
2413 2413
 			<tr class="hide-if-no-js">
2414 2414
 				<th> </th>
2415 2415
 				<td class="reg-admin-edit-attendee-question-td">
2416 2416
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
2417
-               . esc_attr__('click to edit question', 'event_espresso')
2418
-               . '">
2417
+			   . esc_attr__('click to edit question', 'event_espresso')
2418
+			   . '">
2419 2419
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
2420
-               . esc_html__('edit the above question group', 'event_espresso')
2421
-               . '</span>
2420
+			   . esc_html__('edit the above question group', 'event_espresso')
2421
+			   . '</span>
2422 2422
 						<div class="dashicons dashicons-edit"></div>
2423 2423
 					</a>
2424 2424
 				</td>
@@ -2426,606 +2426,606 @@  discard block
 block discarded – undo
2426 2426
 		</tbody>
2427 2427
 	</table>
2428 2428
 ';
2429
-    }
2430
-
2431
-
2432
-    /**
2433
-     * form_form_field_label_wrap
2434
-     *
2435
-     * @deprecated    as of 4.8.32.rc.000
2436
-     * @access        public
2437
-     * @param        string $label
2438
-     * @return        string
2439
-     */
2440
-    public function form_form_field_label_wrap($label)
2441
-    {
2442
-        EE_Error::doing_it_wrong(
2443
-            __CLASS__ . '::' . __FUNCTION__,
2444
-            esc_html__(
2445
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2446
-                'event_espresso'
2447
-            ),
2448
-            '4.8.32.rc.000'
2449
-        );
2450
-        return '
2429
+	}
2430
+
2431
+
2432
+	/**
2433
+	 * form_form_field_label_wrap
2434
+	 *
2435
+	 * @deprecated    as of 4.8.32.rc.000
2436
+	 * @access        public
2437
+	 * @param        string $label
2438
+	 * @return        string
2439
+	 */
2440
+	public function form_form_field_label_wrap($label)
2441
+	{
2442
+		EE_Error::doing_it_wrong(
2443
+			__CLASS__ . '::' . __FUNCTION__,
2444
+			esc_html__(
2445
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2446
+				'event_espresso'
2447
+			),
2448
+			'4.8.32.rc.000'
2449
+		);
2450
+		return '
2451 2451
 			<tr>
2452 2452
 				<th>
2453 2453
 					' . $label . '
2454 2454
 				</th>';
2455
-    }
2456
-
2457
-
2458
-    /**
2459
-     * form_form_field_input__wrap
2460
-     *
2461
-     * @deprecated    as of 4.8.32.rc.000
2462
-     * @access        public
2463
-     * @param        string $input
2464
-     * @return        string
2465
-     */
2466
-    public function form_form_field_input__wrap($input)
2467
-    {
2468
-        EE_Error::doing_it_wrong(
2469
-            __CLASS__ . '::' . __FUNCTION__,
2470
-            esc_html__(
2471
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2472
-                'event_espresso'
2473
-            ),
2474
-            '4.8.32.rc.000'
2475
-        );
2476
-        return '
2455
+	}
2456
+
2457
+
2458
+	/**
2459
+	 * form_form_field_input__wrap
2460
+	 *
2461
+	 * @deprecated    as of 4.8.32.rc.000
2462
+	 * @access        public
2463
+	 * @param        string $input
2464
+	 * @return        string
2465
+	 */
2466
+	public function form_form_field_input__wrap($input)
2467
+	{
2468
+		EE_Error::doing_it_wrong(
2469
+			__CLASS__ . '::' . __FUNCTION__,
2470
+			esc_html__(
2471
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2472
+				'event_espresso'
2473
+			),
2474
+			'4.8.32.rc.000'
2475
+		);
2476
+		return '
2477 2477
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
2478 2478
 					' . $input . '
2479 2479
 				</td>
2480 2480
 			</tr>';
2481
-    }
2482
-
2483
-
2484
-    /**
2485
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
2486
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
2487
-     * to display the page
2488
-     *
2489
-     * @access protected
2490
-     * @return void
2491
-     * @throws EE_Error
2492
-     */
2493
-    protected function _update_attendee_registration_form()
2494
-    {
2495
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2496
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2497
-            $REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2498
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
2499
-            if ($success) {
2500
-                $what = esc_html__('Registration Form', 'event_espresso');
2501
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2502
-                    : array('action' => 'default');
2503
-                $this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2504
-            }
2505
-        }
2506
-    }
2507
-
2508
-
2509
-    /**
2510
-     * Gets the form for saving registrations custom questions (if done
2511
-     * previously retrieves the cached form object, which may have validation errors in it)
2512
-     *
2513
-     * @param int $REG_ID
2514
-     * @return EE_Registration_Custom_Questions_Form
2515
-     * @throws EE_Error
2516
-     * @throws InvalidArgumentException
2517
-     * @throws InvalidDataTypeException
2518
-     * @throws InvalidInterfaceException
2519
-     */
2520
-    protected function _get_reg_custom_questions_form($REG_ID)
2521
-    {
2522
-        if (! $this->_reg_custom_questions_form) {
2523
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2524
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2525
-                EEM_Registration::instance()->get_one_by_ID($REG_ID)
2526
-            );
2527
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
2528
-        }
2529
-        return $this->_reg_custom_questions_form;
2530
-    }
2531
-
2532
-
2533
-    /**
2534
-     * Saves
2535
-     *
2536
-     * @access private
2537
-     * @param bool $REG_ID
2538
-     * @return bool
2539
-     * @throws EE_Error
2540
-     * @throws InvalidArgumentException
2541
-     * @throws InvalidDataTypeException
2542
-     * @throws InvalidInterfaceException
2543
-     */
2544
-    private function _save_reg_custom_questions_form($REG_ID = false)
2545
-    {
2546
-        if (! $REG_ID) {
2547
-            EE_Error::add_error(
2548
-                esc_html__(
2549
-                    'An error occurred. No registration ID was received.',
2550
-                    'event_espresso'
2551
-                ),
2552
-                __FILE__,
2553
-                __FUNCTION__,
2554
-                __LINE__
2555
-            );
2556
-        }
2557
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
2558
-        $form->receive_form_submission($this->_req_data);
2559
-        $success = false;
2560
-        if ($form->is_valid()) {
2561
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
2562
-                foreach ($question_group_form->inputs() as $question_id => $input) {
2563
-                    $where_conditions = array(
2564
-                        'QST_ID' => $question_id,
2565
-                        'REG_ID' => $REG_ID,
2566
-                    );
2567
-                    $possibly_new_values = array(
2568
-                        'ANS_value' => $input->normalized_value(),
2569
-                    );
2570
-                    $answer = EEM_Answer::instance()->get_one(array($where_conditions));
2571
-                    if ($answer instanceof EE_Answer) {
2572
-                        $success = $answer->save($possibly_new_values);
2573
-                    } else {
2574
-                        // insert it then
2575
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2576
-                        $answer = EE_Answer::new_instance($cols_n_vals);
2577
-                        $success = $answer->save();
2578
-                    }
2579
-                }
2580
-            }
2581
-        } else {
2582
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2583
-        }
2584
-        return $success;
2585
-    }
2586
-
2587
-
2588
-    /**
2589
-     *        generates HTML for the Registration main meta box
2590
-     *
2591
-     * @access public
2592
-     * @return void
2593
-     * @throws DomainException
2594
-     * @throws EE_Error
2595
-     * @throws InvalidArgumentException
2596
-     * @throws InvalidDataTypeException
2597
-     * @throws InvalidInterfaceException
2598
-     */
2599
-    public function _reg_attendees_meta_box()
2600
-    {
2601
-        $REG = EEM_Registration::instance();
2602
-        // get all other registrations on this transaction, and cache
2603
-        // the attendees for them so we don't have to run another query using force_join
2604
-        $registrations = $REG->get_all(
2605
-            array(
2606
-                array(
2607
-                    'TXN_ID' => $this->_registration->transaction_ID(),
2608
-                    'REG_ID' => array('!=', $this->_registration->ID()),
2609
-                ),
2610
-                'force_join' => array('Attendee'),
2611
-            )
2612
-        );
2613
-        $this->_template_args['attendees'] = array();
2614
-        $this->_template_args['attendee_notice'] = '';
2615
-        if (empty($registrations)
2616
-            || (is_array($registrations)
2617
-                && ! EEH_Array::get_one_item_from_array($registrations))
2618
-        ) {
2619
-            EE_Error::add_error(
2620
-                esc_html__(
2621
-                    'There are no records attached to this registration. Something may have gone wrong with the registration',
2622
-                    'event_espresso'
2623
-                ),
2624
-                __FILE__,
2625
-                __FUNCTION__,
2626
-                __LINE__
2627
-            );
2628
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
2629
-        } else {
2630
-            $att_nmbr = 1;
2631
-            foreach ($registrations as $registration) {
2632
-                /* @var $registration EE_Registration */
2633
-                $attendee = $registration->attendee()
2634
-                    ? $registration->attendee()
2635
-                    : EEM_Attendee::instance()
2636
-                                  ->create_default_object();
2637
-                $this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2638
-                $this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2639
-                $this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2640
-                $this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2641
-                $this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2642
-                $this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2643
-                    ', ',
2644
-                    $attendee->full_address_as_array()
2645
-                );
2646
-                $this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2647
-                    array(
2648
-                        'action' => 'edit_attendee',
2649
-                        'post'   => $attendee->ID(),
2650
-                    ),
2651
-                    REG_ADMIN_URL
2652
-                );
2653
-                $this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj()->name();
2654
-                $att_nmbr++;
2655
-            }
2656
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2657
-        }
2658
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2659
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2660
-    }
2661
-
2662
-
2663
-    /**
2664
-     *        generates HTML for the Edit Registration side meta box
2665
-     *
2666
-     * @access public
2667
-     * @return void
2668
-     * @throws DomainException
2669
-     * @throws EE_Error
2670
-     * @throws InvalidArgumentException
2671
-     * @throws InvalidDataTypeException
2672
-     * @throws InvalidInterfaceException
2673
-     */
2674
-    public function _reg_registrant_side_meta_box()
2675
-    {
2676
-        /*@var $attendee EE_Attendee */
2677
-        $att_check = $this->_registration->attendee();
2678
-        $attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2679
-        // now let's determine if this is not the primary registration.  If it isn't then we set the
2680
-        // primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2681
-        // primary registration object (that way we know if we need to show create button or not)
2682
-        if (! $this->_registration->is_primary_registrant()) {
2683
-            $primary_registration = $this->_registration->get_primary_registration();
2684
-            $primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2685
-                : null;
2686
-            if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2687
-                // in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2688
-                // custom attendee object so let's not worry about the primary reg.
2689
-                $primary_registration = null;
2690
-            }
2691
-        } else {
2692
-            $primary_registration = null;
2693
-        }
2694
-        $this->_template_args['ATT_ID'] = $attendee->ID();
2695
-        $this->_template_args['fname'] = $attendee->fname();
2696
-        $this->_template_args['lname'] = $attendee->lname();
2697
-        $this->_template_args['email'] = $attendee->email();
2698
-        $this->_template_args['phone'] = $attendee->phone();
2699
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2700
-        // edit link
2701
-        $this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(
2702
-            array(
2703
-                'action' => 'edit_attendee',
2704
-                'post'   => $attendee->ID(),
2705
-            ),
2706
-            REG_ADMIN_URL
2707
-        );
2708
-        $this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2709
-        // create link
2710
-        $this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2711
-            ? EE_Admin_Page::add_query_args_and_nonce(
2712
-                array(
2713
-                    'action'  => 'duplicate_attendee',
2714
-                    '_REG_ID' => $this->_registration->ID(),
2715
-                ),
2716
-                REG_ADMIN_URL
2717
-            ) : '';
2718
-        $this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2719
-        $this->_template_args['att_check'] = $att_check;
2720
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2721
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2722
-    }
2723
-
2724
-
2725
-    /**
2726
-     * trash or restore registrations
2727
-     *
2728
-     * @param  boolean $trash whether to archive or restore
2729
-     * @return void
2730
-     * @throws EE_Error
2731
-     * @throws InvalidArgumentException
2732
-     * @throws InvalidDataTypeException
2733
-     * @throws InvalidInterfaceException
2734
-     * @throws RuntimeException
2735
-     * @access protected
2736
-     */
2737
-    protected function _trash_or_restore_registrations($trash = true)
2738
-    {
2739
-        // if empty _REG_ID then get out because there's nothing to do
2740
-        if (empty($this->_req_data['_REG_ID'])) {
2741
-            EE_Error::add_error(
2742
-                sprintf(
2743
-                    esc_html__(
2744
-                        'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2745
-                        'event_espresso'
2746
-                    ),
2747
-                    $trash ? 'trash' : 'restore'
2748
-                ),
2749
-                __FILE__,
2750
-                __LINE__,
2751
-                __FUNCTION__
2752
-            );
2753
-            $this->_redirect_after_action(false, '', '', array(), true);
2754
-        }
2755
-        $success = 0;
2756
-        $overwrite_msgs = false;
2757
-        // Checkboxes
2758
-        if (! is_array($this->_req_data['_REG_ID'])) {
2759
-            $this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2760
-        }
2761
-        $reg_count = count($this->_req_data['_REG_ID']);
2762
-        // cycle thru checkboxes
2763
-        foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2764
-            /** @var EE_Registration $REG */
2765
-            $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2766
-            $payments = $REG->registration_payments();
2767
-            if (! empty($payments)) {
2768
-                $name = $REG->attendee() instanceof EE_Attendee
2769
-                    ? $REG->attendee()->full_name()
2770
-                    : esc_html__('Unknown Attendee', 'event_espresso');
2771
-                $overwrite_msgs = true;
2772
-                EE_Error::add_error(
2773
-                    sprintf(
2774
-                        esc_html__(
2775
-                            'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2776
-                            'event_espresso'
2777
-                        ),
2778
-                        $name
2779
-                    ),
2780
-                    __FILE__,
2781
-                    __FUNCTION__,
2782
-                    __LINE__
2783
-                );
2784
-                // can't trash this registration because it has payments.
2785
-                continue;
2786
-            }
2787
-            $updated = $trash ? $REG->delete() : $REG->restore();
2788
-            if ($updated) {
2789
-                $success++;
2790
-            }
2791
-        }
2792
-        $this->_redirect_after_action(
2793
-            $success === $reg_count, // were ALL registrations affected?
2794
-            $success > 1
2795
-                ? esc_html__('Registrations', 'event_espresso')
2796
-                : esc_html__('Registration', 'event_espresso'),
2797
-            $trash
2798
-                ? esc_html__('moved to the trash', 'event_espresso')
2799
-                : esc_html__('restored', 'event_espresso'),
2800
-            array('action' => 'default'),
2801
-            $overwrite_msgs
2802
-        );
2803
-    }
2804
-
2805
-
2806
-    /**
2807
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2808
-     * registration but also.
2809
-     * 1. Removing relations to EE_Attendee
2810
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2811
-     * ALSO trashed.
2812
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2813
-     * 4. Removing relationships between all tickets and the related registrations
2814
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2815
-     * 6. Deleting permanently any related Checkins.
2816
-     *
2817
-     * @return void
2818
-     * @throws EE_Error
2819
-     * @throws InvalidArgumentException
2820
-     * @throws InvalidDataTypeException
2821
-     * @throws InvalidInterfaceException
2822
-     */
2823
-    protected function _delete_registrations()
2824
-    {
2825
-        $REG_MDL = EEM_Registration::instance();
2826
-        $success = 1;
2827
-        // Checkboxes
2828
-        if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2829
-            // if array has more than one element than success message should be plural
2830
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2831
-            // cycle thru checkboxes
2832
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2833
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2834
-                if (! $REG instanceof EE_Registration) {
2835
-                    continue;
2836
-                }
2837
-                $deleted = $this->_delete_registration($REG);
2838
-                if (! $deleted) {
2839
-                    $success = 0;
2840
-                }
2841
-            }
2842
-        } else {
2843
-            // grab single id and delete
2844
-            $REG_ID = $this->_req_data['_REG_ID'];
2845
-            $REG = $REG_MDL->get_one_by_ID($REG_ID);
2846
-            $deleted = $this->_delete_registration($REG);
2847
-            if (! $deleted) {
2848
-                $success = 0;
2849
-            }
2850
-        }
2851
-        $what = $success > 1
2852
-            ? esc_html__('Registrations', 'event_espresso')
2853
-            : esc_html__('Registration', 'event_espresso');
2854
-        $action_desc = esc_html__('permanently deleted.', 'event_espresso');
2855
-        $this->_redirect_after_action(
2856
-            $success,
2857
-            $what,
2858
-            $action_desc,
2859
-            array('action' => 'default'),
2860
-            true
2861
-        );
2862
-    }
2863
-
2864
-
2865
-    /**
2866
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2867
-     * models get affected.
2868
-     *
2869
-     * @param  EE_Registration $REG registration to be deleted permenantly
2870
-     * @return bool true = successful deletion, false = fail.
2871
-     * @throws EE_Error
2872
-     */
2873
-    protected function _delete_registration(EE_Registration $REG)
2874
-    {
2875
-        // first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2876
-        // registrations on the transaction that are NOT trashed.
2877
-        $TXN = $REG->get_first_related('Transaction');
2878
-        $REGS = $TXN->get_many_related('Registration');
2879
-        $all_trashed = true;
2880
-        foreach ($REGS as $registration) {
2881
-            if (! $registration->get('REG_deleted')) {
2882
-                $all_trashed = false;
2883
-            }
2884
-        }
2885
-        if (! $all_trashed) {
2886
-            EE_Error::add_error(
2887
-                esc_html__(
2888
-                    'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2889
-                    'event_espresso'
2890
-                ),
2891
-                __FILE__,
2892
-                __FUNCTION__,
2893
-                __LINE__
2894
-            );
2895
-            return false;
2896
-        }
2897
-        // k made it here so that means we can delete all the related transactions and their answers (but let's do them
2898
-        // separately from THIS one).
2899
-        foreach ($REGS as $registration) {
2900
-            // delete related answers
2901
-            $registration->delete_related_permanently('Answer');
2902
-            // remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2903
-            $attendee = $registration->get_first_related('Attendee');
2904
-            if ($attendee instanceof EE_Attendee) {
2905
-                $registration->_remove_relation_to($attendee, 'Attendee');
2906
-            }
2907
-            // now remove relationships to tickets on this registration.
2908
-            $registration->_remove_relations('Ticket');
2909
-            // now delete permanently the checkins related to this registration.
2910
-            $registration->delete_related_permanently('Checkin');
2911
-            if ($registration->ID() === $REG->ID()) {
2912
-                continue;
2913
-            } //we don't want to delete permanently the existing registration just yet.
2914
-            // remove relation to transaction for these registrations if NOT the existing registrations
2915
-            $registration->_remove_relations('Transaction');
2916
-            // delete permanently any related messages.
2917
-            $registration->delete_related_permanently('Message');
2918
-            // now delete this registration permanently
2919
-            $registration->delete_permanently();
2920
-        }
2921
-        // now all related registrations on the transaction are handled.  So let's just handle this registration itself
2922
-        // (the transaction and line items should be all that's left).
2923
-        // delete the line items related to the transaction for this registration.
2924
-        $TXN->delete_related_permanently('Line_Item');
2925
-        // we need to remove all the relationships on the transaction
2926
-        $TXN->delete_related_permanently('Payment');
2927
-        $TXN->delete_related_permanently('Extra_Meta');
2928
-        $TXN->delete_related_permanently('Message');
2929
-        // now we can delete this REG permanently (and the transaction of course)
2930
-        $REG->delete_related_permanently('Transaction');
2931
-        return $REG->delete_permanently();
2932
-    }
2933
-
2934
-
2935
-    /**
2936
-     *    generates HTML for the Register New Attendee Admin page
2937
-     *
2938
-     * @access private
2939
-     * @throws DomainException
2940
-     * @throws EE_Error
2941
-     */
2942
-    public function new_registration()
2943
-    {
2944
-        if (! $this->_set_reg_event()) {
2945
-            throw new EE_Error(
2946
-                esc_html__(
2947
-                    'Unable to continue with registering because there is no Event ID in the request',
2948
-                    'event_espresso'
2949
-                )
2950
-            );
2951
-        }
2952
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2953
-        // gotta start with a clean slate if we're not coming here via ajax
2954
-        if (! defined('DOING_AJAX')
2955
-            && (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2956
-        ) {
2957
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2958
-        }
2959
-        $this->_template_args['event_name'] = '';
2960
-        // event name
2961
-        if ($this->_reg_event) {
2962
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2963
-            $edit_event_url = self::add_query_args_and_nonce(
2964
-                array(
2965
-                    'action' => 'edit',
2966
-                    'post'   => $this->_reg_event->ID(),
2967
-                ),
2968
-                EVENTS_ADMIN_URL
2969
-            );
2970
-            $edit_event_lnk = '<a href="'
2971
-                              . $edit_event_url
2972
-                              . '" title="'
2973
-                              . esc_attr__('Edit ', 'event_espresso')
2974
-                              . $this->_reg_event->name()
2975
-                              . '">'
2976
-                              . esc_html__('Edit Event', 'event_espresso')
2977
-                              . '</a>';
2978
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2979
-                                                   . $edit_event_lnk
2980
-                                                   . '</span>';
2981
-        }
2982
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2983
-        if (defined('DOING_AJAX')) {
2984
-            $this->_return_json();
2985
-        }
2986
-        // grab header
2987
-        $template_path =
2988
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2989
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2990
-            $template_path,
2991
-            $this->_template_args,
2992
-            true
2993
-        );
2994
-        // $this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2995
-        // the details template wrapper
2996
-        $this->display_admin_page_with_sidebar();
2997
-    }
2998
-
2999
-
3000
-    /**
3001
-     * This returns the content for a registration step
3002
-     *
3003
-     * @access protected
3004
-     * @return string html
3005
-     * @throws DomainException
3006
-     * @throws EE_Error
3007
-     * @throws InvalidArgumentException
3008
-     * @throws InvalidDataTypeException
3009
-     * @throws InvalidInterfaceException
3010
-     */
3011
-    protected function _get_registration_step_content()
3012
-    {
3013
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
3014
-            $warning_msg = sprintf(
3015
-                esc_html__(
3016
-                    '%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
3017
-                    'event_espresso'
3018
-                ),
3019
-                '<br />',
3020
-                '<h3 class="important-notice">',
3021
-                '</h3>',
3022
-                '<div class="float-right">',
3023
-                '<span id="redirect_timer" class="important-notice">30</span>',
3024
-                '</div>',
3025
-                '<b>',
3026
-                '</b>'
3027
-            );
3028
-            return '
2481
+	}
2482
+
2483
+
2484
+	/**
2485
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
2486
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
2487
+	 * to display the page
2488
+	 *
2489
+	 * @access protected
2490
+	 * @return void
2491
+	 * @throws EE_Error
2492
+	 */
2493
+	protected function _update_attendee_registration_form()
2494
+	{
2495
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2496
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2497
+			$REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2498
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
2499
+			if ($success) {
2500
+				$what = esc_html__('Registration Form', 'event_espresso');
2501
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2502
+					: array('action' => 'default');
2503
+				$this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2504
+			}
2505
+		}
2506
+	}
2507
+
2508
+
2509
+	/**
2510
+	 * Gets the form for saving registrations custom questions (if done
2511
+	 * previously retrieves the cached form object, which may have validation errors in it)
2512
+	 *
2513
+	 * @param int $REG_ID
2514
+	 * @return EE_Registration_Custom_Questions_Form
2515
+	 * @throws EE_Error
2516
+	 * @throws InvalidArgumentException
2517
+	 * @throws InvalidDataTypeException
2518
+	 * @throws InvalidInterfaceException
2519
+	 */
2520
+	protected function _get_reg_custom_questions_form($REG_ID)
2521
+	{
2522
+		if (! $this->_reg_custom_questions_form) {
2523
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2524
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2525
+				EEM_Registration::instance()->get_one_by_ID($REG_ID)
2526
+			);
2527
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
2528
+		}
2529
+		return $this->_reg_custom_questions_form;
2530
+	}
2531
+
2532
+
2533
+	/**
2534
+	 * Saves
2535
+	 *
2536
+	 * @access private
2537
+	 * @param bool $REG_ID
2538
+	 * @return bool
2539
+	 * @throws EE_Error
2540
+	 * @throws InvalidArgumentException
2541
+	 * @throws InvalidDataTypeException
2542
+	 * @throws InvalidInterfaceException
2543
+	 */
2544
+	private function _save_reg_custom_questions_form($REG_ID = false)
2545
+	{
2546
+		if (! $REG_ID) {
2547
+			EE_Error::add_error(
2548
+				esc_html__(
2549
+					'An error occurred. No registration ID was received.',
2550
+					'event_espresso'
2551
+				),
2552
+				__FILE__,
2553
+				__FUNCTION__,
2554
+				__LINE__
2555
+			);
2556
+		}
2557
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
2558
+		$form->receive_form_submission($this->_req_data);
2559
+		$success = false;
2560
+		if ($form->is_valid()) {
2561
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
2562
+				foreach ($question_group_form->inputs() as $question_id => $input) {
2563
+					$where_conditions = array(
2564
+						'QST_ID' => $question_id,
2565
+						'REG_ID' => $REG_ID,
2566
+					);
2567
+					$possibly_new_values = array(
2568
+						'ANS_value' => $input->normalized_value(),
2569
+					);
2570
+					$answer = EEM_Answer::instance()->get_one(array($where_conditions));
2571
+					if ($answer instanceof EE_Answer) {
2572
+						$success = $answer->save($possibly_new_values);
2573
+					} else {
2574
+						// insert it then
2575
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2576
+						$answer = EE_Answer::new_instance($cols_n_vals);
2577
+						$success = $answer->save();
2578
+					}
2579
+				}
2580
+			}
2581
+		} else {
2582
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2583
+		}
2584
+		return $success;
2585
+	}
2586
+
2587
+
2588
+	/**
2589
+	 *        generates HTML for the Registration main meta box
2590
+	 *
2591
+	 * @access public
2592
+	 * @return void
2593
+	 * @throws DomainException
2594
+	 * @throws EE_Error
2595
+	 * @throws InvalidArgumentException
2596
+	 * @throws InvalidDataTypeException
2597
+	 * @throws InvalidInterfaceException
2598
+	 */
2599
+	public function _reg_attendees_meta_box()
2600
+	{
2601
+		$REG = EEM_Registration::instance();
2602
+		// get all other registrations on this transaction, and cache
2603
+		// the attendees for them so we don't have to run another query using force_join
2604
+		$registrations = $REG->get_all(
2605
+			array(
2606
+				array(
2607
+					'TXN_ID' => $this->_registration->transaction_ID(),
2608
+					'REG_ID' => array('!=', $this->_registration->ID()),
2609
+				),
2610
+				'force_join' => array('Attendee'),
2611
+			)
2612
+		);
2613
+		$this->_template_args['attendees'] = array();
2614
+		$this->_template_args['attendee_notice'] = '';
2615
+		if (empty($registrations)
2616
+			|| (is_array($registrations)
2617
+				&& ! EEH_Array::get_one_item_from_array($registrations))
2618
+		) {
2619
+			EE_Error::add_error(
2620
+				esc_html__(
2621
+					'There are no records attached to this registration. Something may have gone wrong with the registration',
2622
+					'event_espresso'
2623
+				),
2624
+				__FILE__,
2625
+				__FUNCTION__,
2626
+				__LINE__
2627
+			);
2628
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
2629
+		} else {
2630
+			$att_nmbr = 1;
2631
+			foreach ($registrations as $registration) {
2632
+				/* @var $registration EE_Registration */
2633
+				$attendee = $registration->attendee()
2634
+					? $registration->attendee()
2635
+					: EEM_Attendee::instance()
2636
+								  ->create_default_object();
2637
+				$this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2638
+				$this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2639
+				$this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2640
+				$this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2641
+				$this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2642
+				$this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2643
+					', ',
2644
+					$attendee->full_address_as_array()
2645
+				);
2646
+				$this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2647
+					array(
2648
+						'action' => 'edit_attendee',
2649
+						'post'   => $attendee->ID(),
2650
+					),
2651
+					REG_ADMIN_URL
2652
+				);
2653
+				$this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj()->name();
2654
+				$att_nmbr++;
2655
+			}
2656
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2657
+		}
2658
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2659
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2660
+	}
2661
+
2662
+
2663
+	/**
2664
+	 *        generates HTML for the Edit Registration side meta box
2665
+	 *
2666
+	 * @access public
2667
+	 * @return void
2668
+	 * @throws DomainException
2669
+	 * @throws EE_Error
2670
+	 * @throws InvalidArgumentException
2671
+	 * @throws InvalidDataTypeException
2672
+	 * @throws InvalidInterfaceException
2673
+	 */
2674
+	public function _reg_registrant_side_meta_box()
2675
+	{
2676
+		/*@var $attendee EE_Attendee */
2677
+		$att_check = $this->_registration->attendee();
2678
+		$attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2679
+		// now let's determine if this is not the primary registration.  If it isn't then we set the
2680
+		// primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2681
+		// primary registration object (that way we know if we need to show create button or not)
2682
+		if (! $this->_registration->is_primary_registrant()) {
2683
+			$primary_registration = $this->_registration->get_primary_registration();
2684
+			$primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2685
+				: null;
2686
+			if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2687
+				// in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2688
+				// custom attendee object so let's not worry about the primary reg.
2689
+				$primary_registration = null;
2690
+			}
2691
+		} else {
2692
+			$primary_registration = null;
2693
+		}
2694
+		$this->_template_args['ATT_ID'] = $attendee->ID();
2695
+		$this->_template_args['fname'] = $attendee->fname();
2696
+		$this->_template_args['lname'] = $attendee->lname();
2697
+		$this->_template_args['email'] = $attendee->email();
2698
+		$this->_template_args['phone'] = $attendee->phone();
2699
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2700
+		// edit link
2701
+		$this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(
2702
+			array(
2703
+				'action' => 'edit_attendee',
2704
+				'post'   => $attendee->ID(),
2705
+			),
2706
+			REG_ADMIN_URL
2707
+		);
2708
+		$this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2709
+		// create link
2710
+		$this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2711
+			? EE_Admin_Page::add_query_args_and_nonce(
2712
+				array(
2713
+					'action'  => 'duplicate_attendee',
2714
+					'_REG_ID' => $this->_registration->ID(),
2715
+				),
2716
+				REG_ADMIN_URL
2717
+			) : '';
2718
+		$this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2719
+		$this->_template_args['att_check'] = $att_check;
2720
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2721
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2722
+	}
2723
+
2724
+
2725
+	/**
2726
+	 * trash or restore registrations
2727
+	 *
2728
+	 * @param  boolean $trash whether to archive or restore
2729
+	 * @return void
2730
+	 * @throws EE_Error
2731
+	 * @throws InvalidArgumentException
2732
+	 * @throws InvalidDataTypeException
2733
+	 * @throws InvalidInterfaceException
2734
+	 * @throws RuntimeException
2735
+	 * @access protected
2736
+	 */
2737
+	protected function _trash_or_restore_registrations($trash = true)
2738
+	{
2739
+		// if empty _REG_ID then get out because there's nothing to do
2740
+		if (empty($this->_req_data['_REG_ID'])) {
2741
+			EE_Error::add_error(
2742
+				sprintf(
2743
+					esc_html__(
2744
+						'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2745
+						'event_espresso'
2746
+					),
2747
+					$trash ? 'trash' : 'restore'
2748
+				),
2749
+				__FILE__,
2750
+				__LINE__,
2751
+				__FUNCTION__
2752
+			);
2753
+			$this->_redirect_after_action(false, '', '', array(), true);
2754
+		}
2755
+		$success = 0;
2756
+		$overwrite_msgs = false;
2757
+		// Checkboxes
2758
+		if (! is_array($this->_req_data['_REG_ID'])) {
2759
+			$this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2760
+		}
2761
+		$reg_count = count($this->_req_data['_REG_ID']);
2762
+		// cycle thru checkboxes
2763
+		foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2764
+			/** @var EE_Registration $REG */
2765
+			$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2766
+			$payments = $REG->registration_payments();
2767
+			if (! empty($payments)) {
2768
+				$name = $REG->attendee() instanceof EE_Attendee
2769
+					? $REG->attendee()->full_name()
2770
+					: esc_html__('Unknown Attendee', 'event_espresso');
2771
+				$overwrite_msgs = true;
2772
+				EE_Error::add_error(
2773
+					sprintf(
2774
+						esc_html__(
2775
+							'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2776
+							'event_espresso'
2777
+						),
2778
+						$name
2779
+					),
2780
+					__FILE__,
2781
+					__FUNCTION__,
2782
+					__LINE__
2783
+				);
2784
+				// can't trash this registration because it has payments.
2785
+				continue;
2786
+			}
2787
+			$updated = $trash ? $REG->delete() : $REG->restore();
2788
+			if ($updated) {
2789
+				$success++;
2790
+			}
2791
+		}
2792
+		$this->_redirect_after_action(
2793
+			$success === $reg_count, // were ALL registrations affected?
2794
+			$success > 1
2795
+				? esc_html__('Registrations', 'event_espresso')
2796
+				: esc_html__('Registration', 'event_espresso'),
2797
+			$trash
2798
+				? esc_html__('moved to the trash', 'event_espresso')
2799
+				: esc_html__('restored', 'event_espresso'),
2800
+			array('action' => 'default'),
2801
+			$overwrite_msgs
2802
+		);
2803
+	}
2804
+
2805
+
2806
+	/**
2807
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2808
+	 * registration but also.
2809
+	 * 1. Removing relations to EE_Attendee
2810
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2811
+	 * ALSO trashed.
2812
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2813
+	 * 4. Removing relationships between all tickets and the related registrations
2814
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2815
+	 * 6. Deleting permanently any related Checkins.
2816
+	 *
2817
+	 * @return void
2818
+	 * @throws EE_Error
2819
+	 * @throws InvalidArgumentException
2820
+	 * @throws InvalidDataTypeException
2821
+	 * @throws InvalidInterfaceException
2822
+	 */
2823
+	protected function _delete_registrations()
2824
+	{
2825
+		$REG_MDL = EEM_Registration::instance();
2826
+		$success = 1;
2827
+		// Checkboxes
2828
+		if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2829
+			// if array has more than one element than success message should be plural
2830
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2831
+			// cycle thru checkboxes
2832
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2833
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2834
+				if (! $REG instanceof EE_Registration) {
2835
+					continue;
2836
+				}
2837
+				$deleted = $this->_delete_registration($REG);
2838
+				if (! $deleted) {
2839
+					$success = 0;
2840
+				}
2841
+			}
2842
+		} else {
2843
+			// grab single id and delete
2844
+			$REG_ID = $this->_req_data['_REG_ID'];
2845
+			$REG = $REG_MDL->get_one_by_ID($REG_ID);
2846
+			$deleted = $this->_delete_registration($REG);
2847
+			if (! $deleted) {
2848
+				$success = 0;
2849
+			}
2850
+		}
2851
+		$what = $success > 1
2852
+			? esc_html__('Registrations', 'event_espresso')
2853
+			: esc_html__('Registration', 'event_espresso');
2854
+		$action_desc = esc_html__('permanently deleted.', 'event_espresso');
2855
+		$this->_redirect_after_action(
2856
+			$success,
2857
+			$what,
2858
+			$action_desc,
2859
+			array('action' => 'default'),
2860
+			true
2861
+		);
2862
+	}
2863
+
2864
+
2865
+	/**
2866
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2867
+	 * models get affected.
2868
+	 *
2869
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2870
+	 * @return bool true = successful deletion, false = fail.
2871
+	 * @throws EE_Error
2872
+	 */
2873
+	protected function _delete_registration(EE_Registration $REG)
2874
+	{
2875
+		// first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2876
+		// registrations on the transaction that are NOT trashed.
2877
+		$TXN = $REG->get_first_related('Transaction');
2878
+		$REGS = $TXN->get_many_related('Registration');
2879
+		$all_trashed = true;
2880
+		foreach ($REGS as $registration) {
2881
+			if (! $registration->get('REG_deleted')) {
2882
+				$all_trashed = false;
2883
+			}
2884
+		}
2885
+		if (! $all_trashed) {
2886
+			EE_Error::add_error(
2887
+				esc_html__(
2888
+					'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2889
+					'event_espresso'
2890
+				),
2891
+				__FILE__,
2892
+				__FUNCTION__,
2893
+				__LINE__
2894
+			);
2895
+			return false;
2896
+		}
2897
+		// k made it here so that means we can delete all the related transactions and their answers (but let's do them
2898
+		// separately from THIS one).
2899
+		foreach ($REGS as $registration) {
2900
+			// delete related answers
2901
+			$registration->delete_related_permanently('Answer');
2902
+			// remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2903
+			$attendee = $registration->get_first_related('Attendee');
2904
+			if ($attendee instanceof EE_Attendee) {
2905
+				$registration->_remove_relation_to($attendee, 'Attendee');
2906
+			}
2907
+			// now remove relationships to tickets on this registration.
2908
+			$registration->_remove_relations('Ticket');
2909
+			// now delete permanently the checkins related to this registration.
2910
+			$registration->delete_related_permanently('Checkin');
2911
+			if ($registration->ID() === $REG->ID()) {
2912
+				continue;
2913
+			} //we don't want to delete permanently the existing registration just yet.
2914
+			// remove relation to transaction for these registrations if NOT the existing registrations
2915
+			$registration->_remove_relations('Transaction');
2916
+			// delete permanently any related messages.
2917
+			$registration->delete_related_permanently('Message');
2918
+			// now delete this registration permanently
2919
+			$registration->delete_permanently();
2920
+		}
2921
+		// now all related registrations on the transaction are handled.  So let's just handle this registration itself
2922
+		// (the transaction and line items should be all that's left).
2923
+		// delete the line items related to the transaction for this registration.
2924
+		$TXN->delete_related_permanently('Line_Item');
2925
+		// we need to remove all the relationships on the transaction
2926
+		$TXN->delete_related_permanently('Payment');
2927
+		$TXN->delete_related_permanently('Extra_Meta');
2928
+		$TXN->delete_related_permanently('Message');
2929
+		// now we can delete this REG permanently (and the transaction of course)
2930
+		$REG->delete_related_permanently('Transaction');
2931
+		return $REG->delete_permanently();
2932
+	}
2933
+
2934
+
2935
+	/**
2936
+	 *    generates HTML for the Register New Attendee Admin page
2937
+	 *
2938
+	 * @access private
2939
+	 * @throws DomainException
2940
+	 * @throws EE_Error
2941
+	 */
2942
+	public function new_registration()
2943
+	{
2944
+		if (! $this->_set_reg_event()) {
2945
+			throw new EE_Error(
2946
+				esc_html__(
2947
+					'Unable to continue with registering because there is no Event ID in the request',
2948
+					'event_espresso'
2949
+				)
2950
+			);
2951
+		}
2952
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2953
+		// gotta start with a clean slate if we're not coming here via ajax
2954
+		if (! defined('DOING_AJAX')
2955
+			&& (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2956
+		) {
2957
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2958
+		}
2959
+		$this->_template_args['event_name'] = '';
2960
+		// event name
2961
+		if ($this->_reg_event) {
2962
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2963
+			$edit_event_url = self::add_query_args_and_nonce(
2964
+				array(
2965
+					'action' => 'edit',
2966
+					'post'   => $this->_reg_event->ID(),
2967
+				),
2968
+				EVENTS_ADMIN_URL
2969
+			);
2970
+			$edit_event_lnk = '<a href="'
2971
+							  . $edit_event_url
2972
+							  . '" title="'
2973
+							  . esc_attr__('Edit ', 'event_espresso')
2974
+							  . $this->_reg_event->name()
2975
+							  . '">'
2976
+							  . esc_html__('Edit Event', 'event_espresso')
2977
+							  . '</a>';
2978
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2979
+												   . $edit_event_lnk
2980
+												   . '</span>';
2981
+		}
2982
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2983
+		if (defined('DOING_AJAX')) {
2984
+			$this->_return_json();
2985
+		}
2986
+		// grab header
2987
+		$template_path =
2988
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2989
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2990
+			$template_path,
2991
+			$this->_template_args,
2992
+			true
2993
+		);
2994
+		// $this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2995
+		// the details template wrapper
2996
+		$this->display_admin_page_with_sidebar();
2997
+	}
2998
+
2999
+
3000
+	/**
3001
+	 * This returns the content for a registration step
3002
+	 *
3003
+	 * @access protected
3004
+	 * @return string html
3005
+	 * @throws DomainException
3006
+	 * @throws EE_Error
3007
+	 * @throws InvalidArgumentException
3008
+	 * @throws InvalidDataTypeException
3009
+	 * @throws InvalidInterfaceException
3010
+	 */
3011
+	protected function _get_registration_step_content()
3012
+	{
3013
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
3014
+			$warning_msg = sprintf(
3015
+				esc_html__(
3016
+					'%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
3017
+					'event_espresso'
3018
+				),
3019
+				'<br />',
3020
+				'<h3 class="important-notice">',
3021
+				'</h3>',
3022
+				'<div class="float-right">',
3023
+				'<span id="redirect_timer" class="important-notice">30</span>',
3024
+				'</div>',
3025
+				'<b>',
3026
+				'</b>'
3027
+			);
3028
+			return '
3029 3029
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
3030 3030
 	<script >
3031 3031
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -3038,855 +3038,855 @@  discard block
 block discarded – undo
3038 3038
 	        }
3039 3039
 	    }, 800 );
3040 3040
 	</script >';
3041
-        }
3042
-        $template_args = array(
3043
-            'title'                    => '',
3044
-            'content'                  => '',
3045
-            'step_button_text'         => '',
3046
-            'show_notification_toggle' => false,
3047
-        );
3048
-        // to indicate we're processing a new registration
3049
-        $hidden_fields = array(
3050
-            'processing_registration' => array(
3051
-                'type'  => 'hidden',
3052
-                'value' => 0,
3053
-            ),
3054
-            'event_id'                => array(
3055
-                'type'  => 'hidden',
3056
-                'value' => $this->_reg_event->ID(),
3057
-            ),
3058
-        );
3059
-        // if the cart is empty then we know we're at step one so we'll display ticket selector
3060
-        $cart = EE_Registry::instance()->SSN->cart();
3061
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3062
-        switch ($step) {
3063
-            case 'ticket':
3064
-                $hidden_fields['processing_registration']['value'] = 1;
3065
-                $template_args['title'] = esc_html__(
3066
-                    'Step One: Select the Ticket for this registration',
3067
-                    'event_espresso'
3068
-                );
3069
-                $template_args['content'] =
3070
-                    EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
3071
-                $template_args['step_button_text'] = esc_html__(
3072
-                    'Add Tickets and Continue to Registrant Details',
3073
-                    'event_espresso'
3074
-                );
3075
-                $template_args['show_notification_toggle'] = false;
3076
-                break;
3077
-            case 'questions':
3078
-                $hidden_fields['processing_registration']['value'] = 2;
3079
-                $template_args['title'] = esc_html__(
3080
-                    'Step Two: Add Registrant Details for this Registration',
3081
-                    'event_espresso'
3082
-                );
3083
-                // in theory we should be able to run EED_SPCO at this point because the cart should have been setup
3084
-                // properly by the first process_reg_step run.
3085
-                $template_args['content'] =
3086
-                    EED_Single_Page_Checkout::registration_checkout_for_admin();
3087
-                $template_args['step_button_text'] = esc_html__(
3088
-                    'Save Registration and Continue to Details',
3089
-                    'event_espresso'
3090
-                );
3091
-                $template_args['show_notification_toggle'] = true;
3092
-                break;
3093
-        }
3094
-        // we come back to the process_registration_step route.
3095
-        $this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3096
-        return EEH_Template::display_template(
3097
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3098
-            $template_args,
3099
-            true
3100
-        );
3101
-    }
3102
-
3103
-
3104
-    /**
3105
-     *        set_reg_event
3106
-     *
3107
-     * @access private
3108
-     * @return bool
3109
-     * @throws EE_Error
3110
-     * @throws InvalidArgumentException
3111
-     * @throws InvalidDataTypeException
3112
-     * @throws InvalidInterfaceException
3113
-     */
3114
-    private function _set_reg_event()
3115
-    {
3116
-        if (is_object($this->_reg_event)) {
3117
-            return true;
3118
-        }
3119
-        $EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3120
-        if (! $EVT_ID) {
3121
-            return false;
3122
-        }
3123
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
3124
-        return true;
3125
-    }
3126
-
3127
-
3128
-    /**
3129
-     * process_reg_step
3130
-     *
3131
-     * @access        public
3132
-     * @return string
3133
-     * @throws DomainException
3134
-     * @throws EE_Error
3135
-     * @throws InvalidArgumentException
3136
-     * @throws InvalidDataTypeException
3137
-     * @throws InvalidInterfaceException
3138
-     * @throws ReflectionException
3139
-     * @throws RuntimeException
3140
-     */
3141
-    public function process_reg_step()
3142
-    {
3143
-        EE_System::do_not_cache();
3144
-        $this->_set_reg_event();
3145
-        EE_Registry::instance()->REQ->set_espresso_page(true);
3146
-        EE_Registry::instance()->REQ->set('uts', time());
3147
-        // what step are we on?
3148
-        $cart = EE_Registry::instance()->SSN->cart();
3149
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3150
-        // if doing ajax then we need to verify the nonce
3151
-        if (defined('DOING_AJAX')) {
3152
-            $nonce = isset($this->_req_data[ $this->_req_nonce ])
3153
-                ? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3154
-            $this->_verify_nonce($nonce, $this->_req_nonce);
3155
-        }
3156
-        switch ($step) {
3157
-            case 'ticket':
3158
-                // process ticket selection
3159
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
3160
-                if ($success) {
3161
-                    EE_Error::add_success(
3162
-                        esc_html__(
3163
-                            'Tickets Selected. Now complete the registration.',
3164
-                            'event_espresso'
3165
-                        )
3166
-                    );
3167
-                } else {
3168
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
3169
-                }
3170
-                if (defined('DOING_AJAX')) {
3171
-                    $this->new_registration(); // display next step
3172
-                } else {
3173
-                    $query_args = array(
3174
-                        'action'                  => 'new_registration',
3175
-                        'processing_registration' => 1,
3176
-                        'event_id'                => $this->_reg_event->ID(),
3177
-                        'uts'                     => time(),
3178
-                    );
3179
-                    $this->_redirect_after_action(
3180
-                        false,
3181
-                        '',
3182
-                        '',
3183
-                        $query_args,
3184
-                        true
3185
-                    );
3186
-                }
3187
-                break;
3188
-            case 'questions':
3189
-                if (! isset(
3190
-                    $this->_req_data['txn_reg_status_change'],
3191
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
3192
-                )
3193
-                ) {
3194
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
3195
-                }
3196
-                // process registration
3197
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
3198
-                if ($cart instanceof EE_Cart) {
3199
-                    $grand_total = $cart->get_cart_grand_total();
3200
-                    if ($grand_total instanceof EE_Line_Item) {
3201
-                        $grand_total->save_this_and_descendants_to_txn();
3202
-                    }
3203
-                }
3204
-                if (! $transaction instanceof EE_Transaction) {
3205
-                    $query_args = array(
3206
-                        'action'                  => 'new_registration',
3207
-                        'processing_registration' => 2,
3208
-                        'event_id'                => $this->_reg_event->ID(),
3209
-                        'uts'                     => time(),
3210
-                    );
3211
-                    if (defined('DOING_AJAX')) {
3212
-                        // display registration form again because there are errors (maybe validation?)
3213
-                        $this->new_registration();
3214
-                        return;
3215
-                    } else {
3216
-                        $this->_redirect_after_action(
3217
-                            false,
3218
-                            '',
3219
-                            '',
3220
-                            $query_args,
3221
-                            true
3222
-                        );
3223
-                        return;
3224
-                    }
3225
-                }
3226
-                // maybe update status, and make sure to save transaction if not done already
3227
-                if (! $transaction->update_status_based_on_total_paid()) {
3228
-                    $transaction->save();
3229
-                }
3230
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3231
-                $this->_req_data = array();
3232
-                $query_args = array(
3233
-                    'action'        => 'redirect_to_txn',
3234
-                    'TXN_ID'        => $transaction->ID(),
3235
-                    'EVT_ID'        => $this->_reg_event->ID(),
3236
-                    'event_name'    => urlencode($this->_reg_event->name()),
3237
-                    'redirect_from' => 'new_registration',
3238
-                );
3239
-                $this->_redirect_after_action(false, '', '', $query_args, true);
3240
-                break;
3241
-        }
3242
-        // what are you looking here for?  Should be nothing to do at this point.
3243
-    }
3244
-
3245
-
3246
-    /**
3247
-     * redirect_to_txn
3248
-     *
3249
-     * @access public
3250
-     * @return void
3251
-     * @throws EE_Error
3252
-     * @throws InvalidArgumentException
3253
-     * @throws InvalidDataTypeException
3254
-     * @throws InvalidInterfaceException
3255
-     */
3256
-    public function redirect_to_txn()
3257
-    {
3258
-        EE_System::do_not_cache();
3259
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3260
-        $query_args = array(
3261
-            'action' => 'view_transaction',
3262
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3263
-            'page'   => 'espresso_transactions',
3264
-        );
3265
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3266
-            $query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
3267
-            $query_args['event_name'] = urlencode($this->_req_data['event_name']);
3268
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
3269
-        }
3270
-        EE_Error::add_success(
3271
-            esc_html__(
3272
-                'Registration Created.  Please review the transaction and add any payments as necessary',
3273
-                'event_espresso'
3274
-            )
3275
-        );
3276
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3277
-    }
3278
-
3279
-
3280
-    /**
3281
-     *        generates HTML for the Attendee Contact List
3282
-     *
3283
-     * @access protected
3284
-     * @return void
3285
-     */
3286
-    protected function _attendee_contact_list_table()
3287
-    {
3288
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3289
-        $this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3290
-        $this->display_admin_list_table_page_with_no_sidebar();
3291
-    }
3292
-
3293
-
3294
-    /**
3295
-     *        get_attendees
3296
-     *
3297
-     * @param      $per_page
3298
-     * @param bool $count whether to return count or data.
3299
-     * @param bool $trash
3300
-     * @return array
3301
-     * @throws EE_Error
3302
-     * @throws InvalidArgumentException
3303
-     * @throws InvalidDataTypeException
3304
-     * @throws InvalidInterfaceException
3305
-     * @access public
3306
-     */
3307
-    public function get_attendees($per_page, $count = false, $trash = false)
3308
-    {
3309
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3310
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3311
-        $ATT_MDL = EEM_Attendee::instance();
3312
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3313
-        switch ($this->_req_data['orderby']) {
3314
-            case 'ATT_ID':
3315
-                $orderby = 'ATT_ID';
3316
-                break;
3317
-            case 'ATT_fname':
3318
-                $orderby = 'ATT_fname';
3319
-                break;
3320
-            case 'ATT_email':
3321
-                $orderby = 'ATT_email';
3322
-                break;
3323
-            case 'ATT_city':
3324
-                $orderby = 'ATT_city';
3325
-                break;
3326
-            case 'STA_ID':
3327
-                $orderby = 'STA_ID';
3328
-                break;
3329
-            case 'CNT_ID':
3330
-                $orderby = 'CNT_ID';
3331
-                break;
3332
-            case 'Registration_Count':
3333
-                $orderby = 'Registration_Count';
3334
-                break;
3335
-            default:
3336
-                $orderby = 'ATT_lname';
3337
-        }
3338
-        $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3339
-            ? $this->_req_data['order']
3340
-            : 'ASC';
3341
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3342
-            ? $this->_req_data['paged']
3343
-            : 1;
3344
-        $per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3345
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3346
-            ? $this->_req_data['perpage']
3347
-            : $per_page;
3348
-        $_where = array();
3349
-        if (! empty($this->_req_data['s'])) {
3350
-            $sstr = '%' . $this->_req_data['s'] . '%';
3351
-            $_where['OR'] = array(
3352
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3353
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3354
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3355
-                'ATT_fname'                         => array('LIKE', $sstr),
3356
-                'ATT_lname'                         => array('LIKE', $sstr),
3357
-                'ATT_short_bio'                     => array('LIKE', $sstr),
3358
-                'ATT_email'                         => array('LIKE', $sstr),
3359
-                'ATT_address'                       => array('LIKE', $sstr),
3360
-                'ATT_address2'                      => array('LIKE', $sstr),
3361
-                'ATT_city'                          => array('LIKE', $sstr),
3362
-                'Country.CNT_name'                  => array('LIKE', $sstr),
3363
-                'State.STA_name'                    => array('LIKE', $sstr),
3364
-                'ATT_phone'                         => array('LIKE', $sstr),
3365
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
3366
-                'Registration.REG_code'             => array('LIKE', $sstr),
3367
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
3368
-            );
3369
-        }
3370
-        $offset = ($current_page - 1) * $per_page;
3371
-        $limit = $count ? null : array($offset, $per_page);
3372
-        $query_args = array(
3373
-            $_where,
3374
-            'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3375
-            'limit'         => $limit,
3376
-        );
3377
-        if (! $count) {
3378
-            $query_args['order_by'] = array($orderby => $sort);
3379
-        }
3380
-        if ($trash) {
3381
-            $query_args[0]['status'] = array('!=', 'publish');
3382
-            $all_attendees = $count
3383
-                ? $ATT_MDL->count($query_args, 'ATT_ID', true)
3384
-                : $ATT_MDL->get_all($query_args);
3385
-        } else {
3386
-            $query_args[0]['status'] = array('IN', array('publish'));
3387
-            $all_attendees = $count
3388
-                ? $ATT_MDL->count($query_args, 'ATT_ID', true)
3389
-                : $ATT_MDL->get_all($query_args);
3390
-        }
3391
-        return $all_attendees;
3392
-    }
3393
-
3394
-
3395
-    /**
3396
-     * This is just taking care of resending the registration confirmation
3397
-     *
3398
-     * @access protected
3399
-     * @return void
3400
-     */
3401
-    protected function _resend_registration()
3402
-    {
3403
-        $this->_process_resend_registration();
3404
-        $query_args = isset($this->_req_data['redirect_to'])
3405
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3406
-            : array('action' => 'default');
3407
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3408
-    }
3409
-
3410
-    /**
3411
-     * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3412
-     * to use when selecting registrations
3413
-     *
3414
-     * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3415
-     *                                                     the query parameters from the request
3416
-     * @return void ends the request with a redirect or download
3417
-     */
3418
-    public function _registrations_report_base($method_name_for_getting_query_params)
3419
-    {
3420
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3421
-            wp_redirect(
3422
-                EE_Admin_Page::add_query_args_and_nonce(
3423
-                    array(
3424
-                        'page'        => 'espresso_batch',
3425
-                        'batch'       => 'file',
3426
-                        'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3427
-                        'filters'     => urlencode(
3428
-                            serialize(
3429
-                                call_user_func(
3430
-                                    array($this, $method_name_for_getting_query_params),
3431
-                                    EEH_Array::is_set(
3432
-                                        $this->_req_data,
3433
-                                        'filters',
3434
-                                        array()
3435
-                                    )
3436
-                                )
3437
-                            )
3438
-                        ),
3439
-                        'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3440
-                        'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3441
-                        'return_url'  => urlencode($this->_req_data['return_url']),
3442
-                    )
3443
-                )
3444
-            );
3445
-        } else {
3446
-            $new_request_args = array(
3447
-                'export' => 'report',
3448
-                'action' => 'registrations_report_for_event',
3449
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3450
-            );
3451
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
3452
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3453
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3454
-                $EE_Export = EE_Export::instance($this->_req_data);
3455
-                $EE_Export->export();
3456
-            }
3457
-        }
3458
-    }
3459
-
3460
-
3461
-    /**
3462
-     * Creates a registration report using only query parameters in the request
3463
-     *
3464
-     * @return void
3465
-     */
3466
-    public function _registrations_report()
3467
-    {
3468
-        $this->_registrations_report_base('_get_registration_query_parameters');
3469
-    }
3470
-
3471
-
3472
-    public function _contact_list_export()
3473
-    {
3474
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3475
-            require_once(EE_CLASSES . 'EE_Export.class.php');
3476
-            $EE_Export = EE_Export::instance($this->_req_data);
3477
-            $EE_Export->export_attendees();
3478
-        }
3479
-    }
3480
-
3481
-
3482
-    public function _contact_list_report()
3483
-    {
3484
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3485
-            wp_redirect(
3486
-                EE_Admin_Page::add_query_args_and_nonce(
3487
-                    array(
3488
-                        'page'        => 'espresso_batch',
3489
-                        'batch'       => 'file',
3490
-                        'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3491
-                        'return_url'  => urlencode($this->_req_data['return_url']),
3492
-                    )
3493
-                )
3494
-            );
3495
-        } else {
3496
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3497
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3498
-                $EE_Export = EE_Export::instance($this->_req_data);
3499
-                $EE_Export->report_attendees();
3500
-            }
3501
-        }
3502
-    }
3503
-
3504
-
3505
-
3506
-
3507
-
3508
-    /***************************************        ATTENDEE DETAILS        ***************************************/
3509
-    /**
3510
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
3511
-     *
3512
-     * @return void
3513
-     * @throws EE_Error
3514
-     * @throws InvalidArgumentException
3515
-     * @throws InvalidDataTypeException
3516
-     * @throws InvalidInterfaceException
3517
-     */
3518
-    protected function _duplicate_attendee()
3519
-    {
3520
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3521
-        // verify we have necessary info
3522
-        if (empty($this->_req_data['_REG_ID'])) {
3523
-            EE_Error::add_error(
3524
-                esc_html__(
3525
-                    'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3526
-                    'event_espresso'
3527
-                ),
3528
-                __FILE__,
3529
-                __LINE__,
3530
-                __FUNCTION__
3531
-            );
3532
-            $query_args = array('action' => $action);
3533
-            $this->_redirect_after_action('', '', '', $query_args, true);
3534
-        }
3535
-        // okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3536
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3537
-        $attendee = $registration->attendee();
3538
-        // remove relation of existing attendee on registration
3539
-        $registration->_remove_relation_to($attendee, 'Attendee');
3540
-        // new attendee
3541
-        $new_attendee = clone $attendee;
3542
-        $new_attendee->set('ATT_ID', 0);
3543
-        $new_attendee->save();
3544
-        // add new attendee to reg
3545
-        $registration->_add_relation_to($new_attendee, 'Attendee');
3546
-        EE_Error::add_success(
3547
-            esc_html__(
3548
-                'New Contact record created.  Now make any edits you wish to make for this contact.',
3549
-                'event_espresso'
3550
-            )
3551
-        );
3552
-        // redirect to edit page for attendee
3553
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3554
-        $this->_redirect_after_action('', '', '', $query_args, true);
3555
-    }
3556
-
3557
-
3558
-    /**
3559
-     * Callback invoked by parent EE_Admin_CPT class hooked in on `save_post` wp hook.
3560
-     *
3561
-     * @param int     $post_id
3562
-     * @param WP_POST $post
3563
-     * @throws DomainException
3564
-     * @throws EE_Error
3565
-     * @throws InvalidArgumentException
3566
-     * @throws InvalidDataTypeException
3567
-     * @throws InvalidInterfaceException
3568
-     * @throws LogicException
3569
-     * @throws InvalidFormSubmissionException
3570
-     */
3571
-    protected function _insert_update_cpt_item($post_id, $post)
3572
-    {
3573
-        $success = true;
3574
-        $attendee = $post instanceof WP_Post && $post->post_type === 'espresso_attendees'
3575
-            ? EEM_Attendee::instance()->get_one_by_ID($post_id)
3576
-            : null;
3577
-        // for attendee updates
3578
-        if ($attendee instanceof EE_Attendee) {
3579
-            // note we should only be UPDATING attendees at this point.
3580
-            $updated_fields = array(
3581
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
3582
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
3583
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3584
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3585
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3586
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3587
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3588
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3589
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3590
-            );
3591
-            foreach ($updated_fields as $field => $value) {
3592
-                $attendee->set($field, $value);
3593
-            }
3594
-
3595
-            // process contact details metabox form handler (which will also save the attendee)
3596
-            $contact_details_form = $this->getAttendeeContactDetailsMetaboxFormHandler($attendee);
3597
-            $success = $contact_details_form->process($this->_req_data);
3598
-
3599
-            $attendee_update_callbacks = apply_filters(
3600
-                'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3601
-                array()
3602
-            );
3603
-            foreach ($attendee_update_callbacks as $a_callback) {
3604
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3605
-                    throw new EE_Error(
3606
-                        sprintf(
3607
-                            esc_html__(
3608
-                                'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3609
-                                'event_espresso'
3610
-                            ),
3611
-                            $a_callback
3612
-                        )
3613
-                    );
3614
-                }
3615
-            }
3616
-        }
3617
-
3618
-        if ($success === false) {
3619
-            EE_Error::add_error(
3620
-                esc_html__(
3621
-                    'Something went wrong with updating the meta table data for the registration.',
3622
-                    'event_espresso'
3623
-                ),
3624
-                __FILE__,
3625
-                __FUNCTION__,
3626
-                __LINE__
3627
-            );
3628
-        }
3629
-    }
3630
-
3631
-
3632
-    public function trash_cpt_item($post_id)
3633
-    {
3634
-    }
3635
-
3636
-
3637
-    public function delete_cpt_item($post_id)
3638
-    {
3639
-    }
3640
-
3641
-
3642
-    public function restore_cpt_item($post_id)
3643
-    {
3644
-    }
3645
-
3646
-
3647
-    protected function _restore_cpt_item($post_id, $revision_id)
3648
-    {
3649
-    }
3650
-
3651
-
3652
-    public function attendee_editor_metaboxes()
3653
-    {
3654
-        $this->verify_cpt_object();
3655
-        remove_meta_box(
3656
-            'postexcerpt',
3657
-            esc_html__('Excerpt', 'event_espresso'),
3658
-            'post_excerpt_meta_box',
3659
-            $this->_cpt_routes[ $this->_req_action ],
3660
-            'normal',
3661
-            'core'
3662
-        );
3663
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3664
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
3665
-            add_meta_box(
3666
-                'postexcerpt',
3667
-                esc_html__('Short Biography', 'event_espresso'),
3668
-                'post_excerpt_meta_box',
3669
-                $this->_cpt_routes[ $this->_req_action ],
3670
-                'normal'
3671
-            );
3672
-        }
3673
-        if (post_type_supports('espresso_attendees', 'comments')) {
3674
-            add_meta_box(
3675
-                'commentsdiv',
3676
-                esc_html__('Notes on the Contact', 'event_espresso'),
3677
-                'post_comment_meta_box',
3678
-                $this->_cpt_routes[ $this->_req_action ],
3679
-                'normal',
3680
-                'core'
3681
-            );
3682
-        }
3683
-        add_meta_box(
3684
-            'attendee_contact_info',
3685
-            esc_html__('Contact Info', 'event_espresso'),
3686
-            array($this, 'attendee_contact_info'),
3687
-            $this->_cpt_routes[ $this->_req_action ],
3688
-            'side',
3689
-            'core'
3690
-        );
3691
-        add_meta_box(
3692
-            'attendee_details_address',
3693
-            esc_html__('Address Details', 'event_espresso'),
3694
-            array($this, 'attendee_address_details'),
3695
-            $this->_cpt_routes[ $this->_req_action ],
3696
-            'normal',
3697
-            'core'
3698
-        );
3699
-        add_meta_box(
3700
-            'attendee_registrations',
3701
-            esc_html__('Registrations for this Contact', 'event_espresso'),
3702
-            array($this, 'attendee_registrations_meta_box'),
3703
-            $this->_cpt_routes[ $this->_req_action ],
3704
-            'normal',
3705
-            'high'
3706
-        );
3707
-    }
3708
-
3709
-
3710
-    /**
3711
-     * Metabox for attendee contact info
3712
-     *
3713
-     * @param  WP_Post $post wp post object
3714
-     * @return string attendee contact info ( and form )
3715
-     * @throws EE_Error
3716
-     * @throws InvalidArgumentException
3717
-     * @throws InvalidDataTypeException
3718
-     * @throws InvalidInterfaceException
3719
-     * @throws LogicException
3720
-     * @throws DomainException
3721
-     */
3722
-    public function attendee_contact_info($post)
3723
-    {
3724
-        // get attendee object ( should already have it )
3725
-        $form = $this->getAttendeeContactDetailsMetaboxFormHandler($this->_cpt_model_obj);
3726
-        $form->enqueueStylesAndScripts();
3727
-        echo $form->display();
3728
-    }
3729
-
3730
-
3731
-    /**
3732
-     * Return form handler for the contact details metabox
3733
-     *
3734
-     * @param EE_Attendee $attendee
3735
-     * @return AttendeeContactDetailsMetaboxFormHandler
3736
-     * @throws DomainException
3737
-     * @throws InvalidArgumentException
3738
-     * @throws InvalidDataTypeException
3739
-     * @throws InvalidInterfaceException
3740
-     */
3741
-    protected function getAttendeeContactDetailsMetaboxFormHandler(EE_Attendee $attendee)
3742
-    {
3743
-        return new AttendeeContactDetailsMetaboxFormHandler($attendee, EE_Registry::instance());
3744
-    }
3745
-
3746
-
3747
-    /**
3748
-     * Metabox for attendee details
3749
-     *
3750
-     * @param  WP_Post $post wp post object
3751
-     * @throws DomainException
3752
-     */
3753
-    public function attendee_address_details($post)
3754
-    {
3755
-        // get attendee object (should already have it)
3756
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3757
-        $this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(
3758
-            new EE_Question_Form_Input(
3759
-                EE_Question::new_instance(
3760
-                    array(
3761
-                        'QST_ID'           => 0,
3762
-                        'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3763
-                        'QST_system'       => 'admin-state',
3764
-                    )
3765
-                ),
3766
-                EE_Answer::new_instance(
3767
-                    array(
3768
-                        'ANS_ID'    => 0,
3769
-                        'ANS_value' => $this->_cpt_model_obj->state_ID(),
3770
-                    )
3771
-                ),
3772
-                array(
3773
-                    'input_id'       => 'STA_ID',
3774
-                    'input_name'     => 'STA_ID',
3775
-                    'input_prefix'   => '',
3776
-                    'append_qstn_id' => false,
3777
-                )
3778
-            )
3779
-        );
3780
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3781
-            new EE_Question_Form_Input(
3782
-                EE_Question::new_instance(
3783
-                    array(
3784
-                        'QST_ID'           => 0,
3785
-                        'QST_display_text' => esc_html__('Country', 'event_espresso'),
3786
-                        'QST_system'       => 'admin-country',
3787
-                    )
3788
-                ),
3789
-                EE_Answer::new_instance(
3790
-                    array(
3791
-                        'ANS_ID'    => 0,
3792
-                        'ANS_value' => $this->_cpt_model_obj->country_ID(),
3793
-                    )
3794
-                ),
3795
-                array(
3796
-                    'input_id'       => 'CNT_ISO',
3797
-                    'input_name'     => 'CNT_ISO',
3798
-                    'input_prefix'   => '',
3799
-                    'append_qstn_id' => false,
3800
-                )
3801
-            )
3802
-        );
3803
-        $template =
3804
-            REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3805
-        EEH_Template::display_template($template, $this->_template_args);
3806
-    }
3807
-
3808
-
3809
-    /**
3810
-     *        _attendee_details
3811
-     *
3812
-     * @access protected
3813
-     * @param $post
3814
-     * @return void
3815
-     * @throws DomainException
3816
-     * @throws EE_Error
3817
-     */
3818
-    public function attendee_registrations_meta_box($post)
3819
-    {
3820
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3821
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3822
-        $template =
3823
-            REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3824
-        EEH_Template::display_template($template, $this->_template_args);
3825
-    }
3826
-
3827
-
3828
-    /**
3829
-     * add in the form fields for the attendee edit
3830
-     *
3831
-     * @param  WP_Post $post wp post object
3832
-     * @return string html for new form.
3833
-     * @throws DomainException
3834
-     */
3835
-    public function after_title_form_fields($post)
3836
-    {
3837
-        if ($post->post_type == 'espresso_attendees') {
3838
-            $template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3839
-            $template_args['attendee'] = $this->_cpt_model_obj;
3840
-            EEH_Template::display_template($template, $template_args);
3841
-        }
3842
-    }
3843
-
3844
-
3845
-    /**
3846
-     *        _trash_or_restore_attendee
3847
-     *
3848
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3849
-     * @return void
3850
-     * @throws EE_Error
3851
-     * @throws InvalidArgumentException
3852
-     * @throws InvalidDataTypeException
3853
-     * @throws InvalidInterfaceException
3854
-     * @access protected
3855
-     */
3856
-    protected function _trash_or_restore_attendees($trash = true)
3857
-    {
3858
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3859
-        $ATT_MDL = EEM_Attendee::instance();
3860
-        $success = 1;
3861
-        // Checkboxes
3862
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3863
-            // if array has more than one element than success message should be plural
3864
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3865
-            // cycle thru checkboxes
3866
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3867
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3868
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3869
-                if (! $updated) {
3870
-                    $success = 0;
3871
-                }
3872
-            }
3873
-        } else {
3874
-            // grab single id and delete
3875
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
3876
-            // get attendee
3877
-            $att = $ATT_MDL->get_one_by_ID($ATT_ID);
3878
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3879
-            $updated = $att->save();
3880
-            if (! $updated) {
3881
-                $success = 0;
3882
-            }
3883
-        }
3884
-        $what = $success > 1
3885
-            ? esc_html__('Contacts', 'event_espresso')
3886
-            : esc_html__('Contact', 'event_espresso');
3887
-        $action_desc = $trash
3888
-            ? esc_html__('moved to the trash', 'event_espresso')
3889
-            : esc_html__('restored', 'event_espresso');
3890
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3891
-    }
3041
+		}
3042
+		$template_args = array(
3043
+			'title'                    => '',
3044
+			'content'                  => '',
3045
+			'step_button_text'         => '',
3046
+			'show_notification_toggle' => false,
3047
+		);
3048
+		// to indicate we're processing a new registration
3049
+		$hidden_fields = array(
3050
+			'processing_registration' => array(
3051
+				'type'  => 'hidden',
3052
+				'value' => 0,
3053
+			),
3054
+			'event_id'                => array(
3055
+				'type'  => 'hidden',
3056
+				'value' => $this->_reg_event->ID(),
3057
+			),
3058
+		);
3059
+		// if the cart is empty then we know we're at step one so we'll display ticket selector
3060
+		$cart = EE_Registry::instance()->SSN->cart();
3061
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3062
+		switch ($step) {
3063
+			case 'ticket':
3064
+				$hidden_fields['processing_registration']['value'] = 1;
3065
+				$template_args['title'] = esc_html__(
3066
+					'Step One: Select the Ticket for this registration',
3067
+					'event_espresso'
3068
+				);
3069
+				$template_args['content'] =
3070
+					EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
3071
+				$template_args['step_button_text'] = esc_html__(
3072
+					'Add Tickets and Continue to Registrant Details',
3073
+					'event_espresso'
3074
+				);
3075
+				$template_args['show_notification_toggle'] = false;
3076
+				break;
3077
+			case 'questions':
3078
+				$hidden_fields['processing_registration']['value'] = 2;
3079
+				$template_args['title'] = esc_html__(
3080
+					'Step Two: Add Registrant Details for this Registration',
3081
+					'event_espresso'
3082
+				);
3083
+				// in theory we should be able to run EED_SPCO at this point because the cart should have been setup
3084
+				// properly by the first process_reg_step run.
3085
+				$template_args['content'] =
3086
+					EED_Single_Page_Checkout::registration_checkout_for_admin();
3087
+				$template_args['step_button_text'] = esc_html__(
3088
+					'Save Registration and Continue to Details',
3089
+					'event_espresso'
3090
+				);
3091
+				$template_args['show_notification_toggle'] = true;
3092
+				break;
3093
+		}
3094
+		// we come back to the process_registration_step route.
3095
+		$this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3096
+		return EEH_Template::display_template(
3097
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3098
+			$template_args,
3099
+			true
3100
+		);
3101
+	}
3102
+
3103
+
3104
+	/**
3105
+	 *        set_reg_event
3106
+	 *
3107
+	 * @access private
3108
+	 * @return bool
3109
+	 * @throws EE_Error
3110
+	 * @throws InvalidArgumentException
3111
+	 * @throws InvalidDataTypeException
3112
+	 * @throws InvalidInterfaceException
3113
+	 */
3114
+	private function _set_reg_event()
3115
+	{
3116
+		if (is_object($this->_reg_event)) {
3117
+			return true;
3118
+		}
3119
+		$EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3120
+		if (! $EVT_ID) {
3121
+			return false;
3122
+		}
3123
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
3124
+		return true;
3125
+	}
3126
+
3127
+
3128
+	/**
3129
+	 * process_reg_step
3130
+	 *
3131
+	 * @access        public
3132
+	 * @return string
3133
+	 * @throws DomainException
3134
+	 * @throws EE_Error
3135
+	 * @throws InvalidArgumentException
3136
+	 * @throws InvalidDataTypeException
3137
+	 * @throws InvalidInterfaceException
3138
+	 * @throws ReflectionException
3139
+	 * @throws RuntimeException
3140
+	 */
3141
+	public function process_reg_step()
3142
+	{
3143
+		EE_System::do_not_cache();
3144
+		$this->_set_reg_event();
3145
+		EE_Registry::instance()->REQ->set_espresso_page(true);
3146
+		EE_Registry::instance()->REQ->set('uts', time());
3147
+		// what step are we on?
3148
+		$cart = EE_Registry::instance()->SSN->cart();
3149
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3150
+		// if doing ajax then we need to verify the nonce
3151
+		if (defined('DOING_AJAX')) {
3152
+			$nonce = isset($this->_req_data[ $this->_req_nonce ])
3153
+				? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3154
+			$this->_verify_nonce($nonce, $this->_req_nonce);
3155
+		}
3156
+		switch ($step) {
3157
+			case 'ticket':
3158
+				// process ticket selection
3159
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
3160
+				if ($success) {
3161
+					EE_Error::add_success(
3162
+						esc_html__(
3163
+							'Tickets Selected. Now complete the registration.',
3164
+							'event_espresso'
3165
+						)
3166
+					);
3167
+				} else {
3168
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
3169
+				}
3170
+				if (defined('DOING_AJAX')) {
3171
+					$this->new_registration(); // display next step
3172
+				} else {
3173
+					$query_args = array(
3174
+						'action'                  => 'new_registration',
3175
+						'processing_registration' => 1,
3176
+						'event_id'                => $this->_reg_event->ID(),
3177
+						'uts'                     => time(),
3178
+					);
3179
+					$this->_redirect_after_action(
3180
+						false,
3181
+						'',
3182
+						'',
3183
+						$query_args,
3184
+						true
3185
+					);
3186
+				}
3187
+				break;
3188
+			case 'questions':
3189
+				if (! isset(
3190
+					$this->_req_data['txn_reg_status_change'],
3191
+					$this->_req_data['txn_reg_status_change']['send_notifications']
3192
+				)
3193
+				) {
3194
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
3195
+				}
3196
+				// process registration
3197
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
3198
+				if ($cart instanceof EE_Cart) {
3199
+					$grand_total = $cart->get_cart_grand_total();
3200
+					if ($grand_total instanceof EE_Line_Item) {
3201
+						$grand_total->save_this_and_descendants_to_txn();
3202
+					}
3203
+				}
3204
+				if (! $transaction instanceof EE_Transaction) {
3205
+					$query_args = array(
3206
+						'action'                  => 'new_registration',
3207
+						'processing_registration' => 2,
3208
+						'event_id'                => $this->_reg_event->ID(),
3209
+						'uts'                     => time(),
3210
+					);
3211
+					if (defined('DOING_AJAX')) {
3212
+						// display registration form again because there are errors (maybe validation?)
3213
+						$this->new_registration();
3214
+						return;
3215
+					} else {
3216
+						$this->_redirect_after_action(
3217
+							false,
3218
+							'',
3219
+							'',
3220
+							$query_args,
3221
+							true
3222
+						);
3223
+						return;
3224
+					}
3225
+				}
3226
+				// maybe update status, and make sure to save transaction if not done already
3227
+				if (! $transaction->update_status_based_on_total_paid()) {
3228
+					$transaction->save();
3229
+				}
3230
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3231
+				$this->_req_data = array();
3232
+				$query_args = array(
3233
+					'action'        => 'redirect_to_txn',
3234
+					'TXN_ID'        => $transaction->ID(),
3235
+					'EVT_ID'        => $this->_reg_event->ID(),
3236
+					'event_name'    => urlencode($this->_reg_event->name()),
3237
+					'redirect_from' => 'new_registration',
3238
+				);
3239
+				$this->_redirect_after_action(false, '', '', $query_args, true);
3240
+				break;
3241
+		}
3242
+		// what are you looking here for?  Should be nothing to do at this point.
3243
+	}
3244
+
3245
+
3246
+	/**
3247
+	 * redirect_to_txn
3248
+	 *
3249
+	 * @access public
3250
+	 * @return void
3251
+	 * @throws EE_Error
3252
+	 * @throws InvalidArgumentException
3253
+	 * @throws InvalidDataTypeException
3254
+	 * @throws InvalidInterfaceException
3255
+	 */
3256
+	public function redirect_to_txn()
3257
+	{
3258
+		EE_System::do_not_cache();
3259
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3260
+		$query_args = array(
3261
+			'action' => 'view_transaction',
3262
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3263
+			'page'   => 'espresso_transactions',
3264
+		);
3265
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3266
+			$query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
3267
+			$query_args['event_name'] = urlencode($this->_req_data['event_name']);
3268
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
3269
+		}
3270
+		EE_Error::add_success(
3271
+			esc_html__(
3272
+				'Registration Created.  Please review the transaction and add any payments as necessary',
3273
+				'event_espresso'
3274
+			)
3275
+		);
3276
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3277
+	}
3278
+
3279
+
3280
+	/**
3281
+	 *        generates HTML for the Attendee Contact List
3282
+	 *
3283
+	 * @access protected
3284
+	 * @return void
3285
+	 */
3286
+	protected function _attendee_contact_list_table()
3287
+	{
3288
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3289
+		$this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3290
+		$this->display_admin_list_table_page_with_no_sidebar();
3291
+	}
3292
+
3293
+
3294
+	/**
3295
+	 *        get_attendees
3296
+	 *
3297
+	 * @param      $per_page
3298
+	 * @param bool $count whether to return count or data.
3299
+	 * @param bool $trash
3300
+	 * @return array
3301
+	 * @throws EE_Error
3302
+	 * @throws InvalidArgumentException
3303
+	 * @throws InvalidDataTypeException
3304
+	 * @throws InvalidInterfaceException
3305
+	 * @access public
3306
+	 */
3307
+	public function get_attendees($per_page, $count = false, $trash = false)
3308
+	{
3309
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3310
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3311
+		$ATT_MDL = EEM_Attendee::instance();
3312
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3313
+		switch ($this->_req_data['orderby']) {
3314
+			case 'ATT_ID':
3315
+				$orderby = 'ATT_ID';
3316
+				break;
3317
+			case 'ATT_fname':
3318
+				$orderby = 'ATT_fname';
3319
+				break;
3320
+			case 'ATT_email':
3321
+				$orderby = 'ATT_email';
3322
+				break;
3323
+			case 'ATT_city':
3324
+				$orderby = 'ATT_city';
3325
+				break;
3326
+			case 'STA_ID':
3327
+				$orderby = 'STA_ID';
3328
+				break;
3329
+			case 'CNT_ID':
3330
+				$orderby = 'CNT_ID';
3331
+				break;
3332
+			case 'Registration_Count':
3333
+				$orderby = 'Registration_Count';
3334
+				break;
3335
+			default:
3336
+				$orderby = 'ATT_lname';
3337
+		}
3338
+		$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3339
+			? $this->_req_data['order']
3340
+			: 'ASC';
3341
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3342
+			? $this->_req_data['paged']
3343
+			: 1;
3344
+		$per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3345
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3346
+			? $this->_req_data['perpage']
3347
+			: $per_page;
3348
+		$_where = array();
3349
+		if (! empty($this->_req_data['s'])) {
3350
+			$sstr = '%' . $this->_req_data['s'] . '%';
3351
+			$_where['OR'] = array(
3352
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3353
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3354
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3355
+				'ATT_fname'                         => array('LIKE', $sstr),
3356
+				'ATT_lname'                         => array('LIKE', $sstr),
3357
+				'ATT_short_bio'                     => array('LIKE', $sstr),
3358
+				'ATT_email'                         => array('LIKE', $sstr),
3359
+				'ATT_address'                       => array('LIKE', $sstr),
3360
+				'ATT_address2'                      => array('LIKE', $sstr),
3361
+				'ATT_city'                          => array('LIKE', $sstr),
3362
+				'Country.CNT_name'                  => array('LIKE', $sstr),
3363
+				'State.STA_name'                    => array('LIKE', $sstr),
3364
+				'ATT_phone'                         => array('LIKE', $sstr),
3365
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
3366
+				'Registration.REG_code'             => array('LIKE', $sstr),
3367
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
3368
+			);
3369
+		}
3370
+		$offset = ($current_page - 1) * $per_page;
3371
+		$limit = $count ? null : array($offset, $per_page);
3372
+		$query_args = array(
3373
+			$_where,
3374
+			'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3375
+			'limit'         => $limit,
3376
+		);
3377
+		if (! $count) {
3378
+			$query_args['order_by'] = array($orderby => $sort);
3379
+		}
3380
+		if ($trash) {
3381
+			$query_args[0]['status'] = array('!=', 'publish');
3382
+			$all_attendees = $count
3383
+				? $ATT_MDL->count($query_args, 'ATT_ID', true)
3384
+				: $ATT_MDL->get_all($query_args);
3385
+		} else {
3386
+			$query_args[0]['status'] = array('IN', array('publish'));
3387
+			$all_attendees = $count
3388
+				? $ATT_MDL->count($query_args, 'ATT_ID', true)
3389
+				: $ATT_MDL->get_all($query_args);
3390
+		}
3391
+		return $all_attendees;
3392
+	}
3393
+
3394
+
3395
+	/**
3396
+	 * This is just taking care of resending the registration confirmation
3397
+	 *
3398
+	 * @access protected
3399
+	 * @return void
3400
+	 */
3401
+	protected function _resend_registration()
3402
+	{
3403
+		$this->_process_resend_registration();
3404
+		$query_args = isset($this->_req_data['redirect_to'])
3405
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3406
+			: array('action' => 'default');
3407
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3408
+	}
3409
+
3410
+	/**
3411
+	 * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3412
+	 * to use when selecting registrations
3413
+	 *
3414
+	 * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3415
+	 *                                                     the query parameters from the request
3416
+	 * @return void ends the request with a redirect or download
3417
+	 */
3418
+	public function _registrations_report_base($method_name_for_getting_query_params)
3419
+	{
3420
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3421
+			wp_redirect(
3422
+				EE_Admin_Page::add_query_args_and_nonce(
3423
+					array(
3424
+						'page'        => 'espresso_batch',
3425
+						'batch'       => 'file',
3426
+						'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3427
+						'filters'     => urlencode(
3428
+							serialize(
3429
+								call_user_func(
3430
+									array($this, $method_name_for_getting_query_params),
3431
+									EEH_Array::is_set(
3432
+										$this->_req_data,
3433
+										'filters',
3434
+										array()
3435
+									)
3436
+								)
3437
+							)
3438
+						),
3439
+						'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3440
+						'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3441
+						'return_url'  => urlencode($this->_req_data['return_url']),
3442
+					)
3443
+				)
3444
+			);
3445
+		} else {
3446
+			$new_request_args = array(
3447
+				'export' => 'report',
3448
+				'action' => 'registrations_report_for_event',
3449
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3450
+			);
3451
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
3452
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3453
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3454
+				$EE_Export = EE_Export::instance($this->_req_data);
3455
+				$EE_Export->export();
3456
+			}
3457
+		}
3458
+	}
3459
+
3460
+
3461
+	/**
3462
+	 * Creates a registration report using only query parameters in the request
3463
+	 *
3464
+	 * @return void
3465
+	 */
3466
+	public function _registrations_report()
3467
+	{
3468
+		$this->_registrations_report_base('_get_registration_query_parameters');
3469
+	}
3470
+
3471
+
3472
+	public function _contact_list_export()
3473
+	{
3474
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3475
+			require_once(EE_CLASSES . 'EE_Export.class.php');
3476
+			$EE_Export = EE_Export::instance($this->_req_data);
3477
+			$EE_Export->export_attendees();
3478
+		}
3479
+	}
3480
+
3481
+
3482
+	public function _contact_list_report()
3483
+	{
3484
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3485
+			wp_redirect(
3486
+				EE_Admin_Page::add_query_args_and_nonce(
3487
+					array(
3488
+						'page'        => 'espresso_batch',
3489
+						'batch'       => 'file',
3490
+						'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3491
+						'return_url'  => urlencode($this->_req_data['return_url']),
3492
+					)
3493
+				)
3494
+			);
3495
+		} else {
3496
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3497
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3498
+				$EE_Export = EE_Export::instance($this->_req_data);
3499
+				$EE_Export->report_attendees();
3500
+			}
3501
+		}
3502
+	}
3503
+
3504
+
3505
+
3506
+
3507
+
3508
+	/***************************************        ATTENDEE DETAILS        ***************************************/
3509
+	/**
3510
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
3511
+	 *
3512
+	 * @return void
3513
+	 * @throws EE_Error
3514
+	 * @throws InvalidArgumentException
3515
+	 * @throws InvalidDataTypeException
3516
+	 * @throws InvalidInterfaceException
3517
+	 */
3518
+	protected function _duplicate_attendee()
3519
+	{
3520
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3521
+		// verify we have necessary info
3522
+		if (empty($this->_req_data['_REG_ID'])) {
3523
+			EE_Error::add_error(
3524
+				esc_html__(
3525
+					'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3526
+					'event_espresso'
3527
+				),
3528
+				__FILE__,
3529
+				__LINE__,
3530
+				__FUNCTION__
3531
+			);
3532
+			$query_args = array('action' => $action);
3533
+			$this->_redirect_after_action('', '', '', $query_args, true);
3534
+		}
3535
+		// okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3536
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3537
+		$attendee = $registration->attendee();
3538
+		// remove relation of existing attendee on registration
3539
+		$registration->_remove_relation_to($attendee, 'Attendee');
3540
+		// new attendee
3541
+		$new_attendee = clone $attendee;
3542
+		$new_attendee->set('ATT_ID', 0);
3543
+		$new_attendee->save();
3544
+		// add new attendee to reg
3545
+		$registration->_add_relation_to($new_attendee, 'Attendee');
3546
+		EE_Error::add_success(
3547
+			esc_html__(
3548
+				'New Contact record created.  Now make any edits you wish to make for this contact.',
3549
+				'event_espresso'
3550
+			)
3551
+		);
3552
+		// redirect to edit page for attendee
3553
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3554
+		$this->_redirect_after_action('', '', '', $query_args, true);
3555
+	}
3556
+
3557
+
3558
+	/**
3559
+	 * Callback invoked by parent EE_Admin_CPT class hooked in on `save_post` wp hook.
3560
+	 *
3561
+	 * @param int     $post_id
3562
+	 * @param WP_POST $post
3563
+	 * @throws DomainException
3564
+	 * @throws EE_Error
3565
+	 * @throws InvalidArgumentException
3566
+	 * @throws InvalidDataTypeException
3567
+	 * @throws InvalidInterfaceException
3568
+	 * @throws LogicException
3569
+	 * @throws InvalidFormSubmissionException
3570
+	 */
3571
+	protected function _insert_update_cpt_item($post_id, $post)
3572
+	{
3573
+		$success = true;
3574
+		$attendee = $post instanceof WP_Post && $post->post_type === 'espresso_attendees'
3575
+			? EEM_Attendee::instance()->get_one_by_ID($post_id)
3576
+			: null;
3577
+		// for attendee updates
3578
+		if ($attendee instanceof EE_Attendee) {
3579
+			// note we should only be UPDATING attendees at this point.
3580
+			$updated_fields = array(
3581
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
3582
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
3583
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3584
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3585
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3586
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3587
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3588
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3589
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3590
+			);
3591
+			foreach ($updated_fields as $field => $value) {
3592
+				$attendee->set($field, $value);
3593
+			}
3594
+
3595
+			// process contact details metabox form handler (which will also save the attendee)
3596
+			$contact_details_form = $this->getAttendeeContactDetailsMetaboxFormHandler($attendee);
3597
+			$success = $contact_details_form->process($this->_req_data);
3598
+
3599
+			$attendee_update_callbacks = apply_filters(
3600
+				'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3601
+				array()
3602
+			);
3603
+			foreach ($attendee_update_callbacks as $a_callback) {
3604
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3605
+					throw new EE_Error(
3606
+						sprintf(
3607
+							esc_html__(
3608
+								'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3609
+								'event_espresso'
3610
+							),
3611
+							$a_callback
3612
+						)
3613
+					);
3614
+				}
3615
+			}
3616
+		}
3617
+
3618
+		if ($success === false) {
3619
+			EE_Error::add_error(
3620
+				esc_html__(
3621
+					'Something went wrong with updating the meta table data for the registration.',
3622
+					'event_espresso'
3623
+				),
3624
+				__FILE__,
3625
+				__FUNCTION__,
3626
+				__LINE__
3627
+			);
3628
+		}
3629
+	}
3630
+
3631
+
3632
+	public function trash_cpt_item($post_id)
3633
+	{
3634
+	}
3635
+
3636
+
3637
+	public function delete_cpt_item($post_id)
3638
+	{
3639
+	}
3640
+
3641
+
3642
+	public function restore_cpt_item($post_id)
3643
+	{
3644
+	}
3645
+
3646
+
3647
+	protected function _restore_cpt_item($post_id, $revision_id)
3648
+	{
3649
+	}
3650
+
3651
+
3652
+	public function attendee_editor_metaboxes()
3653
+	{
3654
+		$this->verify_cpt_object();
3655
+		remove_meta_box(
3656
+			'postexcerpt',
3657
+			esc_html__('Excerpt', 'event_espresso'),
3658
+			'post_excerpt_meta_box',
3659
+			$this->_cpt_routes[ $this->_req_action ],
3660
+			'normal',
3661
+			'core'
3662
+		);
3663
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3664
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
3665
+			add_meta_box(
3666
+				'postexcerpt',
3667
+				esc_html__('Short Biography', 'event_espresso'),
3668
+				'post_excerpt_meta_box',
3669
+				$this->_cpt_routes[ $this->_req_action ],
3670
+				'normal'
3671
+			);
3672
+		}
3673
+		if (post_type_supports('espresso_attendees', 'comments')) {
3674
+			add_meta_box(
3675
+				'commentsdiv',
3676
+				esc_html__('Notes on the Contact', 'event_espresso'),
3677
+				'post_comment_meta_box',
3678
+				$this->_cpt_routes[ $this->_req_action ],
3679
+				'normal',
3680
+				'core'
3681
+			);
3682
+		}
3683
+		add_meta_box(
3684
+			'attendee_contact_info',
3685
+			esc_html__('Contact Info', 'event_espresso'),
3686
+			array($this, 'attendee_contact_info'),
3687
+			$this->_cpt_routes[ $this->_req_action ],
3688
+			'side',
3689
+			'core'
3690
+		);
3691
+		add_meta_box(
3692
+			'attendee_details_address',
3693
+			esc_html__('Address Details', 'event_espresso'),
3694
+			array($this, 'attendee_address_details'),
3695
+			$this->_cpt_routes[ $this->_req_action ],
3696
+			'normal',
3697
+			'core'
3698
+		);
3699
+		add_meta_box(
3700
+			'attendee_registrations',
3701
+			esc_html__('Registrations for this Contact', 'event_espresso'),
3702
+			array($this, 'attendee_registrations_meta_box'),
3703
+			$this->_cpt_routes[ $this->_req_action ],
3704
+			'normal',
3705
+			'high'
3706
+		);
3707
+	}
3708
+
3709
+
3710
+	/**
3711
+	 * Metabox for attendee contact info
3712
+	 *
3713
+	 * @param  WP_Post $post wp post object
3714
+	 * @return string attendee contact info ( and form )
3715
+	 * @throws EE_Error
3716
+	 * @throws InvalidArgumentException
3717
+	 * @throws InvalidDataTypeException
3718
+	 * @throws InvalidInterfaceException
3719
+	 * @throws LogicException
3720
+	 * @throws DomainException
3721
+	 */
3722
+	public function attendee_contact_info($post)
3723
+	{
3724
+		// get attendee object ( should already have it )
3725
+		$form = $this->getAttendeeContactDetailsMetaboxFormHandler($this->_cpt_model_obj);
3726
+		$form->enqueueStylesAndScripts();
3727
+		echo $form->display();
3728
+	}
3729
+
3730
+
3731
+	/**
3732
+	 * Return form handler for the contact details metabox
3733
+	 *
3734
+	 * @param EE_Attendee $attendee
3735
+	 * @return AttendeeContactDetailsMetaboxFormHandler
3736
+	 * @throws DomainException
3737
+	 * @throws InvalidArgumentException
3738
+	 * @throws InvalidDataTypeException
3739
+	 * @throws InvalidInterfaceException
3740
+	 */
3741
+	protected function getAttendeeContactDetailsMetaboxFormHandler(EE_Attendee $attendee)
3742
+	{
3743
+		return new AttendeeContactDetailsMetaboxFormHandler($attendee, EE_Registry::instance());
3744
+	}
3745
+
3746
+
3747
+	/**
3748
+	 * Metabox for attendee details
3749
+	 *
3750
+	 * @param  WP_Post $post wp post object
3751
+	 * @throws DomainException
3752
+	 */
3753
+	public function attendee_address_details($post)
3754
+	{
3755
+		// get attendee object (should already have it)
3756
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3757
+		$this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(
3758
+			new EE_Question_Form_Input(
3759
+				EE_Question::new_instance(
3760
+					array(
3761
+						'QST_ID'           => 0,
3762
+						'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3763
+						'QST_system'       => 'admin-state',
3764
+					)
3765
+				),
3766
+				EE_Answer::new_instance(
3767
+					array(
3768
+						'ANS_ID'    => 0,
3769
+						'ANS_value' => $this->_cpt_model_obj->state_ID(),
3770
+					)
3771
+				),
3772
+				array(
3773
+					'input_id'       => 'STA_ID',
3774
+					'input_name'     => 'STA_ID',
3775
+					'input_prefix'   => '',
3776
+					'append_qstn_id' => false,
3777
+				)
3778
+			)
3779
+		);
3780
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3781
+			new EE_Question_Form_Input(
3782
+				EE_Question::new_instance(
3783
+					array(
3784
+						'QST_ID'           => 0,
3785
+						'QST_display_text' => esc_html__('Country', 'event_espresso'),
3786
+						'QST_system'       => 'admin-country',
3787
+					)
3788
+				),
3789
+				EE_Answer::new_instance(
3790
+					array(
3791
+						'ANS_ID'    => 0,
3792
+						'ANS_value' => $this->_cpt_model_obj->country_ID(),
3793
+					)
3794
+				),
3795
+				array(
3796
+					'input_id'       => 'CNT_ISO',
3797
+					'input_name'     => 'CNT_ISO',
3798
+					'input_prefix'   => '',
3799
+					'append_qstn_id' => false,
3800
+				)
3801
+			)
3802
+		);
3803
+		$template =
3804
+			REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3805
+		EEH_Template::display_template($template, $this->_template_args);
3806
+	}
3807
+
3808
+
3809
+	/**
3810
+	 *        _attendee_details
3811
+	 *
3812
+	 * @access protected
3813
+	 * @param $post
3814
+	 * @return void
3815
+	 * @throws DomainException
3816
+	 * @throws EE_Error
3817
+	 */
3818
+	public function attendee_registrations_meta_box($post)
3819
+	{
3820
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3821
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3822
+		$template =
3823
+			REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3824
+		EEH_Template::display_template($template, $this->_template_args);
3825
+	}
3826
+
3827
+
3828
+	/**
3829
+	 * add in the form fields for the attendee edit
3830
+	 *
3831
+	 * @param  WP_Post $post wp post object
3832
+	 * @return string html for new form.
3833
+	 * @throws DomainException
3834
+	 */
3835
+	public function after_title_form_fields($post)
3836
+	{
3837
+		if ($post->post_type == 'espresso_attendees') {
3838
+			$template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3839
+			$template_args['attendee'] = $this->_cpt_model_obj;
3840
+			EEH_Template::display_template($template, $template_args);
3841
+		}
3842
+	}
3843
+
3844
+
3845
+	/**
3846
+	 *        _trash_or_restore_attendee
3847
+	 *
3848
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3849
+	 * @return void
3850
+	 * @throws EE_Error
3851
+	 * @throws InvalidArgumentException
3852
+	 * @throws InvalidDataTypeException
3853
+	 * @throws InvalidInterfaceException
3854
+	 * @access protected
3855
+	 */
3856
+	protected function _trash_or_restore_attendees($trash = true)
3857
+	{
3858
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3859
+		$ATT_MDL = EEM_Attendee::instance();
3860
+		$success = 1;
3861
+		// Checkboxes
3862
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3863
+			// if array has more than one element than success message should be plural
3864
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3865
+			// cycle thru checkboxes
3866
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3867
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3868
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3869
+				if (! $updated) {
3870
+					$success = 0;
3871
+				}
3872
+			}
3873
+		} else {
3874
+			// grab single id and delete
3875
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
3876
+			// get attendee
3877
+			$att = $ATT_MDL->get_one_by_ID($ATT_ID);
3878
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3879
+			$updated = $att->save();
3880
+			if (! $updated) {
3881
+				$success = 0;
3882
+			}
3883
+		}
3884
+		$what = $success > 1
3885
+			? esc_html__('Contacts', 'event_espresso')
3886
+			: esc_html__('Contact', 'event_espresso');
3887
+		$action_desc = $trash
3888
+			? esc_html__('moved to the trash', 'event_espresso')
3889
+			: esc_html__('restored', 'event_espresso');
3890
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3891
+	}
3892 3892
 }
Please login to merge, or discard this patch.
admin_pages/registration_form/Registration_Form_Admin_Page.core.php 1 patch
Indentation   +695 added lines, -695 removed lines patch added patch discarded remove patch
@@ -15,646 +15,646 @@  discard block
 block discarded – undo
15 15
 class Registration_Form_Admin_Page extends EE_Admin_Page
16 16
 {
17 17
 
18
-    /**
19
-     * _question
20
-     * holds the specific question object for the question details screen
21
-     *
22
-     * @var EE_Question $_question
23
-     */
24
-    protected $_question;
25
-
26
-    /**
27
-     * _question_group
28
-     * holds the specific question group object for the question group details screen
29
-     *
30
-     * @var EE_Question_Group $_question_group
31
-     */
32
-    protected $_question_group;
33
-
34
-    /**
35
-     *_question_model EEM_Question model instance (for queries)
36
-     *
37
-     * @var EEM_Question $_question_model ;
38
-     */
39
-    protected $_question_model;
40
-
41
-    /**
42
-     * _question_group_model EEM_Question_group instance (for queries)
43
-     *
44
-     * @var EEM_Question_Group $_question_group_model
45
-     */
46
-    protected $_question_group_model;
47
-
48
-
49
-    /**
50
-     * @Constructor
51
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
52
-     * @access public
53
-     */
54
-    public function __construct($routing = true)
55
-    {
56
-        require_once(EE_MODELS . 'EEM_Question.model.php');
57
-        require_once(EE_MODELS . 'EEM_Question_Group.model.php');
58
-        $this->_question_model = EEM_Question::instance();
59
-        $this->_question_group_model = EEM_Question_Group::instance();
60
-        parent::__construct($routing);
61
-    }
62
-
63
-
64
-    protected function _init_page_props()
65
-    {
66
-        $this->page_slug = REGISTRATION_FORM_PG_SLUG;
67
-        $this->page_label = esc_html__('Registration Form', 'event_espresso');
68
-        $this->_admin_base_url = REGISTRATION_FORM_ADMIN_URL;
69
-        $this->_admin_base_path = REGISTRATION_FORM_ADMIN;
70
-    }
71
-
72
-
73
-    protected function _ajax_hooks()
74
-    {
75
-    }
76
-
77
-
78
-    protected function _define_page_props()
79
-    {
80
-        $this->_admin_page_title = esc_html__('Registration Form', 'event_espresso');
81
-        $this->_labels = array(
82
-            'buttons' => array(
83
-                'edit_question' => esc_html__('Edit Question', 'event_espresso'),
84
-            ),
85
-        );
86
-    }
87
-
88
-
89
-    /**
90
-     *_set_page_routes
91
-     */
92
-    protected function _set_page_routes()
93
-    {
94
-        $qst_id = ! empty($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
95
-        $this->_page_routes = array(
96
-            'default' => array(
97
-                'func'       => '_questions_overview_list_table',
98
-                'capability' => 'ee_read_questions',
99
-            ),
100
-
101
-            'edit_question' => array(
102
-                'func'       => '_edit_question',
103
-                'capability' => 'ee_edit_question',
104
-                'obj_id'     => $qst_id,
105
-                'args'       => array('edit'),
106
-            ),
107
-
108
-            'question_groups' => array(
109
-                'func'       => '_questions_groups_preview',
110
-                'capability' => 'ee_read_question_groups',
111
-            ),
112
-
113
-            'update_question' => array(
114
-                'func'       => '_insert_or_update_question',
115
-                'args'       => array('new_question' => false),
116
-                'capability' => 'ee_edit_question',
117
-                'obj_id'     => $qst_id,
118
-                'noheader'   => true,
119
-            ),
120
-        );
121
-    }
122
-
123
-
124
-    protected function _set_page_config()
125
-    {
126
-        $this->_page_config = array(
127
-            'default' => array(
128
-                'nav'           => array(
129
-                    'label' => esc_html__('Questions', 'event_espresso'),
130
-                    'order' => 10,
131
-                ),
132
-                'list_table'    => 'Registration_Form_Questions_Admin_List_Table',
133
-                'metaboxes'     => $this->_default_espresso_metaboxes,
134
-                'help_tabs'     => array(
135
-                    'registration_form_questions_overview_help_tab'                           => array(
136
-                        'title'    => esc_html__('Questions Overview', 'event_espresso'),
137
-                        'filename' => 'registration_form_questions_overview',
138
-                    ),
139
-                    'registration_form_questions_overview_table_column_headings_help_tab'     => array(
140
-                        'title'    => esc_html__('Questions Overview Table Column Headings', 'event_espresso'),
141
-                        'filename' => 'registration_form_questions_overview_table_column_headings',
142
-                    ),
143
-                    'registration_form_questions_overview_views_bulk_actions_search_help_tab' => array(
144
-                        'title'    => esc_html__('Question Overview Views & Bulk Actions & Search', 'event_espresso'),
145
-                        'filename' => 'registration_form_questions_overview_views_bulk_actions_search',
146
-                    ),
147
-                ),
148
-                'help_tour'     => array('Registration_Form_Questions_Overview_Help_Tour'),
149
-                'require_nonce' => false,
150
-                'qtips'         => array(
151
-                    'EE_Registration_Form_Tips',
152
-                )/**/
153
-            ),
154
-
155
-            'question_groups' => array(
156
-                'nav'           => array(
157
-                    'label' => esc_html__('Question Groups', 'event_espresso'),
158
-                    'order' => 20,
159
-                ),
160
-                'metaboxes'     => $this->_default_espresso_metaboxes,
161
-                'help_tabs'     => array(
162
-                    'registration_form_question_groups_help_tab' => array(
163
-                        'title'    => esc_html__('Question Groups', 'event_espresso'),
164
-                        'filename' => 'registration_form_question_groups',
165
-                    ),
166
-                ),
167
-                'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
168
-                'require_nonce' => false,
169
-            ),
170
-
171
-            'edit_question' => array(
172
-                'nav'           => array(
173
-                    'label'      => esc_html__('Edit Question', 'event_espresso'),
174
-                    'order'      => 15,
175
-                    'persistent' => false,
176
-                    'url'        => isset($this->_req_data['question_id']) ? add_query_arg(
177
-                        array('question_id' => $this->_req_data['question_id']),
178
-                        $this->_current_page_view_url
179
-                    ) : $this->_admin_base_url,
180
-                ),
181
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
182
-                'help_tabs'     => array(
183
-                    'registration_form_edit_question_group_help_tab' => array(
184
-                        'title'    => esc_html__('Edit Question', 'event_espresso'),
185
-                        'filename' => 'registration_form_edit_question',
186
-                    ),
187
-                ),
188
-                'help_tour'     => array('Registration_Form_Edit_Question_Help_Tour'),
189
-                'require_nonce' => false,
190
-            ),
191
-        );
192
-    }
193
-
194
-
195
-    protected function _add_screen_options()
196
-    {
197
-        // todo
198
-    }
199
-
200
-    protected function _add_screen_options_default()
201
-    {
202
-        $page_title = $this->_admin_page_title;
203
-        $this->_admin_page_title = esc_html__('Questions', 'event_espresso');
204
-        $this->_per_page_screen_option();
205
-        $this->_admin_page_title = $page_title;
206
-    }
207
-
208
-    protected function _add_screen_options_question_groups()
209
-    {
210
-        $page_title = $this->_admin_page_title;
211
-        $this->_admin_page_title = esc_html__('Question Groups', 'event_espresso');
212
-        $this->_per_page_screen_option();
213
-        $this->_admin_page_title = $page_title;
214
-    }
215
-
216
-    // none of the below group are currently used for Event Categories
217
-    protected function _add_feature_pointers()
218
-    {
219
-    }
220
-
221
-    public function load_scripts_styles()
222
-    {
223
-        wp_register_style(
224
-            'espresso_registration',
225
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.css',
226
-            array(),
227
-            EVENT_ESPRESSO_VERSION
228
-        );
229
-        wp_enqueue_style('espresso_registration');
230
-    }
231
-
232
-    public function admin_init()
233
-    {
234
-    }
235
-
236
-    public function admin_notices()
237
-    {
238
-    }
239
-
240
-    public function admin_footer_scripts()
241
-    {
242
-    }
243
-
244
-
245
-    public function load_scripts_styles_default()
246
-    {
247
-    }
248
-
249
-
250
-    public function load_scripts_styles_add_question()
251
-    {
252
-        $this->load_scripts_styles_question_details();
253
-    }
254
-
255
-    public function load_scripts_styles_edit_question()
256
-    {
257
-        $this->load_scripts_styles_question_details();
258
-    }
259
-
260
-    /**
261
-     * Loads the JS required for adding or editing a question
262
-     */
263
-    protected function load_scripts_styles_question_details()
264
-    {
265
-        $this->load_scripts_styles_forms();
266
-        wp_register_script(
267
-            'espresso_registration_form_single',
268
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js',
269
-            array('jquery-ui-sortable'),
270
-            EVENT_ESPRESSO_VERSION,
271
-            true
272
-        );
273
-        wp_enqueue_script('espresso_registration_form_single');
274
-        wp_localize_script(
275
-            'espresso_registration_form_single',
276
-            'ee_question_data',
277
-            array(
278
-                'question_types_with_max'    => EEM_Question::instance()->questionTypesWithMaxLength(),
279
-                'question_type_with_options' => EEM_Question::instance()->question_types_with_options(),
280
-            )
281
-        );
282
-    }
283
-
284
-
285
-    public function recaptcha_info_help_tab()
286
-    {
287
-        $template = REGISTRATION_FORM_TEMPLATE_PATH . 'recaptcha_info_help_tab.template.php';
288
-        EEH_Template::display_template($template, array());
289
-    }
290
-
291
-
292
-    public function load_scripts_styles_forms()
293
-    {
294
-        // styles
295
-        wp_enqueue_style('espresso-ui-theme');
296
-        // scripts
297
-        wp_enqueue_script('ee_admin_js');
298
-    }
299
-
300
-
301
-    protected function _set_list_table_views_default()
302
-    {
303
-        $this->_views = array(
304
-            'all' => array(
305
-                'slug'  => 'all',
306
-                'label' => esc_html__('View All Questions', 'event_espresso'),
307
-                'count' => 0,
308
-            ),
309
-        );
310
-
311
-        if (EE_Registry::instance()->CAP->current_user_can(
312
-            'ee_delete_questions',
313
-            'espresso_registration_form_trash_questions'
314
-        )
315
-        ) {
316
-            $this->_views['trash'] = array(
317
-                'slug'  => 'trash',
318
-                'label' => esc_html__('Trash', 'event_espresso'),
319
-                'count' => 0,
320
-            );
321
-        }
322
-    }
323
-
324
-    /**
325
-     * This just previews the question groups tab that comes in caffeinated.
326
-     *
327
-     * @return string html
328
-     */
329
-    protected function _questions_groups_preview()
330
-    {
331
-        $this->_admin_page_title = esc_html__('Question Groups (Preview)', 'event_espresso');
332
-        $this->_template_args['preview_img'] = '<img src="' . REGISTRATION_FORM_ASSETS_URL . 'caf_reg_form_preview.jpg" alt="'
333
-                                               . esc_attr__(
334
-                                                   'Preview Question Groups Overview List Table screenshot',
335
-                                                   'event_espresso'
336
-                                               ) . '" />';
337
-        $this->_template_args['preview_text'] = '<strong>'
338
-                                                . esc_html__(
339
-                                                    'Question Groups is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Question Groups feature you are able to create new question groups, edit existing question groups, and create and edit new questions and add them to question groups.',
340
-                                                    'event_espresso'
341
-                                                ) . '</strong>';
342
-        $this->display_admin_caf_preview_page('question_groups_tab');
343
-    }
344
-
345
-
346
-    /**
347
-     * Extracts the question field's values from the POST request to update or insert them
348
-     *
349
-     * @param \EEM_Base $model
350
-     * @return array where each key is the name of a model's field/db column, and each value is its value.
351
-     */
352
-    protected function _set_column_values_for(EEM_Base $model)
353
-    {
354
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
355
-        $set_column_values = array();
356
-
357
-        // some initial checks for proper values.
358
-        // if QST_admin_only, then no matter what QST_required is we disable.
359
-        if (! empty($this->_req_data['QST_admin_only'])) {
360
-            $this->_req_data['QST_required'] = 0;
361
-        }
362
-        // if the question shouldn't have a max length, don't let them set one
363
-        if (! isset(
364
-            $this->_req_data['QST_type'],
365
-            $this->_req_data['QST_max']
366
-        )
367
-            || ! in_array(
368
-                $this->_req_data['QST_type'],
369
-                EEM_Question::instance()->questionTypesWithMaxLength(),
370
-                true
371
-            )
372
-        ) {
373
-            // they're not allowed to set the max
374
-            $this->_req_data['QST_max'] = null;
375
-        }
376
-        foreach ($model->field_settings() as $fieldName => $settings) {
377
-            // basically if QSG_identifier is empty or not set
378
-            if ($fieldName === 'QSG_identifier' && (isset($this->_req_data['QSG_identifier']) && empty($this->_req_data['QSG_identifier']))) {
379
-                $QSG_name = isset($this->_req_data['QSG_name']) ? $this->_req_data['QSG_name'] : '';
380
-                $set_column_values[ $fieldName ] = sanitize_title($QSG_name) . '-' . uniqid('', true);
381
-            } //if the admin label is blank, use a slug version of the question text
382
-            elseif ($fieldName === 'QST_admin_label' && (isset($this->_req_data['QST_admin_label']) && empty($this->_req_data['QST_admin_label']))) {
383
-                $QST_text = isset($this->_req_data['QST_display_text']) ? $this->_req_data['QST_display_text'] : '';
384
-                $set_column_values[ $fieldName ] = sanitize_title(wp_trim_words($QST_text, 10));
385
-            } elseif ($fieldName === 'QST_admin_only' && (! isset($this->_req_data['QST_admin_only']))) {
386
-                $set_column_values[ $fieldName ] = 0;
387
-            } elseif ($fieldName === 'QST_max') {
388
-                $qst_system = EEM_Question::instance()->get_var(
389
-                    array(
390
-                        array(
391
-                            'QST_ID' => isset($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0,
392
-                        ),
393
-                    ),
394
-                    'QST_system'
395
-                );
396
-                $max_max = EEM_Question::instance()->absolute_max_for_system_question($qst_system);
397
-                if (empty($this->_req_data['QST_max']) ||
398
-                    $this->_req_data['QST_max'] > $max_max
399
-                ) {
400
-                    $set_column_values[ $fieldName ] = $max_max;
401
-                }
402
-            }
403
-
404
-
405
-            // only add a property to the array if it's not null (otherwise the model should just use the default value)
406
-            if (! isset($set_column_values[ $fieldName ]) &&
407
-                isset($this->_req_data[ $fieldName ])
408
-            ) {
409
-                $set_column_values[ $fieldName ] = $this->_req_data[ $fieldName ];
410
-            }
411
-        }
412
-        return $set_column_values;// validation fo this data to be performed by the model before insertion.
413
-    }
414
-
415
-
416
-    /**
417
-     *_questions_overview_list_table
418
-     */
419
-    protected function _questions_overview_list_table()
420
-    {
421
-        $this->_search_btn_label = esc_html__('Questions', 'event_espresso');
422
-        $this->display_admin_list_table_page_with_sidebar();
423
-    }
424
-
425
-
426
-    /**
427
-     * _edit_question
428
-     */
429
-    protected function _edit_question()
430
-    {
431
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
432
-        $ID = isset($this->_req_data['QST_ID']) && ! empty($this->_req_data['QST_ID']) ? absint(
433
-            $this->_req_data['QST_ID']
434
-        ) : false;
435
-
436
-        switch ($this->_req_action) {
437
-            case 'add_question':
438
-                $this->_admin_page_title = esc_html__('Add Question', 'event_espresso');
439
-                break;
440
-            case 'edit_question':
441
-                $this->_admin_page_title = esc_html__('Edit Question', 'event_espresso');
442
-                break;
443
-            default:
444
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
445
-        }
446
-
447
-        // add PRC_ID to title if editing
448
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
449
-        if ($ID) {
450
-            $question = $this->_question_model->get_one_by_ID($ID);
451
-            $additional_hidden_fields = array('QST_ID' => array('type' => 'hidden', 'value' => $ID));
452
-            $this->_set_add_edit_form_tags('update_question', $additional_hidden_fields);
453
-        } else {
454
-            $question = EE_Question::new_instance();
455
-            $question->set_order_to_latest();
456
-            $this->_set_add_edit_form_tags('insert_question');
457
-        }
458
-        if ($question->system_ID() === EEM_Attendee::system_question_phone) {
459
-            $question_types = array_intersect_key(
460
-                EEM_Question::instance()->allowed_question_types(),
461
-                array_flip(
462
-                    array(
463
-                        EEM_Question::QST_type_text,
464
-                        EEM_Question::QST_type_us_phone,
465
-                    )
466
-                )
467
-            );
468
-        } else {
469
-            $question_types = $question->has_answers() ? $this->_question_model->question_types_in_same_category(
470
-                $question->type()
471
-            ) : $this->_question_model->allowed_question_types();
472
-        }
473
-        $this->_template_args['QST_ID'] = $ID;
474
-        $this->_template_args['question'] = $question;
475
-        $this->_template_args['question_types'] = $question_types;
476
-        $this->_template_args['max_max'] = EEM_Question::instance()->absolute_max_for_system_question(
477
-            $question->system_ID()
478
-        );
479
-        $this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
480
-        $this->_set_publish_post_box_vars('id', $ID);
481
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
482
-            REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
483
-            $this->_template_args,
484
-            true
485
-        );
486
-
487
-        // the details template wrapper
488
-        $this->display_admin_page_with_sidebar();
489
-    }
490
-
491
-
492
-    /**
493
-     * @return string
494
-     */
495
-    protected function _get_question_type_descriptions()
496
-    {
497
-        EE_Registry::instance()->load_helper('HTML');
498
-        $descriptions = '';
499
-        $question_type_descriptions = EEM_Question::instance()->question_descriptions();
500
-        foreach ($question_type_descriptions as $type => $question_type_description) {
501
-            if ($type == 'HTML_TEXTAREA') {
502
-                $html = new EE_Simple_HTML_Validation_Strategy();
503
-                $question_type_description .= sprintf(
504
-                    esc_html__('%1$s(allowed tags: %2$s)', 'event_espresso'),
505
-                    '<br/>',
506
-                    $html->get_list_of_allowed_tags()
507
-                );
508
-            }
509
-            $descriptions .= EEH_HTML::p(
510
-                $question_type_description,
511
-                'question_type_description-' . $type,
512
-                'question_type_description description',
513
-                'display:none;'
514
-            );
515
-        }
516
-        return $descriptions;
517
-    }
518
-
519
-
520
-    /**
521
-     * @param bool|true $new_question
522
-     * @throws \EE_Error
523
-     */
524
-    protected function _insert_or_update_question($new_question = true)
525
-    {
526
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
527
-        $set_column_values = $this->_set_column_values_for($this->_question_model);
528
-        if ($new_question) {
529
-            $question = EE_Question::new_instance($set_column_values);
530
-            $action_desc = 'added';
531
-        } else {
532
-            $question = EEM_Question::instance()->get_one_by_ID(absint($this->_req_data['QST_ID']));
533
-            foreach ($set_column_values as $field => $new_value) {
534
-                $question->set($field, $new_value);
535
-            }
536
-            $action_desc = 'updated';
537
-        }
538
-        $success = $question->save();
539
-        $ID = $question->ID();
540
-        if ($ID && $question->should_have_question_options()) {
541
-            // save the related options
542
-            // trash removed options, save old ones
543
-            // get list of all options
544
-            $options = $question->options();
545
-            if (! empty($options)) {
546
-                foreach ($options as $option_ID => $option) {
547
-                    $option_req_index = $this->_get_option_req_data_index($option_ID);
548
-                    if ($option_req_index !== false) {
549
-                        $option->save($this->_req_data['question_options'][ $option_req_index ]);
550
-                    } else {
551
-                        // not found, remove it
552
-                        $option->delete();
553
-                    }
554
-                }
555
-            }
556
-            // save new related options
557
-            foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
558
-                // skip $index that is from our sample
559
-                if ($index === 'xxcountxx') {
560
-                    continue;
561
-                }
562
-                // note we allow saving blank options.
563
-                if (empty($option_req_data['QSO_ID'])
564
-                ) {// no ID! save it!
565
-                    $new_option = EE_Question_Option::new_instance(
566
-                        array(
567
-                            'QSO_value' => $option_req_data['QSO_value'],
568
-                            'QSO_desc'  => $option_req_data['QSO_desc'],
569
-                            'QSO_order' => $option_req_data['QSO_order'],
570
-                            'QST_ID'    => $question->ID(),
571
-                        )
572
-                    );
573
-                    $new_option->save();
574
-                }
575
-            }
576
-        }
577
-        $query_args = array('action' => 'edit_question', 'QST_ID' => $ID);
578
-        if ($success !== false) {
579
-            $msg = $new_question
580
-                ? sprintf(
581
-                    esc_html__('The %s has been created', 'event_espresso'),
582
-                    $this->_question_model->item_name()
583
-                )
584
-                : sprintf(
585
-                    esc_html__('The %s has been updated', 'event_espresso'),
586
-                    $this->_question_model->item_name()
587
-                );
588
-            EE_Error::add_success($msg);
589
-        }
590
-
591
-        $this->_redirect_after_action(false, '', $action_desc, $query_args, true);
592
-    }
593
-
594
-
595
-    /**
596
-     * Upon saving a question, there should be an array of 'question_options'. This array is index numerically, but not
597
-     * by ID
598
-     * (this is done because new question options don't have an ID, but we may want to add multiple simultaneously).
599
-     * So, this function gets the index in that request data array called question_options. Returns FALSE if not found.
600
-     *
601
-     * @param int $ID of the question option to find
602
-     * @return int index in question_options array if successful, FALSE if unsuccessful
603
-     */
604
-    protected function _get_option_req_data_index($ID)
605
-    {
606
-        $req_data_for_question_options = $this->_req_data['question_options'];
607
-        foreach ($req_data_for_question_options as $num => $option_data) {
608
-            if (array_key_exists('QSO_ID', $option_data) && (int) $option_data['QSO_ID'] === $ID) {
609
-                return $num;
610
-            }
611
-        }
612
-        return false;
613
-    }
614
-
615
-
616
-
617
-
618
-    /***********/
619
-    /* QUERIES */
620
-    /**
621
-     * For internal use in getting all the query parameters
622
-     * (because it's pretty well the same between question, question groups,
623
-     * and for both when searching for trashed and untrashed ones)
624
-     *
625
-     * @param EEM_Base $model either EEM_Question or EEM_Question_Group
626
-     * @param int      $per_page
627
-     * @param int      $current_page
628
-     * @return array model query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
629
-     */
630
-    protected function get_query_params($model, $per_page = 10, $current_page = 10)
631
-    {
632
-        $query_params = array();
633
-        $offset = ($current_page - 1) * $per_page;
634
-        $query_params['limit'] = array($offset, $per_page);
635
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
636
-            : 'ASC';
637
-        $orderby_field = $model instanceof EEM_Question ? 'QST_ID' : 'QSG_order';
638
-        $field_to_order_by = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
639
-        $query_params['order_by'] = array($field_to_order_by => $order);
640
-        $search_string = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
641
-        if (! empty($search_string)) {
642
-            if ($model instanceof EEM_Question_Group) {
643
-                $query_params[0] = array(
644
-                    'OR' => array(
645
-                        'QSG_name' => array('LIKE', "%$search_string%"),
646
-                        'QSG_desc' => array('LIKE', "%$search_string%"),
647
-                    ),
648
-                );
649
-            } else {
650
-                $query_params[0] = array(
651
-                    'QST_display_text' => array('LIKE', "%$search_string%"),
652
-                );
653
-            }
654
-        }
655
-
656
-        // capability checks (just leaving this commented out for reference because it illustrates some complicated query params that could be useful when fully implemented)
657
-        /*if ( $model instanceof EEM_Question_Group ) {
18
+	/**
19
+	 * _question
20
+	 * holds the specific question object for the question details screen
21
+	 *
22
+	 * @var EE_Question $_question
23
+	 */
24
+	protected $_question;
25
+
26
+	/**
27
+	 * _question_group
28
+	 * holds the specific question group object for the question group details screen
29
+	 *
30
+	 * @var EE_Question_Group $_question_group
31
+	 */
32
+	protected $_question_group;
33
+
34
+	/**
35
+	 *_question_model EEM_Question model instance (for queries)
36
+	 *
37
+	 * @var EEM_Question $_question_model ;
38
+	 */
39
+	protected $_question_model;
40
+
41
+	/**
42
+	 * _question_group_model EEM_Question_group instance (for queries)
43
+	 *
44
+	 * @var EEM_Question_Group $_question_group_model
45
+	 */
46
+	protected $_question_group_model;
47
+
48
+
49
+	/**
50
+	 * @Constructor
51
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
52
+	 * @access public
53
+	 */
54
+	public function __construct($routing = true)
55
+	{
56
+		require_once(EE_MODELS . 'EEM_Question.model.php');
57
+		require_once(EE_MODELS . 'EEM_Question_Group.model.php');
58
+		$this->_question_model = EEM_Question::instance();
59
+		$this->_question_group_model = EEM_Question_Group::instance();
60
+		parent::__construct($routing);
61
+	}
62
+
63
+
64
+	protected function _init_page_props()
65
+	{
66
+		$this->page_slug = REGISTRATION_FORM_PG_SLUG;
67
+		$this->page_label = esc_html__('Registration Form', 'event_espresso');
68
+		$this->_admin_base_url = REGISTRATION_FORM_ADMIN_URL;
69
+		$this->_admin_base_path = REGISTRATION_FORM_ADMIN;
70
+	}
71
+
72
+
73
+	protected function _ajax_hooks()
74
+	{
75
+	}
76
+
77
+
78
+	protected function _define_page_props()
79
+	{
80
+		$this->_admin_page_title = esc_html__('Registration Form', 'event_espresso');
81
+		$this->_labels = array(
82
+			'buttons' => array(
83
+				'edit_question' => esc_html__('Edit Question', 'event_espresso'),
84
+			),
85
+		);
86
+	}
87
+
88
+
89
+	/**
90
+	 *_set_page_routes
91
+	 */
92
+	protected function _set_page_routes()
93
+	{
94
+		$qst_id = ! empty($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
95
+		$this->_page_routes = array(
96
+			'default' => array(
97
+				'func'       => '_questions_overview_list_table',
98
+				'capability' => 'ee_read_questions',
99
+			),
100
+
101
+			'edit_question' => array(
102
+				'func'       => '_edit_question',
103
+				'capability' => 'ee_edit_question',
104
+				'obj_id'     => $qst_id,
105
+				'args'       => array('edit'),
106
+			),
107
+
108
+			'question_groups' => array(
109
+				'func'       => '_questions_groups_preview',
110
+				'capability' => 'ee_read_question_groups',
111
+			),
112
+
113
+			'update_question' => array(
114
+				'func'       => '_insert_or_update_question',
115
+				'args'       => array('new_question' => false),
116
+				'capability' => 'ee_edit_question',
117
+				'obj_id'     => $qst_id,
118
+				'noheader'   => true,
119
+			),
120
+		);
121
+	}
122
+
123
+
124
+	protected function _set_page_config()
125
+	{
126
+		$this->_page_config = array(
127
+			'default' => array(
128
+				'nav'           => array(
129
+					'label' => esc_html__('Questions', 'event_espresso'),
130
+					'order' => 10,
131
+				),
132
+				'list_table'    => 'Registration_Form_Questions_Admin_List_Table',
133
+				'metaboxes'     => $this->_default_espresso_metaboxes,
134
+				'help_tabs'     => array(
135
+					'registration_form_questions_overview_help_tab'                           => array(
136
+						'title'    => esc_html__('Questions Overview', 'event_espresso'),
137
+						'filename' => 'registration_form_questions_overview',
138
+					),
139
+					'registration_form_questions_overview_table_column_headings_help_tab'     => array(
140
+						'title'    => esc_html__('Questions Overview Table Column Headings', 'event_espresso'),
141
+						'filename' => 'registration_form_questions_overview_table_column_headings',
142
+					),
143
+					'registration_form_questions_overview_views_bulk_actions_search_help_tab' => array(
144
+						'title'    => esc_html__('Question Overview Views & Bulk Actions & Search', 'event_espresso'),
145
+						'filename' => 'registration_form_questions_overview_views_bulk_actions_search',
146
+					),
147
+				),
148
+				'help_tour'     => array('Registration_Form_Questions_Overview_Help_Tour'),
149
+				'require_nonce' => false,
150
+				'qtips'         => array(
151
+					'EE_Registration_Form_Tips',
152
+				)/**/
153
+			),
154
+
155
+			'question_groups' => array(
156
+				'nav'           => array(
157
+					'label' => esc_html__('Question Groups', 'event_espresso'),
158
+					'order' => 20,
159
+				),
160
+				'metaboxes'     => $this->_default_espresso_metaboxes,
161
+				'help_tabs'     => array(
162
+					'registration_form_question_groups_help_tab' => array(
163
+						'title'    => esc_html__('Question Groups', 'event_espresso'),
164
+						'filename' => 'registration_form_question_groups',
165
+					),
166
+				),
167
+				'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
168
+				'require_nonce' => false,
169
+			),
170
+
171
+			'edit_question' => array(
172
+				'nav'           => array(
173
+					'label'      => esc_html__('Edit Question', 'event_espresso'),
174
+					'order'      => 15,
175
+					'persistent' => false,
176
+					'url'        => isset($this->_req_data['question_id']) ? add_query_arg(
177
+						array('question_id' => $this->_req_data['question_id']),
178
+						$this->_current_page_view_url
179
+					) : $this->_admin_base_url,
180
+				),
181
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
182
+				'help_tabs'     => array(
183
+					'registration_form_edit_question_group_help_tab' => array(
184
+						'title'    => esc_html__('Edit Question', 'event_espresso'),
185
+						'filename' => 'registration_form_edit_question',
186
+					),
187
+				),
188
+				'help_tour'     => array('Registration_Form_Edit_Question_Help_Tour'),
189
+				'require_nonce' => false,
190
+			),
191
+		);
192
+	}
193
+
194
+
195
+	protected function _add_screen_options()
196
+	{
197
+		// todo
198
+	}
199
+
200
+	protected function _add_screen_options_default()
201
+	{
202
+		$page_title = $this->_admin_page_title;
203
+		$this->_admin_page_title = esc_html__('Questions', 'event_espresso');
204
+		$this->_per_page_screen_option();
205
+		$this->_admin_page_title = $page_title;
206
+	}
207
+
208
+	protected function _add_screen_options_question_groups()
209
+	{
210
+		$page_title = $this->_admin_page_title;
211
+		$this->_admin_page_title = esc_html__('Question Groups', 'event_espresso');
212
+		$this->_per_page_screen_option();
213
+		$this->_admin_page_title = $page_title;
214
+	}
215
+
216
+	// none of the below group are currently used for Event Categories
217
+	protected function _add_feature_pointers()
218
+	{
219
+	}
220
+
221
+	public function load_scripts_styles()
222
+	{
223
+		wp_register_style(
224
+			'espresso_registration',
225
+			REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.css',
226
+			array(),
227
+			EVENT_ESPRESSO_VERSION
228
+		);
229
+		wp_enqueue_style('espresso_registration');
230
+	}
231
+
232
+	public function admin_init()
233
+	{
234
+	}
235
+
236
+	public function admin_notices()
237
+	{
238
+	}
239
+
240
+	public function admin_footer_scripts()
241
+	{
242
+	}
243
+
244
+
245
+	public function load_scripts_styles_default()
246
+	{
247
+	}
248
+
249
+
250
+	public function load_scripts_styles_add_question()
251
+	{
252
+		$this->load_scripts_styles_question_details();
253
+	}
254
+
255
+	public function load_scripts_styles_edit_question()
256
+	{
257
+		$this->load_scripts_styles_question_details();
258
+	}
259
+
260
+	/**
261
+	 * Loads the JS required for adding or editing a question
262
+	 */
263
+	protected function load_scripts_styles_question_details()
264
+	{
265
+		$this->load_scripts_styles_forms();
266
+		wp_register_script(
267
+			'espresso_registration_form_single',
268
+			REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js',
269
+			array('jquery-ui-sortable'),
270
+			EVENT_ESPRESSO_VERSION,
271
+			true
272
+		);
273
+		wp_enqueue_script('espresso_registration_form_single');
274
+		wp_localize_script(
275
+			'espresso_registration_form_single',
276
+			'ee_question_data',
277
+			array(
278
+				'question_types_with_max'    => EEM_Question::instance()->questionTypesWithMaxLength(),
279
+				'question_type_with_options' => EEM_Question::instance()->question_types_with_options(),
280
+			)
281
+		);
282
+	}
283
+
284
+
285
+	public function recaptcha_info_help_tab()
286
+	{
287
+		$template = REGISTRATION_FORM_TEMPLATE_PATH . 'recaptcha_info_help_tab.template.php';
288
+		EEH_Template::display_template($template, array());
289
+	}
290
+
291
+
292
+	public function load_scripts_styles_forms()
293
+	{
294
+		// styles
295
+		wp_enqueue_style('espresso-ui-theme');
296
+		// scripts
297
+		wp_enqueue_script('ee_admin_js');
298
+	}
299
+
300
+
301
+	protected function _set_list_table_views_default()
302
+	{
303
+		$this->_views = array(
304
+			'all' => array(
305
+				'slug'  => 'all',
306
+				'label' => esc_html__('View All Questions', 'event_espresso'),
307
+				'count' => 0,
308
+			),
309
+		);
310
+
311
+		if (EE_Registry::instance()->CAP->current_user_can(
312
+			'ee_delete_questions',
313
+			'espresso_registration_form_trash_questions'
314
+		)
315
+		) {
316
+			$this->_views['trash'] = array(
317
+				'slug'  => 'trash',
318
+				'label' => esc_html__('Trash', 'event_espresso'),
319
+				'count' => 0,
320
+			);
321
+		}
322
+	}
323
+
324
+	/**
325
+	 * This just previews the question groups tab that comes in caffeinated.
326
+	 *
327
+	 * @return string html
328
+	 */
329
+	protected function _questions_groups_preview()
330
+	{
331
+		$this->_admin_page_title = esc_html__('Question Groups (Preview)', 'event_espresso');
332
+		$this->_template_args['preview_img'] = '<img src="' . REGISTRATION_FORM_ASSETS_URL . 'caf_reg_form_preview.jpg" alt="'
333
+											   . esc_attr__(
334
+												   'Preview Question Groups Overview List Table screenshot',
335
+												   'event_espresso'
336
+											   ) . '" />';
337
+		$this->_template_args['preview_text'] = '<strong>'
338
+												. esc_html__(
339
+													'Question Groups is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Question Groups feature you are able to create new question groups, edit existing question groups, and create and edit new questions and add them to question groups.',
340
+													'event_espresso'
341
+												) . '</strong>';
342
+		$this->display_admin_caf_preview_page('question_groups_tab');
343
+	}
344
+
345
+
346
+	/**
347
+	 * Extracts the question field's values from the POST request to update or insert them
348
+	 *
349
+	 * @param \EEM_Base $model
350
+	 * @return array where each key is the name of a model's field/db column, and each value is its value.
351
+	 */
352
+	protected function _set_column_values_for(EEM_Base $model)
353
+	{
354
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
355
+		$set_column_values = array();
356
+
357
+		// some initial checks for proper values.
358
+		// if QST_admin_only, then no matter what QST_required is we disable.
359
+		if (! empty($this->_req_data['QST_admin_only'])) {
360
+			$this->_req_data['QST_required'] = 0;
361
+		}
362
+		// if the question shouldn't have a max length, don't let them set one
363
+		if (! isset(
364
+			$this->_req_data['QST_type'],
365
+			$this->_req_data['QST_max']
366
+		)
367
+			|| ! in_array(
368
+				$this->_req_data['QST_type'],
369
+				EEM_Question::instance()->questionTypesWithMaxLength(),
370
+				true
371
+			)
372
+		) {
373
+			// they're not allowed to set the max
374
+			$this->_req_data['QST_max'] = null;
375
+		}
376
+		foreach ($model->field_settings() as $fieldName => $settings) {
377
+			// basically if QSG_identifier is empty or not set
378
+			if ($fieldName === 'QSG_identifier' && (isset($this->_req_data['QSG_identifier']) && empty($this->_req_data['QSG_identifier']))) {
379
+				$QSG_name = isset($this->_req_data['QSG_name']) ? $this->_req_data['QSG_name'] : '';
380
+				$set_column_values[ $fieldName ] = sanitize_title($QSG_name) . '-' . uniqid('', true);
381
+			} //if the admin label is blank, use a slug version of the question text
382
+			elseif ($fieldName === 'QST_admin_label' && (isset($this->_req_data['QST_admin_label']) && empty($this->_req_data['QST_admin_label']))) {
383
+				$QST_text = isset($this->_req_data['QST_display_text']) ? $this->_req_data['QST_display_text'] : '';
384
+				$set_column_values[ $fieldName ] = sanitize_title(wp_trim_words($QST_text, 10));
385
+			} elseif ($fieldName === 'QST_admin_only' && (! isset($this->_req_data['QST_admin_only']))) {
386
+				$set_column_values[ $fieldName ] = 0;
387
+			} elseif ($fieldName === 'QST_max') {
388
+				$qst_system = EEM_Question::instance()->get_var(
389
+					array(
390
+						array(
391
+							'QST_ID' => isset($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0,
392
+						),
393
+					),
394
+					'QST_system'
395
+				);
396
+				$max_max = EEM_Question::instance()->absolute_max_for_system_question($qst_system);
397
+				if (empty($this->_req_data['QST_max']) ||
398
+					$this->_req_data['QST_max'] > $max_max
399
+				) {
400
+					$set_column_values[ $fieldName ] = $max_max;
401
+				}
402
+			}
403
+
404
+
405
+			// only add a property to the array if it's not null (otherwise the model should just use the default value)
406
+			if (! isset($set_column_values[ $fieldName ]) &&
407
+				isset($this->_req_data[ $fieldName ])
408
+			) {
409
+				$set_column_values[ $fieldName ] = $this->_req_data[ $fieldName ];
410
+			}
411
+		}
412
+		return $set_column_values;// validation fo this data to be performed by the model before insertion.
413
+	}
414
+
415
+
416
+	/**
417
+	 *_questions_overview_list_table
418
+	 */
419
+	protected function _questions_overview_list_table()
420
+	{
421
+		$this->_search_btn_label = esc_html__('Questions', 'event_espresso');
422
+		$this->display_admin_list_table_page_with_sidebar();
423
+	}
424
+
425
+
426
+	/**
427
+	 * _edit_question
428
+	 */
429
+	protected function _edit_question()
430
+	{
431
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
432
+		$ID = isset($this->_req_data['QST_ID']) && ! empty($this->_req_data['QST_ID']) ? absint(
433
+			$this->_req_data['QST_ID']
434
+		) : false;
435
+
436
+		switch ($this->_req_action) {
437
+			case 'add_question':
438
+				$this->_admin_page_title = esc_html__('Add Question', 'event_espresso');
439
+				break;
440
+			case 'edit_question':
441
+				$this->_admin_page_title = esc_html__('Edit Question', 'event_espresso');
442
+				break;
443
+			default:
444
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
445
+		}
446
+
447
+		// add PRC_ID to title if editing
448
+		$this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
449
+		if ($ID) {
450
+			$question = $this->_question_model->get_one_by_ID($ID);
451
+			$additional_hidden_fields = array('QST_ID' => array('type' => 'hidden', 'value' => $ID));
452
+			$this->_set_add_edit_form_tags('update_question', $additional_hidden_fields);
453
+		} else {
454
+			$question = EE_Question::new_instance();
455
+			$question->set_order_to_latest();
456
+			$this->_set_add_edit_form_tags('insert_question');
457
+		}
458
+		if ($question->system_ID() === EEM_Attendee::system_question_phone) {
459
+			$question_types = array_intersect_key(
460
+				EEM_Question::instance()->allowed_question_types(),
461
+				array_flip(
462
+					array(
463
+						EEM_Question::QST_type_text,
464
+						EEM_Question::QST_type_us_phone,
465
+					)
466
+				)
467
+			);
468
+		} else {
469
+			$question_types = $question->has_answers() ? $this->_question_model->question_types_in_same_category(
470
+				$question->type()
471
+			) : $this->_question_model->allowed_question_types();
472
+		}
473
+		$this->_template_args['QST_ID'] = $ID;
474
+		$this->_template_args['question'] = $question;
475
+		$this->_template_args['question_types'] = $question_types;
476
+		$this->_template_args['max_max'] = EEM_Question::instance()->absolute_max_for_system_question(
477
+			$question->system_ID()
478
+		);
479
+		$this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
480
+		$this->_set_publish_post_box_vars('id', $ID);
481
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
482
+			REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
483
+			$this->_template_args,
484
+			true
485
+		);
486
+
487
+		// the details template wrapper
488
+		$this->display_admin_page_with_sidebar();
489
+	}
490
+
491
+
492
+	/**
493
+	 * @return string
494
+	 */
495
+	protected function _get_question_type_descriptions()
496
+	{
497
+		EE_Registry::instance()->load_helper('HTML');
498
+		$descriptions = '';
499
+		$question_type_descriptions = EEM_Question::instance()->question_descriptions();
500
+		foreach ($question_type_descriptions as $type => $question_type_description) {
501
+			if ($type == 'HTML_TEXTAREA') {
502
+				$html = new EE_Simple_HTML_Validation_Strategy();
503
+				$question_type_description .= sprintf(
504
+					esc_html__('%1$s(allowed tags: %2$s)', 'event_espresso'),
505
+					'<br/>',
506
+					$html->get_list_of_allowed_tags()
507
+				);
508
+			}
509
+			$descriptions .= EEH_HTML::p(
510
+				$question_type_description,
511
+				'question_type_description-' . $type,
512
+				'question_type_description description',
513
+				'display:none;'
514
+			);
515
+		}
516
+		return $descriptions;
517
+	}
518
+
519
+
520
+	/**
521
+	 * @param bool|true $new_question
522
+	 * @throws \EE_Error
523
+	 */
524
+	protected function _insert_or_update_question($new_question = true)
525
+	{
526
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
527
+		$set_column_values = $this->_set_column_values_for($this->_question_model);
528
+		if ($new_question) {
529
+			$question = EE_Question::new_instance($set_column_values);
530
+			$action_desc = 'added';
531
+		} else {
532
+			$question = EEM_Question::instance()->get_one_by_ID(absint($this->_req_data['QST_ID']));
533
+			foreach ($set_column_values as $field => $new_value) {
534
+				$question->set($field, $new_value);
535
+			}
536
+			$action_desc = 'updated';
537
+		}
538
+		$success = $question->save();
539
+		$ID = $question->ID();
540
+		if ($ID && $question->should_have_question_options()) {
541
+			// save the related options
542
+			// trash removed options, save old ones
543
+			// get list of all options
544
+			$options = $question->options();
545
+			if (! empty($options)) {
546
+				foreach ($options as $option_ID => $option) {
547
+					$option_req_index = $this->_get_option_req_data_index($option_ID);
548
+					if ($option_req_index !== false) {
549
+						$option->save($this->_req_data['question_options'][ $option_req_index ]);
550
+					} else {
551
+						// not found, remove it
552
+						$option->delete();
553
+					}
554
+				}
555
+			}
556
+			// save new related options
557
+			foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
558
+				// skip $index that is from our sample
559
+				if ($index === 'xxcountxx') {
560
+					continue;
561
+				}
562
+				// note we allow saving blank options.
563
+				if (empty($option_req_data['QSO_ID'])
564
+				) {// no ID! save it!
565
+					$new_option = EE_Question_Option::new_instance(
566
+						array(
567
+							'QSO_value' => $option_req_data['QSO_value'],
568
+							'QSO_desc'  => $option_req_data['QSO_desc'],
569
+							'QSO_order' => $option_req_data['QSO_order'],
570
+							'QST_ID'    => $question->ID(),
571
+						)
572
+					);
573
+					$new_option->save();
574
+				}
575
+			}
576
+		}
577
+		$query_args = array('action' => 'edit_question', 'QST_ID' => $ID);
578
+		if ($success !== false) {
579
+			$msg = $new_question
580
+				? sprintf(
581
+					esc_html__('The %s has been created', 'event_espresso'),
582
+					$this->_question_model->item_name()
583
+				)
584
+				: sprintf(
585
+					esc_html__('The %s has been updated', 'event_espresso'),
586
+					$this->_question_model->item_name()
587
+				);
588
+			EE_Error::add_success($msg);
589
+		}
590
+
591
+		$this->_redirect_after_action(false, '', $action_desc, $query_args, true);
592
+	}
593
+
594
+
595
+	/**
596
+	 * Upon saving a question, there should be an array of 'question_options'. This array is index numerically, but not
597
+	 * by ID
598
+	 * (this is done because new question options don't have an ID, but we may want to add multiple simultaneously).
599
+	 * So, this function gets the index in that request data array called question_options. Returns FALSE if not found.
600
+	 *
601
+	 * @param int $ID of the question option to find
602
+	 * @return int index in question_options array if successful, FALSE if unsuccessful
603
+	 */
604
+	protected function _get_option_req_data_index($ID)
605
+	{
606
+		$req_data_for_question_options = $this->_req_data['question_options'];
607
+		foreach ($req_data_for_question_options as $num => $option_data) {
608
+			if (array_key_exists('QSO_ID', $option_data) && (int) $option_data['QSO_ID'] === $ID) {
609
+				return $num;
610
+			}
611
+		}
612
+		return false;
613
+	}
614
+
615
+
616
+
617
+
618
+	/***********/
619
+	/* QUERIES */
620
+	/**
621
+	 * For internal use in getting all the query parameters
622
+	 * (because it's pretty well the same between question, question groups,
623
+	 * and for both when searching for trashed and untrashed ones)
624
+	 *
625
+	 * @param EEM_Base $model either EEM_Question or EEM_Question_Group
626
+	 * @param int      $per_page
627
+	 * @param int      $current_page
628
+	 * @return array model query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
629
+	 */
630
+	protected function get_query_params($model, $per_page = 10, $current_page = 10)
631
+	{
632
+		$query_params = array();
633
+		$offset = ($current_page - 1) * $per_page;
634
+		$query_params['limit'] = array($offset, $per_page);
635
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
636
+			: 'ASC';
637
+		$orderby_field = $model instanceof EEM_Question ? 'QST_ID' : 'QSG_order';
638
+		$field_to_order_by = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
639
+		$query_params['order_by'] = array($field_to_order_by => $order);
640
+		$search_string = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
641
+		if (! empty($search_string)) {
642
+			if ($model instanceof EEM_Question_Group) {
643
+				$query_params[0] = array(
644
+					'OR' => array(
645
+						'QSG_name' => array('LIKE', "%$search_string%"),
646
+						'QSG_desc' => array('LIKE', "%$search_string%"),
647
+					),
648
+				);
649
+			} else {
650
+				$query_params[0] = array(
651
+					'QST_display_text' => array('LIKE', "%$search_string%"),
652
+				);
653
+			}
654
+		}
655
+
656
+		// capability checks (just leaving this commented out for reference because it illustrates some complicated query params that could be useful when fully implemented)
657
+		/*if ( $model instanceof EEM_Question_Group ) {
658 658
             if ( ! EE_Registry::instance()->CAP->current_user_can( 'edit_others_question_groups', 'espresso_registration_form_edit_question_group' ) ) {
659 659
                 $query_params[0] = array(
660 660
                     'AND' => array(
@@ -684,59 +684,59 @@  discard block
 block discarded – undo
684 684
             }
685 685
         }/**/
686 686
 
687
-        return $query_params;
688
-    }
689
-
690
-
691
-    /**
692
-     * @param int        $per_page
693
-     * @param int        $current_page
694
-     * @param bool|false $count
695
-     * @return \EE_Soft_Delete_Base_Class[]|int
696
-     */
697
-    public function get_questions($per_page = 10, $current_page = 1, $count = false)
698
-    {
699
-        $QST = EEM_Question::instance();
700
-        $query_params = $this->get_query_params($QST, $per_page, $current_page);
701
-        if ($count) {
702
-            $where = isset($query_params[0]) ? array($query_params[0]) : array();
703
-            $results = $QST->count($where);
704
-        } else {
705
-            $results = $QST->get_all($query_params);
706
-        }
707
-        return $results;
708
-    }
709
-
710
-
711
-    /**
712
-     * @param            $per_page
713
-     * @param int        $current_page
714
-     * @param bool|false $count
715
-     * @return \EE_Soft_Delete_Base_Class[]|int
716
-     */
717
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
718
-    {
719
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
720
-        $where = isset($query_params[0]) ? array($query_params[0]) : array();
721
-        $questions = $count ? EEM_Question::instance()->count_deleted($where)
722
-            : EEM_Question::instance()->get_all_deleted($query_params);
723
-        return $questions;
724
-    }
725
-
726
-
727
-    /**
728
-     * @param            $per_page
729
-     * @param int        $current_page
730
-     * @param bool|false $count
731
-     * @return \EE_Soft_Delete_Base_Class[]
732
-     */
733
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
734
-    {
735
-        /** @type EEM_Question_Group $questionGroupModel */
736
-        $questionGroupModel = EEM_Question_Group::instance();
737
-        // note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
738
-        return $questionGroupModel->get_all(
739
-            $this->get_query_params($questionGroupModel, $per_page, $current_page)
740
-        );
741
-    }
687
+		return $query_params;
688
+	}
689
+
690
+
691
+	/**
692
+	 * @param int        $per_page
693
+	 * @param int        $current_page
694
+	 * @param bool|false $count
695
+	 * @return \EE_Soft_Delete_Base_Class[]|int
696
+	 */
697
+	public function get_questions($per_page = 10, $current_page = 1, $count = false)
698
+	{
699
+		$QST = EEM_Question::instance();
700
+		$query_params = $this->get_query_params($QST, $per_page, $current_page);
701
+		if ($count) {
702
+			$where = isset($query_params[0]) ? array($query_params[0]) : array();
703
+			$results = $QST->count($where);
704
+		} else {
705
+			$results = $QST->get_all($query_params);
706
+		}
707
+		return $results;
708
+	}
709
+
710
+
711
+	/**
712
+	 * @param            $per_page
713
+	 * @param int        $current_page
714
+	 * @param bool|false $count
715
+	 * @return \EE_Soft_Delete_Base_Class[]|int
716
+	 */
717
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
718
+	{
719
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
720
+		$where = isset($query_params[0]) ? array($query_params[0]) : array();
721
+		$questions = $count ? EEM_Question::instance()->count_deleted($where)
722
+			: EEM_Question::instance()->get_all_deleted($query_params);
723
+		return $questions;
724
+	}
725
+
726
+
727
+	/**
728
+	 * @param            $per_page
729
+	 * @param int        $current_page
730
+	 * @param bool|false $count
731
+	 * @return \EE_Soft_Delete_Base_Class[]
732
+	 */
733
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
734
+	{
735
+		/** @type EEM_Question_Group $questionGroupModel */
736
+		$questionGroupModel = EEM_Question_Group::instance();
737
+		// note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
738
+		return $questionGroupModel->get_all(
739
+			$this->get_query_params($questionGroupModel, $per_page, $current_page)
740
+		);
741
+	}
742 742
 }
Please login to merge, or discard this patch.