Completed
Branch FET-9856-direct-instantiation (a39e7f)
by
unknown
50:47 queued 37:40
created
core/libraries/batch/JobHandlers/RegistrationsReport.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -418,7 +418,7 @@
 block discarded – undo
418 418
      * In this case, we delete the temporary file
419 419
      *
420 420
      * @param JobParameters $job_parameters
421
-     * @return boolean
421
+     * @return JobStepResponse
422 422
      */
423 423
     public function cleanup_job(JobParameters $job_parameters)
424 424
     {
Please login to merge, or discard this patch.
Indentation   +385 added lines, -385 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 use EventEspressoBatchRequest\Helpers\JobStepResponse;
18 18
 
19 19
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
20
-    exit('No direct script access allowed');
20
+	exit('No direct script access allowed');
21 21
 }
22 22
 
23 23
 
@@ -25,408 +25,408 @@  discard block
 block discarded – undo
25 25
 class RegistrationsReport extends JobHandlerFile
26 26
 {
27 27
 
28
-    /**
29
-     * Performs any necessary setup for starting the job. This is also a good
30
-     * place to setup the $job_arguments which will be used for subsequent HTTP requests
31
-     * when continue_job will be called
32
-     *
33
-     * @param JobParameters $job_parameters
34
-     * @throws BatchRequestException
35
-     * @return JobStepResponse
36
-     */
37
-    public function create_job(JobParameters $job_parameters)
38
-    {
39
-        $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
40
-        if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
41
-            throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
42
-        }
43
-        $filepath = $this->create_file_from_job_with_name($job_parameters->job_id(),
44
-            $this->get_filename_from_event($event_id));
45
-        $job_parameters->add_extra_data('filepath', $filepath);
46
-        $question_data_for_columns = $this->_get_questions_for_report($event_id);
47
-        $job_parameters->add_extra_data('questions_data', $question_data_for_columns);
48
-        $job_parameters->set_job_size($this->count_units_to_process($event_id));
49
-        //we should also set the header columns
50
-        $csv_data_for_row = $this->get_csv_data_for($event_id, 0, 1, $job_parameters->extra_datum('questions_data'));
51
-        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
52
-        //if we actually processed a row there, record it
53
-        if ($job_parameters->job_size()) {
54
-            $job_parameters->mark_processed(1);
55
-        }
56
-        return new JobStepResponse($job_parameters,
57
-            __('Registrations report started successfully...', 'event_espresso'));
58
-    }
28
+	/**
29
+	 * Performs any necessary setup for starting the job. This is also a good
30
+	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
31
+	 * when continue_job will be called
32
+	 *
33
+	 * @param JobParameters $job_parameters
34
+	 * @throws BatchRequestException
35
+	 * @return JobStepResponse
36
+	 */
37
+	public function create_job(JobParameters $job_parameters)
38
+	{
39
+		$event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
40
+		if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
41
+			throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
42
+		}
43
+		$filepath = $this->create_file_from_job_with_name($job_parameters->job_id(),
44
+			$this->get_filename_from_event($event_id));
45
+		$job_parameters->add_extra_data('filepath', $filepath);
46
+		$question_data_for_columns = $this->_get_questions_for_report($event_id);
47
+		$job_parameters->add_extra_data('questions_data', $question_data_for_columns);
48
+		$job_parameters->set_job_size($this->count_units_to_process($event_id));
49
+		//we should also set the header columns
50
+		$csv_data_for_row = $this->get_csv_data_for($event_id, 0, 1, $job_parameters->extra_datum('questions_data'));
51
+		\EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
52
+		//if we actually processed a row there, record it
53
+		if ($job_parameters->job_size()) {
54
+			$job_parameters->mark_processed(1);
55
+		}
56
+		return new JobStepResponse($job_parameters,
57
+			__('Registrations report started successfully...', 'event_espresso'));
58
+	}
59 59
 
60 60
 
61 61
 
62
-    /**
63
-     * Creates teh filename form the event id (or lack thereof)
64
-     *
65
-     * @param int $event_id
66
-     * @return string
67
-     */
68
-    protected function get_filename_from_event($event_id)
69
-    {
70
-        if ($event_id) {
71
-            $event_slug = \EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
72
-            if ( ! $event_slug) {
73
-                $event_slug = __('unknown', 'event_espresso');
74
-            }
75
-        } else {
76
-            $event_slug = __('all', 'event_espresso');
77
-        }
78
-        return sprintf("registrations-for-%s.csv", $event_slug);
79
-    }
62
+	/**
63
+	 * Creates teh filename form the event id (or lack thereof)
64
+	 *
65
+	 * @param int $event_id
66
+	 * @return string
67
+	 */
68
+	protected function get_filename_from_event($event_id)
69
+	{
70
+		if ($event_id) {
71
+			$event_slug = \EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
72
+			if ( ! $event_slug) {
73
+				$event_slug = __('unknown', 'event_espresso');
74
+			}
75
+		} else {
76
+			$event_slug = __('all', 'event_espresso');
77
+		}
78
+		return sprintf("registrations-for-%s.csv", $event_slug);
79
+	}
80 80
 
81 81
 
82 82
 
83
-    /**
84
-     * Gets the questions which are to be used for this report, so they
85
-     * can be remembered for later
86
-     *
87
-     * @param int|null $event_id
88
-     * @return array of wpdb results for questions which are to be used for this report
89
-     */
90
-    protected function _get_questions_for_report($event_id)
91
-    {
92
-        $question_query_params = array(
93
-            array(
94
-                'Answer.ANS_ID' => array('IS_NOT_NULL'),
95
-            ),
96
-            'group_by' => array('QST_ID'),
97
-        );
98
-        if ($event_id) {
99
-            $question_query_params[0]['Answer.Registration.EVT_ID'] = $event_id;
100
-        }
101
-        return \EEM_Question::instance()->get_all_wpdb_results($question_query_params);
102
-    }
83
+	/**
84
+	 * Gets the questions which are to be used for this report, so they
85
+	 * can be remembered for later
86
+	 *
87
+	 * @param int|null $event_id
88
+	 * @return array of wpdb results for questions which are to be used for this report
89
+	 */
90
+	protected function _get_questions_for_report($event_id)
91
+	{
92
+		$question_query_params = array(
93
+			array(
94
+				'Answer.ANS_ID' => array('IS_NOT_NULL'),
95
+			),
96
+			'group_by' => array('QST_ID'),
97
+		);
98
+		if ($event_id) {
99
+			$question_query_params[0]['Answer.Registration.EVT_ID'] = $event_id;
100
+		}
101
+		return \EEM_Question::instance()->get_all_wpdb_results($question_query_params);
102
+	}
103 103
 
104 104
 
105 105
 
106
-    /**
107
-     * Performs another step of the job
108
-     *
109
-     * @param JobParameters $job_parameters
110
-     * @param int           $batch_size
111
-     * @return JobStepResponse
112
-     * @throws \EE_Error
113
-     */
114
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
115
-    {
116
-        $csv_data = $this->get_csv_data_for($job_parameters->request_datum('EVT_ID', '0'),
117
-            $job_parameters->units_processed(), $batch_size, $job_parameters->extra_datum('questions_data'));
118
-        \EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
119
-        $units_processed = count($csv_data);
120
-        $job_parameters->mark_processed($units_processed);
121
-        $extra_response_data = array(
122
-            'file_url' => '',
123
-        );
124
-        if ($units_processed < $batch_size) {
125
-            $job_parameters->set_status(JobParameters::status_complete);
126
-            $extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
127
-        }
128
-        return new JobStepResponse($job_parameters,
129
-            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
130
-            $extra_response_data);
131
-    }
106
+	/**
107
+	 * Performs another step of the job
108
+	 *
109
+	 * @param JobParameters $job_parameters
110
+	 * @param int           $batch_size
111
+	 * @return JobStepResponse
112
+	 * @throws \EE_Error
113
+	 */
114
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
115
+	{
116
+		$csv_data = $this->get_csv_data_for($job_parameters->request_datum('EVT_ID', '0'),
117
+			$job_parameters->units_processed(), $batch_size, $job_parameters->extra_datum('questions_data'));
118
+		\EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
119
+		$units_processed = count($csv_data);
120
+		$job_parameters->mark_processed($units_processed);
121
+		$extra_response_data = array(
122
+			'file_url' => '',
123
+		);
124
+		if ($units_processed < $batch_size) {
125
+			$job_parameters->set_status(JobParameters::status_complete);
126
+			$extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
127
+		}
128
+		return new JobStepResponse($job_parameters,
129
+			sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
130
+			$extra_response_data);
131
+	}
132 132
 
133 133
 
134 134
 
135
-    /**
136
-     * Gets the csv data for a batch of registrations
137
-     *
138
-     * @param int|null $event_id
139
-     * @param int      $offset
140
-     * @param int      $limit
141
-     * @param array    $questions_for_these_regs_rows results of $wpdb->get_results( $something, ARRAY_A) when querying
142
-     *                                                for questions
143
-     * @return array top-level keys are numeric, next-level keys are column headers
144
-     */
145
-    function get_csv_data_for($event_id, $offset, $limit, $questions_for_these_regs_rows)
146
-    {
147
-        $reg_fields_to_include = array(
148
-            'TXN_ID',
149
-            'ATT_ID',
150
-            'REG_ID',
151
-            'REG_date',
152
-            'REG_code',
153
-            'REG_count',
154
-            'REG_final_price',
155
-        );
156
-        $att_fields_to_include = array(
157
-            'ATT_fname',
158
-            'ATT_lname',
159
-            'ATT_email',
160
-            'ATT_address',
161
-            'ATT_address2',
162
-            'ATT_city',
163
-            'STA_ID',
164
-            'CNT_ISO',
165
-            'ATT_zip',
166
-            'ATT_phone',
167
-        );
168
-        $registrations_csv_ready_array = array();
169
-        $reg_model = \EE_Registry::instance()->load_model('Registration');
170
-        $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
171
-                array(
172
-                    'OR'                 => array(
173
-                        //don't include registrations from failed or abandoned transactions...
174
-                        'Transaction.STS_ID' => array(
175
-                            'NOT IN',
176
-                            array(
177
-                                \EEM_Transaction::failed_status_code,
178
-                                \EEM_Transaction::abandoned_status_code,
179
-                            ),
180
-                        ),
181
-                        //unless the registration is approved, in which case include it regardless of transaction status
182
-                        'STS_ID'             => \EEM_Registration::status_id_approved,
183
-                    ),
184
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
185
-                ),
186
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
187
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
188
-                'limit'      => array($offset, $limit),
189
-                'caps'       => \EEM_Base::caps_read_admin,
190
-            ), $event_id);
191
-        if ($event_id) {
192
-            $query_params[0]['EVT_ID'] = $event_id;
193
-        } else {
194
-            $query_params['force_join'][] = 'Event';
195
-        }
196
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
197
-        //get all questions which relate to someone in this group
198
-        $registration_ids = array();
199
-        foreach ($registration_rows as $reg_row) {
200
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
201
-        }
202
-        foreach ($registration_rows as $reg_row) {
203
-            if (is_array($reg_row)) {
204
-                $reg_csv_array = array();
205
-                if ( ! $event_id) {
206
-                    //get the event's name and Id
207
-                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(__('%1$s (%2$s)', 'event_espresso'),
208
-                        \EEH_Export::prepare_value_from_db_for_display(\EEM_Event::instance(), 'EVT_name',
209
-                            $reg_row['Event_CPT.post_title']), $reg_row['Event_CPT.ID']);
210
-                }
211
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
212
-                /*@var $reg_row EE_Registration */
213
-                foreach ($reg_fields_to_include as $field_name) {
214
-                    $field = $reg_model->field_settings_for($field_name);
215
-                    if ($field_name == 'REG_final_price') {
216
-                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
217
-                            $reg_row['Registration.REG_final_price'], 'localized_float');
218
-                    } elseif ($field_name == 'REG_count') {
219
-                        $value = sprintf(__('%s of %s', 'event_espresso'),
220
-                            \EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_count',
221
-                                $reg_row['Registration.REG_count']),
222
-                            \EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_group_size',
223
-                                $reg_row['Registration.REG_group_size']));
224
-                    } elseif ($field_name == 'REG_date') {
225
-                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
226
-                            $reg_row['Registration.REG_date'], 'no_html');
227
-                    } else {
228
-                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
229
-                            $reg_row[$field->get_qualified_column()]);
230
-                    }
231
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
232
-                    if ($field_name == 'REG_final_price') {
233
-                        //add a column named Currency after the final price
234
-                        $reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
235
-                    }
236
-                }
237
-                //get pretty status
238
-                $stati = \EEM_Status::instance()->localized_status(array(
239
-                    $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
240
-                    $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
241
-                ), false, 'sentence');
242
-                $reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
243
-                //get pretty transaction status
244
-                $reg_csv_array[__("Transaction Status",
245
-                    'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
246
-                $reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
247
-                    ? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_total',
248
-                        $reg_row['TransactionTable.TXN_total'], 'localized_float') : '0.00';
249
-                $reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
250
-                    ? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_paid',
251
-                        $reg_row['TransactionTable.TXN_paid'], 'localized_float') : '0.00';
252
-                $payment_methods = array();
253
-                $gateway_txn_ids_etc = array();
254
-                $payment_times = array();
255
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
256
-                    $payments_info = \EEM_Payment::instance()->get_all_wpdb_results(array(
257
-                        array(
258
-                            'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
259
-                            'STS_ID' => \EEM_Payment::status_id_approved,
260
-                        ),
261
-                        'force_join' => array('Payment_Method'),
262
-                    ), ARRAY_A,
263
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time');
264
-                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
265
-                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
266
-                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
267
-                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
268
-                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
269
-                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
270
-                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
271
-                    }
272
-                }
273
-                $reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
274
-                $reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
275
-                $reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
276
-                //get whether or not the user has checked in
277
-                $reg_csv_array[__("Check-Ins",
278
-                    "event_espresso")] = $reg_model->count_related($reg_row['Registration.REG_ID'], 'Checkin');
279
-                //get ticket of registration and its price
280
-                $ticket_model = \EE_Registry::instance()->load_model('Ticket');
281
-                if ($reg_row['Ticket.TKT_ID']) {
282
-                    $ticket_name = \EEH_Export::prepare_value_from_db_for_display($ticket_model, 'TKT_name',
283
-                        $reg_row['Ticket.TKT_name']);
284
-                    $datetimes_strings = array();
285
-                    foreach (
286
-                        \EEM_Datetime::instance()
287
-                                     ->get_all_wpdb_results(array(
288
-                                         array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
289
-                                         'order_by'                 => array('DTT_EVT_start' => 'ASC'),
290
-                                         'default_where_conditions' => 'none',
291
-                                     )) as $datetime
292
-                    ) {
293
-                        $datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(\EEM_Datetime::instance(),
294
-                            'DTT_EVT_start', $datetime['Datetime.DTT_EVT_start']);
295
-                    }
296
-                } else {
297
-                    $ticket_name = __('Unknown', 'event_espresso');
298
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
299
-                }
300
-                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
301
-                $reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
302
-                //get datetime(s) of registration
303
-                //add attendee columns
304
-                foreach ($att_fields_to_include as $att_field_name) {
305
-                    $field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
306
-                    if ($reg_row['Attendee_CPT.ID']) {
307
-                        if ($att_field_name == 'STA_ID') {
308
-                            $value = \EEM_State::instance()
309
-                                               ->get_var(array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
310
-                                                   'STA_name');
311
-                        } elseif ($att_field_name == 'CNT_ISO') {
312
-                            $value = \EEM_Country::instance()
313
-                                                 ->get_var(array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
314
-                                                     'CNT_name');
315
-                        } else {
316
-                            $value = \EEH_Export::prepare_value_from_db_for_display(\EEM_Attendee::instance(),
317
-                                $att_field_name, $reg_row[$field_obj->get_qualified_column()]);
318
-                        }
319
-                    } else {
320
-                        $value = '';
321
-                    }
322
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
323
-                }
324
-                //make sure each registration has the same questions in the same order
325
-                foreach ($questions_for_these_regs_rows as $question_row) {
326
-                    if ( ! isset($reg_csv_array[$question_row['Question.QST_admin_label']])) {
327
-                        $reg_csv_array[$question_row['Question.QST_admin_label']] = null;
328
-                    }
329
-                }
330
-                $answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
331
-                        array('REG_ID' => $reg_row['Registration.REG_ID']),
332
-                        'force_join' => array('Question'),
333
-                    ));
334
-                //now fill out the questions THEY answered
335
-                foreach ($answers as $answer_row) {
336
-                    if ($answer_row['Question.QST_ID']) {
337
-                        $question_label = \EEH_Export::prepare_value_from_db_for_display(\EEM_Question::instance(),
338
-                            'QST_admin_label', $answer_row['Question.QST_admin_label']);
339
-                    } else {
340
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
341
-                    }
342
-                    if (isset($answer_row['Question.QST_type'])
343
-                        && $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
344
-                    ) {
345
-                        $reg_csv_array[$question_label] = \EEM_State::instance()
346
-                                                                    ->get_state_name_by_ID($answer_row['Answer.ANS_value']);
347
-                    } else {
348
-                        //this isn't for html, so don't show html entities
349
-                        $reg_csv_array[$question_label] = html_entity_decode(\EEH_Export::prepare_value_from_db_for_display(\EEM_Answer::instance(),
350
-                            'ANS_value', $answer_row['Answer.ANS_value']));
351
-                    }
352
-                }
353
-                $registrations_csv_ready_array[] = apply_filters('FHEE__EE_Export__report_registrations__reg_csv_array',
354
-                    $reg_csv_array, $reg_row);
355
-            }
356
-        }
357
-        //if we couldn't export anything, we want to at least show the column headers
358
-        if (empty($registrations_csv_ready_array)) {
359
-            $reg_csv_array = array();
360
-            $model_and_fields_to_include = array(
361
-                'Registration' => $reg_fields_to_include,
362
-                'Attendee'     => $att_fields_to_include,
363
-            );
364
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
365
-                $model = \EE_Registry::instance()->load_model($model_name);
366
-                foreach ($field_list as $field_name) {
367
-                    $field = $model->field_settings_for($field_name);
368
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
369
-                }
370
-            }
371
-            $registrations_csv_ready_array[] = $reg_csv_array;
372
-        }
373
-        return $registrations_csv_ready_array;
374
-    }
135
+	/**
136
+	 * Gets the csv data for a batch of registrations
137
+	 *
138
+	 * @param int|null $event_id
139
+	 * @param int      $offset
140
+	 * @param int      $limit
141
+	 * @param array    $questions_for_these_regs_rows results of $wpdb->get_results( $something, ARRAY_A) when querying
142
+	 *                                                for questions
143
+	 * @return array top-level keys are numeric, next-level keys are column headers
144
+	 */
145
+	function get_csv_data_for($event_id, $offset, $limit, $questions_for_these_regs_rows)
146
+	{
147
+		$reg_fields_to_include = array(
148
+			'TXN_ID',
149
+			'ATT_ID',
150
+			'REG_ID',
151
+			'REG_date',
152
+			'REG_code',
153
+			'REG_count',
154
+			'REG_final_price',
155
+		);
156
+		$att_fields_to_include = array(
157
+			'ATT_fname',
158
+			'ATT_lname',
159
+			'ATT_email',
160
+			'ATT_address',
161
+			'ATT_address2',
162
+			'ATT_city',
163
+			'STA_ID',
164
+			'CNT_ISO',
165
+			'ATT_zip',
166
+			'ATT_phone',
167
+		);
168
+		$registrations_csv_ready_array = array();
169
+		$reg_model = \EE_Registry::instance()->load_model('Registration');
170
+		$query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
171
+				array(
172
+					'OR'                 => array(
173
+						//don't include registrations from failed or abandoned transactions...
174
+						'Transaction.STS_ID' => array(
175
+							'NOT IN',
176
+							array(
177
+								\EEM_Transaction::failed_status_code,
178
+								\EEM_Transaction::abandoned_status_code,
179
+							),
180
+						),
181
+						//unless the registration is approved, in which case include it regardless of transaction status
182
+						'STS_ID'             => \EEM_Registration::status_id_approved,
183
+					),
184
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
185
+				),
186
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
187
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
188
+				'limit'      => array($offset, $limit),
189
+				'caps'       => \EEM_Base::caps_read_admin,
190
+			), $event_id);
191
+		if ($event_id) {
192
+			$query_params[0]['EVT_ID'] = $event_id;
193
+		} else {
194
+			$query_params['force_join'][] = 'Event';
195
+		}
196
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
197
+		//get all questions which relate to someone in this group
198
+		$registration_ids = array();
199
+		foreach ($registration_rows as $reg_row) {
200
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
201
+		}
202
+		foreach ($registration_rows as $reg_row) {
203
+			if (is_array($reg_row)) {
204
+				$reg_csv_array = array();
205
+				if ( ! $event_id) {
206
+					//get the event's name and Id
207
+					$reg_csv_array[__('Event', 'event_espresso')] = sprintf(__('%1$s (%2$s)', 'event_espresso'),
208
+						\EEH_Export::prepare_value_from_db_for_display(\EEM_Event::instance(), 'EVT_name',
209
+							$reg_row['Event_CPT.post_title']), $reg_row['Event_CPT.ID']);
210
+				}
211
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
212
+				/*@var $reg_row EE_Registration */
213
+				foreach ($reg_fields_to_include as $field_name) {
214
+					$field = $reg_model->field_settings_for($field_name);
215
+					if ($field_name == 'REG_final_price') {
216
+						$value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
217
+							$reg_row['Registration.REG_final_price'], 'localized_float');
218
+					} elseif ($field_name == 'REG_count') {
219
+						$value = sprintf(__('%s of %s', 'event_espresso'),
220
+							\EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_count',
221
+								$reg_row['Registration.REG_count']),
222
+							\EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_group_size',
223
+								$reg_row['Registration.REG_group_size']));
224
+					} elseif ($field_name == 'REG_date') {
225
+						$value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
226
+							$reg_row['Registration.REG_date'], 'no_html');
227
+					} else {
228
+						$value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
229
+							$reg_row[$field->get_qualified_column()]);
230
+					}
231
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
232
+					if ($field_name == 'REG_final_price') {
233
+						//add a column named Currency after the final price
234
+						$reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
235
+					}
236
+				}
237
+				//get pretty status
238
+				$stati = \EEM_Status::instance()->localized_status(array(
239
+					$reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
240
+					$reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
241
+				), false, 'sentence');
242
+				$reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
243
+				//get pretty transaction status
244
+				$reg_csv_array[__("Transaction Status",
245
+					'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
246
+				$reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
247
+					? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_total',
248
+						$reg_row['TransactionTable.TXN_total'], 'localized_float') : '0.00';
249
+				$reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
250
+					? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_paid',
251
+						$reg_row['TransactionTable.TXN_paid'], 'localized_float') : '0.00';
252
+				$payment_methods = array();
253
+				$gateway_txn_ids_etc = array();
254
+				$payment_times = array();
255
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
256
+					$payments_info = \EEM_Payment::instance()->get_all_wpdb_results(array(
257
+						array(
258
+							'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
259
+							'STS_ID' => \EEM_Payment::status_id_approved,
260
+						),
261
+						'force_join' => array('Payment_Method'),
262
+					), ARRAY_A,
263
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time');
264
+					foreach ($payments_info as $payment_method_and_gateway_txn_id) {
265
+						$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
266
+							? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
267
+						$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
268
+							? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
269
+						$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
270
+							? $payment_method_and_gateway_txn_id['payment_time'] : '';
271
+					}
272
+				}
273
+				$reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
274
+				$reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
275
+				$reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
276
+				//get whether or not the user has checked in
277
+				$reg_csv_array[__("Check-Ins",
278
+					"event_espresso")] = $reg_model->count_related($reg_row['Registration.REG_ID'], 'Checkin');
279
+				//get ticket of registration and its price
280
+				$ticket_model = \EE_Registry::instance()->load_model('Ticket');
281
+				if ($reg_row['Ticket.TKT_ID']) {
282
+					$ticket_name = \EEH_Export::prepare_value_from_db_for_display($ticket_model, 'TKT_name',
283
+						$reg_row['Ticket.TKT_name']);
284
+					$datetimes_strings = array();
285
+					foreach (
286
+						\EEM_Datetime::instance()
287
+									 ->get_all_wpdb_results(array(
288
+										 array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
289
+										 'order_by'                 => array('DTT_EVT_start' => 'ASC'),
290
+										 'default_where_conditions' => 'none',
291
+									 )) as $datetime
292
+					) {
293
+						$datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(\EEM_Datetime::instance(),
294
+							'DTT_EVT_start', $datetime['Datetime.DTT_EVT_start']);
295
+					}
296
+				} else {
297
+					$ticket_name = __('Unknown', 'event_espresso');
298
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
299
+				}
300
+				$reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
301
+				$reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
302
+				//get datetime(s) of registration
303
+				//add attendee columns
304
+				foreach ($att_fields_to_include as $att_field_name) {
305
+					$field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
306
+					if ($reg_row['Attendee_CPT.ID']) {
307
+						if ($att_field_name == 'STA_ID') {
308
+							$value = \EEM_State::instance()
309
+											   ->get_var(array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
310
+												   'STA_name');
311
+						} elseif ($att_field_name == 'CNT_ISO') {
312
+							$value = \EEM_Country::instance()
313
+												 ->get_var(array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
314
+													 'CNT_name');
315
+						} else {
316
+							$value = \EEH_Export::prepare_value_from_db_for_display(\EEM_Attendee::instance(),
317
+								$att_field_name, $reg_row[$field_obj->get_qualified_column()]);
318
+						}
319
+					} else {
320
+						$value = '';
321
+					}
322
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
323
+				}
324
+				//make sure each registration has the same questions in the same order
325
+				foreach ($questions_for_these_regs_rows as $question_row) {
326
+					if ( ! isset($reg_csv_array[$question_row['Question.QST_admin_label']])) {
327
+						$reg_csv_array[$question_row['Question.QST_admin_label']] = null;
328
+					}
329
+				}
330
+				$answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
331
+						array('REG_ID' => $reg_row['Registration.REG_ID']),
332
+						'force_join' => array('Question'),
333
+					));
334
+				//now fill out the questions THEY answered
335
+				foreach ($answers as $answer_row) {
336
+					if ($answer_row['Question.QST_ID']) {
337
+						$question_label = \EEH_Export::prepare_value_from_db_for_display(\EEM_Question::instance(),
338
+							'QST_admin_label', $answer_row['Question.QST_admin_label']);
339
+					} else {
340
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
341
+					}
342
+					if (isset($answer_row['Question.QST_type'])
343
+						&& $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
344
+					) {
345
+						$reg_csv_array[$question_label] = \EEM_State::instance()
346
+																	->get_state_name_by_ID($answer_row['Answer.ANS_value']);
347
+					} else {
348
+						//this isn't for html, so don't show html entities
349
+						$reg_csv_array[$question_label] = html_entity_decode(\EEH_Export::prepare_value_from_db_for_display(\EEM_Answer::instance(),
350
+							'ANS_value', $answer_row['Answer.ANS_value']));
351
+					}
352
+				}
353
+				$registrations_csv_ready_array[] = apply_filters('FHEE__EE_Export__report_registrations__reg_csv_array',
354
+					$reg_csv_array, $reg_row);
355
+			}
356
+		}
357
+		//if we couldn't export anything, we want to at least show the column headers
358
+		if (empty($registrations_csv_ready_array)) {
359
+			$reg_csv_array = array();
360
+			$model_and_fields_to_include = array(
361
+				'Registration' => $reg_fields_to_include,
362
+				'Attendee'     => $att_fields_to_include,
363
+			);
364
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
365
+				$model = \EE_Registry::instance()->load_model($model_name);
366
+				foreach ($field_list as $field_name) {
367
+					$field = $model->field_settings_for($field_name);
368
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
369
+				}
370
+			}
371
+			$registrations_csv_ready_array[] = $reg_csv_array;
372
+		}
373
+		return $registrations_csv_ready_array;
374
+	}
375 375
 
376 376
 
377 377
 
378
-    /**
379
-     * Counts total unit to process
380
-     *
381
-     * @param int $event_id
382
-     * @return int
383
-     */
384
-    public function count_units_to_process($event_id)
385
-    {
386
-        //use the legacy filter
387
-        $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
388
-                array(
389
-                    'OR'                 => array(
390
-                        //don't include registrations from failed or abandoned transactions...
391
-                        'Transaction.STS_ID' => array(
392
-                            'NOT IN',
393
-                            array(
394
-                                \EEM_Transaction::failed_status_code,
395
-                                \EEM_Transaction::abandoned_status_code,
396
-                            ),
397
-                        ),
398
-                        //unless the registration is approved, in which case include it regardless of transaction status
399
-                        'STS_ID'             => \EEM_Registration::status_id_approved,
400
-                    ),
401
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
402
-                ),
403
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
404
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
405
-                'caps'       => \EEM_Base::caps_read_admin,
406
-            ), $event_id);
407
-        if ($event_id) {
408
-            $query_params[0]['EVT_ID'] = $event_id;
409
-        } else {
410
-            $query_params['force_join'][] = 'Event';
411
-        }
412
-        return \EEM_Registration::instance()->count($query_params);
413
-    }
378
+	/**
379
+	 * Counts total unit to process
380
+	 *
381
+	 * @param int $event_id
382
+	 * @return int
383
+	 */
384
+	public function count_units_to_process($event_id)
385
+	{
386
+		//use the legacy filter
387
+		$query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
388
+				array(
389
+					'OR'                 => array(
390
+						//don't include registrations from failed or abandoned transactions...
391
+						'Transaction.STS_ID' => array(
392
+							'NOT IN',
393
+							array(
394
+								\EEM_Transaction::failed_status_code,
395
+								\EEM_Transaction::abandoned_status_code,
396
+							),
397
+						),
398
+						//unless the registration is approved, in which case include it regardless of transaction status
399
+						'STS_ID'             => \EEM_Registration::status_id_approved,
400
+					),
401
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
402
+				),
403
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
404
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
405
+				'caps'       => \EEM_Base::caps_read_admin,
406
+			), $event_id);
407
+		if ($event_id) {
408
+			$query_params[0]['EVT_ID'] = $event_id;
409
+		} else {
410
+			$query_params['force_join'][] = 'Event';
411
+		}
412
+		return \EEM_Registration::instance()->count($query_params);
413
+	}
414 414
 
415 415
 
416 416
 
417
-    /**
418
-     * Performs any clean-up logic when we know the job is completed.
419
-     * In this case, we delete the temporary file
420
-     *
421
-     * @param JobParameters $job_parameters
422
-     * @return boolean
423
-     */
424
-    public function cleanup_job(JobParameters $job_parameters)
425
-    {
426
-        $this->_file_helper->delete(\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
427
-            true, 'd');
428
-        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
429
-    }
417
+	/**
418
+	 * Performs any clean-up logic when we know the job is completed.
419
+	 * In this case, we delete the temporary file
420
+	 *
421
+	 * @param JobParameters $job_parameters
422
+	 * @return boolean
423
+	 */
424
+	public function cleanup_job(JobParameters $job_parameters)
425
+	{
426
+		$this->_file_helper->delete(\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
427
+			true, 'd');
428
+		return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
429
+	}
430 430
 }
431 431
 
432 432
 
Please login to merge, or discard this patch.
admin_pages/registrations/Registrations_Admin_Page.core.php 2 patches
Spacing   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -586,11 +586,11 @@  discard block
 block discarded – undo
586 586
     {
587 587
         //style
588 588
         //wp_register_style('espresso_attendees', ATT_ASSETS_URL . 'espresso_attendees_admin.css', array(), EVENT_ESPRESSO_VERSION );
589
-        wp_register_style('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.css', array('ee-admin-css'),
589
+        wp_register_style('espresso_reg', REG_ASSETS_URL.'espresso_registrations_admin.css', array('ee-admin-css'),
590 590
             EVENT_ESPRESSO_VERSION);
591 591
         wp_enqueue_style('espresso_reg');
592 592
         //script
593
-        wp_register_script('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.js',
593
+        wp_register_script('espresso_reg', REG_ASSETS_URL.'espresso_registrations_admin.js',
594 594
             array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'), EVENT_ESPRESSO_VERSION, true);
595 595
         wp_enqueue_script('espresso_reg');
596 596
     }
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
     public function load_scripts_styles_contact_list()
625 625
     {
626 626
         wp_deregister_style('espresso_reg');
627
-        wp_register_style('espresso_att', REG_ASSETS_URL . 'espresso_attendees_admin.css', array('ee-admin-css'),
627
+        wp_register_style('espresso_att', REG_ASSETS_URL.'espresso_attendees_admin.css', array('ee-admin-css'),
628 628
             EVENT_ESPRESSO_VERSION);
629 629
         wp_enqueue_style('espresso_att');
630 630
     }
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 
634 634
     public function load_scripts_styles_new_registration()
635 635
     {
636
-        wp_register_script('ee-spco-for-admin', REG_ASSETS_URL . 'spco_for_admin.js', array('underscore', 'jquery'),
636
+        wp_register_script('ee-spco-for-admin', REG_ASSETS_URL.'spco_for_admin.js', array('underscore', 'jquery'),
637 637
             EVENT_ESPRESSO_VERSION, true);
638 638
         wp_enqueue_script('ee-spco-for-admin');
639 639
         add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
@@ -833,31 +833,31 @@  discard block
 block discarded – undo
833 833
         }
834 834
         $sc_items = array(
835 835
             'approved_status'   => array(
836
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
836
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_approved,
837 837
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
838 838
             ),
839 839
             'pending_status'    => array(
840
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
840
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_pending_payment,
841 841
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
842 842
             ),
843 843
             'wait_list'         => array(
844
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
844
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_wait_list,
845 845
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
846 846
             ),
847 847
             'incomplete_status' => array(
848
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
848
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_incomplete,
849 849
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_incomplete, false, 'sentence'),
850 850
             ),
851 851
             'not_approved'      => array(
852
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
852
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_not_approved,
853 853
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
854 854
             ),
855 855
             'declined_status'   => array(
856
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
856
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_declined,
857 857
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
858 858
             ),
859 859
             'cancelled_status'  => array(
860
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
860
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_cancelled,
861 861
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
862 862
             ),
863 863
         );
@@ -878,17 +878,17 @@  discard block
 block discarded – undo
878 878
             if (EE_Registry::instance()->CAP->current_user_can('ee_edit_registrations',
879 879
                 'espresso_registrations_new_registration', $EVT_ID)
880 880
             ) {
881
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button('new_registration', 'add-registrant',
881
+                $this->_admin_page_title .= ' '.$this->get_action_link_or_button('new_registration', 'add-registrant',
882 882
                         array('event_id' => $EVT_ID), 'add-new-h2');
883 883
             }
884 884
             $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
885 885
             if ($event instanceof EE_Event) {
886 886
                 $this->_template_args['admin_page_header'] = sprintf(__('%s Viewing registrations for the event: %s%s',
887 887
                     'event_espresso'), '<h3 style="line-height:1.5em;">',
888
-                    '<br /><a href="' . EE_Admin_Page::add_query_args_and_nonce(array(
888
+                    '<br /><a href="'.EE_Admin_Page::add_query_args_and_nonce(array(
889 889
                         'action' => 'edit',
890 890
                         'post'   => $event->ID(),
891
-                    ), EVENTS_ADMIN_URL) . '">&nbsp;' . $event->get('EVT_name') . '&nbsp;</a>&nbsp;', '</h3>');
891
+                    ), EVENTS_ADMIN_URL).'">&nbsp;'.$event->get('EVT_name').'&nbsp;</a>&nbsp;', '</h3>');
892 892
             }
893 893
             $DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
894 894
             $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
                 $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
898 898
                 $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
899 899
                 $this->_template_args['admin_page_header'] .= $datetime->name();
900
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
900
+                $this->_template_args['admin_page_header'] .= ' ( '.$datetime->start_date().' )';
901 901
                 $this->_template_args['admin_page_header'] .= '</span></h3>';
902 902
             }
903 903
         }
@@ -948,13 +948,13 @@  discard block
 block discarded – undo
948 948
     {
949 949
         $EVT_ID = ! empty($this->_req_data['event_id']) && $this->_req_data['event_id'] > 0
950 950
             ? absint($this->_req_data['event_id']) : false;
951
-        $CAT_ID = ! empty($this->_req_data['EVT_CAT']) && (int)$this->_req_data['EVT_CAT'] > 0
951
+        $CAT_ID = ! empty($this->_req_data['EVT_CAT']) && (int) $this->_req_data['EVT_CAT'] > 0
952 952
             ? absint($this->_req_data['EVT_CAT']) : false;
953 953
         $DTT_ID = isset($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : null;
954 954
         $reg_status = ! empty($this->_req_data['_reg_status']) ? sanitize_text_field($this->_req_data['_reg_status'])
955 955
             : false;
956 956
         $month_range = ! empty($this->_req_data['month_range']) ? sanitize_text_field($this->_req_data['month_range'])
957
-            : false;//should be like 2013-april
957
+            : false; //should be like 2013-april
958 958
         $today_a = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'today' ? true : false;
959 959
         $this_month_a = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'month' ? true : false;
960 960
         $start_date = false;
@@ -1018,9 +1018,9 @@  discard block
 block discarded – undo
1018 1018
                 'BETWEEN',
1019 1019
                 array(
1020 1020
                     EEM_Registration::instance()
1021
-                                    ->convert_datetime_for_query('REG_date', $curdate . $time_start, 'Y-m-d H:i:s'),
1021
+                                    ->convert_datetime_for_query('REG_date', $curdate.$time_start, 'Y-m-d H:i:s'),
1022 1022
                     EEM_Registration::instance()
1023
-                                    ->convert_datetime_for_query('REG_date', $curdate . $time_end, 'Y-m-d H:i:s'),
1023
+                                    ->convert_datetime_for_query('REG_date', $curdate.$time_end, 'Y-m-d H:i:s'),
1024 1024
                 ),
1025 1025
             );
1026 1026
         } elseif ($this_month_a || $this_month) {
@@ -1031,10 +1031,10 @@  discard block
 block discarded – undo
1031 1031
                 array(
1032 1032
                     EEM_Registration::instance()
1033 1033
                                     ->convert_datetime_for_query('REG_date',
1034
-                                        $this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start, 'Y-m-d H:i:s'),
1034
+                                        $this_year_r.'-'.$this_month_r.'-01'.' '.$time_start, 'Y-m-d H:i:s'),
1035 1035
                     EEM_Registration::instance()
1036 1036
                                     ->convert_datetime_for_query('REG_date',
1037
-                                        $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
1037
+                                        $this_year_r.'-'.$this_month_r.'-'.$days_this_month.' '.$time_end,
1038 1038
                                         'Y-m-d H:i:s'),
1039 1039
                 ),
1040 1040
             );
@@ -1042,16 +1042,16 @@  discard block
 block discarded – undo
1042 1042
             $pieces = explode(' ', $this->_req_data['month_range'], 3);
1043 1043
             $month_r = ! empty($pieces[0]) ? date('m', strtotime($month_range)) : '';
1044 1044
             $year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1045
-            $days_in_month = date('t', strtotime($year_r . '-' . $month_r . '-' . '01'));
1045
+            $days_in_month = date('t', strtotime($year_r.'-'.$month_r.'-'.'01'));
1046 1046
             $_where['REG_date'] = array(
1047 1047
                 'BETWEEN',
1048 1048
                 array(
1049 1049
                     EEM_Registration::instance()
1050
-                                    ->convert_datetime_for_query('REG_date', $year_r . '-' . $month_r . '-01 00:00:00',
1050
+                                    ->convert_datetime_for_query('REG_date', $year_r.'-'.$month_r.'-01 00:00:00',
1051 1051
                                         'Y-m-d H:i:s'),
1052 1052
                     EEM_Registration::instance()
1053 1053
                                     ->convert_datetime_for_query('REG_date',
1054
-                                        $year_r . '-' . $month_r . '-' . $days_in_month . ' 23:59:59', 'Y-m-d H:i:s'),
1054
+                                        $year_r.'-'.$month_r.'-'.$days_in_month.' 23:59:59', 'Y-m-d H:i:s'),
1055 1055
                 ),
1056 1056
             );
1057 1057
         } elseif ($start_date && $end_date) {
@@ -1062,7 +1062,7 @@  discard block
 block discarded – undo
1062 1062
             throw new EE_Error("not yet supported");
1063 1063
         }
1064 1064
         if ( ! empty($this->_req_data['s'])) {
1065
-            $sstr = '%' . $this->_req_data['s'] . '%';
1065
+            $sstr = '%'.$this->_req_data['s'].'%';
1066 1066
             $_where['OR'] = array(
1067 1067
                 'Event.EVT_name'                          => array('LIKE', $sstr),
1068 1068
                 'Event.EVT_desc'                          => array('LIKE', $sstr),
@@ -1123,16 +1123,16 @@  discard block
 block discarded – undo
1123 1123
                 $event_name = $first_registration->event_obj()->name();
1124 1124
                 $event_date = $first_registration->date_obj()
1125 1125
                                                  ->start_date_and_time('l F j, Y,',
1126
-                                                     'g:i:s a');// isset( $registrations[0]->DTT_EVT_start ) ? date( 'l F j, Y,    g:i:s a', $registrations[0]->DTT_EVT_start ) : '';
1126
+                                                     'g:i:s a'); // isset( $registrations[0]->DTT_EVT_start ) ? date( 'l F j, Y,    g:i:s a', $registrations[0]->DTT_EVT_start ) : '';
1127 1127
                 // edit event link
1128 1128
                 if ($event_name != '') {
1129 1129
                     $edit_event_url = self::add_query_args_and_nonce(array(
1130 1130
                         'action' => 'edit_event',
1131 1131
                         'EVT_ID' => $EVT_ID,
1132 1132
                     ), EVENTS_ADMIN_URL);
1133
-                    $edit_event_lnk = '<a href="' . $edit_event_url . '" title="' . esc_attr__('Edit ',
1134
-                            'event_espresso') . $event_name . '">' . __('Edit Event', 'event_espresso') . '</a>';
1135
-                    $event_name .= ' <span class="admin-page-header-edit-lnk not-bold">' . $edit_event_lnk . '</span>';
1133
+                    $edit_event_lnk = '<a href="'.$edit_event_url.'" title="'.esc_attr__('Edit ',
1134
+                            'event_espresso').$event_name.'">'.__('Edit Event', 'event_espresso').'</a>';
1135
+                    $event_name .= ' <span class="admin-page-header-edit-lnk not-bold">'.$edit_event_lnk.'</span>';
1136 1136
                 }
1137 1137
                 $back_2_reg_url = self::add_query_args_and_nonce(array('action' => 'default'), REG_ADMIN_URL);
1138 1138
                 $back_2_reg_lnk = '<a href="'
@@ -1144,9 +1144,9 @@  discard block
 block discarded – undo
1144 1144
                                   . '</a>';
1145 1145
                 $this->_template_args['before_admin_page_content'] = '
1146 1146
 			<div id="admin-page-header">
1147
-				<h1><span class="small-text not-bold">' . __('Event: ', 'event_espresso') . '</span>' . $event_name . '</h1>
1148
-				<h3><span class="small-text not-bold">' . __('Date: ', 'event_espresso') . '</span>' . $event_date . '</h3>
1149
-				<span class="admin-page-header-go-back-lnk not-bold">' . $back_2_reg_lnk . '</span>
1147
+				<h1><span class="small-text not-bold">' . __('Event: ', 'event_espresso').'</span>'.$event_name.'</h1>
1148
+				<h3><span class="small-text not-bold">' . __('Date: ', 'event_espresso').'</span>'.$event_date.'</h3>
1149
+				<span class="admin-page-header-go-back-lnk not-bold">' . $back_2_reg_lnk.'</span>
1150 1150
 			</div>
1151 1151
 			';
1152 1152
             }
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
                     '_REG_ID' => $previous_reg['REG_ID'],
1218 1218
                 ), REG_ADMIN_URL), 'dashicons dashicons-arrow-left ee-icon-size-22') : '';
1219 1219
             // grab header
1220
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1220
+            $template_path = REG_TEMPLATE_PATH.'reg_admin_details_header.template.php';
1221 1221
             $this->_template_args['REG_ID'] = $this->_registration->ID();
1222 1222
             $this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
1223 1223
                 $this->_template_args, true);
@@ -1294,8 +1294,8 @@  discard block
 block discarded – undo
1294 1294
                         'default' => $this->_registration->ID(),
1295 1295
                     )),
1296 1296
                     'current_status'     => new EE_Form_Section_HTML(EEH_HTML::tr(EEH_HTML::th(EEH_HTML::label(EEH_HTML::strong(__('Current Registration Status',
1297
-                            'event_espresso')))) . EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1298
-                            '', 'status-' . $this->_registration->status_ID(),
1297
+                            'event_espresso')))).EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1298
+                            '', 'status-'.$this->_registration->status_ID(),
1299 1299
                             'line-height: 1em; font-size: 1.5em; font-weight: bold;')))),
1300 1300
                     'reg_status'         => new EE_Select_Input($this->_get_reg_statuses(), array(
1301 1301
                             'html_label_text' => __('Change Registration Status to', 'event_espresso'),
@@ -1383,9 +1383,9 @@  discard block
 block discarded – undo
1383 1383
     {
1384 1384
         if (isset($this->_req_data['reg_status_change_form'])) {
1385 1385
             $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1386
-                ? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1386
+                ? (array) $this->_req_data['reg_status_change_form']['REG_ID'] : array();
1387 1387
         } else {
1388
-            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1388
+            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array) $this->_req_data['_REG_ID'] : array();
1389 1389
         }
1390 1390
         $success = $this->_set_registration_status($REG_IDs, $status);
1391 1391
         //notify?
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
     {
1415 1415
         $success = false;
1416 1416
         // typecast $REG_IDs
1417
-        $REG_IDs = (array)$REG_IDs;
1417
+        $REG_IDs = (array) $REG_IDs;
1418 1418
         if ( ! empty($REG_IDs)) {
1419 1419
             $success = true;
1420 1420
             // set default status if none is passed
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
         ), REG_ADMIN_URL);
1715 1715
         $this->_template_args['REG_ID'] = $this->_registration->ID();
1716 1716
         $this->_template_args['event_id'] = $this->_registration->event_ID();
1717
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
1717
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_details.template.php';
1718 1718
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1719 1719
     }
1720 1720
 
@@ -1737,7 +1737,7 @@  discard block
 block discarded – undo
1737 1737
             $this->_template_args['att_questions'] = count($form->subforms()) > 0 ? $form->get_html_and_js() : '';
1738 1738
             $this->_template_args['reg_questions_form_action'] = 'edit_registration';
1739 1739
             $this->_template_args['REG_ID'] = $this->_registration->ID();
1740
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
1740
+            $template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_questions.template.php';
1741 1741
             echo EEH_Template::display_template($template_path, $this->_template_args, true);
1742 1742
         }
1743 1743
     }
@@ -1754,7 +1754,7 @@  discard block
 block discarded – undo
1754 1754
      */
1755 1755
     public function form_before_question_group($output)
1756 1756
     {
1757
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1757
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1758 1758
             __('This method would have been protected but was used on a filter callback'
1759 1759
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1760 1760
             '4.8.32.rc.000');
@@ -1776,7 +1776,7 @@  discard block
 block discarded – undo
1776 1776
      */
1777 1777
     public function form_after_question_group($output)
1778 1778
     {
1779
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1779
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1780 1780
             __('This method would have been protected but was used on a filter callback'
1781 1781
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1782 1782
             '4.8.32.rc.000');
@@ -1811,14 +1811,14 @@  discard block
 block discarded – undo
1811 1811
      */
1812 1812
     public function form_form_field_label_wrap($label)
1813 1813
     {
1814
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1814
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1815 1815
             __('This method would have been protected but was used on a filter callback'
1816 1816
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1817 1817
             '4.8.32.rc.000');
1818 1818
         return '
1819 1819
 			<tr>
1820 1820
 				<th>
1821
-					' . $label . '
1821
+					' . $label.'
1822 1822
 				</th>';
1823 1823
     }
1824 1824
 
@@ -1834,13 +1834,13 @@  discard block
 block discarded – undo
1834 1834
      */
1835 1835
     public function form_form_field_input__wrap($input)
1836 1836
     {
1837
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1837
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1838 1838
             __('This method would have been protected but was used on a filter callback'
1839 1839
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1840 1840
             '4.8.32.rc.000');
1841 1841
         return '
1842 1842
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
1843
-					' . $input . '
1843
+					' . $input.'
1844 1844
 				</td>
1845 1845
 			</tr>';
1846 1846
     }
@@ -1882,7 +1882,7 @@  discard block
 block discarded – undo
1882 1882
     protected function _get_reg_custom_questions_form($REG_ID)
1883 1883
     {
1884 1884
         if ( ! $this->_reg_custom_questions_form) {
1885
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
1885
+            require_once(REG_ADMIN.'form_sections'.DS.'EE_Registration_Custom_Questions_Form.form.php');
1886 1886
             $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(EEM_Registration::instance()
1887 1887
                                                                                                           ->get_one_by_ID($REG_ID));
1888 1888
             $this->_reg_custom_questions_form->_construct_finalize(null, null);
@@ -1973,10 +1973,10 @@  discard block
 block discarded – undo
1973 1973
                     : EEM_Attendee::instance()
1974 1974
                                   ->create_default_object();
1975 1975
                 $this->_template_args['attendees'][$att_nmbr]['STS_ID'] = $registration->status_ID();
1976
-                $this->_template_args['attendees'][$att_nmbr]['fname'] = $attendee->fname();//( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
1977
-                $this->_template_args['attendees'][$att_nmbr]['lname'] = $attendee->lname();//( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
1978
-                $this->_template_args['attendees'][$att_nmbr]['email'] = $attendee->email();//( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
1979
-                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();//( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
1976
+                $this->_template_args['attendees'][$att_nmbr]['fname'] = $attendee->fname(); //( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
1977
+                $this->_template_args['attendees'][$att_nmbr]['lname'] = $attendee->lname(); //( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
1978
+                $this->_template_args['attendees'][$att_nmbr]['email'] = $attendee->email(); //( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
1979
+                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price(); //( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
1980 1980
                 $this->_template_args['attendees'][$att_nmbr]['address'] = implode(', ',
1981 1981
                     $attendee->full_address_as_array());
1982 1982
                 $this->_template_args['attendees'][$att_nmbr]['att_link'] = self::add_query_args_and_nonce(array(
@@ -1990,7 +1990,7 @@  discard block
 block discarded – undo
1990 1990
             $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1991 1991
             //			$this->_template_args['registration_form_url'] = add_query_arg( array( 'action' => 'edit_registration', 'process' => 'attendees'  ), REG_ADMIN_URL );
1992 1992
         }
1993
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
1993
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_attendees.template.php';
1994 1994
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1995 1995
     }
1996 1996
 
@@ -2020,9 +2020,9 @@  discard block
 block discarded – undo
2020 2020
             $primary_registration = null;
2021 2021
         }
2022 2022
         $this->_template_args['ATT_ID'] = $attendee->ID();
2023
-        $this->_template_args['fname'] = $attendee->fname();//$this->_registration->ATT_fname;
2024
-        $this->_template_args['lname'] = $attendee->lname();//$this->_registration->ATT_lname;
2025
-        $this->_template_args['email'] = $attendee->email();//$this->_registration->ATT_email;
2023
+        $this->_template_args['fname'] = $attendee->fname(); //$this->_registration->ATT_fname;
2024
+        $this->_template_args['lname'] = $attendee->lname(); //$this->_registration->ATT_lname;
2025
+        $this->_template_args['email'] = $attendee->email(); //$this->_registration->ATT_email;
2026 2026
         $this->_template_args['phone'] = $attendee->phone();
2027 2027
         $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2028 2028
         //edit link
@@ -2039,7 +2039,7 @@  discard block
 block discarded – undo
2039 2039
             ), REG_ADMIN_URL) : '';
2040 2040
         $this->_template_args['create_label'] = __('Create Contact', 'event_espresso');
2041 2041
         $this->_template_args['att_check'] = $att_check;
2042
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2042
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_details_side_meta_box_registrant.template.php';
2043 2043
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2044 2044
     }
2045 2045
 
@@ -2274,7 +2274,7 @@  discard block
 block discarded – undo
2274 2274
             $this->_return_json();
2275 2275
         }
2276 2276
         // grab header
2277
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2277
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_register_new_attendee.template.php';
2278 2278
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2279 2279
             $this->_template_args, true);
2280 2280
         //$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
@@ -2297,7 +2297,7 @@  discard block
 block discarded – undo
2297 2297
                 'event_espresso'), '<br />', '<h3 class="important-notice">', '</h3>', '<div class="float-right">',
2298 2298
                 '<span id="redirect_timer" class="important-notice">30</span>', '</div>', '<b>', '</b>');
2299 2299
             return '
2300
-	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
2300
+	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg.'</p></div>
2301 2301
 	<script >
2302 2302
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
2303 2303
 		// after just adding a new registration... we gotta try to put a stop to that !!!
@@ -2518,7 +2518,7 @@  discard block
 block discarded – undo
2518 2518
     public function get_attendees($per_page, $count = false, $trash = false)
2519 2519
     {
2520 2520
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2521
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2521
+        require_once(REG_ADMIN.'EE_Attendee_Contact_List_Table.class.php');
2522 2522
         $ATT_MDL = EEM_Attendee::instance();
2523 2523
         $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2524 2524
         switch ($this->_req_data['orderby']) {
@@ -2552,7 +2552,7 @@  discard block
 block discarded – undo
2552 2552
             ? $this->_req_data['perpage'] : $per_page;
2553 2553
         $_where = array();
2554 2554
         if ( ! empty($this->_req_data['s'])) {
2555
-            $sstr = '%' . $this->_req_data['s'] . '%';
2555
+            $sstr = '%'.$this->_req_data['s'].'%';
2556 2556
             $_where['OR'] = array(
2557 2557
                 'Registration.Event.EVT_name'       => array('LIKE', $sstr),
2558 2558
                 'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
@@ -2643,8 +2643,8 @@  discard block
 block discarded – undo
2643 2643
                 'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2644 2644
             );
2645 2645
             $this->_req_data = array_merge($this->_req_data, $new_request_args);
2646
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2647
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2646
+            if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
2647
+                require_once(EE_CLASSES.'EE_Export.class.php');
2648 2648
                 $EE_Export = EE_Export::instance($this->_req_data);
2649 2649
                 $EE_Export->export();
2650 2650
             }
@@ -2655,8 +2655,8 @@  discard block
 block discarded – undo
2655 2655
 
2656 2656
     public function _contact_list_export()
2657 2657
     {
2658
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2659
-            require_once(EE_CLASSES . 'EE_Export.class.php');
2658
+        if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
2659
+            require_once(EE_CLASSES.'EE_Export.class.php');
2660 2660
             $EE_Export = EE_Export::instance($this->_req_data);
2661 2661
             $EE_Export->export_attendees();
2662 2662
         }
@@ -2674,8 +2674,8 @@  discard block
 block discarded – undo
2674 2674
                 'return_url'  => urlencode($this->_req_data['return_url']),
2675 2675
             )));
2676 2676
         } else {
2677
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2678
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2677
+            if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
2678
+                require_once(EE_CLASSES.'EE_Export.class.php');
2679 2679
                 $EE_Export = EE_Export::instance($this->_req_data);
2680 2680
                 $EE_Export->report_attendees();
2681 2681
             }
@@ -2733,7 +2733,7 @@  discard block
 block discarded – undo
2733 2733
             $updated_fields = array(
2734 2734
                 'ATT_fname'     => $this->_req_data['ATT_fname'],
2735 2735
                 'ATT_lname'     => $this->_req_data['ATT_lname'],
2736
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
2736
+                'ATT_full_name' => $this->_req_data['ATT_fname'].' '.$this->_req_data['ATT_lname'],
2737 2737
                 'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
2738 2738
                 'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
2739 2739
                 'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
@@ -2822,7 +2822,7 @@  discard block
 block discarded – undo
2822 2822
     {
2823 2823
         //get attendee object ( should already have it )
2824 2824
         $this->_template_args['attendee'] = $this->_cpt_model_obj;
2825
-        $template = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
2825
+        $template = REG_TEMPLATE_PATH.'attendee_contact_info_metabox_content.template.php';
2826 2826
         EEH_Template::display_template($template, $this->_template_args);
2827 2827
     }
2828 2828
 
@@ -2864,7 +2864,7 @@  discard block
 block discarded – undo
2864 2864
                 'input_prefix'   => '',
2865 2865
                 'append_qstn_id' => false,
2866 2866
             )));
2867
-        $template = REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
2867
+        $template = REG_TEMPLATE_PATH.'attendee_address_details_metabox_content.template.php';
2868 2868
         EEH_Template::display_template($template, $this->_template_args);
2869 2869
     }
2870 2870
 
@@ -2880,7 +2880,7 @@  discard block
 block discarded – undo
2880 2880
     {
2881 2881
         $this->_template_args['attendee'] = $this->_cpt_model_obj;
2882 2882
         $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
2883
-        $template = REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
2883
+        $template = REG_TEMPLATE_PATH.'attendee_registrations_main_meta_box.template.php';
2884 2884
         EEH_Template::display_template($template, $this->_template_args);
2885 2885
     }
2886 2886
 
@@ -2895,7 +2895,7 @@  discard block
 block discarded – undo
2895 2895
     public function after_title_form_fields($post)
2896 2896
     {
2897 2897
         if ($post->post_type == 'espresso_attendees') {
2898
-            $template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
2898
+            $template = REG_TEMPLATE_PATH.'attendee_details_after_title_form_fields.template.php';
2899 2899
             $template_args['attendee'] = $this->_cpt_model_obj;
2900 2900
             EEH_Template::display_template($template, $template_args);
2901 2901
         }
Please login to merge, or discard this patch.
Indentation   +2885 added lines, -2885 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -24,1772 +24,1772 @@  discard block
 block discarded – undo
24 24
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
25 25
 {
26 26
 
27
-    /**
28
-     * @var EE_Registration
29
-     */
30
-    private $_registration;
31
-
32
-    /**
33
-     * @var EE_Event
34
-     */
35
-    private $_reg_event;
36
-
37
-    /**
38
-     * @var EE_Session
39
-     */
40
-    private        $_session;
41
-
42
-    private static $_reg_status;
43
-
44
-    /**
45
-     * Form for displaying the custom questions for this registration.
46
-     * This gets used a few times throughout the request so its best to cache it
47
-     *
48
-     * @var EE_Registration_Custom_Questions_Form
49
-     */
50
-    protected $_reg_custom_questions_form = null;
51
-
52
-
53
-
54
-    /**
55
-     *        constructor
56
-     *
57
-     * @Constructor
58
-     * @access public
59
-     * @param bool $routing
60
-     * @return Registrations_Admin_Page
61
-     */
62
-    public function __construct($routing = true)
63
-    {
64
-        parent::__construct($routing);
65
-        add_action('wp_loaded', array($this, 'wp_loaded'));
66
-    }
67
-
68
-
69
-
70
-    public function wp_loaded()
71
-    {
72
-        // when adding a new registration...
73
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
74
-            EE_System::do_not_cache();
75
-            if ( ! isset($this->_req_data['processing_registration'])
76
-                 || absint($this->_req_data['processing_registration']) !== 1
77
-            ) {
78
-                // and it's NOT the attendee information reg step
79
-                // force cookie expiration by setting time to last week
80
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
81
-                // and update the global
82
-                $_COOKIE['ee_registration_added'] = 0;
83
-            }
84
-        }
85
-    }
86
-
87
-
88
-
89
-    protected function _init_page_props()
90
-    {
91
-        $this->page_slug = REG_PG_SLUG;
92
-        $this->_admin_base_url = REG_ADMIN_URL;
93
-        $this->_admin_base_path = REG_ADMIN;
94
-        $this->page_label = __('Registrations', 'event_espresso');
95
-        $this->_cpt_routes = array(
96
-            'add_new_attendee' => 'espresso_attendees',
97
-            'edit_attendee'    => 'espresso_attendees',
98
-            'insert_attendee'  => 'espresso_attendees',
99
-            'update_attendee'  => 'espresso_attendees',
100
-        );
101
-        $this->_cpt_model_names = array(
102
-            'add_new_attendee' => 'EEM_Attendee',
103
-            'edit_attendee'    => 'EEM_Attendee',
104
-        );
105
-        $this->_cpt_edit_routes = array(
106
-            'espresso_attendees' => 'edit_attendee',
107
-        );
108
-        $this->_pagenow_map = array(
109
-            'add_new_attendee' => 'post-new.php',
110
-            'edit_attendee'    => 'post.php',
111
-            'trash'            => 'post.php',
112
-        );
113
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
114
-        //add filters so that the comment urls don't take users to a confusing 404 page
115
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
116
-    }
117
-
118
-
119
-
120
-    public function clear_comment_link($link, $comment, $args)
121
-    {
122
-        //gotta make sure this only happens on this route
123
-        $post_type = get_post_type($comment->comment_post_ID);
124
-        if ($post_type === 'espresso_attendees') {
125
-            return '#commentsdiv';
126
-        }
127
-        return $link;
128
-    }
129
-
130
-
131
-
132
-    protected function _ajax_hooks()
133
-    {
134
-        //todo: all hooks for registrations ajax goes in here
135
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
136
-    }
137
-
138
-
139
-
140
-    protected function _define_page_props()
141
-    {
142
-        $this->_admin_page_title = $this->page_label;
143
-        $this->_labels = array(
144
-            'buttons'                      => array(
145
-                'add-registrant'      => __('Add New Registration', 'event_espresso'),
146
-                'add-attendee'        => __('Add Contact', 'event_espresso'),
147
-                'edit'                => __('Edit Contact', 'event_espresso'),
148
-                'report'              => __("Event Registrations CSV Report", "event_espresso"),
149
-                'report_all'          => __('All Registrations CSV Report', 'event_espresso'),
150
-                'contact_list_report' => __('Contact List Report', 'event_espresso'),
151
-                'contact_list_export' => __("Export Data", "event_espresso"),
152
-            ),
153
-            'publishbox'                   => array(
154
-                'add_new_attendee' => __("Add Contact Record", 'event_espresso'),
155
-                'edit_attendee'    => __("Update Contact Record", 'event_espresso'),
156
-            ),
157
-            'hide_add_button_on_cpt_route' => array(
158
-                'edit_attendee' => true,
159
-            ),
160
-        );
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     *        grab url requests and route them
167
-     *
168
-     * @access private
169
-     * @return void
170
-     */
171
-    public function _set_page_routes()
172
-    {
173
-        $this->_get_registration_status_array();
174
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
175
-            ? $this->_req_data['_REG_ID'] : 0;
176
-        $att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
177
-            ? $this->_req_data['ATT_ID'] : 0;
178
-        $att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post']) ? $this->_req_data['post']
179
-            : $att_id;
180
-        $this->_page_routes = array(
181
-            'default' => array(
182
-                'func'       => '_registrations_overview_list_table',
183
-                'capability' => 'ee_read_registrations',
184
-            ),
185
-            'view_registration' => array(
186
-                'func'       => '_registration_details',
187
-                'capability' => 'ee_read_registration',
188
-                'obj_id'     => $reg_id,
189
-            ),
190
-            'edit_registration' => array(
191
-                'func'               => '_update_attendee_registration_form',
192
-                'noheader'           => true,
193
-                'headers_sent_route' => 'view_registration',
194
-                'capability'         => 'ee_edit_registration',
195
-                'obj_id'             => $reg_id,
196
-                '_REG_ID'            => $reg_id,
197
-            ),
198
-            'trash_registrations' => array(
199
-                'func'       => '_trash_or_restore_registrations',
200
-                'args'       => array('trash' => true),
201
-                'noheader'   => true,
202
-                'capability' => 'ee_delete_registrations',
203
-            ),
204
-            'restore_registrations' => array(
205
-                'func'       => '_trash_or_restore_registrations',
206
-                'args'       => array('trash' => false),
207
-                'noheader'   => true,
208
-                'capability' => 'ee_delete_registrations',
209
-            ),
210
-            'delete_registrations' => array(
211
-                'func'       => '_delete_registrations',
212
-                'noheader'   => true,
213
-                'capability' => 'ee_delete_registrations',
214
-            ),
215
-            'new_registration' => array(
216
-                'func'       => 'new_registration',
217
-                'capability' => 'ee_edit_registrations',
218
-            ),
219
-            'process_reg_step' => array(
220
-                'func'       => 'process_reg_step',
221
-                'noheader'   => true,
222
-                'capability' => 'ee_edit_registrations',
223
-            ),
224
-            'redirect_to_txn' => array(
225
-                'func'       => 'redirect_to_txn',
226
-                'noheader'   => true,
227
-                'capability' => 'ee_edit_registrations',
228
-            ),
229
-            'change_reg_status' => array(
230
-                'func'       => '_change_reg_status',
231
-                'noheader'   => true,
232
-                'capability' => 'ee_edit_registration',
233
-                'obj_id'     => $reg_id,
234
-            ),
235
-            'approve_registration' => array(
236
-                'func'       => 'approve_registration',
237
-                'noheader'   => true,
238
-                'capability' => 'ee_edit_registration',
239
-                'obj_id'     => $reg_id,
240
-            ),
241
-            'approve_and_notify_registration' => array(
242
-                'func'       => 'approve_registration',
243
-                'noheader'   => true,
244
-                'args'       => array(true),
245
-                'capability' => 'ee_edit_registration',
246
-                'obj_id'     => $reg_id,
247
-            ),
248
-            'decline_registration' => array(
249
-                'func'       => 'decline_registration',
250
-                'noheader'   => true,
251
-                'capability' => 'ee_edit_registration',
252
-                'obj_id'     => $reg_id,
253
-            ),
254
-            'decline_and_notify_registration' => array(
255
-                'func'       => 'decline_registration',
256
-                'noheader'   => true,
257
-                'args'       => array(true),
258
-                'capability' => 'ee_edit_registration',
259
-                'obj_id'     => $reg_id,
260
-            ),
261
-            'pending_registration' => array(
262
-                'func'       => 'pending_registration',
263
-                'noheader'   => true,
264
-                'capability' => 'ee_edit_registration',
265
-                'obj_id'     => $reg_id,
266
-            ),
267
-            'pending_and_notify_registration' => array(
268
-                'func'       => 'pending_registration',
269
-                'noheader'   => true,
270
-                'args'       => array(true),
271
-                'capability' => 'ee_edit_registration',
272
-                'obj_id'     => $reg_id,
273
-            ),
274
-            'no_approve_registration' => array(
275
-                'func'       => 'not_approve_registration',
276
-                'noheader'   => true,
277
-                'capability' => 'ee_edit_registration',
278
-                'obj_id'     => $reg_id,
279
-            ),
280
-            'no_approve_and_notify_registration' => array(
281
-                'func'       => 'not_approve_registration',
282
-                'noheader'   => true,
283
-                'args'       => array(true),
284
-                'capability' => 'ee_edit_registration',
285
-                'obj_id'     => $reg_id,
286
-            ),
287
-            'cancel_registration' => array(
288
-                'func'       => 'cancel_registration',
289
-                'noheader'   => true,
290
-                'capability' => 'ee_edit_registration',
291
-                'obj_id'     => $reg_id,
292
-            ),
293
-            'cancel_and_notify_registration' => array(
294
-                'func'       => 'cancel_registration',
295
-                'noheader'   => true,
296
-                'args'       => array(true),
297
-                'capability' => 'ee_edit_registration',
298
-                'obj_id'     => $reg_id,
299
-            ),
300
-            'contact_list' => array(
301
-                'func'       => '_attendee_contact_list_table',
302
-                'capability' => 'ee_read_contacts',
303
-            ),
304
-            'add_new_attendee' => array(
305
-                'func' => '_create_new_cpt_item',
306
-                'args' => array(
307
-                    'new_attendee' => true,
308
-                    'capability'   => 'ee_edit_contacts',
309
-                ),
310
-            ),
311
-            'edit_attendee' => array(
312
-                'func'       => '_edit_cpt_item',
313
-                'capability' => 'ee_edit_contacts',
314
-                'obj_id'     => $att_id,
315
-            ),
316
-            'duplicate_attendee' => array(
317
-                'func'       => '_duplicate_attendee',
318
-                'noheader'   => true,
319
-                'capability' => 'ee_edit_contacts',
320
-                'obj_id'     => $att_id,
321
-            ),
322
-            'insert_attendee' => array(
323
-                'func'       => '_insert_or_update_attendee',
324
-                'args'       => array(
325
-                    'new_attendee' => true,
326
-                ),
327
-                'noheader'   => true,
328
-                'capability' => 'ee_edit_contacts',
329
-            ),
330
-            'update_attendee' => array(
331
-                'func'       => '_insert_or_update_attendee',
332
-                'args'       => array(
333
-                    'new_attendee' => false,
334
-                ),
335
-                'noheader'   => true,
336
-                'capability' => 'ee_edit_contacts',
337
-                'obj_id'     => $att_id,
338
-            ),
339
-            'trash_attendees' => array(
340
-                'func'       => '_trash_or_restore_attendees',
341
-                'args'       => array(
342
-                    'trash' => true,
343
-                ),
344
-                'noheader'   => true,
345
-                'capability' => 'ee_delete_contacts',
346
-                'obj_id'     => $att_id,
347
-            ),
348
-            'restore_attendees'    => array(
349
-                'func'       => '_trash_or_restore_attendees',
350
-                'args'       => array(
351
-                    'trash' => false,
352
-                ),
353
-                'noheader'   => true,
354
-                'capability' => 'ee_delete_contacts',
355
-                'obj_id'     => $att_id,
356
-            ),
357
-            'resend_registration'  => array(
358
-                'func'       => '_resend_registration',
359
-                'noheader'   => true,
360
-                'capability' => 'ee_send_message',
361
-            ),
362
-            'registrations_report' => array(
363
-                'func'       => '_registrations_report',
364
-                'noheader'   => true,
365
-                'capability' => 'ee_read_registrations',
366
-            ),
367
-            'contact_list_export'  => array(
368
-                'func'       => '_contact_list_export',
369
-                'noheader'   => true,
370
-                'capability' => 'export',
371
-            ),
372
-            'contact_list_report'  => array(
373
-                'func'       => '_contact_list_report',
374
-                'noheader'   => true,
375
-                'capability' => 'ee_read_contacts',
376
-            ),
377
-        );
378
-    }
379
-
380
-
381
-
382
-    protected function _set_page_config()
383
-    {
384
-        $this->_page_config = array(
385
-            'default' => array(
386
-                'nav'           => array(
387
-                    'label' => __('Overview', 'event_espresso'),
388
-                    'order' => 5,
389
-                ),
390
-                'help_tabs'     => array(
391
-                    'registrations_overview_help_tab'                       => array(
392
-                        'title'    => __('Registrations Overview', 'event_espresso'),
393
-                        'filename' => 'registrations_overview',
394
-                    ),
395
-                    'registrations_overview_table_column_headings_help_tab' => array(
396
-                        'title'    => __('Registrations Table Column Headings', 'event_espresso'),
397
-                        'filename' => 'registrations_overview_table_column_headings',
398
-                    ),
399
-                    'registrations_overview_filters_help_tab'               => array(
400
-                        'title'    => __('Registration Filters', 'event_espresso'),
401
-                        'filename' => 'registrations_overview_filters',
402
-                    ),
403
-                    'registrations_overview_views_help_tab'                 => array(
404
-                        'title'    => __('Registration Views', 'event_espresso'),
405
-                        'filename' => 'registrations_overview_views',
406
-                    ),
407
-                    'registrations_regoverview_other_help_tab'              => array(
408
-                        'title'    => __('Registrations Other', 'event_espresso'),
409
-                        'filename' => 'registrations_overview_other',
410
-                    ),
411
-                ),
412
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
413
-                'qtips'         => array('Registration_List_Table_Tips'),
414
-                'list_table'    => 'EE_Registrations_List_Table',
415
-                'require_nonce' => false,
416
-            ),
417
-            'view_registration' => array(
418
-                'nav'           => array(
419
-                    'label'      => __('REG Details', 'event_espresso'),
420
-                    'order'      => 15,
421
-                    'url'        => isset($this->_req_data['_REG_ID'])
422
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
423
-                        : $this->_admin_base_url,
424
-                    'persistent' => false,
425
-                ),
426
-                'help_tabs'     => array(
427
-                    'registrations_details_help_tab'                    => array(
428
-                        'title'    => __('Registration Details', 'event_espresso'),
429
-                        'filename' => 'registrations_details',
430
-                    ),
431
-                    'registrations_details_table_help_tab'              => array(
432
-                        'title'    => __('Registration Details Table', 'event_espresso'),
433
-                        'filename' => 'registrations_details_table',
434
-                    ),
435
-                    'registrations_details_form_answers_help_tab'       => array(
436
-                        'title'    => __('Registration Form Answers', 'event_espresso'),
437
-                        'filename' => 'registrations_details_form_answers',
438
-                    ),
439
-                    'registrations_details_registrant_details_help_tab' => array(
440
-                        'title'    => __('Contact Details', 'event_espresso'),
441
-                        'filename' => 'registrations_details_registrant_details',
442
-                    ),
443
-                ),
444
-                'help_tour'     => array('Registration_Details_Help_Tour'),
445
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
446
-                    array('_registration_details_metaboxes')),
447
-                'require_nonce' => false,
448
-            ),
449
-            'new_registration' => array(
450
-                'nav'           => array(
451
-                    'label'      => __('Add New Registration', 'event_espresso'),
452
-                    'url'        => '#',
453
-                    'order'      => 15,
454
-                    'persistent' => false,
455
-                ),
456
-                'metaboxes'     => $this->_default_espresso_metaboxes,
457
-                'labels'        => array(
458
-                    'publishbox' => __('Save Registration', 'event_espresso'),
459
-                ),
460
-                'require_nonce' => false,
461
-            ),
462
-            'add_new_attendee' => array(
463
-                'nav'           => array(
464
-                    'label'      => __('Add Contact', 'event_espresso'),
465
-                    'order'      => 15,
466
-                    'persistent' => false,
467
-                ),
468
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
469
-                    array('_publish_post_box', 'attendee_editor_metaboxes')),
470
-                'require_nonce' => false,
471
-            ),
472
-            'edit_attendee' => array(
473
-                'nav'           => array(
474
-                    'label'      => __('Edit Contact', 'event_espresso'),
475
-                    'order'      => 15,
476
-                    'persistent' => false,
477
-                    'url'        => isset($this->_req_data['ATT_ID'])
478
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
479
-                        : $this->_admin_base_url,
480
-                ),
481
-                'metaboxes'     => array('attendee_editor_metaboxes'),
482
-                'require_nonce' => false,
483
-            ),
484
-            'contact_list' => array(
485
-                'nav'           => array(
486
-                    'label' => __('Contact List', 'event_espresso'),
487
-                    'order' => 20,
488
-                ),
489
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
490
-                'help_tabs'     => array(
491
-                    'registrations_contact_list_help_tab'                       => array(
492
-                        'title'    => __('Registrations Contact List', 'event_espresso'),
493
-                        'filename' => 'registrations_contact_list',
494
-                    ),
495
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
496
-                        'title'    => __('Contact List Table Column Headings', 'event_espresso'),
497
-                        'filename' => 'registrations_contact_list_table_column_headings',
498
-                    ),
499
-                    'registrations_contact_list_views_help_tab'                 => array(
500
-                        'title'    => __('Contact List Views', 'event_espresso'),
501
-                        'filename' => 'registrations_contact_list_views',
502
-                    ),
503
-                    'registrations_contact_list_other_help_tab'                 => array(
504
-                        'title'    => __('Contact List Other', 'event_espresso'),
505
-                        'filename' => 'registrations_contact_list_other',
506
-                    ),
507
-                ),
508
-                'help_tour'     => array('Contact_List_Help_Tour'),
509
-                'metaboxes'     => array(),
510
-                'require_nonce' => false,
511
-            ),
512
-            //override default cpt routes
513
-            'create_new'   => '',
514
-            'edit'         => '',
515
-        );
516
-    }
517
-
518
-
519
-
520
-    /**
521
-     * The below methods aren't used by this class currently
522
-     */
523
-    protected function _add_screen_options()
524
-    {
525
-    }
526
-
527
-
528
-
529
-    protected function _add_feature_pointers()
530
-    {
531
-    }
532
-
533
-
534
-
535
-    public function admin_init()
536
-    {
537
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = __('click "Update Registration Questions" to save your changes',
538
-            'event_espresso');
539
-    }
540
-
541
-
542
-
543
-    public function admin_notices()
544
-    {
545
-    }
546
-
547
-
548
-
549
-    public function admin_footer_scripts()
550
-    {
551
-    }
552
-
553
-
554
-
555
-    /**
556
-     *        get list of registration statuses
557
-     *
558
-     * @access private
559
-     * @return void
560
-     */
561
-    private function _get_registration_status_array()
562
-    {
563
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
564
-    }
565
-
566
-
567
-
568
-    protected function _add_screen_options_default()
569
-    {
570
-        $this->_per_page_screen_option();
571
-    }
572
-
573
-
574
-
575
-    protected function _add_screen_options_contact_list()
576
-    {
577
-        $page_title = $this->_admin_page_title;
578
-        $this->_admin_page_title = __("Contacts", 'event_espresso');
579
-        $this->_per_page_screen_option();
580
-        $this->_admin_page_title = $page_title;
581
-    }
582
-
583
-
584
-
585
-    public function load_scripts_styles()
586
-    {
587
-        //style
588
-        //wp_register_style('espresso_attendees', ATT_ASSETS_URL . 'espresso_attendees_admin.css', array(), EVENT_ESPRESSO_VERSION );
589
-        wp_register_style('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.css', array('ee-admin-css'),
590
-            EVENT_ESPRESSO_VERSION);
591
-        wp_enqueue_style('espresso_reg');
592
-        //script
593
-        wp_register_script('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.js',
594
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'), EVENT_ESPRESSO_VERSION, true);
595
-        wp_enqueue_script('espresso_reg');
596
-    }
597
-
598
-
599
-
600
-    public function load_scripts_styles_edit_attendee()
601
-    {
602
-        //stuff to only show up on our attendee edit details page.
603
-        $attendee_details_translations = array(
604
-            'att_publish_text' => sprintf(__('Created on: <b>%1$s</b>', 'event_espresso'),
605
-                $this->_cpt_model_obj->get_datetime('ATT_created')),
606
-        );
607
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
608
-        wp_enqueue_script('jquery-validate');
609
-    }
610
-
611
-
612
-
613
-    public function load_scripts_styles_view_registration()
614
-    {
615
-        //styles
616
-        wp_enqueue_style('espresso-ui-theme');
617
-        //scripts
618
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
619
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
620
-    }
621
-
622
-
623
-
624
-    public function load_scripts_styles_contact_list()
625
-    {
626
-        wp_deregister_style('espresso_reg');
627
-        wp_register_style('espresso_att', REG_ASSETS_URL . 'espresso_attendees_admin.css', array('ee-admin-css'),
628
-            EVENT_ESPRESSO_VERSION);
629
-        wp_enqueue_style('espresso_att');
630
-    }
631
-
632
-
633
-
634
-    public function load_scripts_styles_new_registration()
635
-    {
636
-        wp_register_script('ee-spco-for-admin', REG_ASSETS_URL . 'spco_for_admin.js', array('underscore', 'jquery'),
637
-            EVENT_ESPRESSO_VERSION, true);
638
-        wp_enqueue_script('ee-spco-for-admin');
639
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
640
-        EE_Form_Section_Proper::wp_enqueue_scripts();
641
-        EED_Ticket_Selector::load_tckt_slctr_assets();
642
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
643
-    }
644
-
645
-
646
-
647
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
648
-    {
649
-        add_filter('FHEE_load_EE_messages', '__return_true');
650
-    }
651
-
652
-
653
-
654
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
655
-    {
656
-        add_filter('FHEE_load_EE_messages', '__return_true');
657
-    }
658
-
659
-
660
-
661
-    protected function _set_list_table_views_default()
662
-    {
663
-        //for notification related bulk actions we need to make sure only active messengers have an option.
664
-        EED_Messages::set_autoloaders();
665
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
666
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
667
-        $active_mts = $message_resource_manager->list_of_active_message_types();
668
-        //key= bulk_action_slug, value= message type.
669
-        $match_array = array(
670
-            'approve_registration'    => 'registration',
671
-            'decline_registration'    => 'declined_registration',
672
-            'pending_registration'    => 'pending_approval',
673
-            'no_approve_registration' => 'not_approved_registration',
674
-            'cancel_registration'     => 'cancelled_registration',
675
-        );
676
-        /** setup reg status bulk actions **/
677
-        $def_reg_status_actions['approve_registration'] = __('Approve Registrations', 'event_espresso');
678
-        if (in_array($match_array['approve_registration'], $active_mts)
679
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
680
-        ) {
681
-            $def_reg_status_actions['approve_and_notify_registration'] = __('Approve and Notify Registrations',
682
-                'event_espresso');
683
-        }
684
-        $def_reg_status_actions['decline_registration'] = __('Decline Registrations', 'event_espresso');
685
-        if (in_array($match_array['decline_registration'], $active_mts)
686
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
687
-        ) {
688
-            $def_reg_status_actions['decline_and_notify_registration'] = __('Decline and Notify Registrations',
689
-                'event_espresso');
690
-        }
691
-        $def_reg_status_actions['pending_registration'] = __('Set Registrations to Pending Payment', 'event_espresso');
692
-        if (in_array($match_array['pending_registration'], $active_mts)
693
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
694
-        ) {
695
-            $def_reg_status_actions['pending_and_notify_registration'] = __('Set Registrations to Pending Payment and Notify',
696
-                'event_espresso');
697
-        }
698
-        $def_reg_status_actions['no_approve_registration'] = __('Set Registrations to Not Approved', 'event_espresso');
699
-        if (in_array($match_array['no_approve_registration'], $active_mts)
700
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
701
-        ) {
702
-            $def_reg_status_actions['no_approve_and_notify_registration'] = __('Set Registrations to Not Approved and Notify',
703
-                'event_espresso');
704
-        }
705
-        $def_reg_status_actions['cancel_registration'] = __('Cancel Registrations', 'event_espresso');
706
-        if (in_array($match_array['cancel_registration'], $active_mts)
707
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
708
-        ) {
709
-            $def_reg_status_actions['cancel_and_notify_registration'] = __('Cancel Registrations and Notify',
710
-                'event_espresso');
711
-        }
712
-        $this->_views = array(
713
-            'all'   => array(
714
-                'slug'        => 'all',
715
-                'label'       => __('View All Registrations', 'event_espresso'),
716
-                'count'       => 0,
717
-                'bulk_action' => array_merge($def_reg_status_actions, array(
718
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
719
-                )),
720
-            ),
721
-            'month' => array(
722
-                'slug'        => 'month',
723
-                'label'       => __('This Month', 'event_espresso'),
724
-                'count'       => 0,
725
-                'bulk_action' => array_merge($def_reg_status_actions, array(
726
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
727
-                )),
728
-            ),
729
-            'today' => array(
730
-                'slug'        => 'today',
731
-                'label'       => sprintf(__('Today - %s', 'event_espresso'), date('M d, Y', current_time('timestamp'))),
732
-                'count'       => 0,
733
-                'bulk_action' => array_merge($def_reg_status_actions, array(
734
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
735
-                )),
736
-            ),
737
-        );
738
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
739
-            'espresso_registrations_delete_registration')
740
-        ) {
741
-            $this->_views['incomplete'] = array(
742
-                'slug'        => 'incomplete',
743
-                'label'       => __('Incomplete', 'event_espresso'),
744
-                'count'       => 0,
745
-                'bulk_action' => array(
746
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
747
-                ),
748
-            );
749
-            $this->_views['trash'] = array(
750
-                'slug'        => 'trash',
751
-                'label'       => __('Trash', 'event_espresso'),
752
-                'count'       => 0,
753
-                'bulk_action' => array(
754
-                    'restore_registrations' => __('Restore Registrations', 'event_espresso'),
755
-                    'delete_registrations'  => __('Delete Registrations Permanently', 'event_espresso'),
756
-                ),
757
-            );
758
-        }
759
-    }
760
-
761
-
762
-
763
-    protected function _set_list_table_views_contact_list()
764
-    {
765
-        $this->_views = array(
766
-            'in_use' => array(
767
-                'slug'        => 'in_use',
768
-                'label'       => __('In Use', 'event_espresso'),
769
-                'count'       => 0,
770
-                'bulk_action' => array(
771
-                    'trash_attendees' => __('Move to Trash', 'event_espresso'),
772
-                ),
773
-            ),
774
-        );
775
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
776
-            'espresso_registrations_trash_attendees')
777
-        ) {
778
-            $this->_views['trash'] = array(
779
-                'slug'        => 'trash',
780
-                'label'       => __('Trash', 'event_espresso'),
781
-                'count'       => 0,
782
-                'bulk_action' => array(
783
-                    'restore_attendees' => __('Restore from Trash', 'event_espresso'),
784
-                ),
785
-            );
786
-        }
787
-    }
788
-
789
-
790
-
791
-    protected function _registration_legend_items()
792
-    {
793
-        $fc_items = array(
794
-            'star-icon'        => array(
795
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
796
-                'desc'  => __('This is the Primary Registrant', 'event_espresso'),
797
-            ),
798
-            'view_details'     => array(
799
-                'class' => 'dashicons dashicons-clipboard',
800
-                'desc'  => __('View Registration Details', 'event_espresso'),
801
-            ),
802
-            'edit_attendee'    => array(
803
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
804
-                'desc'  => __('Edit Contact Details', 'event_espresso'),
805
-            ),
806
-            'view_transaction' => array(
807
-                'class' => 'dashicons dashicons-cart',
808
-                'desc'  => __('View Transaction Details', 'event_espresso'),
809
-            ),
810
-            'view_invoice'     => array(
811
-                'class' => 'dashicons dashicons-media-spreadsheet',
812
-                'desc'  => __('View Transaction Invoice', 'event_espresso'),
813
-            ),
814
-        );
815
-        if (EE_Registry::instance()->CAP->current_user_can('ee_send_message',
816
-            'espresso_registrations_resend_registration')
817
-        ) {
818
-            $fc_items['resend_registration'] = array(
819
-                'class' => 'dashicons dashicons-email-alt',
820
-                'desc'  => __('Resend Registration Details', 'event_espresso'),
821
-            );
822
-        } else {
823
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
824
-        }
825
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
826
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
827
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
828
-                $fc_items['view_related_messages'] = array(
829
-                    'class' => $related_for_icon['css_class'],
830
-                    'desc'  => $related_for_icon['label'],
831
-                );
832
-            }
833
-        }
834
-        $sc_items = array(
835
-            'approved_status'   => array(
836
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
837
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
838
-            ),
839
-            'pending_status'    => array(
840
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
841
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
842
-            ),
843
-            'wait_list'         => array(
844
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
845
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
846
-            ),
847
-            'incomplete_status' => array(
848
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
849
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_incomplete, false, 'sentence'),
850
-            ),
851
-            'not_approved'      => array(
852
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
853
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
854
-            ),
855
-            'declined_status'   => array(
856
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
857
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
858
-            ),
859
-            'cancelled_status'  => array(
860
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
861
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
862
-            ),
863
-        );
864
-        return array_merge($fc_items, $sc_items);
865
-    }
866
-
867
-
868
-
869
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
870
-    /**
871
-     * @throws \EE_Error
872
-     */
873
-    protected function _registrations_overview_list_table()
874
-    {
875
-        $this->_template_args['admin_page_header'] = '';
876
-        $EVT_ID = ! empty($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : 0;
877
-        if ($EVT_ID) {
878
-            if (EE_Registry::instance()->CAP->current_user_can('ee_edit_registrations',
879
-                'espresso_registrations_new_registration', $EVT_ID)
880
-            ) {
881
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button('new_registration', 'add-registrant',
882
-                        array('event_id' => $EVT_ID), 'add-new-h2');
883
-            }
884
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
885
-            if ($event instanceof EE_Event) {
886
-                $this->_template_args['admin_page_header'] = sprintf(__('%s Viewing registrations for the event: %s%s',
887
-                    'event_espresso'), '<h3 style="line-height:1.5em;">',
888
-                    '<br /><a href="' . EE_Admin_Page::add_query_args_and_nonce(array(
889
-                        'action' => 'edit',
890
-                        'post'   => $event->ID(),
891
-                    ), EVENTS_ADMIN_URL) . '">&nbsp;' . $event->get('EVT_name') . '&nbsp;</a>&nbsp;', '</h3>');
892
-            }
893
-            $DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
894
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
895
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
896
-                $this->_template_args['admin_page_header'] = substr($this->_template_args['admin_page_header'], 0, -5);
897
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
898
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
899
-                $this->_template_args['admin_page_header'] .= $datetime->name();
900
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
901
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
902
-            }
903
-        }
904
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
905
-        $this->display_admin_list_table_page_with_no_sidebar();
906
-    }
907
-
908
-
909
-
910
-    /**
911
-     * This sets the _registration property for the registration details screen
912
-     *
913
-     * @access private
914
-     * @return bool
915
-     */
916
-    private function _set_registration_object()
917
-    {
918
-        //get out if we've already set the object
919
-        if (is_object($this->_registration)) {
920
-            return true;
921
-        }
922
-        $REG = EEM_Registration::instance();
923
-        $REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
924
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
925
-            return true;
926
-        } else {
927
-            $error_msg = sprintf(__('An error occurred and the details for Registration ID #%s could not be retrieved.',
928
-                'event_espresso'), $REG_ID);
929
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
930
-            $this->_registration = null;
931
-            return false;
932
-        }
933
-    }
934
-
935
-
936
-
937
-    /**
938
-     * get registrations for given parameters (used by list table)
939
-     *
940
-     * @param  int     $per_page   how many registrations displayed per page
941
-     * @param  boolean $count      return the count or objects
942
-     * @param  boolean $this_month whether to return for just this month
943
-     * @param  boolean $today      whether to return results for just today
944
-     * @throws \EE_Error
945
-     * @return mixed (int|array)  int = count || array of registration objects
946
-     */
947
-    public function get_registrations($per_page = 10, $count = false, $this_month = false, $today = false)
948
-    {
949
-        $EVT_ID = ! empty($this->_req_data['event_id']) && $this->_req_data['event_id'] > 0
950
-            ? absint($this->_req_data['event_id']) : false;
951
-        $CAT_ID = ! empty($this->_req_data['EVT_CAT']) && (int)$this->_req_data['EVT_CAT'] > 0
952
-            ? absint($this->_req_data['EVT_CAT']) : false;
953
-        $DTT_ID = isset($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : null;
954
-        $reg_status = ! empty($this->_req_data['_reg_status']) ? sanitize_text_field($this->_req_data['_reg_status'])
955
-            : false;
956
-        $month_range = ! empty($this->_req_data['month_range']) ? sanitize_text_field($this->_req_data['month_range'])
957
-            : false;//should be like 2013-april
958
-        $today_a = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'today' ? true : false;
959
-        $this_month_a = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'month' ? true : false;
960
-        $start_date = false;
961
-        $end_date = false;
962
-        $_where = array();
963
-        $trash = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'trash' ? true : false;
964
-        $incomplete = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' ? true : false;
965
-        //set orderby
966
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
967
-        switch ($this->_req_data['orderby']) {
968
-            case '_REG_ID':
969
-                $orderby = 'REG_ID';
970
-                break;
971
-            case '_Reg_status':
972
-                $orderby = 'STS_ID';
973
-                break;
974
-            case 'ATT_fname':
975
-                $orderby = 'Attendee.ATT_lname';
976
-                break;
977
-            case 'event_name':
978
-                $orderby = 'Event.EVT_name';
979
-                break;
980
-            case 'DTT_EVT_start':
981
-                $orderby = 'Event.Datetime.DTT_EVT_start';
982
-                break;
983
-            default: //'REG_date'
984
-                $orderby = 'REG_date';
985
-        }
986
-        $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
987
-            : 'DESC';
988
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
989
-            ? $this->_req_data['paged'] : 1;
990
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
991
-            ? $this->_req_data['perpage'] : $per_page;
992
-        $offset = ($current_page - 1) * $per_page;
993
-        $limit = $count ? null : array($offset, $per_page);
994
-        if ($EVT_ID) {
995
-            $_where['EVT_ID'] = $EVT_ID;
996
-        }
997
-        if ($CAT_ID) {
998
-            $_where['Event.Term_Taxonomy.term_id'] = $CAT_ID;
999
-        }
1000
-        //if DTT is included we filter by that datetime.
1001
-        if ($DTT_ID) {
1002
-            $_where['Ticket.Datetime.DTT_ID'] = $DTT_ID;
1003
-        }
1004
-        if ($incomplete) {
1005
-            $_where['STS_ID'] = EEM_Registration::status_id_incomplete;
1006
-        } else if ( ! $trash) {
1007
-            $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1008
-        }
1009
-        if ($reg_status) {
1010
-            $_where['STS_ID'] = $reg_status;
1011
-        }
1012
-        $this_year_r = date('Y', current_time('timestamp'));
1013
-        $time_start = ' 00:00:00';
1014
-        $time_end = ' 23:59:59';
1015
-        if ($today_a || $today) {
1016
-            $curdate = date('Y-m-d', current_time('timestamp'));
1017
-            $_where['REG_date'] = array(
1018
-                'BETWEEN',
1019
-                array(
1020
-                    EEM_Registration::instance()
1021
-                                    ->convert_datetime_for_query('REG_date', $curdate . $time_start, 'Y-m-d H:i:s'),
1022
-                    EEM_Registration::instance()
1023
-                                    ->convert_datetime_for_query('REG_date', $curdate . $time_end, 'Y-m-d H:i:s'),
1024
-                ),
1025
-            );
1026
-        } elseif ($this_month_a || $this_month) {
1027
-            $this_month_r = date('m', current_time('timestamp'));
1028
-            $days_this_month = date('t', current_time('timestamp'));
1029
-            $_where['REG_date'] = array(
1030
-                'BETWEEN',
1031
-                array(
1032
-                    EEM_Registration::instance()
1033
-                                    ->convert_datetime_for_query('REG_date',
1034
-                                        $this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start, 'Y-m-d H:i:s'),
1035
-                    EEM_Registration::instance()
1036
-                                    ->convert_datetime_for_query('REG_date',
1037
-                                        $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
1038
-                                        'Y-m-d H:i:s'),
1039
-                ),
1040
-            );
1041
-        } elseif ($month_range) {
1042
-            $pieces = explode(' ', $this->_req_data['month_range'], 3);
1043
-            $month_r = ! empty($pieces[0]) ? date('m', strtotime($month_range)) : '';
1044
-            $year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1045
-            $days_in_month = date('t', strtotime($year_r . '-' . $month_r . '-' . '01'));
1046
-            $_where['REG_date'] = array(
1047
-                'BETWEEN',
1048
-                array(
1049
-                    EEM_Registration::instance()
1050
-                                    ->convert_datetime_for_query('REG_date', $year_r . '-' . $month_r . '-01 00:00:00',
1051
-                                        'Y-m-d H:i:s'),
1052
-                    EEM_Registration::instance()
1053
-                                    ->convert_datetime_for_query('REG_date',
1054
-                                        $year_r . '-' . $month_r . '-' . $days_in_month . ' 23:59:59', 'Y-m-d H:i:s'),
1055
-                ),
1056
-            );
1057
-        } elseif ($start_date && $end_date) {
1058
-            throw new EE_Error("not yet supported");
1059
-        } elseif ($start_date) {
1060
-            throw new EE_Error("not yet supported");
1061
-        } elseif ($end_date) {
1062
-            throw new EE_Error("not yet supported");
1063
-        }
1064
-        if ( ! empty($this->_req_data['s'])) {
1065
-            $sstr = '%' . $this->_req_data['s'] . '%';
1066
-            $_where['OR'] = array(
1067
-                'Event.EVT_name'                          => array('LIKE', $sstr),
1068
-                'Event.EVT_desc'                          => array('LIKE', $sstr),
1069
-                'Event.EVT_short_desc'                    => array('LIKE', $sstr),
1070
-                'Attendee.ATT_full_name'                  => array('LIKE', $sstr),
1071
-                'Attendee.ATT_fname'                      => array('LIKE', $sstr),
1072
-                'Attendee.ATT_lname'                      => array('LIKE', $sstr),
1073
-                'Attendee.ATT_short_bio'                  => array('LIKE', $sstr),
1074
-                'Attendee.ATT_email'                      => array('LIKE', $sstr),
1075
-                'Attendee.ATT_address'                    => array('LIKE', $sstr),
1076
-                'Attendee.ATT_address2'                   => array('LIKE', $sstr),
1077
-                'Attendee.ATT_city'                       => array('LIKE', $sstr),
1078
-                'REG_final_price'                         => array('LIKE', $sstr),
1079
-                'REG_code'                                => array('LIKE', $sstr),
1080
-                'REG_count'                               => array('LIKE', $sstr),
1081
-                'REG_group_size'                          => array('LIKE', $sstr),
1082
-                'Ticket.TKT_name'                         => array('LIKE', $sstr),
1083
-                'Ticket.TKT_description'                  => array('LIKE', $sstr),
1084
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $sstr),
1085
-            );
1086
-        }
1087
-        //capability checks
1088
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'get_registrations')) {
1089
-            $_where['AND'] = array(
1090
-                'Event.EVT_wp_user' => get_current_user_id(),
1091
-            );
1092
-        }
1093
-        if ($count) {
1094
-            if ($trash) {
1095
-                return EEM_Registration::instance()->count_deleted(array($_where));
1096
-            } else if ($incomplete) {
1097
-                return EEM_Registration::instance()->count(array($_where));
1098
-            } else {
1099
-                return EEM_Registration::instance()->count(array(
1100
-                    $_where,
1101
-                    'default_where_conditions' => 'this_model_only',
1102
-                ));
1103
-            }
1104
-        } else {
1105
-            //make sure we remove default where conditions cause all registrations matching query are returned
1106
-            $query_params = array(
1107
-                $_where,
1108
-                'order_by'                 => array($orderby => $sort),
1109
-                'default_where_conditions' => 'this_model_only',
1110
-            );
1111
-            if ($per_page !== -1) {
1112
-                $query_params['limit'] = $limit;
1113
-            }
1114
-            $registrations = $trash ? EEM_Registration::instance()->get_all_deleted($query_params)
1115
-                : EEM_Registration::instance()->get_all($query_params);
1116
-            if ($EVT_ID
1117
-                && isset($registrations[0])
1118
-                && $registrations[0] instanceof EE_Registration
1119
-                && $registrations[0]->event_obj()
1120
-            ) {
1121
-                $first_registration = $registrations[0];
1122
-                //EEH_Debug_Tools::printr( $registrations[0], '$registrations  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
1123
-                $event_name = $first_registration->event_obj()->name();
1124
-                $event_date = $first_registration->date_obj()
1125
-                                                 ->start_date_and_time('l F j, Y,',
1126
-                                                     'g:i:s a');// isset( $registrations[0]->DTT_EVT_start ) ? date( 'l F j, Y,    g:i:s a', $registrations[0]->DTT_EVT_start ) : '';
1127
-                // edit event link
1128
-                if ($event_name != '') {
1129
-                    $edit_event_url = self::add_query_args_and_nonce(array(
1130
-                        'action' => 'edit_event',
1131
-                        'EVT_ID' => $EVT_ID,
1132
-                    ), EVENTS_ADMIN_URL);
1133
-                    $edit_event_lnk = '<a href="' . $edit_event_url . '" title="' . esc_attr__('Edit ',
1134
-                            'event_espresso') . $event_name . '">' . __('Edit Event', 'event_espresso') . '</a>';
1135
-                    $event_name .= ' <span class="admin-page-header-edit-lnk not-bold">' . $edit_event_lnk . '</span>';
1136
-                }
1137
-                $back_2_reg_url = self::add_query_args_and_nonce(array('action' => 'default'), REG_ADMIN_URL);
1138
-                $back_2_reg_lnk = '<a href="'
1139
-                                  . $back_2_reg_url
1140
-                                  . '" title="'
1141
-                                  . esc_attr__('click to return to viewing all registrations ', 'event_espresso')
1142
-                                  . '">&laquo; '
1143
-                                  . __('Back to All Registrations', 'event_espresso')
1144
-                                  . '</a>';
1145
-                $this->_template_args['before_admin_page_content'] = '
27
+	/**
28
+	 * @var EE_Registration
29
+	 */
30
+	private $_registration;
31
+
32
+	/**
33
+	 * @var EE_Event
34
+	 */
35
+	private $_reg_event;
36
+
37
+	/**
38
+	 * @var EE_Session
39
+	 */
40
+	private        $_session;
41
+
42
+	private static $_reg_status;
43
+
44
+	/**
45
+	 * Form for displaying the custom questions for this registration.
46
+	 * This gets used a few times throughout the request so its best to cache it
47
+	 *
48
+	 * @var EE_Registration_Custom_Questions_Form
49
+	 */
50
+	protected $_reg_custom_questions_form = null;
51
+
52
+
53
+
54
+	/**
55
+	 *        constructor
56
+	 *
57
+	 * @Constructor
58
+	 * @access public
59
+	 * @param bool $routing
60
+	 * @return Registrations_Admin_Page
61
+	 */
62
+	public function __construct($routing = true)
63
+	{
64
+		parent::__construct($routing);
65
+		add_action('wp_loaded', array($this, 'wp_loaded'));
66
+	}
67
+
68
+
69
+
70
+	public function wp_loaded()
71
+	{
72
+		// when adding a new registration...
73
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
74
+			EE_System::do_not_cache();
75
+			if ( ! isset($this->_req_data['processing_registration'])
76
+				 || absint($this->_req_data['processing_registration']) !== 1
77
+			) {
78
+				// and it's NOT the attendee information reg step
79
+				// force cookie expiration by setting time to last week
80
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
81
+				// and update the global
82
+				$_COOKIE['ee_registration_added'] = 0;
83
+			}
84
+		}
85
+	}
86
+
87
+
88
+
89
+	protected function _init_page_props()
90
+	{
91
+		$this->page_slug = REG_PG_SLUG;
92
+		$this->_admin_base_url = REG_ADMIN_URL;
93
+		$this->_admin_base_path = REG_ADMIN;
94
+		$this->page_label = __('Registrations', 'event_espresso');
95
+		$this->_cpt_routes = array(
96
+			'add_new_attendee' => 'espresso_attendees',
97
+			'edit_attendee'    => 'espresso_attendees',
98
+			'insert_attendee'  => 'espresso_attendees',
99
+			'update_attendee'  => 'espresso_attendees',
100
+		);
101
+		$this->_cpt_model_names = array(
102
+			'add_new_attendee' => 'EEM_Attendee',
103
+			'edit_attendee'    => 'EEM_Attendee',
104
+		);
105
+		$this->_cpt_edit_routes = array(
106
+			'espresso_attendees' => 'edit_attendee',
107
+		);
108
+		$this->_pagenow_map = array(
109
+			'add_new_attendee' => 'post-new.php',
110
+			'edit_attendee'    => 'post.php',
111
+			'trash'            => 'post.php',
112
+		);
113
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
114
+		//add filters so that the comment urls don't take users to a confusing 404 page
115
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
116
+	}
117
+
118
+
119
+
120
+	public function clear_comment_link($link, $comment, $args)
121
+	{
122
+		//gotta make sure this only happens on this route
123
+		$post_type = get_post_type($comment->comment_post_ID);
124
+		if ($post_type === 'espresso_attendees') {
125
+			return '#commentsdiv';
126
+		}
127
+		return $link;
128
+	}
129
+
130
+
131
+
132
+	protected function _ajax_hooks()
133
+	{
134
+		//todo: all hooks for registrations ajax goes in here
135
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
136
+	}
137
+
138
+
139
+
140
+	protected function _define_page_props()
141
+	{
142
+		$this->_admin_page_title = $this->page_label;
143
+		$this->_labels = array(
144
+			'buttons'                      => array(
145
+				'add-registrant'      => __('Add New Registration', 'event_espresso'),
146
+				'add-attendee'        => __('Add Contact', 'event_espresso'),
147
+				'edit'                => __('Edit Contact', 'event_espresso'),
148
+				'report'              => __("Event Registrations CSV Report", "event_espresso"),
149
+				'report_all'          => __('All Registrations CSV Report', 'event_espresso'),
150
+				'contact_list_report' => __('Contact List Report', 'event_espresso'),
151
+				'contact_list_export' => __("Export Data", "event_espresso"),
152
+			),
153
+			'publishbox'                   => array(
154
+				'add_new_attendee' => __("Add Contact Record", 'event_espresso'),
155
+				'edit_attendee'    => __("Update Contact Record", 'event_espresso'),
156
+			),
157
+			'hide_add_button_on_cpt_route' => array(
158
+				'edit_attendee' => true,
159
+			),
160
+		);
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 *        grab url requests and route them
167
+	 *
168
+	 * @access private
169
+	 * @return void
170
+	 */
171
+	public function _set_page_routes()
172
+	{
173
+		$this->_get_registration_status_array();
174
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
175
+			? $this->_req_data['_REG_ID'] : 0;
176
+		$att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
177
+			? $this->_req_data['ATT_ID'] : 0;
178
+		$att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post']) ? $this->_req_data['post']
179
+			: $att_id;
180
+		$this->_page_routes = array(
181
+			'default' => array(
182
+				'func'       => '_registrations_overview_list_table',
183
+				'capability' => 'ee_read_registrations',
184
+			),
185
+			'view_registration' => array(
186
+				'func'       => '_registration_details',
187
+				'capability' => 'ee_read_registration',
188
+				'obj_id'     => $reg_id,
189
+			),
190
+			'edit_registration' => array(
191
+				'func'               => '_update_attendee_registration_form',
192
+				'noheader'           => true,
193
+				'headers_sent_route' => 'view_registration',
194
+				'capability'         => 'ee_edit_registration',
195
+				'obj_id'             => $reg_id,
196
+				'_REG_ID'            => $reg_id,
197
+			),
198
+			'trash_registrations' => array(
199
+				'func'       => '_trash_or_restore_registrations',
200
+				'args'       => array('trash' => true),
201
+				'noheader'   => true,
202
+				'capability' => 'ee_delete_registrations',
203
+			),
204
+			'restore_registrations' => array(
205
+				'func'       => '_trash_or_restore_registrations',
206
+				'args'       => array('trash' => false),
207
+				'noheader'   => true,
208
+				'capability' => 'ee_delete_registrations',
209
+			),
210
+			'delete_registrations' => array(
211
+				'func'       => '_delete_registrations',
212
+				'noheader'   => true,
213
+				'capability' => 'ee_delete_registrations',
214
+			),
215
+			'new_registration' => array(
216
+				'func'       => 'new_registration',
217
+				'capability' => 'ee_edit_registrations',
218
+			),
219
+			'process_reg_step' => array(
220
+				'func'       => 'process_reg_step',
221
+				'noheader'   => true,
222
+				'capability' => 'ee_edit_registrations',
223
+			),
224
+			'redirect_to_txn' => array(
225
+				'func'       => 'redirect_to_txn',
226
+				'noheader'   => true,
227
+				'capability' => 'ee_edit_registrations',
228
+			),
229
+			'change_reg_status' => array(
230
+				'func'       => '_change_reg_status',
231
+				'noheader'   => true,
232
+				'capability' => 'ee_edit_registration',
233
+				'obj_id'     => $reg_id,
234
+			),
235
+			'approve_registration' => array(
236
+				'func'       => 'approve_registration',
237
+				'noheader'   => true,
238
+				'capability' => 'ee_edit_registration',
239
+				'obj_id'     => $reg_id,
240
+			),
241
+			'approve_and_notify_registration' => array(
242
+				'func'       => 'approve_registration',
243
+				'noheader'   => true,
244
+				'args'       => array(true),
245
+				'capability' => 'ee_edit_registration',
246
+				'obj_id'     => $reg_id,
247
+			),
248
+			'decline_registration' => array(
249
+				'func'       => 'decline_registration',
250
+				'noheader'   => true,
251
+				'capability' => 'ee_edit_registration',
252
+				'obj_id'     => $reg_id,
253
+			),
254
+			'decline_and_notify_registration' => array(
255
+				'func'       => 'decline_registration',
256
+				'noheader'   => true,
257
+				'args'       => array(true),
258
+				'capability' => 'ee_edit_registration',
259
+				'obj_id'     => $reg_id,
260
+			),
261
+			'pending_registration' => array(
262
+				'func'       => 'pending_registration',
263
+				'noheader'   => true,
264
+				'capability' => 'ee_edit_registration',
265
+				'obj_id'     => $reg_id,
266
+			),
267
+			'pending_and_notify_registration' => array(
268
+				'func'       => 'pending_registration',
269
+				'noheader'   => true,
270
+				'args'       => array(true),
271
+				'capability' => 'ee_edit_registration',
272
+				'obj_id'     => $reg_id,
273
+			),
274
+			'no_approve_registration' => array(
275
+				'func'       => 'not_approve_registration',
276
+				'noheader'   => true,
277
+				'capability' => 'ee_edit_registration',
278
+				'obj_id'     => $reg_id,
279
+			),
280
+			'no_approve_and_notify_registration' => array(
281
+				'func'       => 'not_approve_registration',
282
+				'noheader'   => true,
283
+				'args'       => array(true),
284
+				'capability' => 'ee_edit_registration',
285
+				'obj_id'     => $reg_id,
286
+			),
287
+			'cancel_registration' => array(
288
+				'func'       => 'cancel_registration',
289
+				'noheader'   => true,
290
+				'capability' => 'ee_edit_registration',
291
+				'obj_id'     => $reg_id,
292
+			),
293
+			'cancel_and_notify_registration' => array(
294
+				'func'       => 'cancel_registration',
295
+				'noheader'   => true,
296
+				'args'       => array(true),
297
+				'capability' => 'ee_edit_registration',
298
+				'obj_id'     => $reg_id,
299
+			),
300
+			'contact_list' => array(
301
+				'func'       => '_attendee_contact_list_table',
302
+				'capability' => 'ee_read_contacts',
303
+			),
304
+			'add_new_attendee' => array(
305
+				'func' => '_create_new_cpt_item',
306
+				'args' => array(
307
+					'new_attendee' => true,
308
+					'capability'   => 'ee_edit_contacts',
309
+				),
310
+			),
311
+			'edit_attendee' => array(
312
+				'func'       => '_edit_cpt_item',
313
+				'capability' => 'ee_edit_contacts',
314
+				'obj_id'     => $att_id,
315
+			),
316
+			'duplicate_attendee' => array(
317
+				'func'       => '_duplicate_attendee',
318
+				'noheader'   => true,
319
+				'capability' => 'ee_edit_contacts',
320
+				'obj_id'     => $att_id,
321
+			),
322
+			'insert_attendee' => array(
323
+				'func'       => '_insert_or_update_attendee',
324
+				'args'       => array(
325
+					'new_attendee' => true,
326
+				),
327
+				'noheader'   => true,
328
+				'capability' => 'ee_edit_contacts',
329
+			),
330
+			'update_attendee' => array(
331
+				'func'       => '_insert_or_update_attendee',
332
+				'args'       => array(
333
+					'new_attendee' => false,
334
+				),
335
+				'noheader'   => true,
336
+				'capability' => 'ee_edit_contacts',
337
+				'obj_id'     => $att_id,
338
+			),
339
+			'trash_attendees' => array(
340
+				'func'       => '_trash_or_restore_attendees',
341
+				'args'       => array(
342
+					'trash' => true,
343
+				),
344
+				'noheader'   => true,
345
+				'capability' => 'ee_delete_contacts',
346
+				'obj_id'     => $att_id,
347
+			),
348
+			'restore_attendees'    => array(
349
+				'func'       => '_trash_or_restore_attendees',
350
+				'args'       => array(
351
+					'trash' => false,
352
+				),
353
+				'noheader'   => true,
354
+				'capability' => 'ee_delete_contacts',
355
+				'obj_id'     => $att_id,
356
+			),
357
+			'resend_registration'  => array(
358
+				'func'       => '_resend_registration',
359
+				'noheader'   => true,
360
+				'capability' => 'ee_send_message',
361
+			),
362
+			'registrations_report' => array(
363
+				'func'       => '_registrations_report',
364
+				'noheader'   => true,
365
+				'capability' => 'ee_read_registrations',
366
+			),
367
+			'contact_list_export'  => array(
368
+				'func'       => '_contact_list_export',
369
+				'noheader'   => true,
370
+				'capability' => 'export',
371
+			),
372
+			'contact_list_report'  => array(
373
+				'func'       => '_contact_list_report',
374
+				'noheader'   => true,
375
+				'capability' => 'ee_read_contacts',
376
+			),
377
+		);
378
+	}
379
+
380
+
381
+
382
+	protected function _set_page_config()
383
+	{
384
+		$this->_page_config = array(
385
+			'default' => array(
386
+				'nav'           => array(
387
+					'label' => __('Overview', 'event_espresso'),
388
+					'order' => 5,
389
+				),
390
+				'help_tabs'     => array(
391
+					'registrations_overview_help_tab'                       => array(
392
+						'title'    => __('Registrations Overview', 'event_espresso'),
393
+						'filename' => 'registrations_overview',
394
+					),
395
+					'registrations_overview_table_column_headings_help_tab' => array(
396
+						'title'    => __('Registrations Table Column Headings', 'event_espresso'),
397
+						'filename' => 'registrations_overview_table_column_headings',
398
+					),
399
+					'registrations_overview_filters_help_tab'               => array(
400
+						'title'    => __('Registration Filters', 'event_espresso'),
401
+						'filename' => 'registrations_overview_filters',
402
+					),
403
+					'registrations_overview_views_help_tab'                 => array(
404
+						'title'    => __('Registration Views', 'event_espresso'),
405
+						'filename' => 'registrations_overview_views',
406
+					),
407
+					'registrations_regoverview_other_help_tab'              => array(
408
+						'title'    => __('Registrations Other', 'event_espresso'),
409
+						'filename' => 'registrations_overview_other',
410
+					),
411
+				),
412
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
413
+				'qtips'         => array('Registration_List_Table_Tips'),
414
+				'list_table'    => 'EE_Registrations_List_Table',
415
+				'require_nonce' => false,
416
+			),
417
+			'view_registration' => array(
418
+				'nav'           => array(
419
+					'label'      => __('REG Details', 'event_espresso'),
420
+					'order'      => 15,
421
+					'url'        => isset($this->_req_data['_REG_ID'])
422
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
423
+						: $this->_admin_base_url,
424
+					'persistent' => false,
425
+				),
426
+				'help_tabs'     => array(
427
+					'registrations_details_help_tab'                    => array(
428
+						'title'    => __('Registration Details', 'event_espresso'),
429
+						'filename' => 'registrations_details',
430
+					),
431
+					'registrations_details_table_help_tab'              => array(
432
+						'title'    => __('Registration Details Table', 'event_espresso'),
433
+						'filename' => 'registrations_details_table',
434
+					),
435
+					'registrations_details_form_answers_help_tab'       => array(
436
+						'title'    => __('Registration Form Answers', 'event_espresso'),
437
+						'filename' => 'registrations_details_form_answers',
438
+					),
439
+					'registrations_details_registrant_details_help_tab' => array(
440
+						'title'    => __('Contact Details', 'event_espresso'),
441
+						'filename' => 'registrations_details_registrant_details',
442
+					),
443
+				),
444
+				'help_tour'     => array('Registration_Details_Help_Tour'),
445
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
446
+					array('_registration_details_metaboxes')),
447
+				'require_nonce' => false,
448
+			),
449
+			'new_registration' => array(
450
+				'nav'           => array(
451
+					'label'      => __('Add New Registration', 'event_espresso'),
452
+					'url'        => '#',
453
+					'order'      => 15,
454
+					'persistent' => false,
455
+				),
456
+				'metaboxes'     => $this->_default_espresso_metaboxes,
457
+				'labels'        => array(
458
+					'publishbox' => __('Save Registration', 'event_espresso'),
459
+				),
460
+				'require_nonce' => false,
461
+			),
462
+			'add_new_attendee' => array(
463
+				'nav'           => array(
464
+					'label'      => __('Add Contact', 'event_espresso'),
465
+					'order'      => 15,
466
+					'persistent' => false,
467
+				),
468
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
469
+					array('_publish_post_box', 'attendee_editor_metaboxes')),
470
+				'require_nonce' => false,
471
+			),
472
+			'edit_attendee' => array(
473
+				'nav'           => array(
474
+					'label'      => __('Edit Contact', 'event_espresso'),
475
+					'order'      => 15,
476
+					'persistent' => false,
477
+					'url'        => isset($this->_req_data['ATT_ID'])
478
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
479
+						: $this->_admin_base_url,
480
+				),
481
+				'metaboxes'     => array('attendee_editor_metaboxes'),
482
+				'require_nonce' => false,
483
+			),
484
+			'contact_list' => array(
485
+				'nav'           => array(
486
+					'label' => __('Contact List', 'event_espresso'),
487
+					'order' => 20,
488
+				),
489
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
490
+				'help_tabs'     => array(
491
+					'registrations_contact_list_help_tab'                       => array(
492
+						'title'    => __('Registrations Contact List', 'event_espresso'),
493
+						'filename' => 'registrations_contact_list',
494
+					),
495
+					'registrations_contact-list_table_column_headings_help_tab' => array(
496
+						'title'    => __('Contact List Table Column Headings', 'event_espresso'),
497
+						'filename' => 'registrations_contact_list_table_column_headings',
498
+					),
499
+					'registrations_contact_list_views_help_tab'                 => array(
500
+						'title'    => __('Contact List Views', 'event_espresso'),
501
+						'filename' => 'registrations_contact_list_views',
502
+					),
503
+					'registrations_contact_list_other_help_tab'                 => array(
504
+						'title'    => __('Contact List Other', 'event_espresso'),
505
+						'filename' => 'registrations_contact_list_other',
506
+					),
507
+				),
508
+				'help_tour'     => array('Contact_List_Help_Tour'),
509
+				'metaboxes'     => array(),
510
+				'require_nonce' => false,
511
+			),
512
+			//override default cpt routes
513
+			'create_new'   => '',
514
+			'edit'         => '',
515
+		);
516
+	}
517
+
518
+
519
+
520
+	/**
521
+	 * The below methods aren't used by this class currently
522
+	 */
523
+	protected function _add_screen_options()
524
+	{
525
+	}
526
+
527
+
528
+
529
+	protected function _add_feature_pointers()
530
+	{
531
+	}
532
+
533
+
534
+
535
+	public function admin_init()
536
+	{
537
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = __('click "Update Registration Questions" to save your changes',
538
+			'event_espresso');
539
+	}
540
+
541
+
542
+
543
+	public function admin_notices()
544
+	{
545
+	}
546
+
547
+
548
+
549
+	public function admin_footer_scripts()
550
+	{
551
+	}
552
+
553
+
554
+
555
+	/**
556
+	 *        get list of registration statuses
557
+	 *
558
+	 * @access private
559
+	 * @return void
560
+	 */
561
+	private function _get_registration_status_array()
562
+	{
563
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
564
+	}
565
+
566
+
567
+
568
+	protected function _add_screen_options_default()
569
+	{
570
+		$this->_per_page_screen_option();
571
+	}
572
+
573
+
574
+
575
+	protected function _add_screen_options_contact_list()
576
+	{
577
+		$page_title = $this->_admin_page_title;
578
+		$this->_admin_page_title = __("Contacts", 'event_espresso');
579
+		$this->_per_page_screen_option();
580
+		$this->_admin_page_title = $page_title;
581
+	}
582
+
583
+
584
+
585
+	public function load_scripts_styles()
586
+	{
587
+		//style
588
+		//wp_register_style('espresso_attendees', ATT_ASSETS_URL . 'espresso_attendees_admin.css', array(), EVENT_ESPRESSO_VERSION );
589
+		wp_register_style('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.css', array('ee-admin-css'),
590
+			EVENT_ESPRESSO_VERSION);
591
+		wp_enqueue_style('espresso_reg');
592
+		//script
593
+		wp_register_script('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.js',
594
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'), EVENT_ESPRESSO_VERSION, true);
595
+		wp_enqueue_script('espresso_reg');
596
+	}
597
+
598
+
599
+
600
+	public function load_scripts_styles_edit_attendee()
601
+	{
602
+		//stuff to only show up on our attendee edit details page.
603
+		$attendee_details_translations = array(
604
+			'att_publish_text' => sprintf(__('Created on: <b>%1$s</b>', 'event_espresso'),
605
+				$this->_cpt_model_obj->get_datetime('ATT_created')),
606
+		);
607
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
608
+		wp_enqueue_script('jquery-validate');
609
+	}
610
+
611
+
612
+
613
+	public function load_scripts_styles_view_registration()
614
+	{
615
+		//styles
616
+		wp_enqueue_style('espresso-ui-theme');
617
+		//scripts
618
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
619
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
620
+	}
621
+
622
+
623
+
624
+	public function load_scripts_styles_contact_list()
625
+	{
626
+		wp_deregister_style('espresso_reg');
627
+		wp_register_style('espresso_att', REG_ASSETS_URL . 'espresso_attendees_admin.css', array('ee-admin-css'),
628
+			EVENT_ESPRESSO_VERSION);
629
+		wp_enqueue_style('espresso_att');
630
+	}
631
+
632
+
633
+
634
+	public function load_scripts_styles_new_registration()
635
+	{
636
+		wp_register_script('ee-spco-for-admin', REG_ASSETS_URL . 'spco_for_admin.js', array('underscore', 'jquery'),
637
+			EVENT_ESPRESSO_VERSION, true);
638
+		wp_enqueue_script('ee-spco-for-admin');
639
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
640
+		EE_Form_Section_Proper::wp_enqueue_scripts();
641
+		EED_Ticket_Selector::load_tckt_slctr_assets();
642
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
643
+	}
644
+
645
+
646
+
647
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
648
+	{
649
+		add_filter('FHEE_load_EE_messages', '__return_true');
650
+	}
651
+
652
+
653
+
654
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
655
+	{
656
+		add_filter('FHEE_load_EE_messages', '__return_true');
657
+	}
658
+
659
+
660
+
661
+	protected function _set_list_table_views_default()
662
+	{
663
+		//for notification related bulk actions we need to make sure only active messengers have an option.
664
+		EED_Messages::set_autoloaders();
665
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
666
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
667
+		$active_mts = $message_resource_manager->list_of_active_message_types();
668
+		//key= bulk_action_slug, value= message type.
669
+		$match_array = array(
670
+			'approve_registration'    => 'registration',
671
+			'decline_registration'    => 'declined_registration',
672
+			'pending_registration'    => 'pending_approval',
673
+			'no_approve_registration' => 'not_approved_registration',
674
+			'cancel_registration'     => 'cancelled_registration',
675
+		);
676
+		/** setup reg status bulk actions **/
677
+		$def_reg_status_actions['approve_registration'] = __('Approve Registrations', 'event_espresso');
678
+		if (in_array($match_array['approve_registration'], $active_mts)
679
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
680
+		) {
681
+			$def_reg_status_actions['approve_and_notify_registration'] = __('Approve and Notify Registrations',
682
+				'event_espresso');
683
+		}
684
+		$def_reg_status_actions['decline_registration'] = __('Decline Registrations', 'event_espresso');
685
+		if (in_array($match_array['decline_registration'], $active_mts)
686
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
687
+		) {
688
+			$def_reg_status_actions['decline_and_notify_registration'] = __('Decline and Notify Registrations',
689
+				'event_espresso');
690
+		}
691
+		$def_reg_status_actions['pending_registration'] = __('Set Registrations to Pending Payment', 'event_espresso');
692
+		if (in_array($match_array['pending_registration'], $active_mts)
693
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
694
+		) {
695
+			$def_reg_status_actions['pending_and_notify_registration'] = __('Set Registrations to Pending Payment and Notify',
696
+				'event_espresso');
697
+		}
698
+		$def_reg_status_actions['no_approve_registration'] = __('Set Registrations to Not Approved', 'event_espresso');
699
+		if (in_array($match_array['no_approve_registration'], $active_mts)
700
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
701
+		) {
702
+			$def_reg_status_actions['no_approve_and_notify_registration'] = __('Set Registrations to Not Approved and Notify',
703
+				'event_espresso');
704
+		}
705
+		$def_reg_status_actions['cancel_registration'] = __('Cancel Registrations', 'event_espresso');
706
+		if (in_array($match_array['cancel_registration'], $active_mts)
707
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
708
+		) {
709
+			$def_reg_status_actions['cancel_and_notify_registration'] = __('Cancel Registrations and Notify',
710
+				'event_espresso');
711
+		}
712
+		$this->_views = array(
713
+			'all'   => array(
714
+				'slug'        => 'all',
715
+				'label'       => __('View All Registrations', 'event_espresso'),
716
+				'count'       => 0,
717
+				'bulk_action' => array_merge($def_reg_status_actions, array(
718
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
719
+				)),
720
+			),
721
+			'month' => array(
722
+				'slug'        => 'month',
723
+				'label'       => __('This Month', 'event_espresso'),
724
+				'count'       => 0,
725
+				'bulk_action' => array_merge($def_reg_status_actions, array(
726
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
727
+				)),
728
+			),
729
+			'today' => array(
730
+				'slug'        => 'today',
731
+				'label'       => sprintf(__('Today - %s', 'event_espresso'), date('M d, Y', current_time('timestamp'))),
732
+				'count'       => 0,
733
+				'bulk_action' => array_merge($def_reg_status_actions, array(
734
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
735
+				)),
736
+			),
737
+		);
738
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
739
+			'espresso_registrations_delete_registration')
740
+		) {
741
+			$this->_views['incomplete'] = array(
742
+				'slug'        => 'incomplete',
743
+				'label'       => __('Incomplete', 'event_espresso'),
744
+				'count'       => 0,
745
+				'bulk_action' => array(
746
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
747
+				),
748
+			);
749
+			$this->_views['trash'] = array(
750
+				'slug'        => 'trash',
751
+				'label'       => __('Trash', 'event_espresso'),
752
+				'count'       => 0,
753
+				'bulk_action' => array(
754
+					'restore_registrations' => __('Restore Registrations', 'event_espresso'),
755
+					'delete_registrations'  => __('Delete Registrations Permanently', 'event_espresso'),
756
+				),
757
+			);
758
+		}
759
+	}
760
+
761
+
762
+
763
+	protected function _set_list_table_views_contact_list()
764
+	{
765
+		$this->_views = array(
766
+			'in_use' => array(
767
+				'slug'        => 'in_use',
768
+				'label'       => __('In Use', 'event_espresso'),
769
+				'count'       => 0,
770
+				'bulk_action' => array(
771
+					'trash_attendees' => __('Move to Trash', 'event_espresso'),
772
+				),
773
+			),
774
+		);
775
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
776
+			'espresso_registrations_trash_attendees')
777
+		) {
778
+			$this->_views['trash'] = array(
779
+				'slug'        => 'trash',
780
+				'label'       => __('Trash', 'event_espresso'),
781
+				'count'       => 0,
782
+				'bulk_action' => array(
783
+					'restore_attendees' => __('Restore from Trash', 'event_espresso'),
784
+				),
785
+			);
786
+		}
787
+	}
788
+
789
+
790
+
791
+	protected function _registration_legend_items()
792
+	{
793
+		$fc_items = array(
794
+			'star-icon'        => array(
795
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
796
+				'desc'  => __('This is the Primary Registrant', 'event_espresso'),
797
+			),
798
+			'view_details'     => array(
799
+				'class' => 'dashicons dashicons-clipboard',
800
+				'desc'  => __('View Registration Details', 'event_espresso'),
801
+			),
802
+			'edit_attendee'    => array(
803
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
804
+				'desc'  => __('Edit Contact Details', 'event_espresso'),
805
+			),
806
+			'view_transaction' => array(
807
+				'class' => 'dashicons dashicons-cart',
808
+				'desc'  => __('View Transaction Details', 'event_espresso'),
809
+			),
810
+			'view_invoice'     => array(
811
+				'class' => 'dashicons dashicons-media-spreadsheet',
812
+				'desc'  => __('View Transaction Invoice', 'event_espresso'),
813
+			),
814
+		);
815
+		if (EE_Registry::instance()->CAP->current_user_can('ee_send_message',
816
+			'espresso_registrations_resend_registration')
817
+		) {
818
+			$fc_items['resend_registration'] = array(
819
+				'class' => 'dashicons dashicons-email-alt',
820
+				'desc'  => __('Resend Registration Details', 'event_espresso'),
821
+			);
822
+		} else {
823
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
824
+		}
825
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
826
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
827
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
828
+				$fc_items['view_related_messages'] = array(
829
+					'class' => $related_for_icon['css_class'],
830
+					'desc'  => $related_for_icon['label'],
831
+				);
832
+			}
833
+		}
834
+		$sc_items = array(
835
+			'approved_status'   => array(
836
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
837
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
838
+			),
839
+			'pending_status'    => array(
840
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
841
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
842
+			),
843
+			'wait_list'         => array(
844
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
845
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
846
+			),
847
+			'incomplete_status' => array(
848
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
849
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_incomplete, false, 'sentence'),
850
+			),
851
+			'not_approved'      => array(
852
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
853
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
854
+			),
855
+			'declined_status'   => array(
856
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
857
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
858
+			),
859
+			'cancelled_status'  => array(
860
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
861
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
862
+			),
863
+		);
864
+		return array_merge($fc_items, $sc_items);
865
+	}
866
+
867
+
868
+
869
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
870
+	/**
871
+	 * @throws \EE_Error
872
+	 */
873
+	protected function _registrations_overview_list_table()
874
+	{
875
+		$this->_template_args['admin_page_header'] = '';
876
+		$EVT_ID = ! empty($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : 0;
877
+		if ($EVT_ID) {
878
+			if (EE_Registry::instance()->CAP->current_user_can('ee_edit_registrations',
879
+				'espresso_registrations_new_registration', $EVT_ID)
880
+			) {
881
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button('new_registration', 'add-registrant',
882
+						array('event_id' => $EVT_ID), 'add-new-h2');
883
+			}
884
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
885
+			if ($event instanceof EE_Event) {
886
+				$this->_template_args['admin_page_header'] = sprintf(__('%s Viewing registrations for the event: %s%s',
887
+					'event_espresso'), '<h3 style="line-height:1.5em;">',
888
+					'<br /><a href="' . EE_Admin_Page::add_query_args_and_nonce(array(
889
+						'action' => 'edit',
890
+						'post'   => $event->ID(),
891
+					), EVENTS_ADMIN_URL) . '">&nbsp;' . $event->get('EVT_name') . '&nbsp;</a>&nbsp;', '</h3>');
892
+			}
893
+			$DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
894
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
895
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
896
+				$this->_template_args['admin_page_header'] = substr($this->_template_args['admin_page_header'], 0, -5);
897
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
898
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
899
+				$this->_template_args['admin_page_header'] .= $datetime->name();
900
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
901
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
902
+			}
903
+		}
904
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
905
+		$this->display_admin_list_table_page_with_no_sidebar();
906
+	}
907
+
908
+
909
+
910
+	/**
911
+	 * This sets the _registration property for the registration details screen
912
+	 *
913
+	 * @access private
914
+	 * @return bool
915
+	 */
916
+	private function _set_registration_object()
917
+	{
918
+		//get out if we've already set the object
919
+		if (is_object($this->_registration)) {
920
+			return true;
921
+		}
922
+		$REG = EEM_Registration::instance();
923
+		$REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
924
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
925
+			return true;
926
+		} else {
927
+			$error_msg = sprintf(__('An error occurred and the details for Registration ID #%s could not be retrieved.',
928
+				'event_espresso'), $REG_ID);
929
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
930
+			$this->_registration = null;
931
+			return false;
932
+		}
933
+	}
934
+
935
+
936
+
937
+	/**
938
+	 * get registrations for given parameters (used by list table)
939
+	 *
940
+	 * @param  int     $per_page   how many registrations displayed per page
941
+	 * @param  boolean $count      return the count or objects
942
+	 * @param  boolean $this_month whether to return for just this month
943
+	 * @param  boolean $today      whether to return results for just today
944
+	 * @throws \EE_Error
945
+	 * @return mixed (int|array)  int = count || array of registration objects
946
+	 */
947
+	public function get_registrations($per_page = 10, $count = false, $this_month = false, $today = false)
948
+	{
949
+		$EVT_ID = ! empty($this->_req_data['event_id']) && $this->_req_data['event_id'] > 0
950
+			? absint($this->_req_data['event_id']) : false;
951
+		$CAT_ID = ! empty($this->_req_data['EVT_CAT']) && (int)$this->_req_data['EVT_CAT'] > 0
952
+			? absint($this->_req_data['EVT_CAT']) : false;
953
+		$DTT_ID = isset($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : null;
954
+		$reg_status = ! empty($this->_req_data['_reg_status']) ? sanitize_text_field($this->_req_data['_reg_status'])
955
+			: false;
956
+		$month_range = ! empty($this->_req_data['month_range']) ? sanitize_text_field($this->_req_data['month_range'])
957
+			: false;//should be like 2013-april
958
+		$today_a = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'today' ? true : false;
959
+		$this_month_a = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'month' ? true : false;
960
+		$start_date = false;
961
+		$end_date = false;
962
+		$_where = array();
963
+		$trash = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'trash' ? true : false;
964
+		$incomplete = ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' ? true : false;
965
+		//set orderby
966
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
967
+		switch ($this->_req_data['orderby']) {
968
+			case '_REG_ID':
969
+				$orderby = 'REG_ID';
970
+				break;
971
+			case '_Reg_status':
972
+				$orderby = 'STS_ID';
973
+				break;
974
+			case 'ATT_fname':
975
+				$orderby = 'Attendee.ATT_lname';
976
+				break;
977
+			case 'event_name':
978
+				$orderby = 'Event.EVT_name';
979
+				break;
980
+			case 'DTT_EVT_start':
981
+				$orderby = 'Event.Datetime.DTT_EVT_start';
982
+				break;
983
+			default: //'REG_date'
984
+				$orderby = 'REG_date';
985
+		}
986
+		$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
987
+			: 'DESC';
988
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
989
+			? $this->_req_data['paged'] : 1;
990
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
991
+			? $this->_req_data['perpage'] : $per_page;
992
+		$offset = ($current_page - 1) * $per_page;
993
+		$limit = $count ? null : array($offset, $per_page);
994
+		if ($EVT_ID) {
995
+			$_where['EVT_ID'] = $EVT_ID;
996
+		}
997
+		if ($CAT_ID) {
998
+			$_where['Event.Term_Taxonomy.term_id'] = $CAT_ID;
999
+		}
1000
+		//if DTT is included we filter by that datetime.
1001
+		if ($DTT_ID) {
1002
+			$_where['Ticket.Datetime.DTT_ID'] = $DTT_ID;
1003
+		}
1004
+		if ($incomplete) {
1005
+			$_where['STS_ID'] = EEM_Registration::status_id_incomplete;
1006
+		} else if ( ! $trash) {
1007
+			$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1008
+		}
1009
+		if ($reg_status) {
1010
+			$_where['STS_ID'] = $reg_status;
1011
+		}
1012
+		$this_year_r = date('Y', current_time('timestamp'));
1013
+		$time_start = ' 00:00:00';
1014
+		$time_end = ' 23:59:59';
1015
+		if ($today_a || $today) {
1016
+			$curdate = date('Y-m-d', current_time('timestamp'));
1017
+			$_where['REG_date'] = array(
1018
+				'BETWEEN',
1019
+				array(
1020
+					EEM_Registration::instance()
1021
+									->convert_datetime_for_query('REG_date', $curdate . $time_start, 'Y-m-d H:i:s'),
1022
+					EEM_Registration::instance()
1023
+									->convert_datetime_for_query('REG_date', $curdate . $time_end, 'Y-m-d H:i:s'),
1024
+				),
1025
+			);
1026
+		} elseif ($this_month_a || $this_month) {
1027
+			$this_month_r = date('m', current_time('timestamp'));
1028
+			$days_this_month = date('t', current_time('timestamp'));
1029
+			$_where['REG_date'] = array(
1030
+				'BETWEEN',
1031
+				array(
1032
+					EEM_Registration::instance()
1033
+									->convert_datetime_for_query('REG_date',
1034
+										$this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start, 'Y-m-d H:i:s'),
1035
+					EEM_Registration::instance()
1036
+									->convert_datetime_for_query('REG_date',
1037
+										$this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
1038
+										'Y-m-d H:i:s'),
1039
+				),
1040
+			);
1041
+		} elseif ($month_range) {
1042
+			$pieces = explode(' ', $this->_req_data['month_range'], 3);
1043
+			$month_r = ! empty($pieces[0]) ? date('m', strtotime($month_range)) : '';
1044
+			$year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1045
+			$days_in_month = date('t', strtotime($year_r . '-' . $month_r . '-' . '01'));
1046
+			$_where['REG_date'] = array(
1047
+				'BETWEEN',
1048
+				array(
1049
+					EEM_Registration::instance()
1050
+									->convert_datetime_for_query('REG_date', $year_r . '-' . $month_r . '-01 00:00:00',
1051
+										'Y-m-d H:i:s'),
1052
+					EEM_Registration::instance()
1053
+									->convert_datetime_for_query('REG_date',
1054
+										$year_r . '-' . $month_r . '-' . $days_in_month . ' 23:59:59', 'Y-m-d H:i:s'),
1055
+				),
1056
+			);
1057
+		} elseif ($start_date && $end_date) {
1058
+			throw new EE_Error("not yet supported");
1059
+		} elseif ($start_date) {
1060
+			throw new EE_Error("not yet supported");
1061
+		} elseif ($end_date) {
1062
+			throw new EE_Error("not yet supported");
1063
+		}
1064
+		if ( ! empty($this->_req_data['s'])) {
1065
+			$sstr = '%' . $this->_req_data['s'] . '%';
1066
+			$_where['OR'] = array(
1067
+				'Event.EVT_name'                          => array('LIKE', $sstr),
1068
+				'Event.EVT_desc'                          => array('LIKE', $sstr),
1069
+				'Event.EVT_short_desc'                    => array('LIKE', $sstr),
1070
+				'Attendee.ATT_full_name'                  => array('LIKE', $sstr),
1071
+				'Attendee.ATT_fname'                      => array('LIKE', $sstr),
1072
+				'Attendee.ATT_lname'                      => array('LIKE', $sstr),
1073
+				'Attendee.ATT_short_bio'                  => array('LIKE', $sstr),
1074
+				'Attendee.ATT_email'                      => array('LIKE', $sstr),
1075
+				'Attendee.ATT_address'                    => array('LIKE', $sstr),
1076
+				'Attendee.ATT_address2'                   => array('LIKE', $sstr),
1077
+				'Attendee.ATT_city'                       => array('LIKE', $sstr),
1078
+				'REG_final_price'                         => array('LIKE', $sstr),
1079
+				'REG_code'                                => array('LIKE', $sstr),
1080
+				'REG_count'                               => array('LIKE', $sstr),
1081
+				'REG_group_size'                          => array('LIKE', $sstr),
1082
+				'Ticket.TKT_name'                         => array('LIKE', $sstr),
1083
+				'Ticket.TKT_description'                  => array('LIKE', $sstr),
1084
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $sstr),
1085
+			);
1086
+		}
1087
+		//capability checks
1088
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'get_registrations')) {
1089
+			$_where['AND'] = array(
1090
+				'Event.EVT_wp_user' => get_current_user_id(),
1091
+			);
1092
+		}
1093
+		if ($count) {
1094
+			if ($trash) {
1095
+				return EEM_Registration::instance()->count_deleted(array($_where));
1096
+			} else if ($incomplete) {
1097
+				return EEM_Registration::instance()->count(array($_where));
1098
+			} else {
1099
+				return EEM_Registration::instance()->count(array(
1100
+					$_where,
1101
+					'default_where_conditions' => 'this_model_only',
1102
+				));
1103
+			}
1104
+		} else {
1105
+			//make sure we remove default where conditions cause all registrations matching query are returned
1106
+			$query_params = array(
1107
+				$_where,
1108
+				'order_by'                 => array($orderby => $sort),
1109
+				'default_where_conditions' => 'this_model_only',
1110
+			);
1111
+			if ($per_page !== -1) {
1112
+				$query_params['limit'] = $limit;
1113
+			}
1114
+			$registrations = $trash ? EEM_Registration::instance()->get_all_deleted($query_params)
1115
+				: EEM_Registration::instance()->get_all($query_params);
1116
+			if ($EVT_ID
1117
+				&& isset($registrations[0])
1118
+				&& $registrations[0] instanceof EE_Registration
1119
+				&& $registrations[0]->event_obj()
1120
+			) {
1121
+				$first_registration = $registrations[0];
1122
+				//EEH_Debug_Tools::printr( $registrations[0], '$registrations  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
1123
+				$event_name = $first_registration->event_obj()->name();
1124
+				$event_date = $first_registration->date_obj()
1125
+												 ->start_date_and_time('l F j, Y,',
1126
+													 'g:i:s a');// isset( $registrations[0]->DTT_EVT_start ) ? date( 'l F j, Y,    g:i:s a', $registrations[0]->DTT_EVT_start ) : '';
1127
+				// edit event link
1128
+				if ($event_name != '') {
1129
+					$edit_event_url = self::add_query_args_and_nonce(array(
1130
+						'action' => 'edit_event',
1131
+						'EVT_ID' => $EVT_ID,
1132
+					), EVENTS_ADMIN_URL);
1133
+					$edit_event_lnk = '<a href="' . $edit_event_url . '" title="' . esc_attr__('Edit ',
1134
+							'event_espresso') . $event_name . '">' . __('Edit Event', 'event_espresso') . '</a>';
1135
+					$event_name .= ' <span class="admin-page-header-edit-lnk not-bold">' . $edit_event_lnk . '</span>';
1136
+				}
1137
+				$back_2_reg_url = self::add_query_args_and_nonce(array('action' => 'default'), REG_ADMIN_URL);
1138
+				$back_2_reg_lnk = '<a href="'
1139
+								  . $back_2_reg_url
1140
+								  . '" title="'
1141
+								  . esc_attr__('click to return to viewing all registrations ', 'event_espresso')
1142
+								  . '">&laquo; '
1143
+								  . __('Back to All Registrations', 'event_espresso')
1144
+								  . '</a>';
1145
+				$this->_template_args['before_admin_page_content'] = '
1146 1146
 			<div id="admin-page-header">
1147 1147
 				<h1><span class="small-text not-bold">' . __('Event: ', 'event_espresso') . '</span>' . $event_name . '</h1>
1148 1148
 				<h3><span class="small-text not-bold">' . __('Date: ', 'event_espresso') . '</span>' . $event_date . '</h3>
1149 1149
 				<span class="admin-page-header-go-back-lnk not-bold">' . $back_2_reg_lnk . '</span>
1150 1150
 			</div>
1151 1151
 			';
1152
-            }
1153
-            return $registrations;
1154
-        }
1155
-    }
1156
-
1157
-
1158
-
1159
-    public function get_registration_status_array()
1160
-    {
1161
-        return self::$_reg_status;
1162
-    }
1163
-
1164
-
1165
-
1166
-
1167
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1168
-    /**
1169
-     *        generates HTML for the View Registration Details Admin page
1170
-     *
1171
-     * @access protected
1172
-     * @return void
1173
-     */
1174
-    protected function _registration_details()
1175
-    {
1176
-        $this->_template_args = array();
1177
-        $this->_set_registration_object();
1178
-        if (is_object($this->_registration)) {
1179
-            $transaction = $this->_registration->transaction() ? $this->_registration->transaction()
1180
-                : EE_Transaction::new_instance();
1181
-            $this->_session = $transaction->session_data();
1182
-            $event_id = $this->_registration->event_ID();
1183
-            $this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1184
-            $this->_template_args['reg_nmbr']['label'] = __('Registration Number', 'event_espresso');
1185
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1186
-            $this->_template_args['reg_datetime']['label'] = __('Date', 'event_espresso');
1187
-            $this->_template_args['grand_total'] = $transaction->total();
1188
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1189
-            // link back to overview
1190
-            $this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1191
-            $this->_template_args['registration'] = $this->_registration;
1192
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1193
-                'action'   => 'default',
1194
-                'event_id' => $event_id,
1195
-            ), REG_ADMIN_URL);
1196
-            $this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1197
-                'action' => 'default',
1198
-                'EVT_ID' => $event_id,
1199
-                'page'   => 'espresso_transactions',
1200
-            ), admin_url('admin.php'));
1201
-            $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1202
-                'page'   => 'espresso_events',
1203
-                'action' => 'edit',
1204
-                'post'   => $event_id,
1205
-            ), admin_url('admin.php'));
1206
-            //next and previous links
1207
-            $next_reg = $this->_registration->next(null, array(), 'REG_ID');
1208
-            $this->_template_args['next_registration'] = $next_reg
1209
-                ? $this->_next_link(EE_Admin_Page::add_query_args_and_nonce(array(
1210
-                    'action'  => 'view_registration',
1211
-                    '_REG_ID' => $next_reg['REG_ID'],
1212
-                ), REG_ADMIN_URL), 'dashicons dashicons-arrow-right ee-icon-size-22') : '';
1213
-            $previous_reg = $this->_registration->previous(null, array(), 'REG_ID');
1214
-            $this->_template_args['previous_registration'] = $previous_reg
1215
-                ? $this->_previous_link(EE_Admin_Page::add_query_args_and_nonce(array(
1216
-                    'action'  => 'view_registration',
1217
-                    '_REG_ID' => $previous_reg['REG_ID'],
1218
-                ), REG_ADMIN_URL), 'dashicons dashicons-arrow-left ee-icon-size-22') : '';
1219
-            // grab header
1220
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1221
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
1222
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
1223
-                $this->_template_args, true);
1224
-        } else {
1225
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1226
-        }
1227
-        // the details template wrapper
1228
-        $this->display_admin_page_with_sidebar();
1229
-    }
1230
-
1231
-
1232
-
1233
-    protected function _registration_details_metaboxes()
1234
-    {
1235
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1236
-        $this->_set_registration_object();
1237
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1238
-        add_meta_box('edit-reg-status-mbox', __('Registration Status', 'event_espresso'),
1239
-            array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1240
-        add_meta_box('edit-reg-details-mbox', __('Registration Details', 'event_espresso'),
1241
-            array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1242
-        if ($attendee instanceof EE_Attendee
1243
-            && EE_Registry::instance()->CAP->current_user_can('ee_edit_registration', 'edit-reg-questions-mbox')
1244
-        ) {
1245
-            add_meta_box('edit-reg-questions-mbox', __('Registration Form Answers', 'event_espresso'),
1246
-                array($this, '_reg_questions_meta_box'), $this->wp_page_slug, 'normal', 'high');
1247
-        }
1248
-        add_meta_box('edit-reg-registrant-mbox', __('Contact Details', 'event_espresso'),
1249
-            array($this, '_reg_registrant_side_meta_box'), $this->wp_page_slug, 'side', 'high');
1250
-        if ($this->_registration->group_size() > 1) {
1251
-            add_meta_box('edit-reg-attendees-mbox', __('Other Registrations in this Transaction', 'event_espresso'),
1252
-                array($this, '_reg_attendees_meta_box'), $this->wp_page_slug, 'normal', 'high');
1253
-        }
1254
-    }
1255
-
1256
-
1257
-
1258
-    /**
1259
-     * set_reg_status_buttons_metabox
1260
-     *
1261
-     * @access protected
1262
-     * @return string
1263
-     * @throws \EE_Error
1264
-     */
1265
-    public function set_reg_status_buttons_metabox()
1266
-    {
1267
-        $this->_set_registration_object();
1268
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1269
-        echo $change_reg_status_form->form_open(self::add_query_args_and_nonce(array(
1270
-            'action' => 'change_reg_status',
1271
-        ), REG_ADMIN_URL));
1272
-        echo $change_reg_status_form->get_html();
1273
-        echo $change_reg_status_form->form_close();
1274
-    }
1275
-
1276
-
1277
-
1278
-    /**
1279
-     * @return EE_Form_Section_Proper
1280
-     */
1281
-    protected function _generate_reg_status_change_form()
1282
-    {
1283
-        return new EE_Form_Section_Proper(array(
1284
-                'name'            => 'reg_status_change_form',
1285
-                'html_id'         => 'reg-status-change-form',
1286
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1287
-                'subsections'     => array(
1288
-                    'return'             => new EE_Hidden_Input(array(
1289
-                        'name'    => 'return',
1290
-                        'default' => 'view_registration',
1291
-                    )),
1292
-                    'REG_ID'             => new EE_Hidden_Input(array(
1293
-                        'name'    => 'REG_ID',
1294
-                        'default' => $this->_registration->ID(),
1295
-                    )),
1296
-                    'current_status'     => new EE_Form_Section_HTML(EEH_HTML::tr(EEH_HTML::th(EEH_HTML::label(EEH_HTML::strong(__('Current Registration Status',
1297
-                            'event_espresso')))) . EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1298
-                            '', 'status-' . $this->_registration->status_ID(),
1299
-                            'line-height: 1em; font-size: 1.5em; font-weight: bold;')))),
1300
-                    'reg_status'         => new EE_Select_Input($this->_get_reg_statuses(), array(
1301
-                            'html_label_text' => __('Change Registration Status to', 'event_espresso'),
1302
-                            'default'         => $this->_registration->status_ID(),
1303
-                        )),
1304
-                    'send_notifications' => new EE_Yes_No_Input(array(
1305
-                            'html_label_text' => __('Send Related Messages', 'event_espresso'),
1306
-                            'default'         => false,
1307
-                            'html_help_text'  => __('If set to "Yes", then the related messages will be sent to the registrant.',
1308
-                                'event_espresso'),
1309
-                        )),
1310
-                    'submit'             => new EE_Submit_Input(array(
1311
-                        'html_class'      => 'button-primary',
1312
-                        'html_label_text' => '&nbsp;',
1313
-                        'default'         => __('Update Registration Status', 'event_espresso'),
1314
-                    )),
1315
-                ),
1316
-            ));
1317
-    }
1318
-
1319
-
1320
-
1321
-    /**
1322
-     * Returns an array of all the buttons for the various statuses and switch status actions
1323
-     *
1324
-     * @return string
1325
-     */
1326
-    protected function _get_current_reg_status_help_text($STS_ID = '')
1327
-    {
1328
-        //$reg_status_help_text = array(
1329
-        //	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1330
-        //	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1331
-        //	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1332
-        //	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1333
-        //	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1334
-        //	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1335
-        //);
1336
-        //Approved
1337
-        //An approved registration allows payments and may have a transaction status of incomplete or complete . The registration is marked as active and a space is reserved for the registrant .
1338
-        //Cancelled
1339
-        //	A {
1340
-        //	cancelled} registration is performed by the registrant . Payments are not allowed, the registration is inactive, and no space is reserved .
1341
-        //Declined
1342
-        //A declined registration is performed by the event admin . Payments are not allowed, the registration is inactive, and not space is reserved .
1343
-        //Not Approved
1344
-        //A not approved registration is performed by the event admin . Payments are not allowed, the registration is active, and no space is reserved .
1345
-        //Pending Payment
1346
-        //A pending registration allows payments . The status will be automatically toggled to approved if the {
1347
-        //	payment} is made in full by registrant .
1348
-    }
1349
-
1350
-
1351
-
1352
-    /**
1353
-     * Returns an array of all the buttons for the various statuses and switch status actions
1354
-     *
1355
-     * @return array
1356
-     */
1357
-    protected function _get_reg_statuses()
1358
-    {
1359
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1360
-        unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1361
-        // get current reg status
1362
-        $current_status = $this->_registration->status_ID();
1363
-        // is registration for free event? This will determine whether to display the pending payment option
1364
-        if ($current_status != EEM_Registration::status_id_pending_payment
1365
-            && $this->_registration->transaction()
1366
-                                   ->is_free()
1367
-        ) {
1368
-            unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1369
-        }
1370
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1371
-    }
1372
-
1373
-
1374
-
1375
-    /**
1376
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1377
-     *
1378
-     * @param bool $status REG status given for changing registrations to.
1379
-     * @param bool $notify Whether to send messages notifications or not.
1380
-     * @return array  (array with reg_id(s) updated and whether update was successful.
1381
-     */
1382
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1383
-    {
1384
-        if (isset($this->_req_data['reg_status_change_form'])) {
1385
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1386
-                ? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1387
-        } else {
1388
-            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1389
-        }
1390
-        $success = $this->_set_registration_status($REG_IDs, $status);
1391
-        //notify?
1392
-        if ($success
1393
-            && $notify
1394
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1395
-                'espresso_registrations_resend_registration')
1396
-        ) {
1397
-            $this->_process_resend_registration();
1398
-        }
1399
-        return $success;
1400
-    }
1401
-
1402
-
1403
-
1404
-    /**
1405
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1406
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1407
-     *
1408
-     * @param array $REG_IDs
1409
-     * @param bool  $status
1410
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1411
-     *               the array of updated registrations).
1412
-     */
1413
-    protected function _set_registration_status($REG_IDs = array(), $status = false)
1414
-    {
1415
-        $success = false;
1416
-        // typecast $REG_IDs
1417
-        $REG_IDs = (array)$REG_IDs;
1418
-        if ( ! empty($REG_IDs)) {
1419
-            $success = true;
1420
-            // set default status if none is passed
1421
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1422
-            // sanitize $REG_IDs
1423
-            $REG_IDs = array_filter($REG_IDs, 'absint');
1424
-            //loop through REG_ID's and change status
1425
-            foreach ($REG_IDs as $REG_ID) {
1426
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1427
-                if ($registration instanceof EE_Registration) {
1428
-                    $registration->set_status($status);
1429
-                    $result = $registration->save();
1430
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1431
-                    $success = $result !== false ? $success : false;
1432
-                }
1433
-            }
1434
-        }
1435
-        //reset _req_data['_REG_ID'] for any potential future messages notifications
1436
-        $this->_req_data['_REG_ID'] = $REG_IDs;
1437
-        //return $success and processed registrations
1438
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1439
-    }
1440
-
1441
-
1442
-
1443
-    /**
1444
-     * Common logic for setting up success message and redirecting to appropriate route
1445
-     *
1446
-     * @param  string $STS_ID status id for the registration changed to
1447
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1448
-     * @return void
1449
-     */
1450
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1451
-    {
1452
-        $result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1453
-            : array('success' => false);
1454
-        $success = isset($result['success']) && $result['success'];
1455
-        //setup success message
1456
-        if ($success) {
1457
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1458
-                $msg = sprintf(__('Registration status has been set to %s', 'event_espresso'),
1459
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1460
-            } else {
1461
-                $msg = sprintf(__('Registrations have been set to %s.', 'event_espresso'),
1462
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1463
-            }
1464
-            EE_Error::add_success($msg);
1465
-        } else {
1466
-            EE_Error::add_error(__('Something went wrong, and the status was not changed', 'event_espresso'), __FILE__,
1467
-                __LINE__, __FUNCTION__);
1468
-        }
1469
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1470
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1471
-        } else {
1472
-            $route = array('action' => 'default');
1473
-        }
1474
-        //unset nonces
1475
-        foreach ($this->_req_data as $ref => $value) {
1476
-            if (strpos($ref, 'nonce') !== false) {
1477
-                unset($this->_req_data[$ref]);
1478
-                continue;
1479
-            }
1480
-            $value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1481
-            $this->_req_data[$ref] = $value;
1482
-        }
1483
-        //merge request vars so that the reloaded list table contains any existing filter query params
1484
-        $route = array_merge($this->_req_data, $route);
1485
-        $this->_redirect_after_action($success, '', '', $route, true);
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * incoming reg status change from reg details page.
1492
-     *
1493
-     * @return void
1494
-     */
1495
-    protected function _change_reg_status()
1496
-    {
1497
-        $this->_req_data['return'] = 'view_registration';
1498
-        //set notify based on whether the send notifications toggle is set or not
1499
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1500
-        //$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1501
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1502
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1503
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1504
-            case EEM_Registration::status_id_approved :
1505
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1506
-                $this->approve_registration($notify);
1507
-                break;
1508
-            case EEM_Registration::status_id_pending_payment :
1509
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1510
-                $this->pending_registration($notify);
1511
-                break;
1512
-            case EEM_Registration::status_id_not_approved :
1513
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1514
-                $this->not_approve_registration($notify);
1515
-                break;
1516
-            case EEM_Registration::status_id_declined :
1517
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1518
-                $this->decline_registration($notify);
1519
-                break;
1520
-            case EEM_Registration::status_id_cancelled :
1521
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1522
-                $this->cancel_registration($notify);
1523
-                break;
1524
-            case EEM_Registration::status_id_wait_list :
1525
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1526
-                $this->waitlist_registration($notify);
1527
-                break;
1528
-            case EEM_Registration::status_id_incomplete :
1529
-            default :
1530
-                $result['success'] = false;
1531
-                unset($this->_req_data['return']);
1532
-                $this->_reg_status_change_return('', false);
1533
-                break;
1534
-        }
1535
-    }
1536
-
1537
-
1538
-
1539
-    /**
1540
-     * approve_registration
1541
-     *
1542
-     * @access protected
1543
-     * @param bool $notify whether or not to notify the registrant about their approval.
1544
-     * @return void
1545
-     */
1546
-    protected function approve_registration($notify = false)
1547
-    {
1548
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1549
-    }
1550
-
1551
-
1552
-
1553
-    /**
1554
-     *        decline_registration
1555
-     *
1556
-     * @access protected
1557
-     * @param bool $notify whether or not to notify the registrant about their status change.
1558
-     * @return void
1559
-     */
1560
-    protected function decline_registration($notify = false)
1561
-    {
1562
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1563
-    }
1564
-
1565
-
1566
-
1567
-    /**
1568
-     *        cancel_registration
1569
-     *
1570
-     * @access protected
1571
-     * @param bool $notify whether or not to notify the registrant about their status change.
1572
-     * @return void
1573
-     */
1574
-    protected function cancel_registration($notify = false)
1575
-    {
1576
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1577
-    }
1578
-
1579
-
1580
-
1581
-    /**
1582
-     *        not_approve_registration
1583
-     *
1584
-     * @access protected
1585
-     * @param bool $notify whether or not to notify the registrant about their status change.
1586
-     * @return void
1587
-     */
1588
-    protected function not_approve_registration($notify = false)
1589
-    {
1590
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1591
-    }
1592
-
1593
-
1594
-
1595
-    /**
1596
-     *        decline_registration
1597
-     *
1598
-     * @access protected
1599
-     * @param bool $notify whether or not to notify the registrant about their status change.
1600
-     * @return void
1601
-     */
1602
-    protected function pending_registration($notify = false)
1603
-    {
1604
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1605
-    }
1606
-
1607
-
1608
-
1609
-    /**
1610
-     * waitlist_registration
1611
-     *
1612
-     * @access protected
1613
-     * @param bool $notify whether or not to notify the registrant about their status change.
1614
-     * @return void
1615
-     */
1616
-    protected function waitlist_registration($notify = false)
1617
-    {
1618
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
1619
-    }
1620
-
1621
-
1622
-
1623
-    /**
1624
-     *        generates HTML for the Registration main meta box
1625
-     *
1626
-     * @access public
1627
-     * @return void
1628
-     */
1629
-    public function _reg_details_meta_box()
1630
-    {
1631
-        EEH_Autoloader::register_line_item_display_autoloaders();
1632
-        EEH_Autoloader::register_line_item_filter_autoloaders();
1633
-        EE_Registry::instance()->load_helper('Line_Item');
1634
-        $transaction = $this->_registration->transaction() ? $this->_registration->transaction()
1635
-            : EE_Transaction::new_instance();
1636
-        $this->_session = $transaction->session_data();
1637
-        $filters = new EE_Line_Item_Filter_Collection();
1638
-        //$filters->add( new EE_Non_Zero_Line_Item_Filter() );
1639
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
1640
-        $line_item_filter_processor = new EE_Line_Item_Filter_Processor($filters, $transaction->total_line_item());
1641
-        $filtered_line_item_tree = $line_item_filter_processor->process();
1642
-        $line_item_display = new EE_Line_Item_Display('reg_admin_table',
1643
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
1644
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item($filtered_line_item_tree,
1645
-            array('EE_Registration' => $this->_registration));
1646
-        $attendee = $this->_registration->attendee();
1647
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
1648
-            'espresso_transactions_view_transaction')
1649
-        ) {
1650
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1651
-                'action' => 'view_transaction',
1652
-                'TXN_ID' => $transaction->ID(),
1653
-            ), TXN_ADMIN_URL), esc_html__(' View Transaction'), 'button secondary-button right',
1654
-                'dashicons dashicons-cart');
1655
-        } else {
1656
-            $this->_template_args['view_transaction_button'] = '';
1657
-        }
1658
-        if ($attendee instanceof EE_Attendee
1659
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1660
-                'espresso_registrations_resend_registration')
1661
-        ) {
1662
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1663
-                'action'      => 'resend_registration',
1664
-                '_REG_ID'     => $this->_registration->ID(),
1665
-                'redirect_to' => 'view_registration',
1666
-            ), REG_ADMIN_URL), esc_html__(' Resend Registration'), 'button secondary-button right',
1667
-                'dashicons dashicons-email-alt');
1668
-        } else {
1669
-            $this->_template_args['resend_registration_button'] = '';
1670
-        }
1671
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1672
-        $payment = $transaction->get_first_related('Payment');
1673
-        $payment = ! $payment instanceof EE_Payment ? EE_Payment::new_instance() : $payment;
1674
-        $payment_method = $payment->get_first_related('Payment_Method');
1675
-        $payment_method = ! $payment_method instanceof EE_Payment_Method ? EE_Payment_Method::new_instance()
1676
-            : $payment_method;
1677
-        $reg_details = array(
1678
-            'payment_method'       => $payment_method->name(),
1679
-            'response_msg'         => $payment->gateway_response(),
1680
-            'registration_id'      => $this->_registration->get('REG_code'),
1681
-            'registration_session' => $this->_registration->session_ID(),
1682
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
1683
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
1684
-        );
1685
-        if (isset($reg_details['registration_id'])) {
1686
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
1687
-            $this->_template_args['reg_details']['registration_id']['label'] = __('Registration ID', 'event_espresso');
1688
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
1689
-        }
1690
-        if (isset($reg_details['payment_method'])) {
1691
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
1692
-            $this->_template_args['reg_details']['payment_method']['label'] = __('Most Recent Payment Method',
1693
-                'event_espresso');
1694
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
1695
-            $this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
1696
-            $this->_template_args['reg_details']['response_msg']['label'] = __('Payment method response',
1697
-                'event_espresso');
1698
-            $this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
1699
-        }
1700
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
1701
-        $this->_template_args['reg_details']['registration_session']['label'] = __('Registration Session',
1702
-            'event_espresso');
1703
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
1704
-        $this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
1705
-        $this->_template_args['reg_details']['ip_address']['label'] = __('Registration placed from IP',
1706
-            'event_espresso');
1707
-        $this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
1708
-        $this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
1709
-        $this->_template_args['reg_details']['user_agent']['label'] = __('Registrant User Agent', 'event_espresso');
1710
-        $this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
1711
-        $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1712
-            'action'   => 'default',
1713
-            'event_id' => $this->_registration->event_ID(),
1714
-        ), REG_ADMIN_URL);
1715
-        $this->_template_args['REG_ID'] = $this->_registration->ID();
1716
-        $this->_template_args['event_id'] = $this->_registration->event_ID();
1717
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
1718
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1719
-    }
1720
-
1721
-
1722
-
1723
-    /**
1724
-     * generates HTML for the Registration Questions meta box.
1725
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
1726
-     * otherwise uses new forms system
1727
-     *
1728
-     * @access public
1729
-     * @return void
1730
-     */
1731
-    public function _reg_questions_meta_box()
1732
-    {
1733
-        //allow someone to override this method entirely
1734
-        if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
1735
-            $this->_registration)) {
1736
-            $form = $this->_get_reg_custom_questions_form($this->_registration->ID());
1737
-            $this->_template_args['att_questions'] = count($form->subforms()) > 0 ? $form->get_html_and_js() : '';
1738
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
1739
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
1740
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
1741
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
1742
-        }
1743
-    }
1744
-
1745
-
1746
-
1747
-    /**
1748
-     * form_before_question_group
1749
-     *
1750
-     * @deprecated    as of 4.8.32.rc.000
1751
-     * @access        public
1752
-     * @param        string $output
1753
-     * @return        string
1754
-     */
1755
-    public function form_before_question_group($output)
1756
-    {
1757
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1758
-            __('This method would have been protected but was used on a filter callback'
1759
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1760
-            '4.8.32.rc.000');
1761
-        return '
1152
+			}
1153
+			return $registrations;
1154
+		}
1155
+	}
1156
+
1157
+
1158
+
1159
+	public function get_registration_status_array()
1160
+	{
1161
+		return self::$_reg_status;
1162
+	}
1163
+
1164
+
1165
+
1166
+
1167
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1168
+	/**
1169
+	 *        generates HTML for the View Registration Details Admin page
1170
+	 *
1171
+	 * @access protected
1172
+	 * @return void
1173
+	 */
1174
+	protected function _registration_details()
1175
+	{
1176
+		$this->_template_args = array();
1177
+		$this->_set_registration_object();
1178
+		if (is_object($this->_registration)) {
1179
+			$transaction = $this->_registration->transaction() ? $this->_registration->transaction()
1180
+				: EE_Transaction::new_instance();
1181
+			$this->_session = $transaction->session_data();
1182
+			$event_id = $this->_registration->event_ID();
1183
+			$this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1184
+			$this->_template_args['reg_nmbr']['label'] = __('Registration Number', 'event_espresso');
1185
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1186
+			$this->_template_args['reg_datetime']['label'] = __('Date', 'event_espresso');
1187
+			$this->_template_args['grand_total'] = $transaction->total();
1188
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1189
+			// link back to overview
1190
+			$this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1191
+			$this->_template_args['registration'] = $this->_registration;
1192
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1193
+				'action'   => 'default',
1194
+				'event_id' => $event_id,
1195
+			), REG_ADMIN_URL);
1196
+			$this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1197
+				'action' => 'default',
1198
+				'EVT_ID' => $event_id,
1199
+				'page'   => 'espresso_transactions',
1200
+			), admin_url('admin.php'));
1201
+			$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1202
+				'page'   => 'espresso_events',
1203
+				'action' => 'edit',
1204
+				'post'   => $event_id,
1205
+			), admin_url('admin.php'));
1206
+			//next and previous links
1207
+			$next_reg = $this->_registration->next(null, array(), 'REG_ID');
1208
+			$this->_template_args['next_registration'] = $next_reg
1209
+				? $this->_next_link(EE_Admin_Page::add_query_args_and_nonce(array(
1210
+					'action'  => 'view_registration',
1211
+					'_REG_ID' => $next_reg['REG_ID'],
1212
+				), REG_ADMIN_URL), 'dashicons dashicons-arrow-right ee-icon-size-22') : '';
1213
+			$previous_reg = $this->_registration->previous(null, array(), 'REG_ID');
1214
+			$this->_template_args['previous_registration'] = $previous_reg
1215
+				? $this->_previous_link(EE_Admin_Page::add_query_args_and_nonce(array(
1216
+					'action'  => 'view_registration',
1217
+					'_REG_ID' => $previous_reg['REG_ID'],
1218
+				), REG_ADMIN_URL), 'dashicons dashicons-arrow-left ee-icon-size-22') : '';
1219
+			// grab header
1220
+			$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1221
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
1222
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
1223
+				$this->_template_args, true);
1224
+		} else {
1225
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1226
+		}
1227
+		// the details template wrapper
1228
+		$this->display_admin_page_with_sidebar();
1229
+	}
1230
+
1231
+
1232
+
1233
+	protected function _registration_details_metaboxes()
1234
+	{
1235
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1236
+		$this->_set_registration_object();
1237
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1238
+		add_meta_box('edit-reg-status-mbox', __('Registration Status', 'event_espresso'),
1239
+			array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1240
+		add_meta_box('edit-reg-details-mbox', __('Registration Details', 'event_espresso'),
1241
+			array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1242
+		if ($attendee instanceof EE_Attendee
1243
+			&& EE_Registry::instance()->CAP->current_user_can('ee_edit_registration', 'edit-reg-questions-mbox')
1244
+		) {
1245
+			add_meta_box('edit-reg-questions-mbox', __('Registration Form Answers', 'event_espresso'),
1246
+				array($this, '_reg_questions_meta_box'), $this->wp_page_slug, 'normal', 'high');
1247
+		}
1248
+		add_meta_box('edit-reg-registrant-mbox', __('Contact Details', 'event_espresso'),
1249
+			array($this, '_reg_registrant_side_meta_box'), $this->wp_page_slug, 'side', 'high');
1250
+		if ($this->_registration->group_size() > 1) {
1251
+			add_meta_box('edit-reg-attendees-mbox', __('Other Registrations in this Transaction', 'event_espresso'),
1252
+				array($this, '_reg_attendees_meta_box'), $this->wp_page_slug, 'normal', 'high');
1253
+		}
1254
+	}
1255
+
1256
+
1257
+
1258
+	/**
1259
+	 * set_reg_status_buttons_metabox
1260
+	 *
1261
+	 * @access protected
1262
+	 * @return string
1263
+	 * @throws \EE_Error
1264
+	 */
1265
+	public function set_reg_status_buttons_metabox()
1266
+	{
1267
+		$this->_set_registration_object();
1268
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1269
+		echo $change_reg_status_form->form_open(self::add_query_args_and_nonce(array(
1270
+			'action' => 'change_reg_status',
1271
+		), REG_ADMIN_URL));
1272
+		echo $change_reg_status_form->get_html();
1273
+		echo $change_reg_status_form->form_close();
1274
+	}
1275
+
1276
+
1277
+
1278
+	/**
1279
+	 * @return EE_Form_Section_Proper
1280
+	 */
1281
+	protected function _generate_reg_status_change_form()
1282
+	{
1283
+		return new EE_Form_Section_Proper(array(
1284
+				'name'            => 'reg_status_change_form',
1285
+				'html_id'         => 'reg-status-change-form',
1286
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1287
+				'subsections'     => array(
1288
+					'return'             => new EE_Hidden_Input(array(
1289
+						'name'    => 'return',
1290
+						'default' => 'view_registration',
1291
+					)),
1292
+					'REG_ID'             => new EE_Hidden_Input(array(
1293
+						'name'    => 'REG_ID',
1294
+						'default' => $this->_registration->ID(),
1295
+					)),
1296
+					'current_status'     => new EE_Form_Section_HTML(EEH_HTML::tr(EEH_HTML::th(EEH_HTML::label(EEH_HTML::strong(__('Current Registration Status',
1297
+							'event_espresso')))) . EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1298
+							'', 'status-' . $this->_registration->status_ID(),
1299
+							'line-height: 1em; font-size: 1.5em; font-weight: bold;')))),
1300
+					'reg_status'         => new EE_Select_Input($this->_get_reg_statuses(), array(
1301
+							'html_label_text' => __('Change Registration Status to', 'event_espresso'),
1302
+							'default'         => $this->_registration->status_ID(),
1303
+						)),
1304
+					'send_notifications' => new EE_Yes_No_Input(array(
1305
+							'html_label_text' => __('Send Related Messages', 'event_espresso'),
1306
+							'default'         => false,
1307
+							'html_help_text'  => __('If set to "Yes", then the related messages will be sent to the registrant.',
1308
+								'event_espresso'),
1309
+						)),
1310
+					'submit'             => new EE_Submit_Input(array(
1311
+						'html_class'      => 'button-primary',
1312
+						'html_label_text' => '&nbsp;',
1313
+						'default'         => __('Update Registration Status', 'event_espresso'),
1314
+					)),
1315
+				),
1316
+			));
1317
+	}
1318
+
1319
+
1320
+
1321
+	/**
1322
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1323
+	 *
1324
+	 * @return string
1325
+	 */
1326
+	protected function _get_current_reg_status_help_text($STS_ID = '')
1327
+	{
1328
+		//$reg_status_help_text = array(
1329
+		//	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1330
+		//	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1331
+		//	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1332
+		//	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1333
+		//	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1334
+		//	'RAP' => __( 'XXXXXXXXXXX', 'event_espresso' ),
1335
+		//);
1336
+		//Approved
1337
+		//An approved registration allows payments and may have a transaction status of incomplete or complete . The registration is marked as active and a space is reserved for the registrant .
1338
+		//Cancelled
1339
+		//	A {
1340
+		//	cancelled} registration is performed by the registrant . Payments are not allowed, the registration is inactive, and no space is reserved .
1341
+		//Declined
1342
+		//A declined registration is performed by the event admin . Payments are not allowed, the registration is inactive, and not space is reserved .
1343
+		//Not Approved
1344
+		//A not approved registration is performed by the event admin . Payments are not allowed, the registration is active, and no space is reserved .
1345
+		//Pending Payment
1346
+		//A pending registration allows payments . The status will be automatically toggled to approved if the {
1347
+		//	payment} is made in full by registrant .
1348
+	}
1349
+
1350
+
1351
+
1352
+	/**
1353
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1354
+	 *
1355
+	 * @return array
1356
+	 */
1357
+	protected function _get_reg_statuses()
1358
+	{
1359
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1360
+		unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1361
+		// get current reg status
1362
+		$current_status = $this->_registration->status_ID();
1363
+		// is registration for free event? This will determine whether to display the pending payment option
1364
+		if ($current_status != EEM_Registration::status_id_pending_payment
1365
+			&& $this->_registration->transaction()
1366
+								   ->is_free()
1367
+		) {
1368
+			unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1369
+		}
1370
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1371
+	}
1372
+
1373
+
1374
+
1375
+	/**
1376
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1377
+	 *
1378
+	 * @param bool $status REG status given for changing registrations to.
1379
+	 * @param bool $notify Whether to send messages notifications or not.
1380
+	 * @return array  (array with reg_id(s) updated and whether update was successful.
1381
+	 */
1382
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1383
+	{
1384
+		if (isset($this->_req_data['reg_status_change_form'])) {
1385
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1386
+				? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1387
+		} else {
1388
+			$REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1389
+		}
1390
+		$success = $this->_set_registration_status($REG_IDs, $status);
1391
+		//notify?
1392
+		if ($success
1393
+			&& $notify
1394
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1395
+				'espresso_registrations_resend_registration')
1396
+		) {
1397
+			$this->_process_resend_registration();
1398
+		}
1399
+		return $success;
1400
+	}
1401
+
1402
+
1403
+
1404
+	/**
1405
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1406
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1407
+	 *
1408
+	 * @param array $REG_IDs
1409
+	 * @param bool  $status
1410
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1411
+	 *               the array of updated registrations).
1412
+	 */
1413
+	protected function _set_registration_status($REG_IDs = array(), $status = false)
1414
+	{
1415
+		$success = false;
1416
+		// typecast $REG_IDs
1417
+		$REG_IDs = (array)$REG_IDs;
1418
+		if ( ! empty($REG_IDs)) {
1419
+			$success = true;
1420
+			// set default status if none is passed
1421
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1422
+			// sanitize $REG_IDs
1423
+			$REG_IDs = array_filter($REG_IDs, 'absint');
1424
+			//loop through REG_ID's and change status
1425
+			foreach ($REG_IDs as $REG_ID) {
1426
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1427
+				if ($registration instanceof EE_Registration) {
1428
+					$registration->set_status($status);
1429
+					$result = $registration->save();
1430
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1431
+					$success = $result !== false ? $success : false;
1432
+				}
1433
+			}
1434
+		}
1435
+		//reset _req_data['_REG_ID'] for any potential future messages notifications
1436
+		$this->_req_data['_REG_ID'] = $REG_IDs;
1437
+		//return $success and processed registrations
1438
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1439
+	}
1440
+
1441
+
1442
+
1443
+	/**
1444
+	 * Common logic for setting up success message and redirecting to appropriate route
1445
+	 *
1446
+	 * @param  string $STS_ID status id for the registration changed to
1447
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1448
+	 * @return void
1449
+	 */
1450
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1451
+	{
1452
+		$result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1453
+			: array('success' => false);
1454
+		$success = isset($result['success']) && $result['success'];
1455
+		//setup success message
1456
+		if ($success) {
1457
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1458
+				$msg = sprintf(__('Registration status has been set to %s', 'event_espresso'),
1459
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1460
+			} else {
1461
+				$msg = sprintf(__('Registrations have been set to %s.', 'event_espresso'),
1462
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1463
+			}
1464
+			EE_Error::add_success($msg);
1465
+		} else {
1466
+			EE_Error::add_error(__('Something went wrong, and the status was not changed', 'event_espresso'), __FILE__,
1467
+				__LINE__, __FUNCTION__);
1468
+		}
1469
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1470
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1471
+		} else {
1472
+			$route = array('action' => 'default');
1473
+		}
1474
+		//unset nonces
1475
+		foreach ($this->_req_data as $ref => $value) {
1476
+			if (strpos($ref, 'nonce') !== false) {
1477
+				unset($this->_req_data[$ref]);
1478
+				continue;
1479
+			}
1480
+			$value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1481
+			$this->_req_data[$ref] = $value;
1482
+		}
1483
+		//merge request vars so that the reloaded list table contains any existing filter query params
1484
+		$route = array_merge($this->_req_data, $route);
1485
+		$this->_redirect_after_action($success, '', '', $route, true);
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * incoming reg status change from reg details page.
1492
+	 *
1493
+	 * @return void
1494
+	 */
1495
+	protected function _change_reg_status()
1496
+	{
1497
+		$this->_req_data['return'] = 'view_registration';
1498
+		//set notify based on whether the send notifications toggle is set or not
1499
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1500
+		//$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1501
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1502
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1503
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1504
+			case EEM_Registration::status_id_approved :
1505
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1506
+				$this->approve_registration($notify);
1507
+				break;
1508
+			case EEM_Registration::status_id_pending_payment :
1509
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1510
+				$this->pending_registration($notify);
1511
+				break;
1512
+			case EEM_Registration::status_id_not_approved :
1513
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1514
+				$this->not_approve_registration($notify);
1515
+				break;
1516
+			case EEM_Registration::status_id_declined :
1517
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1518
+				$this->decline_registration($notify);
1519
+				break;
1520
+			case EEM_Registration::status_id_cancelled :
1521
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1522
+				$this->cancel_registration($notify);
1523
+				break;
1524
+			case EEM_Registration::status_id_wait_list :
1525
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1526
+				$this->waitlist_registration($notify);
1527
+				break;
1528
+			case EEM_Registration::status_id_incomplete :
1529
+			default :
1530
+				$result['success'] = false;
1531
+				unset($this->_req_data['return']);
1532
+				$this->_reg_status_change_return('', false);
1533
+				break;
1534
+		}
1535
+	}
1536
+
1537
+
1538
+
1539
+	/**
1540
+	 * approve_registration
1541
+	 *
1542
+	 * @access protected
1543
+	 * @param bool $notify whether or not to notify the registrant about their approval.
1544
+	 * @return void
1545
+	 */
1546
+	protected function approve_registration($notify = false)
1547
+	{
1548
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1549
+	}
1550
+
1551
+
1552
+
1553
+	/**
1554
+	 *        decline_registration
1555
+	 *
1556
+	 * @access protected
1557
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1558
+	 * @return void
1559
+	 */
1560
+	protected function decline_registration($notify = false)
1561
+	{
1562
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1563
+	}
1564
+
1565
+
1566
+
1567
+	/**
1568
+	 *        cancel_registration
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1572
+	 * @return void
1573
+	 */
1574
+	protected function cancel_registration($notify = false)
1575
+	{
1576
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1577
+	}
1578
+
1579
+
1580
+
1581
+	/**
1582
+	 *        not_approve_registration
1583
+	 *
1584
+	 * @access protected
1585
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1586
+	 * @return void
1587
+	 */
1588
+	protected function not_approve_registration($notify = false)
1589
+	{
1590
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1591
+	}
1592
+
1593
+
1594
+
1595
+	/**
1596
+	 *        decline_registration
1597
+	 *
1598
+	 * @access protected
1599
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1600
+	 * @return void
1601
+	 */
1602
+	protected function pending_registration($notify = false)
1603
+	{
1604
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1605
+	}
1606
+
1607
+
1608
+
1609
+	/**
1610
+	 * waitlist_registration
1611
+	 *
1612
+	 * @access protected
1613
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1614
+	 * @return void
1615
+	 */
1616
+	protected function waitlist_registration($notify = false)
1617
+	{
1618
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
1619
+	}
1620
+
1621
+
1622
+
1623
+	/**
1624
+	 *        generates HTML for the Registration main meta box
1625
+	 *
1626
+	 * @access public
1627
+	 * @return void
1628
+	 */
1629
+	public function _reg_details_meta_box()
1630
+	{
1631
+		EEH_Autoloader::register_line_item_display_autoloaders();
1632
+		EEH_Autoloader::register_line_item_filter_autoloaders();
1633
+		EE_Registry::instance()->load_helper('Line_Item');
1634
+		$transaction = $this->_registration->transaction() ? $this->_registration->transaction()
1635
+			: EE_Transaction::new_instance();
1636
+		$this->_session = $transaction->session_data();
1637
+		$filters = new EE_Line_Item_Filter_Collection();
1638
+		//$filters->add( new EE_Non_Zero_Line_Item_Filter() );
1639
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
1640
+		$line_item_filter_processor = new EE_Line_Item_Filter_Processor($filters, $transaction->total_line_item());
1641
+		$filtered_line_item_tree = $line_item_filter_processor->process();
1642
+		$line_item_display = new EE_Line_Item_Display('reg_admin_table',
1643
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
1644
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item($filtered_line_item_tree,
1645
+			array('EE_Registration' => $this->_registration));
1646
+		$attendee = $this->_registration->attendee();
1647
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
1648
+			'espresso_transactions_view_transaction')
1649
+		) {
1650
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1651
+				'action' => 'view_transaction',
1652
+				'TXN_ID' => $transaction->ID(),
1653
+			), TXN_ADMIN_URL), esc_html__(' View Transaction'), 'button secondary-button right',
1654
+				'dashicons dashicons-cart');
1655
+		} else {
1656
+			$this->_template_args['view_transaction_button'] = '';
1657
+		}
1658
+		if ($attendee instanceof EE_Attendee
1659
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1660
+				'espresso_registrations_resend_registration')
1661
+		) {
1662
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1663
+				'action'      => 'resend_registration',
1664
+				'_REG_ID'     => $this->_registration->ID(),
1665
+				'redirect_to' => 'view_registration',
1666
+			), REG_ADMIN_URL), esc_html__(' Resend Registration'), 'button secondary-button right',
1667
+				'dashicons dashicons-email-alt');
1668
+		} else {
1669
+			$this->_template_args['resend_registration_button'] = '';
1670
+		}
1671
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1672
+		$payment = $transaction->get_first_related('Payment');
1673
+		$payment = ! $payment instanceof EE_Payment ? EE_Payment::new_instance() : $payment;
1674
+		$payment_method = $payment->get_first_related('Payment_Method');
1675
+		$payment_method = ! $payment_method instanceof EE_Payment_Method ? EE_Payment_Method::new_instance()
1676
+			: $payment_method;
1677
+		$reg_details = array(
1678
+			'payment_method'       => $payment_method->name(),
1679
+			'response_msg'         => $payment->gateway_response(),
1680
+			'registration_id'      => $this->_registration->get('REG_code'),
1681
+			'registration_session' => $this->_registration->session_ID(),
1682
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
1683
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
1684
+		);
1685
+		if (isset($reg_details['registration_id'])) {
1686
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
1687
+			$this->_template_args['reg_details']['registration_id']['label'] = __('Registration ID', 'event_espresso');
1688
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
1689
+		}
1690
+		if (isset($reg_details['payment_method'])) {
1691
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
1692
+			$this->_template_args['reg_details']['payment_method']['label'] = __('Most Recent Payment Method',
1693
+				'event_espresso');
1694
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
1695
+			$this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
1696
+			$this->_template_args['reg_details']['response_msg']['label'] = __('Payment method response',
1697
+				'event_espresso');
1698
+			$this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
1699
+		}
1700
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
1701
+		$this->_template_args['reg_details']['registration_session']['label'] = __('Registration Session',
1702
+			'event_espresso');
1703
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
1704
+		$this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
1705
+		$this->_template_args['reg_details']['ip_address']['label'] = __('Registration placed from IP',
1706
+			'event_espresso');
1707
+		$this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
1708
+		$this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
1709
+		$this->_template_args['reg_details']['user_agent']['label'] = __('Registrant User Agent', 'event_espresso');
1710
+		$this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
1711
+		$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1712
+			'action'   => 'default',
1713
+			'event_id' => $this->_registration->event_ID(),
1714
+		), REG_ADMIN_URL);
1715
+		$this->_template_args['REG_ID'] = $this->_registration->ID();
1716
+		$this->_template_args['event_id'] = $this->_registration->event_ID();
1717
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
1718
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1719
+	}
1720
+
1721
+
1722
+
1723
+	/**
1724
+	 * generates HTML for the Registration Questions meta box.
1725
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
1726
+	 * otherwise uses new forms system
1727
+	 *
1728
+	 * @access public
1729
+	 * @return void
1730
+	 */
1731
+	public function _reg_questions_meta_box()
1732
+	{
1733
+		//allow someone to override this method entirely
1734
+		if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
1735
+			$this->_registration)) {
1736
+			$form = $this->_get_reg_custom_questions_form($this->_registration->ID());
1737
+			$this->_template_args['att_questions'] = count($form->subforms()) > 0 ? $form->get_html_and_js() : '';
1738
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
1739
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
1740
+			$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
1741
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
1742
+		}
1743
+	}
1744
+
1745
+
1746
+
1747
+	/**
1748
+	 * form_before_question_group
1749
+	 *
1750
+	 * @deprecated    as of 4.8.32.rc.000
1751
+	 * @access        public
1752
+	 * @param        string $output
1753
+	 * @return        string
1754
+	 */
1755
+	public function form_before_question_group($output)
1756
+	{
1757
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1758
+			__('This method would have been protected but was used on a filter callback'
1759
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1760
+			'4.8.32.rc.000');
1761
+		return '
1762 1762
 	<table class="form-table ee-width-100">
1763 1763
 		<tbody>
1764 1764
 			';
1765
-    }
1766
-
1767
-
1768
-
1769
-    /**
1770
-     * form_after_question_group
1771
-     *
1772
-     * @deprecated    as of 4.8.32.rc.000
1773
-     * @access        public
1774
-     * @param        string $output
1775
-     * @return        string
1776
-     */
1777
-    public function form_after_question_group($output)
1778
-    {
1779
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1780
-            __('This method would have been protected but was used on a filter callback'
1781
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1782
-            '4.8.32.rc.000');
1783
-        return '
1765
+	}
1766
+
1767
+
1768
+
1769
+	/**
1770
+	 * form_after_question_group
1771
+	 *
1772
+	 * @deprecated    as of 4.8.32.rc.000
1773
+	 * @access        public
1774
+	 * @param        string $output
1775
+	 * @return        string
1776
+	 */
1777
+	public function form_after_question_group($output)
1778
+	{
1779
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1780
+			__('This method would have been protected but was used on a filter callback'
1781
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1782
+			'4.8.32.rc.000');
1783
+		return '
1784 1784
 			<tr class="hide-if-no-js">
1785 1785
 				<th> </th>
1786 1786
 				<td class="reg-admin-edit-attendee-question-td">
1787 1787
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
1788
-               . esc_attr__('click to edit question', 'event_espresso')
1789
-               . '">
1788
+			   . esc_attr__('click to edit question', 'event_espresso')
1789
+			   . '">
1790 1790
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
1791
-               . __('edit the above question group', 'event_espresso')
1792
-               . '</span>
1791
+			   . __('edit the above question group', 'event_espresso')
1792
+			   . '</span>
1793 1793
 						<div class="dashicons dashicons-edit"></div>
1794 1794
 					</a>
1795 1795
 				</td>
@@ -1797,506 +1797,506 @@  discard block
 block discarded – undo
1797 1797
 		</tbody>
1798 1798
 	</table>
1799 1799
 ';
1800
-    }
1801
-
1802
-
1803
-
1804
-    /**
1805
-     * form_form_field_label_wrap
1806
-     *
1807
-     * @deprecated    as of 4.8.32.rc.000
1808
-     * @access        public
1809
-     * @param        string $label
1810
-     * @return        string
1811
-     */
1812
-    public function form_form_field_label_wrap($label)
1813
-    {
1814
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1815
-            __('This method would have been protected but was used on a filter callback'
1816
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1817
-            '4.8.32.rc.000');
1818
-        return '
1800
+	}
1801
+
1802
+
1803
+
1804
+	/**
1805
+	 * form_form_field_label_wrap
1806
+	 *
1807
+	 * @deprecated    as of 4.8.32.rc.000
1808
+	 * @access        public
1809
+	 * @param        string $label
1810
+	 * @return        string
1811
+	 */
1812
+	public function form_form_field_label_wrap($label)
1813
+	{
1814
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1815
+			__('This method would have been protected but was used on a filter callback'
1816
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1817
+			'4.8.32.rc.000');
1818
+		return '
1819 1819
 			<tr>
1820 1820
 				<th>
1821 1821
 					' . $label . '
1822 1822
 				</th>';
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * form_form_field_input__wrap
1829
-     *
1830
-     * @deprecated    as of 4.8.32.rc.000
1831
-     * @access        public
1832
-     * @param        string $input
1833
-     * @return        string
1834
-     */
1835
-    public function form_form_field_input__wrap($input)
1836
-    {
1837
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1838
-            __('This method would have been protected but was used on a filter callback'
1839
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1840
-            '4.8.32.rc.000');
1841
-        return '
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * form_form_field_input__wrap
1829
+	 *
1830
+	 * @deprecated    as of 4.8.32.rc.000
1831
+	 * @access        public
1832
+	 * @param        string $input
1833
+	 * @return        string
1834
+	 */
1835
+	public function form_form_field_input__wrap($input)
1836
+	{
1837
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1838
+			__('This method would have been protected but was used on a filter callback'
1839
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1840
+			'4.8.32.rc.000');
1841
+		return '
1842 1842
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
1843 1843
 					' . $input . '
1844 1844
 				</td>
1845 1845
 			</tr>';
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
1852
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
1853
-     * to display the page
1854
-     *
1855
-     * @access protected
1856
-     * @return void
1857
-     */
1858
-    protected function _update_attendee_registration_form()
1859
-    {
1860
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
1861
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
1862
-            $REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
1863
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
1864
-            if ($success) {
1865
-                $what = __('Registration Form', 'event_espresso');
1866
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
1867
-                    : array('action' => 'default');
1868
-                $this->_redirect_after_action($success, $what, __('updated', 'event_espresso'), $route);
1869
-            }
1870
-        }
1871
-    }
1872
-
1873
-
1874
-
1875
-    /**
1876
-     * Gets the form for saving registrations custom questions (if done
1877
-     * previously retrieves the cached form object, which may have validation errors in it)
1878
-     *
1879
-     * @param int $REG_ID
1880
-     * @return EE_Registration_Custom_Questions_Form
1881
-     */
1882
-    protected function _get_reg_custom_questions_form($REG_ID)
1883
-    {
1884
-        if ( ! $this->_reg_custom_questions_form) {
1885
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
1886
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(EEM_Registration::instance()
1887
-                                                                                                          ->get_one_by_ID($REG_ID));
1888
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
1889
-        }
1890
-        return $this->_reg_custom_questions_form;
1891
-    }
1892
-
1893
-
1894
-
1895
-    /**
1896
-     * Saves
1897
-     *
1898
-     * @access private
1899
-     * @param bool $REG_ID
1900
-     * @return bool
1901
-     */
1902
-    private function _save_reg_custom_questions_form($REG_ID = false)
1903
-    {
1904
-        if ( ! $REG_ID) {
1905
-            EE_Error::add_error(__('An error occurred. No registration ID was received.', 'event_espresso'), __FILE__,
1906
-                __FUNCTION__, __LINE__);
1907
-        }
1908
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
1909
-        $form->receive_form_submission($this->_req_data);
1910
-        $success = false;
1911
-        if ($form->is_valid()) {
1912
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
1913
-                foreach ($question_group_form->inputs() as $question_id => $input) {
1914
-                    $where_conditions = array(
1915
-                        'QST_ID' => $question_id,
1916
-                        'REG_ID' => $REG_ID,
1917
-                    );
1918
-                    $possibly_new_values = array(
1919
-                        'ANS_value' => $input->normalized_value(),
1920
-                    );
1921
-                    $answer = EEM_Answer::instance()->get_one(array($where_conditions));
1922
-                    if ($answer instanceof EE_Answer) {
1923
-                        $success = $answer->save($possibly_new_values);
1924
-                    } else {
1925
-                        //insert it then
1926
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
1927
-                        $answer = EE_Answer::new_instance($cols_n_vals);
1928
-                        $success = $answer->save();
1929
-                    }
1930
-                }
1931
-            }
1932
-        } else {
1933
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
1934
-        }
1935
-        return $success;
1936
-    }
1937
-
1938
-
1939
-
1940
-    /**
1941
-     *        generates HTML for the Registration main meta box
1942
-     *
1943
-     * @access public
1944
-     * @return void
1945
-     */
1946
-    public function _reg_attendees_meta_box()
1947
-    {
1948
-        $REG = EEM_Registration::instance();
1949
-        //get all other registrations on this transaction, and cache
1950
-        //the attendees for them so we don't have to run another query using force_join
1951
-        $registrations = $REG->get_all(array(
1952
-            array(
1953
-                'TXN_ID' => $this->_registration->transaction_ID(),
1954
-                'REG_ID' => array('!=', $this->_registration->ID()),
1955
-            ),
1956
-            'force_join' => array('Attendee'),
1957
-        ));
1958
-        $this->_template_args['attendees'] = array();
1959
-        $this->_template_args['attendee_notice'] = '';
1960
-        if (empty($registrations)
1961
-            || (is_array($registrations)
1962
-                && ! EEH_Array::get_one_item_from_array($registrations))
1963
-        ) {
1964
-            EE_Error::add_error(__('There are no records attached to this registration. Something may have gone wrong with the registration',
1965
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1966
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
1967
-        } else {
1968
-            $att_nmbr = 1;
1969
-            foreach ($registrations as $registration) {
1970
-                /* @var $registration EE_Registration */
1971
-                $attendee = $registration->attendee()
1972
-                    ? $registration->attendee()
1973
-                    : EEM_Attendee::instance()
1974
-                                  ->create_default_object();
1975
-                $this->_template_args['attendees'][$att_nmbr]['STS_ID'] = $registration->status_ID();
1976
-                $this->_template_args['attendees'][$att_nmbr]['fname'] = $attendee->fname();//( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
1977
-                $this->_template_args['attendees'][$att_nmbr]['lname'] = $attendee->lname();//( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
1978
-                $this->_template_args['attendees'][$att_nmbr]['email'] = $attendee->email();//( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
1979
-                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();//( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
1980
-                $this->_template_args['attendees'][$att_nmbr]['address'] = implode(', ',
1981
-                    $attendee->full_address_as_array());
1982
-                $this->_template_args['attendees'][$att_nmbr]['att_link'] = self::add_query_args_and_nonce(array(
1983
-                    'action' => 'edit_attendee',
1984
-                    'post'   => $attendee->ID(),
1985
-                ), REG_ADMIN_URL);
1986
-                $this->_template_args['attendees'][$att_nmbr]['event_name'] = $registration->event_obj()->name();
1987
-                $att_nmbr++;
1988
-            }
1989
-            //EEH_Debug_Tools::printr( $attendees, '$attendees  <br /><span style="font-size:10px;font-weight:normal;">( file: '. __FILE__ . ' - line no: ' . __LINE__ . ' )</span>', 'auto' );
1990
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1991
-            //			$this->_template_args['registration_form_url'] = add_query_arg( array( 'action' => 'edit_registration', 'process' => 'attendees'  ), REG_ADMIN_URL );
1992
-        }
1993
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
1994
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1995
-    }
1996
-
1997
-
1998
-
1999
-    /**
2000
-     *        generates HTML for the Edit Registration side meta box
2001
-     *
2002
-     * @access public
2003
-     * @return void
2004
-     */
2005
-    public function _reg_registrant_side_meta_box()
2006
-    {
2007
-        /*@var $attendee EE_Attendee */
2008
-        $att_check = $this->_registration->attendee();
2009
-        $attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2010
-        //now let's determine if this is not the primary registration.  If it isn't then we set the primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the primary registration object (that way we know if we need to show create button or not)
2011
-        if ( ! $this->_registration->is_primary_registrant()) {
2012
-            $primary_registration = $this->_registration->get_primary_registration();
2013
-            $primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2014
-                : null;
2015
-            if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2016
-                //in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own custom attendee object so let's not worry about the primary reg.
2017
-                $primary_registration = null;
2018
-            }
2019
-        } else {
2020
-            $primary_registration = null;
2021
-        }
2022
-        $this->_template_args['ATT_ID'] = $attendee->ID();
2023
-        $this->_template_args['fname'] = $attendee->fname();//$this->_registration->ATT_fname;
2024
-        $this->_template_args['lname'] = $attendee->lname();//$this->_registration->ATT_lname;
2025
-        $this->_template_args['email'] = $attendee->email();//$this->_registration->ATT_email;
2026
-        $this->_template_args['phone'] = $attendee->phone();
2027
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2028
-        //edit link
2029
-        $this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
2030
-            'action' => 'edit_attendee',
2031
-            'post'   => $attendee->ID(),
2032
-        ), REG_ADMIN_URL);
2033
-        $this->_template_args['att_edit_label'] = __('View/Edit Contact', 'event_espresso');
2034
-        //create link
2035
-        $this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2036
-            ? EE_Admin_Page::add_query_args_and_nonce(array(
2037
-                'action'  => 'duplicate_attendee',
2038
-                '_REG_ID' => $this->_registration->ID(),
2039
-            ), REG_ADMIN_URL) : '';
2040
-        $this->_template_args['create_label'] = __('Create Contact', 'event_espresso');
2041
-        $this->_template_args['att_check'] = $att_check;
2042
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2043
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2044
-    }
2045
-
2046
-
2047
-
2048
-    /**
2049
-     * trash or restore registrations
2050
-     *
2051
-     * @param  boolean $trash whether to archive or restore
2052
-     * @access protected
2053
-     * @return void
2054
-     */
2055
-    protected function _trash_or_restore_registrations($trash = true)
2056
-    {
2057
-        $REGM = EEM_Registration::instance();
2058
-        $success = 1;
2059
-        $error = 0;
2060
-        $tickets = array();
2061
-        $dtts = array();
2062
-        //if empty _REG_ID then get out because there's nothing to do
2063
-        if (empty($this->_req_data['_REG_ID'])) {
2064
-            $msg = $trash
2065
-                ? __('In order to trash registrations you must select which ones you wish to trash by clicking the checkboxes.',
2066
-                    'event_espresso')
2067
-                : __('In order to restore registrations you must select which ones you wish to restore by clicking the checkboxes.',
2068
-                    'event_espresso');
2069
-            EE_Error::add_error($msg, __FILE__, __LINE__, __FUNCTION__);
2070
-            $this->_redirect_after_action(false, '', '', array(), true);
2071
-        }
2072
-        //Checkboxes
2073
-        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2074
-            // if array has more than one element than success message should be plural
2075
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2076
-            // cycle thru checkboxes
2077
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2078
-                /** @var EE_Registration $REG */
2079
-                $REG = $REGM->get_one_by_ID($REG_ID);
2080
-                $payment_count = $REG->get_first_related('Transaction')->count_related('Payment');
2081
-                if ($payment_count > 0) {
2082
-                    $name = $REG->attendee() instanceof EE_Attendee ? $REG->attendee()->full_name()
2083
-                        : __('Unknown Attendee', 'event_espresso');
2084
-                    $error = 1;
2085
-                    $success = 0;
2086
-                    EE_Error::add_error(sprintf(__('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.',
2087
-                        'event_espresso'), $name), __FILE__, __FUNCTION__, __LINE__);
2088
-                    continue; //can't trash this registration because it has payments.
2089
-                }
2090
-                $ticket = $REG->get_first_related('Ticket');
2091
-                $tickets[$ticket->ID()] = $ticket;
2092
-                $dtt = $ticket->get_many_related('Datetime');
2093
-                $dtts = array_merge($dtts, $dtt);
2094
-                $updated = $trash ? $REG->delete() : $REG->restore();
2095
-                if ( ! $updated) {
2096
-                    $success = 0;
2097
-                } else {
2098
-                    $success = 2;
2099
-                }/**/
2100
-            }
2101
-        } else {
2102
-            // grab single id and delete
2103
-            $REG_ID = absint($this->_req_data['_REG_ID']);
2104
-            $REG = $REGM->get_one_by_ID($REG_ID);
2105
-            $ticket = $REG->get_first_related('Ticket');
2106
-            $tickets[$ticket->ID()] = $ticket;
2107
-            $dtts = $ticket->get_many_related('Datetime');
2108
-            $updated = $trash ? $REG->delete() : $REG->restore();
2109
-            if ( ! $updated) {
2110
-                $success = 0;
2111
-            }
2112
-        }
2113
-        //now let's update counts
2114
-        EEM_Ticket::instance()->update_tickets_sold($tickets);
2115
-        EEM_Datetime::instance()->update_sold($dtts);
2116
-        $what = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2117
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2118
-        $overwrite_msgs = $error ? true : false;
2119
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), $overwrite_msgs);
2120
-    }
2121
-
2122
-
2123
-
2124
-    /**
2125
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2126
-     * registration but also.
2127
-     * 1. Removing relations to EE_Attendee
2128
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2129
-     * ALSO trashed.
2130
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2131
-     * 4. Removing relationships between all tickets and the related registrations
2132
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2133
-     * 6. Deleting permanently any related Checkins.
2134
-     *
2135
-     * @return void
2136
-     */
2137
-    protected function _delete_registrations()
2138
-    {
2139
-        $REG_MDL = EEM_Registration::instance();
2140
-        $success = 1;
2141
-        //Checkboxes
2142
-        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2143
-            // if array has more than one element than success message should be plural
2144
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2145
-            // cycle thru checkboxes
2146
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2147
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2148
-                if ( ! $REG instanceof EE_Registration) {
2149
-                    continue;
2150
-                }
2151
-                $deleted = $this->_delete_registration($REG);
2152
-                if ( ! $deleted) {
2153
-                    $success = 0;
2154
-                }
2155
-            }
2156
-        } else {
2157
-            // grab single id and delete
2158
-            $REG_ID = $this->_req_data['_REG_ID'];
2159
-            $REG = $REG_MDL->get_one_by_ID($REG_ID);
2160
-            $deleted = $this->_delete_registration($REG);
2161
-            if ( ! $deleted) {
2162
-                $success = 0;
2163
-            }
2164
-        }
2165
-        $what = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2166
-        $action_desc = __('permanently deleted.', 'event_espresso');
2167
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), true);
2168
-    }
2169
-
2170
-
2171
-
2172
-    /**
2173
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2174
-     * models get affected.
2175
-     *
2176
-     * @param  EE_Registration $REG registration to be deleted permenantly
2177
-     * @return boolean              true = successful deletion, false = fail.
2178
-     */
2179
-    protected function _delete_registration(EE_Registration $REG)
2180
-    {
2181
-        //first we start with the transaction... ultimately, we WILL not delete permanently if there are any related registrations on the transaction that are NOT trashed.
2182
-        $TXN = $REG->get_first_related('Transaction');
2183
-        $REGS = $TXN->get_many_related('Registration');
2184
-        $all_trashed = true;
2185
-        foreach ($REGS as $registration) {
2186
-            if ( ! $registration->get('REG_deleted')) {
2187
-                $all_trashed = false;
2188
-            }
2189
-        }
2190
-        if ( ! $all_trashed) {
2191
-            EE_Error::add_error(__('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.',
2192
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2193
-            return false;
2194
-        }
2195
-        //k made it here so that means we can delete all the related transactions and their answers (but let's do them separately from THIS one).
2196
-        foreach ($REGS as $registration) {
2197
-            //delete related answers
2198
-            $registration->delete_related_permanently('Answer');
2199
-            //remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2200
-            $attendee = $registration->get_first_related('Attendee');
2201
-            if ($attendee instanceof EE_Attendee) {
2202
-                $registration->_remove_relation_to($attendee, 'Attendee');
2203
-            }
2204
-            //now remove relationships to tickets on this registration.
2205
-            $registration->_remove_relations('Ticket');
2206
-            //now delete permanently the checkins related to this registration.
2207
-            $registration->delete_related_permanently('Checkin');
2208
-            if ($registration->ID() === $REG->ID()) {
2209
-                continue;
2210
-            } //we don't want to delete permanently the existing registration just yet.
2211
-            //remove relation to transaction for these registrations if NOT the existing registrations
2212
-            $registration->_remove_relations('Transaction');
2213
-            //delete permanently any related messages.
2214
-            $registration->delete_related_permanently('Message');
2215
-            //now delete this registration permanently
2216
-            $registration->delete_permanently();
2217
-        }
2218
-        //now all related registrations on the transaction are handled.  So let's just handle this registration itself (the transaction and line items should be all that's left).
2219
-        //delete the line items related to the transaction for this registration.
2220
-        $TXN->delete_related_permanently('Line_Item');
2221
-        //we need to remove all the relationships on the transaction
2222
-        $TXN->delete_related_permanently('Payment');
2223
-        $TXN->delete_related_permanently('Extra_Meta');
2224
-        $TXN->delete_related_permanently('Message');
2225
-        //now we can delete this REG permanently (and the transaction of course)
2226
-        $REG->delete_related_permanently('Transaction');
2227
-        return $REG->delete_permanently();
2228
-    }
2229
-
2230
-
2231
-
2232
-    /**
2233
-     *    generates HTML for the Register New Attendee Admin page
2234
-     *
2235
-     * @access private
2236
-     * @throws \EE_Error
2237
-     * @return void
2238
-     */
2239
-    public function new_registration()
2240
-    {
2241
-        if ( ! $this->_set_reg_event()) {
2242
-            throw new EE_Error(__('Unable to continue with registering because there is no Event ID in the request',
2243
-                'event_espresso'));
2244
-        }
2245
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2246
-        // gotta start with a clean slate if we're not coming here via ajax
2247
-        if ( ! defined('DOING_AJAX')
2248
-             && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2249
-        ) {
2250
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2251
-        }
2252
-        $this->_template_args['event_name'] = '';
2253
-        // event name
2254
-        if ($this->_reg_event) {
2255
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2256
-            $edit_event_url = self::add_query_args_and_nonce(array(
2257
-                'action' => 'edit',
2258
-                'post'   => $this->_reg_event->ID(),
2259
-            ), EVENTS_ADMIN_URL);
2260
-            $edit_event_lnk = '<a href="'
2261
-                              . $edit_event_url
2262
-                              . '" title="'
2263
-                              . esc_attr__('Edit ', 'event_espresso')
2264
-                              . $this->_reg_event->name()
2265
-                              . '">'
2266
-                              . __('Edit Event', 'event_espresso')
2267
-                              . '</a>';
2268
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2269
-                                                   . $edit_event_lnk
2270
-                                                   . '</span>';
2271
-        }
2272
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2273
-        if (defined('DOING_AJAX')) {
2274
-            $this->_return_json();
2275
-        }
2276
-        // grab header
2277
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2278
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2279
-            $this->_template_args, true);
2280
-        //$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2281
-        // the details template wrapper
2282
-        $this->display_admin_page_with_sidebar();
2283
-    }
2284
-
2285
-
2286
-
2287
-    /**
2288
-     * This returns the content for a registration step
2289
-     *
2290
-     * @access protected
2291
-     * @return string html
2292
-     */
2293
-    protected function _get_registration_step_content()
2294
-    {
2295
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2296
-            $warning_msg = sprintf(__('%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',
2297
-                'event_espresso'), '<br />', '<h3 class="important-notice">', '</h3>', '<div class="float-right">',
2298
-                '<span id="redirect_timer" class="important-notice">30</span>', '</div>', '<b>', '</b>');
2299
-            return '
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
1852
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
1853
+	 * to display the page
1854
+	 *
1855
+	 * @access protected
1856
+	 * @return void
1857
+	 */
1858
+	protected function _update_attendee_registration_form()
1859
+	{
1860
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
1861
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
1862
+			$REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
1863
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
1864
+			if ($success) {
1865
+				$what = __('Registration Form', 'event_espresso');
1866
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
1867
+					: array('action' => 'default');
1868
+				$this->_redirect_after_action($success, $what, __('updated', 'event_espresso'), $route);
1869
+			}
1870
+		}
1871
+	}
1872
+
1873
+
1874
+
1875
+	/**
1876
+	 * Gets the form for saving registrations custom questions (if done
1877
+	 * previously retrieves the cached form object, which may have validation errors in it)
1878
+	 *
1879
+	 * @param int $REG_ID
1880
+	 * @return EE_Registration_Custom_Questions_Form
1881
+	 */
1882
+	protected function _get_reg_custom_questions_form($REG_ID)
1883
+	{
1884
+		if ( ! $this->_reg_custom_questions_form) {
1885
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
1886
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(EEM_Registration::instance()
1887
+																										  ->get_one_by_ID($REG_ID));
1888
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
1889
+		}
1890
+		return $this->_reg_custom_questions_form;
1891
+	}
1892
+
1893
+
1894
+
1895
+	/**
1896
+	 * Saves
1897
+	 *
1898
+	 * @access private
1899
+	 * @param bool $REG_ID
1900
+	 * @return bool
1901
+	 */
1902
+	private function _save_reg_custom_questions_form($REG_ID = false)
1903
+	{
1904
+		if ( ! $REG_ID) {
1905
+			EE_Error::add_error(__('An error occurred. No registration ID was received.', 'event_espresso'), __FILE__,
1906
+				__FUNCTION__, __LINE__);
1907
+		}
1908
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
1909
+		$form->receive_form_submission($this->_req_data);
1910
+		$success = false;
1911
+		if ($form->is_valid()) {
1912
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
1913
+				foreach ($question_group_form->inputs() as $question_id => $input) {
1914
+					$where_conditions = array(
1915
+						'QST_ID' => $question_id,
1916
+						'REG_ID' => $REG_ID,
1917
+					);
1918
+					$possibly_new_values = array(
1919
+						'ANS_value' => $input->normalized_value(),
1920
+					);
1921
+					$answer = EEM_Answer::instance()->get_one(array($where_conditions));
1922
+					if ($answer instanceof EE_Answer) {
1923
+						$success = $answer->save($possibly_new_values);
1924
+					} else {
1925
+						//insert it then
1926
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
1927
+						$answer = EE_Answer::new_instance($cols_n_vals);
1928
+						$success = $answer->save();
1929
+					}
1930
+				}
1931
+			}
1932
+		} else {
1933
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
1934
+		}
1935
+		return $success;
1936
+	}
1937
+
1938
+
1939
+
1940
+	/**
1941
+	 *        generates HTML for the Registration main meta box
1942
+	 *
1943
+	 * @access public
1944
+	 * @return void
1945
+	 */
1946
+	public function _reg_attendees_meta_box()
1947
+	{
1948
+		$REG = EEM_Registration::instance();
1949
+		//get all other registrations on this transaction, and cache
1950
+		//the attendees for them so we don't have to run another query using force_join
1951
+		$registrations = $REG->get_all(array(
1952
+			array(
1953
+				'TXN_ID' => $this->_registration->transaction_ID(),
1954
+				'REG_ID' => array('!=', $this->_registration->ID()),
1955
+			),
1956
+			'force_join' => array('Attendee'),
1957
+		));
1958
+		$this->_template_args['attendees'] = array();
1959
+		$this->_template_args['attendee_notice'] = '';
1960
+		if (empty($registrations)
1961
+			|| (is_array($registrations)
1962
+				&& ! EEH_Array::get_one_item_from_array($registrations))
1963
+		) {
1964
+			EE_Error::add_error(__('There are no records attached to this registration. Something may have gone wrong with the registration',
1965
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1966
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
1967
+		} else {
1968
+			$att_nmbr = 1;
1969
+			foreach ($registrations as $registration) {
1970
+				/* @var $registration EE_Registration */
1971
+				$attendee = $registration->attendee()
1972
+					? $registration->attendee()
1973
+					: EEM_Attendee::instance()
1974
+								  ->create_default_object();
1975
+				$this->_template_args['attendees'][$att_nmbr]['STS_ID'] = $registration->status_ID();
1976
+				$this->_template_args['attendees'][$att_nmbr]['fname'] = $attendee->fname();//( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
1977
+				$this->_template_args['attendees'][$att_nmbr]['lname'] = $attendee->lname();//( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
1978
+				$this->_template_args['attendees'][$att_nmbr]['email'] = $attendee->email();//( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
1979
+				$this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();//( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
1980
+				$this->_template_args['attendees'][$att_nmbr]['address'] = implode(', ',
1981
+					$attendee->full_address_as_array());
1982
+				$this->_template_args['attendees'][$att_nmbr]['att_link'] = self::add_query_args_and_nonce(array(
1983
+					'action' => 'edit_attendee',
1984
+					'post'   => $attendee->ID(),
1985
+				), REG_ADMIN_URL);
1986
+				$this->_template_args['attendees'][$att_nmbr]['event_name'] = $registration->event_obj()->name();
1987
+				$att_nmbr++;
1988
+			}
1989
+			//EEH_Debug_Tools::printr( $attendees, '$attendees  <br /><span style="font-size:10px;font-weight:normal;">( file: '. __FILE__ . ' - line no: ' . __LINE__ . ' )</span>', 'auto' );
1990
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1991
+			//			$this->_template_args['registration_form_url'] = add_query_arg( array( 'action' => 'edit_registration', 'process' => 'attendees'  ), REG_ADMIN_URL );
1992
+		}
1993
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
1994
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1995
+	}
1996
+
1997
+
1998
+
1999
+	/**
2000
+	 *        generates HTML for the Edit Registration side meta box
2001
+	 *
2002
+	 * @access public
2003
+	 * @return void
2004
+	 */
2005
+	public function _reg_registrant_side_meta_box()
2006
+	{
2007
+		/*@var $attendee EE_Attendee */
2008
+		$att_check = $this->_registration->attendee();
2009
+		$attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2010
+		//now let's determine if this is not the primary registration.  If it isn't then we set the primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the primary registration object (that way we know if we need to show create button or not)
2011
+		if ( ! $this->_registration->is_primary_registrant()) {
2012
+			$primary_registration = $this->_registration->get_primary_registration();
2013
+			$primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2014
+				: null;
2015
+			if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2016
+				//in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own custom attendee object so let's not worry about the primary reg.
2017
+				$primary_registration = null;
2018
+			}
2019
+		} else {
2020
+			$primary_registration = null;
2021
+		}
2022
+		$this->_template_args['ATT_ID'] = $attendee->ID();
2023
+		$this->_template_args['fname'] = $attendee->fname();//$this->_registration->ATT_fname;
2024
+		$this->_template_args['lname'] = $attendee->lname();//$this->_registration->ATT_lname;
2025
+		$this->_template_args['email'] = $attendee->email();//$this->_registration->ATT_email;
2026
+		$this->_template_args['phone'] = $attendee->phone();
2027
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2028
+		//edit link
2029
+		$this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
2030
+			'action' => 'edit_attendee',
2031
+			'post'   => $attendee->ID(),
2032
+		), REG_ADMIN_URL);
2033
+		$this->_template_args['att_edit_label'] = __('View/Edit Contact', 'event_espresso');
2034
+		//create link
2035
+		$this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2036
+			? EE_Admin_Page::add_query_args_and_nonce(array(
2037
+				'action'  => 'duplicate_attendee',
2038
+				'_REG_ID' => $this->_registration->ID(),
2039
+			), REG_ADMIN_URL) : '';
2040
+		$this->_template_args['create_label'] = __('Create Contact', 'event_espresso');
2041
+		$this->_template_args['att_check'] = $att_check;
2042
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2043
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2044
+	}
2045
+
2046
+
2047
+
2048
+	/**
2049
+	 * trash or restore registrations
2050
+	 *
2051
+	 * @param  boolean $trash whether to archive or restore
2052
+	 * @access protected
2053
+	 * @return void
2054
+	 */
2055
+	protected function _trash_or_restore_registrations($trash = true)
2056
+	{
2057
+		$REGM = EEM_Registration::instance();
2058
+		$success = 1;
2059
+		$error = 0;
2060
+		$tickets = array();
2061
+		$dtts = array();
2062
+		//if empty _REG_ID then get out because there's nothing to do
2063
+		if (empty($this->_req_data['_REG_ID'])) {
2064
+			$msg = $trash
2065
+				? __('In order to trash registrations you must select which ones you wish to trash by clicking the checkboxes.',
2066
+					'event_espresso')
2067
+				: __('In order to restore registrations you must select which ones you wish to restore by clicking the checkboxes.',
2068
+					'event_espresso');
2069
+			EE_Error::add_error($msg, __FILE__, __LINE__, __FUNCTION__);
2070
+			$this->_redirect_after_action(false, '', '', array(), true);
2071
+		}
2072
+		//Checkboxes
2073
+		if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2074
+			// if array has more than one element than success message should be plural
2075
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2076
+			// cycle thru checkboxes
2077
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2078
+				/** @var EE_Registration $REG */
2079
+				$REG = $REGM->get_one_by_ID($REG_ID);
2080
+				$payment_count = $REG->get_first_related('Transaction')->count_related('Payment');
2081
+				if ($payment_count > 0) {
2082
+					$name = $REG->attendee() instanceof EE_Attendee ? $REG->attendee()->full_name()
2083
+						: __('Unknown Attendee', 'event_espresso');
2084
+					$error = 1;
2085
+					$success = 0;
2086
+					EE_Error::add_error(sprintf(__('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.',
2087
+						'event_espresso'), $name), __FILE__, __FUNCTION__, __LINE__);
2088
+					continue; //can't trash this registration because it has payments.
2089
+				}
2090
+				$ticket = $REG->get_first_related('Ticket');
2091
+				$tickets[$ticket->ID()] = $ticket;
2092
+				$dtt = $ticket->get_many_related('Datetime');
2093
+				$dtts = array_merge($dtts, $dtt);
2094
+				$updated = $trash ? $REG->delete() : $REG->restore();
2095
+				if ( ! $updated) {
2096
+					$success = 0;
2097
+				} else {
2098
+					$success = 2;
2099
+				}/**/
2100
+			}
2101
+		} else {
2102
+			// grab single id and delete
2103
+			$REG_ID = absint($this->_req_data['_REG_ID']);
2104
+			$REG = $REGM->get_one_by_ID($REG_ID);
2105
+			$ticket = $REG->get_first_related('Ticket');
2106
+			$tickets[$ticket->ID()] = $ticket;
2107
+			$dtts = $ticket->get_many_related('Datetime');
2108
+			$updated = $trash ? $REG->delete() : $REG->restore();
2109
+			if ( ! $updated) {
2110
+				$success = 0;
2111
+			}
2112
+		}
2113
+		//now let's update counts
2114
+		EEM_Ticket::instance()->update_tickets_sold($tickets);
2115
+		EEM_Datetime::instance()->update_sold($dtts);
2116
+		$what = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2117
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2118
+		$overwrite_msgs = $error ? true : false;
2119
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), $overwrite_msgs);
2120
+	}
2121
+
2122
+
2123
+
2124
+	/**
2125
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2126
+	 * registration but also.
2127
+	 * 1. Removing relations to EE_Attendee
2128
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2129
+	 * ALSO trashed.
2130
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2131
+	 * 4. Removing relationships between all tickets and the related registrations
2132
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2133
+	 * 6. Deleting permanently any related Checkins.
2134
+	 *
2135
+	 * @return void
2136
+	 */
2137
+	protected function _delete_registrations()
2138
+	{
2139
+		$REG_MDL = EEM_Registration::instance();
2140
+		$success = 1;
2141
+		//Checkboxes
2142
+		if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2143
+			// if array has more than one element than success message should be plural
2144
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2145
+			// cycle thru checkboxes
2146
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2147
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2148
+				if ( ! $REG instanceof EE_Registration) {
2149
+					continue;
2150
+				}
2151
+				$deleted = $this->_delete_registration($REG);
2152
+				if ( ! $deleted) {
2153
+					$success = 0;
2154
+				}
2155
+			}
2156
+		} else {
2157
+			// grab single id and delete
2158
+			$REG_ID = $this->_req_data['_REG_ID'];
2159
+			$REG = $REG_MDL->get_one_by_ID($REG_ID);
2160
+			$deleted = $this->_delete_registration($REG);
2161
+			if ( ! $deleted) {
2162
+				$success = 0;
2163
+			}
2164
+		}
2165
+		$what = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2166
+		$action_desc = __('permanently deleted.', 'event_espresso');
2167
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), true);
2168
+	}
2169
+
2170
+
2171
+
2172
+	/**
2173
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2174
+	 * models get affected.
2175
+	 *
2176
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2177
+	 * @return boolean              true = successful deletion, false = fail.
2178
+	 */
2179
+	protected function _delete_registration(EE_Registration $REG)
2180
+	{
2181
+		//first we start with the transaction... ultimately, we WILL not delete permanently if there are any related registrations on the transaction that are NOT trashed.
2182
+		$TXN = $REG->get_first_related('Transaction');
2183
+		$REGS = $TXN->get_many_related('Registration');
2184
+		$all_trashed = true;
2185
+		foreach ($REGS as $registration) {
2186
+			if ( ! $registration->get('REG_deleted')) {
2187
+				$all_trashed = false;
2188
+			}
2189
+		}
2190
+		if ( ! $all_trashed) {
2191
+			EE_Error::add_error(__('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.',
2192
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2193
+			return false;
2194
+		}
2195
+		//k made it here so that means we can delete all the related transactions and their answers (but let's do them separately from THIS one).
2196
+		foreach ($REGS as $registration) {
2197
+			//delete related answers
2198
+			$registration->delete_related_permanently('Answer');
2199
+			//remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2200
+			$attendee = $registration->get_first_related('Attendee');
2201
+			if ($attendee instanceof EE_Attendee) {
2202
+				$registration->_remove_relation_to($attendee, 'Attendee');
2203
+			}
2204
+			//now remove relationships to tickets on this registration.
2205
+			$registration->_remove_relations('Ticket');
2206
+			//now delete permanently the checkins related to this registration.
2207
+			$registration->delete_related_permanently('Checkin');
2208
+			if ($registration->ID() === $REG->ID()) {
2209
+				continue;
2210
+			} //we don't want to delete permanently the existing registration just yet.
2211
+			//remove relation to transaction for these registrations if NOT the existing registrations
2212
+			$registration->_remove_relations('Transaction');
2213
+			//delete permanently any related messages.
2214
+			$registration->delete_related_permanently('Message');
2215
+			//now delete this registration permanently
2216
+			$registration->delete_permanently();
2217
+		}
2218
+		//now all related registrations on the transaction are handled.  So let's just handle this registration itself (the transaction and line items should be all that's left).
2219
+		//delete the line items related to the transaction for this registration.
2220
+		$TXN->delete_related_permanently('Line_Item');
2221
+		//we need to remove all the relationships on the transaction
2222
+		$TXN->delete_related_permanently('Payment');
2223
+		$TXN->delete_related_permanently('Extra_Meta');
2224
+		$TXN->delete_related_permanently('Message');
2225
+		//now we can delete this REG permanently (and the transaction of course)
2226
+		$REG->delete_related_permanently('Transaction');
2227
+		return $REG->delete_permanently();
2228
+	}
2229
+
2230
+
2231
+
2232
+	/**
2233
+	 *    generates HTML for the Register New Attendee Admin page
2234
+	 *
2235
+	 * @access private
2236
+	 * @throws \EE_Error
2237
+	 * @return void
2238
+	 */
2239
+	public function new_registration()
2240
+	{
2241
+		if ( ! $this->_set_reg_event()) {
2242
+			throw new EE_Error(__('Unable to continue with registering because there is no Event ID in the request',
2243
+				'event_espresso'));
2244
+		}
2245
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2246
+		// gotta start with a clean slate if we're not coming here via ajax
2247
+		if ( ! defined('DOING_AJAX')
2248
+			 && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2249
+		) {
2250
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2251
+		}
2252
+		$this->_template_args['event_name'] = '';
2253
+		// event name
2254
+		if ($this->_reg_event) {
2255
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2256
+			$edit_event_url = self::add_query_args_and_nonce(array(
2257
+				'action' => 'edit',
2258
+				'post'   => $this->_reg_event->ID(),
2259
+			), EVENTS_ADMIN_URL);
2260
+			$edit_event_lnk = '<a href="'
2261
+							  . $edit_event_url
2262
+							  . '" title="'
2263
+							  . esc_attr__('Edit ', 'event_espresso')
2264
+							  . $this->_reg_event->name()
2265
+							  . '">'
2266
+							  . __('Edit Event', 'event_espresso')
2267
+							  . '</a>';
2268
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2269
+												   . $edit_event_lnk
2270
+												   . '</span>';
2271
+		}
2272
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2273
+		if (defined('DOING_AJAX')) {
2274
+			$this->_return_json();
2275
+		}
2276
+		// grab header
2277
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2278
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2279
+			$this->_template_args, true);
2280
+		//$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2281
+		// the details template wrapper
2282
+		$this->display_admin_page_with_sidebar();
2283
+	}
2284
+
2285
+
2286
+
2287
+	/**
2288
+	 * This returns the content for a registration step
2289
+	 *
2290
+	 * @access protected
2291
+	 * @return string html
2292
+	 */
2293
+	protected function _get_registration_step_content()
2294
+	{
2295
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2296
+			$warning_msg = sprintf(__('%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',
2297
+				'event_espresso'), '<br />', '<h3 class="important-notice">', '</h3>', '<div class="float-right">',
2298
+				'<span id="redirect_timer" class="important-notice">30</span>', '</div>', '<b>', '</b>');
2299
+			return '
2300 2300
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
2301 2301
 	<script >
2302 2302
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -2309,646 +2309,646 @@  discard block
 block discarded – undo
2309 2309
 	        }
2310 2310
 	    }, 800 );
2311 2311
 	</script >';
2312
-        }
2313
-        $template_args = array(
2314
-            'title'                    => '',
2315
-            'content'                  => '',
2316
-            'step_button_text'         => '',
2317
-            'show_notification_toggle' => false,
2318
-        );
2319
-        //to indicate we're processing a new registration
2320
-        $hidden_fields = array(
2321
-            'processing_registration' => array(
2322
-                'type'  => 'hidden',
2323
-                'value' => 0,
2324
-            ),
2325
-            'event_id'                => array(
2326
-                'type'  => 'hidden',
2327
-                'value' => $this->_reg_event->ID(),
2328
-            ),
2329
-        );
2330
-        //if the cart is empty then we know we're at step one so we'll display ticket selector
2331
-        $cart = EE_Registry::instance()->SSN->cart();
2332
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2333
-        switch ($step) {
2334
-            case 'ticket' :
2335
-                $hidden_fields['processing_registration']['value'] = 1;
2336
-                $template_args['title'] = __('Step One: Select the Ticket for this registration', 'event_espresso');
2337
-                $template_args['content'] = EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2338
-                $template_args['step_button_text'] = __('Add Tickets and Continue to Registrant Details',
2339
-                    'event_espresso');
2340
-                $template_args['show_notification_toggle'] = false;
2341
-                break;
2342
-            case 'questions' :
2343
-                $hidden_fields['processing_registration']['value'] = 2;
2344
-                $template_args['title'] = __('Step Two: Add Registrant Details for this Registration',
2345
-                    'event_espresso');
2346
-                //in theory we should be able to run EED_SPCO at this point because the cart should have been setup properly by the first process_reg_step run.
2347
-                $template_args['content'] = EED_Single_Page_Checkout::registration_checkout_for_admin();
2348
-                $template_args['step_button_text'] = __('Save Registration and Continue to Details', 'event_espresso');
2349
-                $template_args['show_notification_toggle'] = true;
2350
-                break;
2351
-        }
2352
-        $this->_set_add_edit_form_tags('process_reg_step',
2353
-            $hidden_fields); //we come back to the process_registration_step route.
2354
-        return EEH_Template::display_template(REG_TEMPLATE_PATH
2355
-                                              . 'reg_admin_register_new_attendee_step_content.template.php',
2356
-            $template_args, true);
2357
-    }
2358
-
2359
-
2360
-
2361
-    /**
2362
-     *        set_reg_event
2363
-     *
2364
-     * @access private
2365
-     * @return boolean
2366
-     */
2367
-    private function _set_reg_event()
2368
-    {
2369
-        if (is_object($this->_reg_event)) {
2370
-            return true;
2371
-        }
2372
-        $EVT_ID = ( ! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2373
-        if ( ! $EVT_ID) {
2374
-            return false;
2375
-        }
2376
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2377
-        return true;
2378
-    }
2379
-
2380
-
2381
-
2382
-    /**
2383
-     * process_reg_step
2384
-     *
2385
-     * @access        public
2386
-     * @return        string
2387
-     * @throws \RuntimeException
2388
-     * @throws \EE_Error
2389
-     */
2390
-    public function process_reg_step()
2391
-    {
2392
-        EE_System::do_not_cache();
2393
-        $this->_set_reg_event();
2394
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2395
-        EE_Registry::instance()->REQ->set('uts', time());
2396
-        //what step are we on?
2397
-        $cart = EE_Registry::instance()->SSN->cart();
2398
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2399
-        //if doing ajax then we need to verify the nonce
2400
-        if (defined('DOING_AJAX')) {
2401
-            $nonce = isset($this->_req_data[$this->_req_nonce])
2402
-                ? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2403
-            $this->_verify_nonce($nonce, $this->_req_nonce);
2404
-        }
2405
-        switch ($step) {
2406
-            case 'ticket' :
2407
-                //process ticket selection
2408
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
2409
-                if ($success) {
2410
-                    EE_Error::add_success(esc_html__('Tickets Selected. Now complete the registration.',
2411
-                        'event_espresso'));
2412
-                } else {
2413
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
2414
-                }
2415
-                if (defined('DOING_AJAX')) {
2416
-                    $this->new_registration(); //display next step
2417
-                } else {
2418
-                    $query_args = array(
2419
-                        'action'                  => 'new_registration',
2420
-                        'processing_registration' => 1,
2421
-                        'event_id'                => $this->_reg_event->ID(),
2422
-                        'uts'                     => time(),
2423
-                    );
2424
-                    $this->_redirect_after_action(false, '', '', $query_args, true);
2425
-                }
2426
-                break;
2427
-            case 'questions' :
2428
-                if ( ! isset($this->_req_data['txn_reg_status_change'], $this->_req_data['txn_reg_status_change']['send_notifications'])) {
2429
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2430
-                }
2431
-                //process registration
2432
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2433
-                if ($cart instanceof EE_Cart) {
2434
-                    $grand_total = $cart->get_cart_grand_total();
2435
-                    if ($grand_total instanceof EE_Line_Item) {
2436
-                        $grand_total->save_this_and_descendants_to_txn();
2437
-                    }
2438
-                }
2439
-                if ( ! $transaction instanceof EE_Transaction) {
2440
-                    $query_args = array(
2441
-                        'action'                  => 'new_registration',
2442
-                        'processing_registration' => 2,
2443
-                        'event_id'                => $this->_reg_event->ID(),
2444
-                        'uts'                     => time(),
2445
-                    );
2446
-                    if (defined('DOING_AJAX')) {
2447
-                        //display registration form again because there are errors (maybe validation?)
2448
-                        $this->new_registration();
2449
-                        return;
2450
-                    } else {
2451
-                        $this->_redirect_after_action(false, '', '', $query_args, true);
2452
-                        return;
2453
-                    }
2454
-                }
2455
-                // maybe update status, and make sure to save transaction if not done already
2456
-                if ( ! $transaction->update_status_based_on_total_paid()) {
2457
-                    $transaction->save();
2458
-                }
2459
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2460
-                $this->_req_data = array();
2461
-                $query_args = array(
2462
-                    'action'        => 'redirect_to_txn',
2463
-                    'TXN_ID'        => $transaction->ID(),
2464
-                    'EVT_ID'        => $this->_reg_event->ID(),
2465
-                    'event_name'    => urlencode($this->_reg_event->name()),
2466
-                    'redirect_from' => 'new_registration',
2467
-                );
2468
-                $this->_redirect_after_action(false, '', '', $query_args, true);
2469
-                break;
2470
-        }
2471
-        //what are you looking here for?  Should be nothing to do at this point.
2472
-    }
2473
-
2474
-
2475
-
2476
-    /**
2477
-     * redirect_to_txn
2478
-     *
2479
-     * @access public
2480
-     * @return void
2481
-     */
2482
-    public function redirect_to_txn()
2483
-    {
2484
-        EE_System::do_not_cache();
2485
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2486
-        $query_args = array(
2487
-            'action' => 'view_transaction',
2488
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
2489
-            'page'   => 'espresso_transactions',
2490
-        );
2491
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
2492
-            $query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
2493
-            $query_args['event_name'] = urlencode($this->_req_data['event_name']);
2494
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
2495
-        }
2496
-        EE_Error::add_success(__('Registration Created.  Please review the transaction and add any payments as necessary',
2497
-                'event_espresso'));
2498
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2499
-    }
2500
-
2501
-
2502
-
2503
-    /**
2504
-     *        generates HTML for the Attendee Contact List
2505
-     *
2506
-     * @access protected
2507
-     * @return void
2508
-     */
2509
-    protected function _attendee_contact_list_table()
2510
-    {
2511
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2512
-        $this->_search_btn_label = __('Contacts', 'event_espresso');
2513
-        $this->display_admin_list_table_page_with_no_sidebar();
2514
-    }
2515
-
2516
-
2517
-
2518
-    /**
2519
-     *        get_attendees
2520
-     *
2521
-     * @param bool $count whether to return count or data.
2522
-     * @access public
2523
-     * @return array
2524
-     */
2525
-    public function get_attendees($per_page, $count = false, $trash = false)
2526
-    {
2527
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2528
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2529
-        $ATT_MDL = EEM_Attendee::instance();
2530
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2531
-        switch ($this->_req_data['orderby']) {
2532
-            case 'ATT_ID':
2533
-                $orderby = 'ATT_ID';
2534
-                break;
2535
-            case 'ATT_fname':
2536
-                $orderby = 'ATT_fname';
2537
-                break;
2538
-            case 'ATT_email':
2539
-                $orderby = 'ATT_email';
2540
-                break;
2541
-            case 'ATT_city':
2542
-                $orderby = 'ATT_city';
2543
-                break;
2544
-            case 'STA_ID':
2545
-                $orderby = 'STA_ID';
2546
-                break;
2547
-            case 'CNT_ID':
2548
-                $orderby = 'CNT_ID';
2549
-                break;
2550
-            default:
2551
-                $orderby = 'ATT_lname';
2552
-        }
2553
-        $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
2554
-            : 'ASC';
2555
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
2556
-            ? $this->_req_data['paged'] : 1;
2557
-        $per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
2558
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
2559
-            ? $this->_req_data['perpage'] : $per_page;
2560
-        $_where = array();
2561
-        if ( ! empty($this->_req_data['s'])) {
2562
-            $sstr = '%' . $this->_req_data['s'] . '%';
2563
-            $_where['OR'] = array(
2564
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
2565
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
2566
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
2567
-                'ATT_fname'                         => array('LIKE', $sstr),
2568
-                'ATT_lname'                         => array('LIKE', $sstr),
2569
-                'ATT_short_bio'                     => array('LIKE', $sstr),
2570
-                'ATT_email'                         => array('LIKE', $sstr),
2571
-                'ATT_address'                       => array('LIKE', $sstr),
2572
-                'ATT_address2'                      => array('LIKE', $sstr),
2573
-                'ATT_city'                          => array('LIKE', $sstr),
2574
-                'Country.CNT_name'                  => array('LIKE', $sstr),
2575
-                'State.STA_name'                    => array('LIKE', $sstr),
2576
-                'ATT_phone'                         => array('LIKE', $sstr),
2577
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
2578
-                'Registration.REG_code'             => array('LIKE', $sstr),
2579
-                'Registration.REG_count'            => array('LIKE', $sstr),
2580
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
2581
-            );
2582
-        }
2583
-        $offset = ($current_page - 1) * $per_page;
2584
-        $limit = $count ? null : array($offset, $per_page);
2585
-        if ($trash) {
2586
-            $_where['status'] = array('!=', 'publish');
2587
-            $all_attendees = $count
2588
-                ? $ATT_MDL->count(array(
2589
-                    $_where,
2590
-                    'order_by' => array($orderby => $sort),
2591
-                    'limit'    => $limit,
2592
-                ), 'ATT_ID', true)
2593
-                : $ATT_MDL->get_all(array(
2594
-                    $_where,
2595
-                    'order_by' => array($orderby => $sort),
2596
-                    'limit'    => $limit,
2597
-                ));
2598
-        } else {
2599
-            $_where['status'] = array('IN', array('publish'));
2600
-            $all_attendees = $count
2601
-                ? $ATT_MDL->count(array(
2602
-                    $_where,
2603
-                    'order_by' => array($orderby => $sort),
2604
-                    'limit'    => $limit,
2605
-                ), 'ATT_ID', true)
2606
-                : $ATT_MDL->get_all(array(
2607
-                    $_where,
2608
-                    'order_by' => array($orderby => $sort),
2609
-                    'limit'    => $limit,
2610
-                ));
2611
-        }
2612
-        return $all_attendees;
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * This is just taking care of resending the registration confirmation
2619
-     *
2620
-     * @access protected
2621
-     * @return void
2622
-     */
2623
-    protected function _resend_registration()
2624
-    {
2625
-        $this->_process_resend_registration();
2626
-        $query_args = isset($this->_req_data['redirect_to'])
2627
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
2628
-            : array(
2629
-                'action' => 'default',
2630
-            );
2631
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2632
-    }
2633
-
2634
-
2635
-
2636
-    public function _registrations_report()
2637
-    {
2638
-        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2639
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2640
-                'page'        => 'espresso_batch',
2641
-                'batch'       => 'file',
2642
-                'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2643
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
2644
-                'return_url'  => urlencode($this->_req_data['return_url']),
2645
-            )));
2646
-        } else {
2647
-            $new_request_args = array(
2648
-                'export' => 'report',
2649
-                'action' => 'registrations_report_for_event',
2650
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2651
-            );
2652
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
2653
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2654
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2655
-                $EE_Export = EE_Export::instance($this->_req_data);
2656
-                $EE_Export->export();
2657
-            }
2658
-        }
2659
-    }
2660
-
2661
-
2662
-
2663
-    public function _contact_list_export()
2664
-    {
2665
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2666
-            require_once(EE_CLASSES . 'EE_Export.class.php');
2667
-            $EE_Export = EE_Export::instance($this->_req_data);
2668
-            $EE_Export->export_attendees();
2669
-        }
2670
-    }
2671
-
2672
-
2673
-
2674
-    public function _contact_list_report()
2675
-    {
2676
-        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2677
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2678
-                'page'        => 'espresso_batch',
2679
-                'batch'       => 'file',
2680
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
2681
-                'return_url'  => urlencode($this->_req_data['return_url']),
2682
-            )));
2683
-        } else {
2684
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2685
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2686
-                $EE_Export = EE_Export::instance($this->_req_data);
2687
-                $EE_Export->report_attendees();
2688
-            }
2689
-        }
2690
-    }
2691
-
2692
-
2693
-
2694
-
2695
-
2696
-    /***************************************        ATTENDEE DETAILS        ***************************************/
2697
-    /**
2698
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
2699
-     *
2700
-     * @return void
2701
-     */
2702
-    protected function _duplicate_attendee()
2703
-    {
2704
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
2705
-        //verify we have necessary info
2706
-        if (empty($this->_req_data['_REG_ID'])) {
2707
-            EE_Error::add_error(__('Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
2708
-                'event_espresso'), __FILE__, __LINE__, __FUNCTION__);
2709
-            $query_args = array('action' => $action);
2710
-            $this->_redirect_after_action('', '', '', $query_args, true);
2711
-        }
2712
-        //okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
2713
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
2714
-        $attendee = $registration->attendee();
2715
-        //remove relation of existing attendee on registration
2716
-        $registration->_remove_relation_to($attendee, 'Attendee');
2717
-        //new attendee
2718
-        $new_attendee = clone $attendee;
2719
-        $new_attendee->set('ATT_ID', 0);
2720
-        $new_attendee->save();
2721
-        //add new attendee to reg
2722
-        $registration->_add_relation_to($new_attendee, 'Attendee');
2723
-        EE_Error::add_success(__('New Contact record created.  Now make any edits you wish to make for this contact.',
2724
-            'event_espresso'));
2725
-        //redirect to edit page for attendee
2726
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
2727
-        $this->_redirect_after_action('', '', '', $query_args, true);
2728
-    }
2729
-
2730
-
2731
-
2732
-    //related to cpt routes
2733
-    protected function _insert_update_cpt_item($post_id, $post)
2734
-    {
2735
-        $success = true;
2736
-        $attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
2737
-        //for attendee updates
2738
-        if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
2739
-            //note we should only be UPDATING attendees at this point.
2740
-            $updated_fields = array(
2741
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
2742
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
2743
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
2744
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
2745
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
2746
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
2747
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
2748
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
2749
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
2750
-                'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
2751
-                'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
2752
-            );
2753
-            foreach ($updated_fields as $field => $value) {
2754
-                $attendee->set($field, $value);
2755
-            }
2756
-            $success = $attendee->save();
2757
-            $attendee_update_callbacks = apply_filters('FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
2758
-                array());
2759
-            foreach ($attendee_update_callbacks as $a_callback) {
2760
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
2761
-                    throw new EE_Error(sprintf(__('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.',
2762
-                        'event_espresso'), $a_callback));
2763
-                }
2764
-            }
2765
-        }
2766
-        if ($success === false) {
2767
-            EE_Error::add_error(__('Something went wrong with updating the meta table data for the registration.',
2768
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2769
-        }
2770
-    }
2771
-
2772
-
2773
-
2774
-    public function trash_cpt_item($post_id)
2775
-    {
2776
-    }
2777
-
2778
-
2779
-
2780
-    public function delete_cpt_item($post_id)
2781
-    {
2782
-    }
2783
-
2784
-
2785
-
2786
-    public function restore_cpt_item($post_id)
2787
-    {
2788
-    }
2789
-
2790
-
2791
-
2792
-    protected function _restore_cpt_item($post_id, $revision_id)
2793
-    {
2794
-    }
2795
-
2796
-
2797
-
2798
-    public function attendee_editor_metaboxes()
2799
-    {
2800
-        $this->verify_cpt_object();
2801
-        remove_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', $this->_cpt_routes[$this->_req_action],
2802
-            'normal', 'core');
2803
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2804
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
2805
-            add_meta_box('postexcerpt', __('Short Biography', 'event_espresso'), 'post_excerpt_meta_box',
2806
-                $this->_cpt_routes[$this->_req_action], 'normal');
2807
-        }
2808
-        if (post_type_supports('espresso_attendees', 'comments')) {
2809
-            add_meta_box('commentsdiv', __('Notes on the Contact', 'event_espresso'), 'post_comment_meta_box',
2810
-                $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2811
-        }
2812
-        add_meta_box('attendee_contact_info', __('Contact Info', 'event_espresso'),
2813
-            array($this, 'attendee_contact_info'), $this->_cpt_routes[$this->_req_action], 'side', 'core');
2814
-        add_meta_box('attendee_details_address', __('Address Details', 'event_espresso'),
2815
-            array($this, 'attendee_address_details'), $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2816
-        add_meta_box('attendee_registrations', __('Registrations for this Contact', 'event_espresso'),
2817
-            array($this, 'attendee_registrations_meta_box'), $this->_cpt_routes[$this->_req_action], 'normal', 'high');
2818
-    }
2819
-
2820
-
2821
-
2822
-    /**
2823
-     * Metabox for attendee contact info
2824
-     *
2825
-     * @param  WP_Post $post wp post object
2826
-     * @return string        attendee contact info ( and form )
2827
-     */
2828
-    public function attendee_contact_info($post)
2829
-    {
2830
-        //get attendee object ( should already have it )
2831
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
2832
-        $template = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
2833
-        EEH_Template::display_template($template, $this->_template_args);
2834
-    }
2835
-
2836
-
2837
-
2838
-    /**
2839
-     * Metabox for attendee details
2840
-     *
2841
-     * @param  WP_Post $post wp post object
2842
-     * @return string        attendee address details (and form)
2843
-     */
2844
-    public function attendee_address_details($post)
2845
-    {
2846
-        //get attendee object (should already have it)
2847
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
2848
-        $this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2849
-            'QST_ID'           => 0,
2850
-            'QST_display_text' => __('State/Province', 'event_espresso'),
2851
-            'QST_system'       => 'admin-state',
2852
-        )), EE_Answer::new_instance(array(
2853
-            'ANS_ID'    => 0,
2854
-            'ANS_value' => $this->_cpt_model_obj->state_ID(),
2855
-        )), array(
2856
-                'input_id'       => 'STA_ID',
2857
-                'input_name'     => 'STA_ID',
2858
-                'input_prefix'   => '',
2859
-                'append_qstn_id' => false,
2860
-            )));
2861
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2862
-            'QST_ID'           => 0,
2863
-            'QST_display_text' => __('Country', 'event_espresso'),
2864
-            'QST_system'       => 'admin-country',
2865
-        )), EE_Answer::new_instance(array(
2866
-            'ANS_ID'    => 0,
2867
-            'ANS_value' => $this->_cpt_model_obj->country_ID(),
2868
-        )), array(
2869
-                'input_id'       => 'CNT_ISO',
2870
-                'input_name'     => 'CNT_ISO',
2871
-                'input_prefix'   => '',
2872
-                'append_qstn_id' => false,
2873
-            )));
2874
-        $template = REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
2875
-        EEH_Template::display_template($template, $this->_template_args);
2876
-    }
2877
-
2878
-
2879
-
2880
-    /**
2881
-     *        _attendee_details
2882
-     *
2883
-     * @access protected
2884
-     * @return void
2885
-     */
2886
-    public function attendee_registrations_meta_box($post)
2887
-    {
2888
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
2889
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
2890
-        $template = REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
2891
-        EEH_Template::display_template($template, $this->_template_args);
2892
-    }
2893
-
2894
-
2895
-
2896
-    /**
2897
-     * add in the form fields for the attendee edit
2898
-     *
2899
-     * @param  WP_Post $post wp post object
2900
-     * @return string        html for new form.
2901
-     */
2902
-    public function after_title_form_fields($post)
2903
-    {
2904
-        if ($post->post_type == 'espresso_attendees') {
2905
-            $template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
2906
-            $template_args['attendee'] = $this->_cpt_model_obj;
2907
-            EEH_Template::display_template($template, $template_args);
2908
-        }
2909
-    }
2910
-
2911
-
2912
-
2913
-    /**
2914
-     *        _trash_or_restore_attendee
2915
-     *
2916
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
2917
-     * @access protected
2918
-     * @return void
2919
-     */
2920
-    protected function _trash_or_restore_attendees($trash = true)
2921
-    {
2922
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2923
-        $ATT_MDL = EEM_Attendee::instance();
2924
-        $success = 1;
2925
-        //Checkboxes
2926
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2927
-            // if array has more than one element than success message should be plural
2928
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2929
-            // cycle thru checkboxes
2930
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
2931
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
2932
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
2933
-                if ( ! $updated) {
2934
-                    $success = 0;
2935
-                }
2936
-            }
2937
-        } else {
2938
-            // grab single id and delete
2939
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
2940
-            //get attendee
2941
-            $att = $ATT_MDL->get_one_by_ID($ATT_ID);
2942
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
2943
-            $updated = $att->save();
2944
-            if ( ! $updated) {
2945
-                $success = 0;
2946
-            }
2947
-        }
2948
-        $what = $success > 1 ? __('Contacts', 'event_espresso') : __('Contact', 'event_espresso');
2949
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2950
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
2951
-    }
2312
+		}
2313
+		$template_args = array(
2314
+			'title'                    => '',
2315
+			'content'                  => '',
2316
+			'step_button_text'         => '',
2317
+			'show_notification_toggle' => false,
2318
+		);
2319
+		//to indicate we're processing a new registration
2320
+		$hidden_fields = array(
2321
+			'processing_registration' => array(
2322
+				'type'  => 'hidden',
2323
+				'value' => 0,
2324
+			),
2325
+			'event_id'                => array(
2326
+				'type'  => 'hidden',
2327
+				'value' => $this->_reg_event->ID(),
2328
+			),
2329
+		);
2330
+		//if the cart is empty then we know we're at step one so we'll display ticket selector
2331
+		$cart = EE_Registry::instance()->SSN->cart();
2332
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2333
+		switch ($step) {
2334
+			case 'ticket' :
2335
+				$hidden_fields['processing_registration']['value'] = 1;
2336
+				$template_args['title'] = __('Step One: Select the Ticket for this registration', 'event_espresso');
2337
+				$template_args['content'] = EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2338
+				$template_args['step_button_text'] = __('Add Tickets and Continue to Registrant Details',
2339
+					'event_espresso');
2340
+				$template_args['show_notification_toggle'] = false;
2341
+				break;
2342
+			case 'questions' :
2343
+				$hidden_fields['processing_registration']['value'] = 2;
2344
+				$template_args['title'] = __('Step Two: Add Registrant Details for this Registration',
2345
+					'event_espresso');
2346
+				//in theory we should be able to run EED_SPCO at this point because the cart should have been setup properly by the first process_reg_step run.
2347
+				$template_args['content'] = EED_Single_Page_Checkout::registration_checkout_for_admin();
2348
+				$template_args['step_button_text'] = __('Save Registration and Continue to Details', 'event_espresso');
2349
+				$template_args['show_notification_toggle'] = true;
2350
+				break;
2351
+		}
2352
+		$this->_set_add_edit_form_tags('process_reg_step',
2353
+			$hidden_fields); //we come back to the process_registration_step route.
2354
+		return EEH_Template::display_template(REG_TEMPLATE_PATH
2355
+											  . 'reg_admin_register_new_attendee_step_content.template.php',
2356
+			$template_args, true);
2357
+	}
2358
+
2359
+
2360
+
2361
+	/**
2362
+	 *        set_reg_event
2363
+	 *
2364
+	 * @access private
2365
+	 * @return boolean
2366
+	 */
2367
+	private function _set_reg_event()
2368
+	{
2369
+		if (is_object($this->_reg_event)) {
2370
+			return true;
2371
+		}
2372
+		$EVT_ID = ( ! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2373
+		if ( ! $EVT_ID) {
2374
+			return false;
2375
+		}
2376
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2377
+		return true;
2378
+	}
2379
+
2380
+
2381
+
2382
+	/**
2383
+	 * process_reg_step
2384
+	 *
2385
+	 * @access        public
2386
+	 * @return        string
2387
+	 * @throws \RuntimeException
2388
+	 * @throws \EE_Error
2389
+	 */
2390
+	public function process_reg_step()
2391
+	{
2392
+		EE_System::do_not_cache();
2393
+		$this->_set_reg_event();
2394
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2395
+		EE_Registry::instance()->REQ->set('uts', time());
2396
+		//what step are we on?
2397
+		$cart = EE_Registry::instance()->SSN->cart();
2398
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2399
+		//if doing ajax then we need to verify the nonce
2400
+		if (defined('DOING_AJAX')) {
2401
+			$nonce = isset($this->_req_data[$this->_req_nonce])
2402
+				? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2403
+			$this->_verify_nonce($nonce, $this->_req_nonce);
2404
+		}
2405
+		switch ($step) {
2406
+			case 'ticket' :
2407
+				//process ticket selection
2408
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
2409
+				if ($success) {
2410
+					EE_Error::add_success(esc_html__('Tickets Selected. Now complete the registration.',
2411
+						'event_espresso'));
2412
+				} else {
2413
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
2414
+				}
2415
+				if (defined('DOING_AJAX')) {
2416
+					$this->new_registration(); //display next step
2417
+				} else {
2418
+					$query_args = array(
2419
+						'action'                  => 'new_registration',
2420
+						'processing_registration' => 1,
2421
+						'event_id'                => $this->_reg_event->ID(),
2422
+						'uts'                     => time(),
2423
+					);
2424
+					$this->_redirect_after_action(false, '', '', $query_args, true);
2425
+				}
2426
+				break;
2427
+			case 'questions' :
2428
+				if ( ! isset($this->_req_data['txn_reg_status_change'], $this->_req_data['txn_reg_status_change']['send_notifications'])) {
2429
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2430
+				}
2431
+				//process registration
2432
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2433
+				if ($cart instanceof EE_Cart) {
2434
+					$grand_total = $cart->get_cart_grand_total();
2435
+					if ($grand_total instanceof EE_Line_Item) {
2436
+						$grand_total->save_this_and_descendants_to_txn();
2437
+					}
2438
+				}
2439
+				if ( ! $transaction instanceof EE_Transaction) {
2440
+					$query_args = array(
2441
+						'action'                  => 'new_registration',
2442
+						'processing_registration' => 2,
2443
+						'event_id'                => $this->_reg_event->ID(),
2444
+						'uts'                     => time(),
2445
+					);
2446
+					if (defined('DOING_AJAX')) {
2447
+						//display registration form again because there are errors (maybe validation?)
2448
+						$this->new_registration();
2449
+						return;
2450
+					} else {
2451
+						$this->_redirect_after_action(false, '', '', $query_args, true);
2452
+						return;
2453
+					}
2454
+				}
2455
+				// maybe update status, and make sure to save transaction if not done already
2456
+				if ( ! $transaction->update_status_based_on_total_paid()) {
2457
+					$transaction->save();
2458
+				}
2459
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2460
+				$this->_req_data = array();
2461
+				$query_args = array(
2462
+					'action'        => 'redirect_to_txn',
2463
+					'TXN_ID'        => $transaction->ID(),
2464
+					'EVT_ID'        => $this->_reg_event->ID(),
2465
+					'event_name'    => urlencode($this->_reg_event->name()),
2466
+					'redirect_from' => 'new_registration',
2467
+				);
2468
+				$this->_redirect_after_action(false, '', '', $query_args, true);
2469
+				break;
2470
+		}
2471
+		//what are you looking here for?  Should be nothing to do at this point.
2472
+	}
2473
+
2474
+
2475
+
2476
+	/**
2477
+	 * redirect_to_txn
2478
+	 *
2479
+	 * @access public
2480
+	 * @return void
2481
+	 */
2482
+	public function redirect_to_txn()
2483
+	{
2484
+		EE_System::do_not_cache();
2485
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2486
+		$query_args = array(
2487
+			'action' => 'view_transaction',
2488
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
2489
+			'page'   => 'espresso_transactions',
2490
+		);
2491
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
2492
+			$query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
2493
+			$query_args['event_name'] = urlencode($this->_req_data['event_name']);
2494
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
2495
+		}
2496
+		EE_Error::add_success(__('Registration Created.  Please review the transaction and add any payments as necessary',
2497
+				'event_espresso'));
2498
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2499
+	}
2500
+
2501
+
2502
+
2503
+	/**
2504
+	 *        generates HTML for the Attendee Contact List
2505
+	 *
2506
+	 * @access protected
2507
+	 * @return void
2508
+	 */
2509
+	protected function _attendee_contact_list_table()
2510
+	{
2511
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2512
+		$this->_search_btn_label = __('Contacts', 'event_espresso');
2513
+		$this->display_admin_list_table_page_with_no_sidebar();
2514
+	}
2515
+
2516
+
2517
+
2518
+	/**
2519
+	 *        get_attendees
2520
+	 *
2521
+	 * @param bool $count whether to return count or data.
2522
+	 * @access public
2523
+	 * @return array
2524
+	 */
2525
+	public function get_attendees($per_page, $count = false, $trash = false)
2526
+	{
2527
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2528
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2529
+		$ATT_MDL = EEM_Attendee::instance();
2530
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2531
+		switch ($this->_req_data['orderby']) {
2532
+			case 'ATT_ID':
2533
+				$orderby = 'ATT_ID';
2534
+				break;
2535
+			case 'ATT_fname':
2536
+				$orderby = 'ATT_fname';
2537
+				break;
2538
+			case 'ATT_email':
2539
+				$orderby = 'ATT_email';
2540
+				break;
2541
+			case 'ATT_city':
2542
+				$orderby = 'ATT_city';
2543
+				break;
2544
+			case 'STA_ID':
2545
+				$orderby = 'STA_ID';
2546
+				break;
2547
+			case 'CNT_ID':
2548
+				$orderby = 'CNT_ID';
2549
+				break;
2550
+			default:
2551
+				$orderby = 'ATT_lname';
2552
+		}
2553
+		$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
2554
+			: 'ASC';
2555
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
2556
+			? $this->_req_data['paged'] : 1;
2557
+		$per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
2558
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
2559
+			? $this->_req_data['perpage'] : $per_page;
2560
+		$_where = array();
2561
+		if ( ! empty($this->_req_data['s'])) {
2562
+			$sstr = '%' . $this->_req_data['s'] . '%';
2563
+			$_where['OR'] = array(
2564
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
2565
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
2566
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
2567
+				'ATT_fname'                         => array('LIKE', $sstr),
2568
+				'ATT_lname'                         => array('LIKE', $sstr),
2569
+				'ATT_short_bio'                     => array('LIKE', $sstr),
2570
+				'ATT_email'                         => array('LIKE', $sstr),
2571
+				'ATT_address'                       => array('LIKE', $sstr),
2572
+				'ATT_address2'                      => array('LIKE', $sstr),
2573
+				'ATT_city'                          => array('LIKE', $sstr),
2574
+				'Country.CNT_name'                  => array('LIKE', $sstr),
2575
+				'State.STA_name'                    => array('LIKE', $sstr),
2576
+				'ATT_phone'                         => array('LIKE', $sstr),
2577
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
2578
+				'Registration.REG_code'             => array('LIKE', $sstr),
2579
+				'Registration.REG_count'            => array('LIKE', $sstr),
2580
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
2581
+			);
2582
+		}
2583
+		$offset = ($current_page - 1) * $per_page;
2584
+		$limit = $count ? null : array($offset, $per_page);
2585
+		if ($trash) {
2586
+			$_where['status'] = array('!=', 'publish');
2587
+			$all_attendees = $count
2588
+				? $ATT_MDL->count(array(
2589
+					$_where,
2590
+					'order_by' => array($orderby => $sort),
2591
+					'limit'    => $limit,
2592
+				), 'ATT_ID', true)
2593
+				: $ATT_MDL->get_all(array(
2594
+					$_where,
2595
+					'order_by' => array($orderby => $sort),
2596
+					'limit'    => $limit,
2597
+				));
2598
+		} else {
2599
+			$_where['status'] = array('IN', array('publish'));
2600
+			$all_attendees = $count
2601
+				? $ATT_MDL->count(array(
2602
+					$_where,
2603
+					'order_by' => array($orderby => $sort),
2604
+					'limit'    => $limit,
2605
+				), 'ATT_ID', true)
2606
+				: $ATT_MDL->get_all(array(
2607
+					$_where,
2608
+					'order_by' => array($orderby => $sort),
2609
+					'limit'    => $limit,
2610
+				));
2611
+		}
2612
+		return $all_attendees;
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * This is just taking care of resending the registration confirmation
2619
+	 *
2620
+	 * @access protected
2621
+	 * @return void
2622
+	 */
2623
+	protected function _resend_registration()
2624
+	{
2625
+		$this->_process_resend_registration();
2626
+		$query_args = isset($this->_req_data['redirect_to'])
2627
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
2628
+			: array(
2629
+				'action' => 'default',
2630
+			);
2631
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2632
+	}
2633
+
2634
+
2635
+
2636
+	public function _registrations_report()
2637
+	{
2638
+		if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2639
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2640
+				'page'        => 'espresso_batch',
2641
+				'batch'       => 'file',
2642
+				'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2643
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
2644
+				'return_url'  => urlencode($this->_req_data['return_url']),
2645
+			)));
2646
+		} else {
2647
+			$new_request_args = array(
2648
+				'export' => 'report',
2649
+				'action' => 'registrations_report_for_event',
2650
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2651
+			);
2652
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
2653
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2654
+				require_once(EE_CLASSES . 'EE_Export.class.php');
2655
+				$EE_Export = EE_Export::instance($this->_req_data);
2656
+				$EE_Export->export();
2657
+			}
2658
+		}
2659
+	}
2660
+
2661
+
2662
+
2663
+	public function _contact_list_export()
2664
+	{
2665
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2666
+			require_once(EE_CLASSES . 'EE_Export.class.php');
2667
+			$EE_Export = EE_Export::instance($this->_req_data);
2668
+			$EE_Export->export_attendees();
2669
+		}
2670
+	}
2671
+
2672
+
2673
+
2674
+	public function _contact_list_report()
2675
+	{
2676
+		if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2677
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2678
+				'page'        => 'espresso_batch',
2679
+				'batch'       => 'file',
2680
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
2681
+				'return_url'  => urlencode($this->_req_data['return_url']),
2682
+			)));
2683
+		} else {
2684
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2685
+				require_once(EE_CLASSES . 'EE_Export.class.php');
2686
+				$EE_Export = EE_Export::instance($this->_req_data);
2687
+				$EE_Export->report_attendees();
2688
+			}
2689
+		}
2690
+	}
2691
+
2692
+
2693
+
2694
+
2695
+
2696
+	/***************************************        ATTENDEE DETAILS        ***************************************/
2697
+	/**
2698
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
2699
+	 *
2700
+	 * @return void
2701
+	 */
2702
+	protected function _duplicate_attendee()
2703
+	{
2704
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
2705
+		//verify we have necessary info
2706
+		if (empty($this->_req_data['_REG_ID'])) {
2707
+			EE_Error::add_error(__('Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
2708
+				'event_espresso'), __FILE__, __LINE__, __FUNCTION__);
2709
+			$query_args = array('action' => $action);
2710
+			$this->_redirect_after_action('', '', '', $query_args, true);
2711
+		}
2712
+		//okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
2713
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
2714
+		$attendee = $registration->attendee();
2715
+		//remove relation of existing attendee on registration
2716
+		$registration->_remove_relation_to($attendee, 'Attendee');
2717
+		//new attendee
2718
+		$new_attendee = clone $attendee;
2719
+		$new_attendee->set('ATT_ID', 0);
2720
+		$new_attendee->save();
2721
+		//add new attendee to reg
2722
+		$registration->_add_relation_to($new_attendee, 'Attendee');
2723
+		EE_Error::add_success(__('New Contact record created.  Now make any edits you wish to make for this contact.',
2724
+			'event_espresso'));
2725
+		//redirect to edit page for attendee
2726
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
2727
+		$this->_redirect_after_action('', '', '', $query_args, true);
2728
+	}
2729
+
2730
+
2731
+
2732
+	//related to cpt routes
2733
+	protected function _insert_update_cpt_item($post_id, $post)
2734
+	{
2735
+		$success = true;
2736
+		$attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
2737
+		//for attendee updates
2738
+		if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
2739
+			//note we should only be UPDATING attendees at this point.
2740
+			$updated_fields = array(
2741
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
2742
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
2743
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
2744
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
2745
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
2746
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
2747
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
2748
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
2749
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
2750
+				'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
2751
+				'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
2752
+			);
2753
+			foreach ($updated_fields as $field => $value) {
2754
+				$attendee->set($field, $value);
2755
+			}
2756
+			$success = $attendee->save();
2757
+			$attendee_update_callbacks = apply_filters('FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
2758
+				array());
2759
+			foreach ($attendee_update_callbacks as $a_callback) {
2760
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
2761
+					throw new EE_Error(sprintf(__('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.',
2762
+						'event_espresso'), $a_callback));
2763
+				}
2764
+			}
2765
+		}
2766
+		if ($success === false) {
2767
+			EE_Error::add_error(__('Something went wrong with updating the meta table data for the registration.',
2768
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2769
+		}
2770
+	}
2771
+
2772
+
2773
+
2774
+	public function trash_cpt_item($post_id)
2775
+	{
2776
+	}
2777
+
2778
+
2779
+
2780
+	public function delete_cpt_item($post_id)
2781
+	{
2782
+	}
2783
+
2784
+
2785
+
2786
+	public function restore_cpt_item($post_id)
2787
+	{
2788
+	}
2789
+
2790
+
2791
+
2792
+	protected function _restore_cpt_item($post_id, $revision_id)
2793
+	{
2794
+	}
2795
+
2796
+
2797
+
2798
+	public function attendee_editor_metaboxes()
2799
+	{
2800
+		$this->verify_cpt_object();
2801
+		remove_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', $this->_cpt_routes[$this->_req_action],
2802
+			'normal', 'core');
2803
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2804
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
2805
+			add_meta_box('postexcerpt', __('Short Biography', 'event_espresso'), 'post_excerpt_meta_box',
2806
+				$this->_cpt_routes[$this->_req_action], 'normal');
2807
+		}
2808
+		if (post_type_supports('espresso_attendees', 'comments')) {
2809
+			add_meta_box('commentsdiv', __('Notes on the Contact', 'event_espresso'), 'post_comment_meta_box',
2810
+				$this->_cpt_routes[$this->_req_action], 'normal', 'core');
2811
+		}
2812
+		add_meta_box('attendee_contact_info', __('Contact Info', 'event_espresso'),
2813
+			array($this, 'attendee_contact_info'), $this->_cpt_routes[$this->_req_action], 'side', 'core');
2814
+		add_meta_box('attendee_details_address', __('Address Details', 'event_espresso'),
2815
+			array($this, 'attendee_address_details'), $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2816
+		add_meta_box('attendee_registrations', __('Registrations for this Contact', 'event_espresso'),
2817
+			array($this, 'attendee_registrations_meta_box'), $this->_cpt_routes[$this->_req_action], 'normal', 'high');
2818
+	}
2819
+
2820
+
2821
+
2822
+	/**
2823
+	 * Metabox for attendee contact info
2824
+	 *
2825
+	 * @param  WP_Post $post wp post object
2826
+	 * @return string        attendee contact info ( and form )
2827
+	 */
2828
+	public function attendee_contact_info($post)
2829
+	{
2830
+		//get attendee object ( should already have it )
2831
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
2832
+		$template = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
2833
+		EEH_Template::display_template($template, $this->_template_args);
2834
+	}
2835
+
2836
+
2837
+
2838
+	/**
2839
+	 * Metabox for attendee details
2840
+	 *
2841
+	 * @param  WP_Post $post wp post object
2842
+	 * @return string        attendee address details (and form)
2843
+	 */
2844
+	public function attendee_address_details($post)
2845
+	{
2846
+		//get attendee object (should already have it)
2847
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
2848
+		$this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2849
+			'QST_ID'           => 0,
2850
+			'QST_display_text' => __('State/Province', 'event_espresso'),
2851
+			'QST_system'       => 'admin-state',
2852
+		)), EE_Answer::new_instance(array(
2853
+			'ANS_ID'    => 0,
2854
+			'ANS_value' => $this->_cpt_model_obj->state_ID(),
2855
+		)), array(
2856
+				'input_id'       => 'STA_ID',
2857
+				'input_name'     => 'STA_ID',
2858
+				'input_prefix'   => '',
2859
+				'append_qstn_id' => false,
2860
+			)));
2861
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2862
+			'QST_ID'           => 0,
2863
+			'QST_display_text' => __('Country', 'event_espresso'),
2864
+			'QST_system'       => 'admin-country',
2865
+		)), EE_Answer::new_instance(array(
2866
+			'ANS_ID'    => 0,
2867
+			'ANS_value' => $this->_cpt_model_obj->country_ID(),
2868
+		)), array(
2869
+				'input_id'       => 'CNT_ISO',
2870
+				'input_name'     => 'CNT_ISO',
2871
+				'input_prefix'   => '',
2872
+				'append_qstn_id' => false,
2873
+			)));
2874
+		$template = REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
2875
+		EEH_Template::display_template($template, $this->_template_args);
2876
+	}
2877
+
2878
+
2879
+
2880
+	/**
2881
+	 *        _attendee_details
2882
+	 *
2883
+	 * @access protected
2884
+	 * @return void
2885
+	 */
2886
+	public function attendee_registrations_meta_box($post)
2887
+	{
2888
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
2889
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
2890
+		$template = REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
2891
+		EEH_Template::display_template($template, $this->_template_args);
2892
+	}
2893
+
2894
+
2895
+
2896
+	/**
2897
+	 * add in the form fields for the attendee edit
2898
+	 *
2899
+	 * @param  WP_Post $post wp post object
2900
+	 * @return string        html for new form.
2901
+	 */
2902
+	public function after_title_form_fields($post)
2903
+	{
2904
+		if ($post->post_type == 'espresso_attendees') {
2905
+			$template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
2906
+			$template_args['attendee'] = $this->_cpt_model_obj;
2907
+			EEH_Template::display_template($template, $template_args);
2908
+		}
2909
+	}
2910
+
2911
+
2912
+
2913
+	/**
2914
+	 *        _trash_or_restore_attendee
2915
+	 *
2916
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
2917
+	 * @access protected
2918
+	 * @return void
2919
+	 */
2920
+	protected function _trash_or_restore_attendees($trash = true)
2921
+	{
2922
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2923
+		$ATT_MDL = EEM_Attendee::instance();
2924
+		$success = 1;
2925
+		//Checkboxes
2926
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2927
+			// if array has more than one element than success message should be plural
2928
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2929
+			// cycle thru checkboxes
2930
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
2931
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
2932
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
2933
+				if ( ! $updated) {
2934
+					$success = 0;
2935
+				}
2936
+			}
2937
+		} else {
2938
+			// grab single id and delete
2939
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
2940
+			//get attendee
2941
+			$att = $ATT_MDL->get_one_by_ID($ATT_ID);
2942
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
2943
+			$updated = $att->save();
2944
+			if ( ! $updated) {
2945
+				$success = 0;
2946
+			}
2947
+		}
2948
+		$what = $success > 1 ? __('Contacts', 'event_espresso') : __('Contact', 'event_espresso');
2949
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2950
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
2951
+	}
2952 2952
 
2953 2953
 }
2954 2954
 
Please login to merge, or discard this patch.
admin_pages/venues/Venues_Admin_Page.core.php 1 patch
Spacing   +241 added lines, -241 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (!defined('EVENT_ESPRESSO_VERSION') )
2
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
3 3
 	exit('NO direct script access allowed');
4 4
 
5 5
 /**
@@ -62,10 +62,10 @@  discard block
 block discarded – undo
62 62
 
63 63
 
64 64
 	protected function _init_page_props() {
65
-		require_once( EE_MODELS . 'EEM_Venue.model.php' );
65
+		require_once(EE_MODELS.'EEM_Venue.model.php');
66 66
 		$this->page_slug = EE_VENUES_PG_SLUG;
67 67
 		$this->_admin_base_url = EE_VENUES_ADMIN_URL;
68
-		$this->_admin_base_path = EE_ADMIN_PAGES . 'venues';
68
+		$this->_admin_base_path = EE_ADMIN_PAGES.'venues';
69 69
 		$this->page_label = __('Event Venues', 'event_espresso');
70 70
 		$this->_cpt_model_names = array(
71 71
 			'create_new' => 'EEM_Venue',
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 				'edit' => __('Update Venue', 'event_espresso'),
109 109
 				'add_category' => __('Save New Category', 'event_espresso'),
110 110
 				'edit_category' => __('Update Category', 'event_espresso'),
111
-				'google_map_settings' => __( 'Update Settings', 'event_espresso' )
111
+				'google_map_settings' => __('Update Settings', 'event_espresso')
112 112
 				)
113 113
 		);
114 114
 	}
@@ -123,8 +123,8 @@  discard block
 block discarded – undo
123 123
 		//load field generator helper
124 124
 
125 125
 		//is there a vnu_id in the request?
126
-		$vnu_id = ! empty( $this->_req_data['VNU_ID'] ) && ! is_array( $this->_req_data['VNU_ID'] ) ? $this->_req_data['VNU_ID'] : 0;
127
-		$vnu_id = ! empty( $this->_req_data['post'] ) ? $this->_req_data['post'] : $vnu_id;
126
+		$vnu_id = ! empty($this->_req_data['VNU_ID']) && ! is_array($this->_req_data['VNU_ID']) ? $this->_req_data['VNU_ID'] : 0;
127
+		$vnu_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $vnu_id;
128 128
 
129 129
 		$this->_page_routes = array(
130 130
 			'default' => array(
@@ -142,27 +142,27 @@  discard block
 block discarded – undo
142 142
 				),
143 143
 			'trash_venue' => array(
144 144
 				'func' => '_trash_or_restore_venue',
145
-				'args' => array( 'venue_status' => 'trash' ),
145
+				'args' => array('venue_status' => 'trash'),
146 146
 				'noheader' => TRUE,
147 147
 				'capability' => 'ee_delete_venue',
148 148
 				'obj_id' => $vnu_id
149 149
 				),
150 150
 			'trash_venues' => array(
151 151
 				'func' => '_trash_or_restore_venues',
152
-				'args' => array( 'venue_status' => 'trash' ),
152
+				'args' => array('venue_status' => 'trash'),
153 153
 				'noheader' => TRUE,
154 154
 				'capability' => 'ee_delete_venues'
155 155
 				),
156 156
 			'restore_venue' => array(
157 157
 				'func' => '_trash_or_restore_venue',
158
-				'args' => array( 'venue_status' => 'draft' ),
158
+				'args' => array('venue_status' => 'draft'),
159 159
 				'noheader' => TRUE,
160 160
 				'capability' => 'ee_delete_venue',
161 161
 				'obj_id' => $vnu_id
162 162
 				),
163 163
 			'restore_venues' => array(
164 164
 				'func' => '_trash_or_restore_venues',
165
-				'args' => array( 'venue_status' => 'draft' ),
165
+				'args' => array('venue_status' => 'draft'),
166 166
 				'noheader' => TRUE,
167 167
 				'capability' => 'ee_delete_venues'
168 168
 				),
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 						'filename' => 'venues_overview_views_bulk_actions_search'
265 265
 					)
266 266
 				),
267
-				'help_tour' => array( 'Venues_Overview_Help_Tour' ),
267
+				'help_tour' => array('Venues_Overview_Help_Tour'),
268 268
 				'metaboxes' => array('_espresso_news_post_box', '_espresso_links_post_box'),
269 269
 				'require_nonce' => FALSE
270 270
 			),
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 						'filename' => 'venues_editor_other'
301 301
 					)
302 302
 				),
303
-				'help_tour' => array( 'Venues_Add_Venue_Help_Tour' ),
303
+				'help_tour' => array('Venues_Add_Venue_Help_Tour'),
304 304
 				'metaboxes' => array('_venue_editor_metaboxes'),
305 305
 				'require_nonce' => FALSE
306 306
 				),
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 					'label' => __('Edit Venue', 'event_espresso'),
310 310
 					'order' => 5,
311 311
 					'persistent' => FALSE,
312
-					'url' => isset($this->_req_data['post']) ? add_query_arg(array('post' => $this->_req_data['post'] ), $this->_current_page_view_url )  : $this->_admin_base_url
312
+					'url' => isset($this->_req_data['post']) ? add_query_arg(array('post' => $this->_req_data['post']), $this->_current_page_view_url) : $this->_admin_base_url
313 313
 				),
314 314
 				'help_tabs' => array(
315 315
 					'venues_editor_help_tab' => array(
@@ -343,17 +343,17 @@  discard block
 block discarded – undo
343 343
 			),
344 344
 			'google_map_settings' => array(
345 345
 				'nav' => array(
346
-					'label' => esc_html__('Google Maps', 'event_espresso' ),
346
+					'label' => esc_html__('Google Maps', 'event_espresso'),
347 347
 					'order' => 40
348 348
 				),
349
-				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array('_publish_post_box' ) ),
349
+				'metaboxes' => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
350 350
 				'help_tabs' => array(
351 351
 					'general_settings_google_maps_help_tab' => array(
352 352
 						'title' => __('Google Maps', 'event_espresso'),
353 353
 						'filename' => 'general_settings_google_maps'
354 354
 					)
355 355
 				),
356
-				'help_tour' => array( 'Google_Maps_Help_Tour' ),
356
+				'help_tour' => array('Google_Maps_Help_Tour'),
357 357
 				'require_nonce' => FALSE
358 358
 			),
359 359
 			//venue category stuff
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 						'filename' => 'venues_add_category'
370 370
 					)
371 371
 				),
372
-				'help_tour' => array( 'Venues_Add_Category_Help_Tour' ),
372
+				'help_tour' => array('Venues_Add_Category_Help_Tour'),
373 373
 				'require_nonce' => FALSE
374 374
 				),
375 375
 			'edit_category' => array(
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 					'label' => __('Edit Category', 'event_espresso'),
378 378
 					'order' => 15,
379 379
 					'persistent' => FALSE,
380
-					'url' => isset($this->_req_data['EVT_CAT_ID']) ? add_query_arg(array('EVT_CAT_ID' => $this->_req_data['EVT_CAT_ID'] ), $this->_current_page_view_url )  : $this->_admin_base_url
380
+					'url' => isset($this->_req_data['EVT_CAT_ID']) ? add_query_arg(array('EVT_CAT_ID' => $this->_req_data['EVT_CAT_ID']), $this->_current_page_view_url) : $this->_admin_base_url
381 381
 					),
382 382
 				'metaboxes' => array('_publish_post_box'),
383 383
 				'help_tabs' => array(
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 						'filename' => 'venues_categories_other'
414 414
 					)
415 415
 				),
416
-				'help_tour' => array( 'Venues_Categories_Help_Tour' ),
416
+				'help_tour' => array('Venues_Categories_Help_Tour'),
417 417
 				'metaboxes' => $this->_default_espresso_metaboxes,
418 418
 				'require_nonce' => FALSE
419 419
 				)
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 
471 471
 
472 472
 	public function load_scripts_styles() {
473
-		wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', array(), EVENT_ESPRESSO_VERSION );
473
+		wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL.'ee-cat-admin.css', array(), EVENT_ESPRESSO_VERSION);
474 474
 		wp_enqueue_style('ee-cat-admin');
475 475
 	}
476 476
 
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 	public function load_scripts_styles_edit() {
494 494
 		//styles
495 495
 		wp_enqueue_style('espresso-ui-theme');
496
-		wp_register_style( 'espresso_venues', EE_VENUES_ASSETS_URL . 'ee-venues-admin.css', array(), EVENT_ESPRESSO_VERSION );
496
+		wp_register_style('espresso_venues', EE_VENUES_ASSETS_URL.'ee-venues-admin.css', array(), EVENT_ESPRESSO_VERSION);
497 497
 		wp_enqueue_style('espresso_venues');
498 498
 	}
499 499
 
@@ -512,13 +512,13 @@  discard block
 block discarded – undo
512 512
 				)
513 513
 		);
514 514
 
515
-		if ( EE_Registry::instance()->CAP->current_user_can( 'ee_delete_venues', 'espresso_venues_trash_venues' ) ) {
515
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_venues', 'espresso_venues_trash_venues')) {
516 516
 			$this->_views['all']['bulk_action'] = array(
517 517
 				'trash_venues' => __('Move to Trash', 'event_espresso')
518 518
 			);
519 519
 			$this->_views['trash'] = array(
520 520
 				'slug' => 'trash',
521
-				'label' => __( 'Trash', 'event_espresso' ),
521
+				'label' => __('Trash', 'event_espresso'),
522 522
 				'count' => 0,
523 523
 				'bulk_action' => array(
524 524
 					'restore_venues' => __('Restore from Trash', 'event_espresso'),
@@ -551,9 +551,9 @@  discard block
 block discarded – undo
551 551
 
552 552
 
553 553
 	protected function _overview_list_table() {
554
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
555
-		$this->_template_args['after_list_table'] = EEH_Template::get_button_or_link( get_post_type_archive_link('espresso_venues'), __("View Venue Archive Page", "event_espresso"), 'button' );
556
-		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button('create_new', 'add', array(), 'add-new-h2');
554
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
555
+		$this->_template_args['after_list_table'] = EEH_Template::get_button_or_link(get_post_type_archive_link('espresso_venues'), __("View Venue Archive Page", "event_espresso"), 'button');
556
+		$this->_admin_page_title .= ' '.$this->get_action_link_or_button('create_new', 'add', array(), 'add-new-h2');
557 557
 		$this->_search_btn_label = __('Venues', 'event_espresso');
558 558
 		$this->display_admin_list_table_page_with_sidebar();
559 559
 	}
@@ -566,8 +566,8 @@  discard block
 block discarded – undo
566 566
 			'vnu_url' => $this->_cpt_model_obj->venue_url(),
567 567
 			'vnu_phone' => $this->_cpt_model_obj->phone()
568 568
 			);
569
-		$template = EE_VENUES_TEMPLATE_PATH . 'venue_publish_box_extras.template.php';
570
-		EEH_Template::display_template( $template, $extra_rows );
569
+		$template = EE_VENUES_TEMPLATE_PATH.'venue_publish_box_extras.template.php';
570
+		EEH_Template::display_template($template, $extra_rows);
571 571
 	}
572 572
 
573 573
 
@@ -583,31 +583,31 @@  discard block
 block discarded – undo
583 583
 		$default_map_settings->use_google_maps = TRUE;
584 584
 		$default_map_settings->google_map_api_key = '';
585 585
 		// for event details pages (reg page)
586
-		$default_map_settings->event_details_map_width = 585; 			// ee_map_width_single
587
-		$default_map_settings->event_details_map_height = 362; 			// ee_map_height_single
588
-		$default_map_settings->event_details_map_zoom = 14; 			// ee_map_zoom_single
589
-		$default_map_settings->event_details_display_nav = TRUE; 			// ee_map_nav_display_single
590
-		$default_map_settings->event_details_nav_size = FALSE; 			// ee_map_nav_size_single
591
-		$default_map_settings->event_details_control_type = 'default'; 		// ee_map_type_control_single
592
-		$default_map_settings->event_details_map_align = 'center'; 			// ee_map_align_single
586
+		$default_map_settings->event_details_map_width = 585; // ee_map_width_single
587
+		$default_map_settings->event_details_map_height = 362; // ee_map_height_single
588
+		$default_map_settings->event_details_map_zoom = 14; // ee_map_zoom_single
589
+		$default_map_settings->event_details_display_nav = TRUE; // ee_map_nav_display_single
590
+		$default_map_settings->event_details_nav_size = FALSE; // ee_map_nav_size_single
591
+		$default_map_settings->event_details_control_type = 'default'; // ee_map_type_control_single
592
+		$default_map_settings->event_details_map_align = 'center'; // ee_map_align_single
593 593
 		// for event list pages
594
-		$default_map_settings->event_list_map_width = 300; 			// ee_map_width
595
-		$default_map_settings->event_list_map_height = 185; 		// ee_map_height
596
-		$default_map_settings->event_list_map_zoom = 12; 			// ee_map_zoom
597
-		$default_map_settings->event_list_display_nav = FALSE; 		// ee_map_nav_display
598
-		$default_map_settings->event_list_nav_size = TRUE; 			// ee_map_nav_size
599
-		$default_map_settings->event_list_control_type = 'dropdown'; 		// ee_map_type_control
600
-		$default_map_settings->event_list_map_align = 'center'; 			// ee_map_align
594
+		$default_map_settings->event_list_map_width = 300; // ee_map_width
595
+		$default_map_settings->event_list_map_height = 185; // ee_map_height
596
+		$default_map_settings->event_list_map_zoom = 12; // ee_map_zoom
597
+		$default_map_settings->event_list_display_nav = FALSE; // ee_map_nav_display
598
+		$default_map_settings->event_list_nav_size = TRUE; // ee_map_nav_size
599
+		$default_map_settings->event_list_control_type = 'dropdown'; // ee_map_type_control
600
+		$default_map_settings->event_list_map_align = 'center'; // ee_map_align
601 601
 
602 602
 		$this->_template_args['map_settings'] =
603
-			isset( EE_Registry::instance()->CFG->map_settings ) && ! empty( EE_Registry::instance()->CFG->map_settings )
604
-				? (object)array_merge( (array)$default_map_settings, (array)EE_Registry::instance()->CFG->map_settings )
603
+			isset(EE_Registry::instance()->CFG->map_settings) && ! empty(EE_Registry::instance()->CFG->map_settings)
604
+				? (object) array_merge((array) $default_map_settings, (array) EE_Registry::instance()->CFG->map_settings)
605 605
 				: $default_map_settings;
606 606
 
607
-		$this->_set_add_edit_form_tags( 'update_google_map_settings' );
608
-		$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
607
+		$this->_set_add_edit_form_tags('update_google_map_settings');
608
+		$this->_set_publish_post_box_vars(NULL, FALSE, FALSE, NULL, FALSE);
609 609
 		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
610
-			EE_VENUES_TEMPLATE_PATH . 'google_map.template.php',
610
+			EE_VENUES_TEMPLATE_PATH.'google_map.template.php',
611 611
 			$this->_template_args,
612 612
 			true
613 613
 		);
@@ -617,83 +617,83 @@  discard block
 block discarded – undo
617 617
 	protected function _update_google_map_settings() {
618 618
 
619 619
 		EE_Registry::instance()->CFG->map_settings->use_google_maps =
620
-			isset( $this->_req_data['use_google_maps'] )
621
-				? absint( $this->_req_data['use_google_maps'] )
620
+			isset($this->_req_data['use_google_maps'])
621
+				? absint($this->_req_data['use_google_maps'])
622 622
 				: EE_Registry::instance()->CFG->map_settings->use_google_maps;
623 623
 
624 624
 		EE_Registry::instance()->CFG->map_settings->google_map_api_key =
625
-			isset( $this->_req_data['google_map_api_key'] )
626
-				? sanitize_text_field( $this->_req_data['google_map_api_key'] )
625
+			isset($this->_req_data['google_map_api_key'])
626
+				? sanitize_text_field($this->_req_data['google_map_api_key'])
627 627
 				: EE_Registry::instance()->CFG->map_settings->google_map_api_key;
628 628
 
629 629
 		EE_Registry::instance()->CFG->map_settings->event_details_map_width =
630
-			isset( $this->_req_data['event_details_map_width'] )
631
-				? absint( $this->_req_data['event_details_map_width'] )
630
+			isset($this->_req_data['event_details_map_width'])
631
+				? absint($this->_req_data['event_details_map_width'])
632 632
 				: EE_Registry::instance()->CFG->map_settings->event_details_map_width;
633 633
 
634 634
 		EE_Registry::instance()->CFG->map_settings->event_details_map_height =
635
-			isset( $this->_req_data['event_details_map_height'] )
636
-				? absint( $this->_req_data['event_details_map_height'] )
635
+			isset($this->_req_data['event_details_map_height'])
636
+				? absint($this->_req_data['event_details_map_height'])
637 637
 				: EE_Registry::instance()->CFG->map_settings->event_details_map_height;
638 638
 
639 639
 		EE_Registry::instance()->CFG->map_settings->event_details_map_zoom =
640
-			isset( $this->_req_data['event_details_map_zoom'] )
641
-				? absint( $this->_req_data['event_details_map_zoom'] )
640
+			isset($this->_req_data['event_details_map_zoom'])
641
+				? absint($this->_req_data['event_details_map_zoom'])
642 642
 				: EE_Registry::instance()->CFG->map_settings->event_details_map_zoom;
643 643
 
644 644
 		EE_Registry::instance()->CFG->map_settings->event_details_display_nav =
645
-			isset( $this->_req_data['event_details_display_nav'] )
646
-				? absint( $this->_req_data['event_details_display_nav'] )
645
+			isset($this->_req_data['event_details_display_nav'])
646
+				? absint($this->_req_data['event_details_display_nav'])
647 647
 				: EE_Registry::instance()->CFG->map_settings->event_details_display_nav;
648 648
 
649 649
 		EE_Registry::instance()->CFG->map_settings->event_details_nav_size =
650
-			isset( $this->_req_data['event_details_nav_size'] )
651
-				? absint( $this->_req_data['event_details_nav_size'] )
650
+			isset($this->_req_data['event_details_nav_size'])
651
+				? absint($this->_req_data['event_details_nav_size'])
652 652
 				: EE_Registry::instance()->CFG->map_settings->event_details_nav_size;
653 653
 
654 654
 		EE_Registry::instance()->CFG->map_settings->event_details_control_type =
655
-			isset( $this->_req_data['event_details_control_type'] )
656
-				? sanitize_text_field( $this->_req_data['event_details_control_type'] )
655
+			isset($this->_req_data['event_details_control_type'])
656
+				? sanitize_text_field($this->_req_data['event_details_control_type'])
657 657
 				: EE_Registry::instance()->CFG->map_settings->event_details_control_type;
658 658
 
659 659
 		EE_Registry::instance()->CFG->map_settings->event_details_map_align =
660
-			isset( $this->_req_data['event_details_map_align'] )
661
-				? sanitize_text_field( $this->_req_data['event_details_map_align'] )
660
+			isset($this->_req_data['event_details_map_align'])
661
+				? sanitize_text_field($this->_req_data['event_details_map_align'])
662 662
 				: EE_Registry::instance()->CFG->map_settings->event_details_map_align;
663 663
 
664 664
 		EE_Registry::instance()->CFG->map_settings->event_list_map_width =
665
-			isset( $this->_req_data['event_list_map_width'] )
666
-				? absint( $this->_req_data['event_list_map_width'] )
665
+			isset($this->_req_data['event_list_map_width'])
666
+				? absint($this->_req_data['event_list_map_width'])
667 667
 				: EE_Registry::instance()->CFG->map_settings->event_list_map_width;
668 668
 
669 669
 		EE_Registry::instance()->CFG->map_settings->event_list_map_height =
670
-			isset( $this->_req_data['event_list_map_height'] )
671
-				? absint( $this->_req_data['event_list_map_height'] )
670
+			isset($this->_req_data['event_list_map_height'])
671
+				? absint($this->_req_data['event_list_map_height'])
672 672
 				: EE_Registry::instance()->CFG->map_settings->event_list_map_height;
673 673
 
674 674
 		EE_Registry::instance()->CFG->map_settings->event_list_map_zoom =
675
-			isset( $this->_req_data['event_list_map_zoom'] )
676
-				? absint( $this->_req_data['event_list_map_zoom'] )
675
+			isset($this->_req_data['event_list_map_zoom'])
676
+				? absint($this->_req_data['event_list_map_zoom'])
677 677
 				: EE_Registry::instance()->CFG->map_settings->event_list_map_zoom;
678 678
 
679 679
 		EE_Registry::instance()->CFG->map_settings->event_list_display_nav =
680
-			isset( $this->_req_data['event_list_display_nav'] )
681
-				? absint( $this->_req_data['event_list_display_nav'] )
680
+			isset($this->_req_data['event_list_display_nav'])
681
+				? absint($this->_req_data['event_list_display_nav'])
682 682
 				: EE_Registry::instance()->CFG->map_settings->event_list_display_nav;
683 683
 
684 684
 		EE_Registry::instance()->CFG->map_settings->event_list_nav_size =
685
-			isset( $this->_req_data['event_list_nav_size'] )
686
-				? absint( $this->_req_data['event_list_nav_size'] )
685
+			isset($this->_req_data['event_list_nav_size'])
686
+				? absint($this->_req_data['event_list_nav_size'])
687 687
 				: EE_Registry::instance()->CFG->map_settings->event_list_nav_size;
688 688
 
689 689
 		EE_Registry::instance()->CFG->map_settings->event_list_control_type =
690
-			isset( $this->_req_data['event_list_control_type'] )
691
-				? sanitize_text_field( $this->_req_data['event_list_control_type'] )
690
+			isset($this->_req_data['event_list_control_type'])
691
+				? sanitize_text_field($this->_req_data['event_list_control_type'])
692 692
 				: EE_Registry::instance()->CFG->map_settings->event_list_control_type;
693 693
 
694 694
 		EE_Registry::instance()->CFG->map_settings->event_list_map_align =
695
-			isset( $this->_req_data['event_list_map_align'] )
696
-				? sanitize_text_field( $this->_req_data['event_list_map_align'] )
695
+			isset($this->_req_data['event_list_map_align'])
696
+				? sanitize_text_field($this->_req_data['event_list_map_align'])
697 697
 				: EE_Registry::instance()->CFG->map_settings->event_list_map_align;
698 698
 
699 699
 		EE_Registry::instance()->CFG->map_settings = apply_filters(
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 			EE_Registry::instance()->CFG->map_settings,
708 708
 			__FILE__, __FUNCTION__, __LINE__
709 709
 		);
710
-		$this->_redirect_after_action( $success, $what, 'updated', array( 'action' => 'google_map_settings' ) );
710
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'google_map_settings'));
711 711
 
712 712
 	}
713 713
 
@@ -716,9 +716,9 @@  discard block
 block discarded – undo
716 716
 	protected function _venue_editor_metaboxes() {
717 717
 		$this->verify_cpt_object();
718 718
 
719
-		add_meta_box( 'espresso_venue_address_options', __('Physical Location', 'event_espresso'), array( $this, 'venue_address_metabox'), $this->page_slug, 'side', 'default' );
720
-		add_meta_box( 'espresso_venue_gmap_options', __('Google Map', 'event_espresso'), array( $this, 'venue_gmap_metabox'), $this->page_slug, 'side', 'default' );
721
-		add_meta_box( 'espresso_venue_virtual_loc_options', __('Virtual Location', 'event_espresso'), array( $this, 'venue_virtual_loc_metabox'), $this->page_slug, 'side', 'default' );
719
+		add_meta_box('espresso_venue_address_options', __('Physical Location', 'event_espresso'), array($this, 'venue_address_metabox'), $this->page_slug, 'side', 'default');
720
+		add_meta_box('espresso_venue_gmap_options', __('Google Map', 'event_espresso'), array($this, 'venue_gmap_metabox'), $this->page_slug, 'side', 'default');
721
+		add_meta_box('espresso_venue_virtual_loc_options', __('Virtual Location', 'event_espresso'), array($this, 'venue_virtual_loc_metabox'), $this->page_slug, 'side', 'default');
722 722
 
723 723
 	}
724 724
 
@@ -726,23 +726,23 @@  discard block
 block discarded – undo
726 726
 
727 727
 	public function venue_gmap_metabox() {
728 728
 		$template_args = array(
729
-			'vnu_enable_for_gmap' => EEH_Form_Fields::select_input('vnu_enable_for_gmap', $this->get_yes_no_values(), $this->_cpt_model_obj->enable_for_gmap() ),
729
+			'vnu_enable_for_gmap' => EEH_Form_Fields::select_input('vnu_enable_for_gmap', $this->get_yes_no_values(), $this->_cpt_model_obj->enable_for_gmap()),
730 730
 			'vnu_google_map_link' => $this->_cpt_model_obj->google_map_link(),
731 731
 			);
732
-		$template = EE_VENUES_TEMPLATE_PATH . 'venue_gmap_metabox_content.template.php';
733
-		EEH_Template::display_template( $template, $template_args );
732
+		$template = EE_VENUES_TEMPLATE_PATH.'venue_gmap_metabox_content.template.php';
733
+		EEH_Template::display_template($template, $template_args);
734 734
 	}
735 735
 
736 736
 
737 737
 
738 738
 	public function venue_address_metabox() {
739 739
 
740
-		$template_args['_venue'] =$this->_cpt_model_obj;
740
+		$template_args['_venue'] = $this->_cpt_model_obj;
741 741
 
742 742
 		$template_args['states_dropdown'] = EEH_Form_Fields::generate_form_input(
743 743
 			$QFI = new EE_Question_Form_Input(
744
-				EE_Question::new_instance( array( 'QST_display_text' => esc_html__( 'State', 'event_espresso' ), 'QST_system' => 'state' )),
745
-				EE_Answer::new_instance( array(  'ANS_value'=> $this->_cpt_model_obj->state_ID() )),
744
+				EE_Question::new_instance(array('QST_display_text' => esc_html__('State', 'event_espresso'), 'QST_system' => 'state')),
745
+				EE_Answer::new_instance(array('ANS_value'=> $this->_cpt_model_obj->state_ID())),
746 746
 				array(
747 747
 					'input_name' =>  'sta_id',
748 748
 					'input_id' => 'sta_id',
@@ -754,8 +754,8 @@  discard block
 block discarded – undo
754 754
 		);
755 755
 		$template_args['countries_dropdown'] = EEH_Form_Fields::generate_form_input(
756 756
 			$QFI = new EE_Question_Form_Input(
757
-				EE_Question::new_instance( array( 'QST_display_text' => esc_html__( 'Country', 'event_espresso' ), 'QST_system' => 'country' )),
758
-				EE_Answer::new_instance( array(  'ANS_value'=> $this->_cpt_model_obj->country_ID() )),
757
+				EE_Question::new_instance(array('QST_display_text' => esc_html__('Country', 'event_espresso'), 'QST_system' => 'country')),
758
+				EE_Answer::new_instance(array('ANS_value'=> $this->_cpt_model_obj->country_ID())),
759 759
 				array(
760 760
 					'input_name' =>  'cnt_iso',
761 761
 					'input_id' => 'cnt_iso',
@@ -766,8 +766,8 @@  discard block
 block discarded – undo
766 766
 			)
767 767
 		);
768 768
 
769
-		$template = EE_VENUES_TEMPLATE_PATH . 'venue_address_metabox_content.template.php';
770
-		EEH_Template::display_template( $template, $template_args );
769
+		$template = EE_VENUES_TEMPLATE_PATH.'venue_address_metabox_content.template.php';
770
+		EEH_Template::display_template($template, $template_args);
771 771
 	}
772 772
 
773 773
 
@@ -779,8 +779,8 @@  discard block
 block discarded – undo
779 779
 		$template_args = array(
780 780
 			'_venue' => $this->_cpt_model_obj
781 781
 			);
782
-		$template = EE_VENUES_TEMPLATE_PATH . 'venue_virtual_location_metabox_content.template.php';
783
-		EEH_Template::display_template( $template, $template_args );
782
+		$template = EE_VENUES_TEMPLATE_PATH.'venue_virtual_location_metabox_content.template.php';
783
+		EEH_Template::display_template($template, $template_args);
784 784
 	}
785 785
 
786 786
 
@@ -803,52 +803,52 @@  discard block
 block discarded – undo
803 803
 	 * @param  object $post    Post object (with "blessed" WP properties)
804 804
 	 * @return void
805 805
 	 */
806
-	protected function _insert_update_cpt_item( $post_id, $post ) {
806
+	protected function _insert_update_cpt_item($post_id, $post) {
807 807
 
808
-		if ( $post instanceof WP_Post && $post->post_type !== 'espresso_venues' ) {
809
-			return;// get out we're not processing the saving of venues.
808
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_venues') {
809
+			return; // get out we're not processing the saving of venues.
810 810
 		}
811 811
 
812
-		$wheres = array( $this->_venue_model->primary_key_name() => $post_id );
812
+		$wheres = array($this->_venue_model->primary_key_name() => $post_id);
813 813
 
814 814
 		$venue_values = array(
815
-			'VNU_address' => !empty( $this->_req_data['vnu_address'] ) ? $this->_req_data['vnu_address'] : NULL,
816
-			'VNU_address2' => !empty( $this->_req_data['vnu_address2'] ) ? $this->_req_data['vnu_address2'] : NULL,
817
-			'VNU_city' => !empty( $this->_req_data['vnu_city'] ) ? $this->_req_data['vnu_city'] : NULL,
818
-			'STA_ID' => !empty( $this->_req_data['sta_id'] ) ? $this->_req_data['sta_id'] : NULL,
819
-			'CNT_ISO' => !empty( $this->_req_data['cnt_iso'] ) ? $this->_req_data['cnt_iso'] : NULL,
820
-			'VNU_zip' => !empty( $this->_req_data['vnu_zip'] ) ? $this->_req_data['vnu_zip'] : NULL,
821
-			'VNU_phone' => !empty( $this->_req_data['vnu_phone'] ) ? $this->_req_data['vnu_phone'] : NULL,
822
-			'VNU_capacity' => !empty( $this->_req_data['vnu_capacity'] ) ? str_replace( ',', '', $this->_req_data['vnu_capacity'] ) : EE_INF,
823
-			'VNU_url' => !empty( $this->_req_data['vnu_url'] ) ? $this->_req_data['vnu_url'] : NULL,
824
-			'VNU_virtual_phone' => !empty( $this->_req_data['vnu_virtual_phone'] ) ? $this->_req_data['vnu_virtual_phone'] : NULL,
825
-			'VNU_virtual_url' => !empty( $this->_req_data['vnu_virtual_url'] ) ? $this->_req_data['vnu_virtual_url'] : NULL,
826
-			'VNU_enable_for_gmap' => !empty( $this->_req_data['vnu_enable_for_gmap'] ) ? TRUE : FALSE,
827
-			'VNU_google_map_link' => !empty( $this->_req_data['vnu_google_map_link'] ) ? $this->_req_data['vnu_google_map_link'] : NULL
815
+			'VNU_address' => ! empty($this->_req_data['vnu_address']) ? $this->_req_data['vnu_address'] : NULL,
816
+			'VNU_address2' => ! empty($this->_req_data['vnu_address2']) ? $this->_req_data['vnu_address2'] : NULL,
817
+			'VNU_city' => ! empty($this->_req_data['vnu_city']) ? $this->_req_data['vnu_city'] : NULL,
818
+			'STA_ID' => ! empty($this->_req_data['sta_id']) ? $this->_req_data['sta_id'] : NULL,
819
+			'CNT_ISO' => ! empty($this->_req_data['cnt_iso']) ? $this->_req_data['cnt_iso'] : NULL,
820
+			'VNU_zip' => ! empty($this->_req_data['vnu_zip']) ? $this->_req_data['vnu_zip'] : NULL,
821
+			'VNU_phone' => ! empty($this->_req_data['vnu_phone']) ? $this->_req_data['vnu_phone'] : NULL,
822
+			'VNU_capacity' => ! empty($this->_req_data['vnu_capacity']) ? str_replace(',', '', $this->_req_data['vnu_capacity']) : EE_INF,
823
+			'VNU_url' => ! empty($this->_req_data['vnu_url']) ? $this->_req_data['vnu_url'] : NULL,
824
+			'VNU_virtual_phone' => ! empty($this->_req_data['vnu_virtual_phone']) ? $this->_req_data['vnu_virtual_phone'] : NULL,
825
+			'VNU_virtual_url' => ! empty($this->_req_data['vnu_virtual_url']) ? $this->_req_data['vnu_virtual_url'] : NULL,
826
+			'VNU_enable_for_gmap' => ! empty($this->_req_data['vnu_enable_for_gmap']) ? TRUE : FALSE,
827
+			'VNU_google_map_link' => ! empty($this->_req_data['vnu_google_map_link']) ? $this->_req_data['vnu_google_map_link'] : NULL
828 828
 			);
829 829
 
830 830
 		//update venue
831
-		$success = $this->_venue_model->update( $venue_values, array( $wheres ) );
831
+		$success = $this->_venue_model->update($venue_values, array($wheres));
832 832
 
833 833
 		//get venue_object for other metaboxes that might be added via the filter... though it would seem to make sense to just use $this->_venue_model->get_one_by_ID( $post_id ).. i have to setup where conditions to override the filters in the model that filter out autodraft and inherit statuses so we GET the inherit id!
834
-		$get_one_where = array( $this->_venue_model->primary_key_name() => $post_id, 'status' => $post->post_status  );
835
-		$venue = $this->_venue_model->get_one( array( $get_one_where ) );
834
+		$get_one_where = array($this->_venue_model->primary_key_name() => $post_id, 'status' => $post->post_status);
835
+		$venue = $this->_venue_model->get_one(array($get_one_where));
836 836
 
837 837
 		//notice we've applied a filter for venue metabox callbacks but we don't actually have any default venue metaboxes in use.  So this is just here for addons to more easily hook into venue saves.
838
-		$venue_update_callbacks = apply_filters( 'FHEE__Venues_Admin_Page___insert_update_cpt_item__venue_update_callbacks', array() );
838
+		$venue_update_callbacks = apply_filters('FHEE__Venues_Admin_Page___insert_update_cpt_item__venue_update_callbacks', array());
839 839
 
840 840
 		$att_success = TRUE;
841 841
 
842
-		foreach ( $venue_update_callbacks as $v_callback ) {
843
-			$_succ = call_user_func_array( $v_callback, array( $venue,  $this->_req_data ) );
844
-			$att_success = !$att_success ? $att_success : $_succ; //if ANY of these updates fail then we want the appropriate global error message
842
+		foreach ($venue_update_callbacks as $v_callback) {
843
+			$_succ = call_user_func_array($v_callback, array($venue, $this->_req_data));
844
+			$att_success = ! $att_success ? $att_success : $_succ; //if ANY of these updates fail then we want the appropriate global error message
845 845
 		}
846 846
 
847 847
 		//any errors?
848
-		if ( $success && !$att_success ) {
849
-			EE_Error::add_error( __('Venue Details saved successfully but something went wrong with saving attachments.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
850
-		} else if ( $success === FALSE ) {
851
-			EE_Error::add_error( __('Venue Details did not save successfully.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
848
+		if ($success && ! $att_success) {
849
+			EE_Error::add_error(__('Venue Details saved successfully but something went wrong with saving attachments.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
850
+		} else if ($success === FALSE) {
851
+			EE_Error::add_error(__('Venue Details did not save successfully.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
852 852
 		}
853 853
 	}
854 854
 
@@ -856,9 +856,9 @@  discard block
 block discarded – undo
856 856
 
857 857
 
858 858
 
859
-	public function trash_cpt_item( $post_id ) {
859
+	public function trash_cpt_item($post_id) {
860 860
 		$this->_req_data['VNU_ID'] = $post_id;
861
-		$this->_trash_or_restore_venue( 'trash', FALSE );
861
+		$this->_trash_or_restore_venue('trash', FALSE);
862 862
 	}
863 863
 
864 864
 
@@ -866,18 +866,18 @@  discard block
 block discarded – undo
866 866
 
867 867
 
868 868
 
869
-	public function restore_cpt_item( $post_id ) {
869
+	public function restore_cpt_item($post_id) {
870 870
 		$this->_req_data['VNU_ID'] = $post_id;
871
-		$this->_trash_or_restore_venue( 'draft', FALSE );
871
+		$this->_trash_or_restore_venue('draft', FALSE);
872 872
 	}
873 873
 
874 874
 
875 875
 
876 876
 
877 877
 
878
-	public function delete_cpt_item( $post_id ) {
878
+	public function delete_cpt_item($post_id) {
879 879
 		$this->_req_data['VNU_ID'] = $post_id;
880
-		$this->_delete_venue( FALSE );
880
+		$this->_delete_venue(FALSE);
881 881
 	}
882 882
 
883 883
 
@@ -892,15 +892,15 @@  discard block
 block discarded – undo
892 892
 
893 893
 
894 894
 
895
-	protected function _trash_or_restore_venue( $venue_status = 'trash', $redirect_after = TRUE ) {
896
-		$VNU_ID = isset( $this->_req_data['VNU_ID'] ) ? absint( $this->_req_data['VNU_ID'] ) : FALSE;
895
+	protected function _trash_or_restore_venue($venue_status = 'trash', $redirect_after = TRUE) {
896
+		$VNU_ID = isset($this->_req_data['VNU_ID']) ? absint($this->_req_data['VNU_ID']) : FALSE;
897 897
 
898 898
 		//loop thru venues
899
-		if ( $VNU_ID ) {
899
+		if ($VNU_ID) {
900 900
 			//clean status
901
-			$venue_status = sanitize_key( $venue_status );
901
+			$venue_status = sanitize_key($venue_status);
902 902
 			// grab status
903
-			if (!empty($venue_status)) {
903
+			if ( ! empty($venue_status)) {
904 904
 				$success = $this->_change_venue_status($VNU_ID, $venue_status);
905 905
 			} else {
906 906
 				$success = FALSE;
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 		}
915 915
 		$action = $venue_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
916 916
 
917
-		if ( $redirect_after )
917
+		if ($redirect_after)
918 918
 			$this->_redirect_after_action($success, 'Venue', $action, array('action' => 'default'));
919 919
 
920 920
 	}
@@ -923,11 +923,11 @@  discard block
 block discarded – undo
923 923
 
924 924
 
925 925
 
926
-	protected function _trash_or_restore_venues( $venue_status = 'trash' ) {
926
+	protected function _trash_or_restore_venues($venue_status = 'trash') {
927 927
 		// clean status
928 928
 		$venue_status = sanitize_key($venue_status);
929 929
 		// grab status
930
-		if (!empty($venue_status)) {
930
+		if ( ! empty($venue_status)) {
931 931
 			$success = TRUE;
932 932
 			//determine the event id and set to array.
933 933
 			$VNU_IDs = isset($this->_req_data['venue_id']) ? (array) $this->_req_data['venue_id'] : array();
@@ -967,20 +967,20 @@  discard block
 block discarded – undo
967 967
 	 * @param  string $venue_status
968 968
 	 * @return void
969 969
 	 */
970
-	private function _change_venue_status( $VNU_ID = 0, $venue_status = '' ) {
970
+	private function _change_venue_status($VNU_ID = 0, $venue_status = '') {
971 971
 		// grab venue id
972
-		if (! $VNU_ID) {
972
+		if ( ! $VNU_ID) {
973 973
 			$msg = __('An error occurred. No Venue ID or an invalid Venue ID was received.', 'event_espresso');
974 974
 			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
975 975
 			return FALSE;
976 976
 		}
977 977
 
978
-		$this->_cpt_model_obj = EEM_Venue::instance()->get_one_by_ID( $VNU_ID );
978
+		$this->_cpt_model_obj = EEM_Venue::instance()->get_one_by_ID($VNU_ID);
979 979
 
980 980
 		// clean status
981 981
 		$venue_status = sanitize_key($venue_status);
982 982
 		// grab status
983
-		if ( ! $venue_status ) {
983
+		if ( ! $venue_status) {
984 984
 			$msg = __('An error occurred. No Venue Status or an invalid Venue Status was received.', 'event_espresso');
985 985
 			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
986 986
 			return FALSE;
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
 				$hook = FALSE;
1002 1002
 		}
1003 1003
 		//use class to change status
1004
-		$this->_cpt_model_obj->set_status( $venue_status );
1004
+		$this->_cpt_model_obj->set_status($venue_status);
1005 1005
 		$success = $this->_cpt_model_obj->save();
1006 1006
 
1007 1007
 		if ($success === FALSE) {
@@ -1020,21 +1020,21 @@  discard block
 block discarded – undo
1020 1020
 	 * @param  bool $redirect_after
1021 1021
 	 * @return void
1022 1022
 	 */
1023
-	protected function _delete_venue( $redirect_after = true ) {
1023
+	protected function _delete_venue($redirect_after = true) {
1024 1024
 		//determine the venue id and set to array.
1025 1025
 		$VNU_ID = isset($this->_req_data['VNU_ID']) ? absint($this->_req_data['VNU_ID']) : NULL;
1026
-		$VNU_ID = isset( $this->_req_data['post'] ) ? absint( $this->_req_data['post'] ) : $VNU_ID;
1026
+		$VNU_ID = isset($this->_req_data['post']) ? absint($this->_req_data['post']) : $VNU_ID;
1027 1027
 
1028 1028
 
1029 1029
 		// loop thru venues
1030 1030
 		if ($VNU_ID) {
1031
-			$success = $this->_delete_or_trash_venue( $VNU_ID );
1031
+			$success = $this->_delete_or_trash_venue($VNU_ID);
1032 1032
 		} else {
1033 1033
 			$success = FALSE;
1034 1034
 			$msg = __('An error occurred. An venue could not be deleted because a valid venue ID was not not supplied.', 'event_espresso');
1035 1035
 			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1036 1036
 		}
1037
-		if ( $redirect_after )
1037
+		if ($redirect_after)
1038 1038
 			$this->_redirect_after_action($success, 'Venue', 'deleted', array('action' => 'default'));
1039 1039
 	}
1040 1040
 
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
 	//todo: put in parent
1067 1067
 	private function _delete_or_trash_venue($VNU_ID = FALSE) {
1068 1068
 		// grab event id
1069
-		if (!$VNU_ID = absint($VNU_ID)) {
1069
+		if ( ! $VNU_ID = absint($VNU_ID)) {
1070 1070
 			$msg = __('An error occurred. No Venue ID or an invalid Venue ID was received.', 'event_espresso');
1071 1071
 			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1072 1072
 			return FALSE;
@@ -1086,7 +1086,7 @@  discard block
 block discarded – undo
1086 1086
 			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1087 1087
 			return FALSE;
1088 1088
 		}
1089
-		do_action( 'AHEE__Venues_Admin_Page___delete_or_trash_venue__after_venue_deleted' );
1089
+		do_action('AHEE__Venues_Admin_Page___delete_or_trash_venue__after_venue_deleted');
1090 1090
 		return TRUE;
1091 1091
 	}
1092 1092
 
@@ -1097,11 +1097,11 @@  discard block
 block discarded – undo
1097 1097
 	/* QUERIES */
1098 1098
 
1099 1099
 
1100
-	public function get_venues( $per_page = 10, $count = FALSE ) {
1100
+	public function get_venues($per_page = 10, $count = FALSE) {
1101 1101
 
1102
-		$_orderby = !empty( $this->_req_data['orderby'] ) ? $this->_req_data['orderby'] : '';
1102
+		$_orderby = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
1103 1103
 
1104
-		switch ( $_orderby ) {
1104
+		switch ($_orderby) {
1105 1105
 			case 'id':
1106 1106
 				$orderby = 'VNU_ID';
1107 1107
 				break;
@@ -1119,43 +1119,43 @@  discard block
 block discarded – undo
1119 1119
 		}
1120 1120
 
1121 1121
 
1122
-		$sort = ( isset( $this->_req_data['order'] ) && ! empty( $this->_req_data['order'] )) ? $this->_req_data['order'] : 'ASC';
1122
+		$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1123 1123
 
1124
-		$current_page = isset( $this->_req_data['paged'] ) && !empty( $this->_req_data['paged'] ) ? $this->_req_data['paged'] : 1;
1125
-		$per_page = isset( $per_page ) && !empty( $per_page ) ? $per_page : 10;
1126
-		$per_page = isset( $this->_req_data['perpage'] ) && !empty( $this->_req_data['perpage'] ) ? $this->_req_data['perpage'] : $per_page;
1124
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1125
+		$per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
1126
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
1127 1127
 
1128 1128
 
1129
-		$offset = ($current_page-1)*$per_page;
1129
+		$offset = ($current_page - 1) * $per_page;
1130 1130
 		$limit = array($offset, $per_page);
1131 1131
 
1132
-		$category = isset( $this->_req_data['category'] ) && $this->_req_data['category'] > 0 ? $this->_req_data['category'] : NULL;
1132
+		$category = isset($this->_req_data['category']) && $this->_req_data['category'] > 0 ? $this->_req_data['category'] : NULL;
1133 1133
 		$where = array();
1134 1134
 
1135 1135
 		//only set initial status if it is in the incoming request.  Otherwise the "all" view display's all statuses.
1136
-		if ( isset( $this->_req_data['status'] ) && $this->_req_data['status'] != 'all' ) {
1136
+		if (isset($this->_req_data['status']) && $this->_req_data['status'] != 'all') {
1137 1137
 			$where['status'] = $this->_req_data['status'];
1138 1138
 		}
1139 1139
 
1140
-		if ( isset( $this->_req_data['venue_status'] ) ) {
1140
+		if (isset($this->_req_data['venue_status'])) {
1141 1141
 			$where['status'] = $this->_req_data['venue_status'];
1142 1142
 		}
1143 1143
 
1144 1144
 
1145
-		if ( $category ) {
1145
+		if ($category) {
1146 1146
 			$where['Term_Taxonomy.taxonomy'] = 'espresso_venue_categories';
1147 1147
 			$where['Term_Taxonomy.term_id'] = $category;
1148 1148
 		}
1149 1149
 
1150 1150
 
1151
-		if ( ! EE_Registry::instance()->CAP->current_user_can( 'ee_read_others_venues', 'get_venues' ) ) {
1152
-			$where['VNU_wp_user'] =  get_current_user_id();
1151
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_venues', 'get_venues')) {
1152
+			$where['VNU_wp_user'] = get_current_user_id();
1153 1153
 		} else {
1154
-				if ( ! EE_Registry::instance()->CAP->current_user_can( 'ee_read_private_venues', 'get_venues' ) ) {
1154
+				if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_private_venues', 'get_venues')) {
1155 1155
 					$where['OR'] = array(
1156
-						'status*restrict_private' => array( '!=', 'private' ),
1156
+						'status*restrict_private' => array('!=', 'private'),
1157 1157
 						'AND'                     => array(
1158
-							'status*inclusive' => array( '=', 'private' ),
1158
+							'status*inclusive' => array('=', 'private'),
1159 1159
 							'VNU_wp_user'      => get_current_user_id()
1160 1160
 						)
1161 1161
 					);
@@ -1165,30 +1165,30 @@  discard block
 block discarded – undo
1165 1165
 
1166 1166
 
1167 1167
 
1168
-		if ( isset( $this->_req_data['s'] ) ) {
1169
-			$sstr = '%' . $this->_req_data['s'] . '%';
1168
+		if (isset($this->_req_data['s'])) {
1169
+			$sstr = '%'.$this->_req_data['s'].'%';
1170 1170
 			$where['OR'] = array(
1171
-				'VNU_name' => array('LIKE',$sstr ),
1172
-				'VNU_desc' => array('LIKE',$sstr ),
1173
-				'VNU_short_desc' => array( 'LIKE',$sstr ),
1174
-				'VNU_address' => array( 'LIKE', $sstr ),
1175
-				'VNU_address2' => array( 'LIKE', $sstr ),
1176
-				'VNU_city' => array( 'LIKE', $sstr ),
1177
-				'VNU_zip' => array( 'LIKE', $sstr ),
1178
-				'VNU_phone' => array( 'LIKE', $sstr ),
1179
-				'VNU_url' => array( 'LIKE', $sstr ),
1180
-				'VNU_virtual_phone' => array( 'LIKE', $sstr ),
1181
-				'VNU_virtual_url' => array( 'LIKE', $sstr ),
1182
-				'VNU_google_map_link' => array( 'LIKE', $sstr ),
1183
-				'Event.EVT_name' => array('LIKE', $sstr ),
1184
-				'Event.EVT_desc' => array('LIKE', $sstr ),
1185
-				'Event.EVT_phone' => array('LIKE', $sstr ),
1186
-				'Event.EVT_external_URL' => array('LIKE', $sstr ),
1171
+				'VNU_name' => array('LIKE', $sstr),
1172
+				'VNU_desc' => array('LIKE', $sstr),
1173
+				'VNU_short_desc' => array('LIKE', $sstr),
1174
+				'VNU_address' => array('LIKE', $sstr),
1175
+				'VNU_address2' => array('LIKE', $sstr),
1176
+				'VNU_city' => array('LIKE', $sstr),
1177
+				'VNU_zip' => array('LIKE', $sstr),
1178
+				'VNU_phone' => array('LIKE', $sstr),
1179
+				'VNU_url' => array('LIKE', $sstr),
1180
+				'VNU_virtual_phone' => array('LIKE', $sstr),
1181
+				'VNU_virtual_url' => array('LIKE', $sstr),
1182
+				'VNU_google_map_link' => array('LIKE', $sstr),
1183
+				'Event.EVT_name' => array('LIKE', $sstr),
1184
+				'Event.EVT_desc' => array('LIKE', $sstr),
1185
+				'Event.EVT_phone' => array('LIKE', $sstr),
1186
+				'Event.EVT_external_URL' => array('LIKE', $sstr),
1187 1187
 				);
1188 1188
 		}
1189 1189
 
1190 1190
 
1191
-		$venues = $count ? $this->_venue_model->count( array($where), 'VNU_ID' ) : $this->_venue_model->get_all( array( $where, 'limit' => $limit, 'order_by' => $orderby, 'order' => $sort ) );
1191
+		$venues = $count ? $this->_venue_model->count(array($where), 'VNU_ID') : $this->_venue_model->get_all(array($where, 'limit' => $limit, 'order_by' => $orderby, 'order' => $sort));
1192 1192
 
1193 1193
 		return $venues;
1194 1194
 
@@ -1206,22 +1206,22 @@  discard block
 block discarded – undo
1206 1206
 	 * @return void
1207 1207
 	 */
1208 1208
 	private function _set_category_object() {
1209
-		if ( isset( $this->_category->id ) && !empty( $this->_category->id ) )
1209
+		if (isset($this->_category->id) && ! empty($this->_category->id))
1210 1210
 			return; //already have the category object so get out.
1211 1211
 
1212 1212
 		//set default category object
1213 1213
 		$this->_set_empty_category_object();
1214 1214
 
1215 1215
 		//only set if we've got an id
1216
-		if ( !isset($this->_req_data['VEN_CAT_ID'] ) ) {
1216
+		if ( ! isset($this->_req_data['VEN_CAT_ID'])) {
1217 1217
 			return;
1218 1218
 		}
1219 1219
 
1220 1220
 		$category_id = absint($this->_req_data['VEN_CAT_ID']);
1221
-		$term = get_term( $category_id, 'espresso_venue_categories' );
1221
+		$term = get_term($category_id, 'espresso_venue_categories');
1222 1222
 
1223 1223
 
1224
-		if ( !empty( $term ) ) {
1224
+		if ( ! empty($term)) {
1225 1225
 			$this->_category->category_name = $term->name;
1226 1226
 			$this->_category->category_identifier = $term->slug;
1227 1227
 			$this->_category->category_desc = $term->description;
@@ -1235,15 +1235,15 @@  discard block
 block discarded – undo
1235 1235
 
1236 1236
 	private function _set_empty_category_object() {
1237 1237
 		$this->_category = new stdClass();
1238
-		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc  = '';
1238
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
1239 1239
 		$this->_category->id = $this->_category->parent = 0;
1240 1240
 	}
1241 1241
 
1242 1242
 
1243 1243
 
1244 1244
 	protected function _category_list_table() {
1245
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
1246
-		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1245
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1246
+		$this->_admin_page_title .= ' '.$this->get_action_link_or_button(
1247 1247
 		    'add_category',
1248 1248
             'add_category',
1249 1249
             array(),
@@ -1263,13 +1263,13 @@  discard block
 block discarded – undo
1263 1263
 		$this->_set_add_edit_form_tags($route);
1264 1264
 
1265 1265
 		$this->_set_category_object();
1266
-		$id = !empty($this->_category->id) ? $this->_category->id : '';
1266
+		$id = ! empty($this->_category->id) ? $this->_category->id : '';
1267 1267
 
1268 1268
 		$delete_action = 'delete_category';
1269 1269
 
1270
-		$redirect = EE_Admin_Page::add_query_args_and_nonce( array( 'action' => 'category_list' ), $this->_admin_base_url );
1270
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'category_list'), $this->_admin_base_url);
1271 1271
 
1272
-		$this->_set_publish_post_box_vars( 'VEN_CAT_ID', $id, $delete_action, $redirect );
1272
+		$this->_set_publish_post_box_vars('VEN_CAT_ID', $id, $delete_action, $redirect);
1273 1273
 
1274 1274
 		//take care of contents
1275 1275
 		$this->_template_args['admin_page_content'] = $this->_category_details_content();
@@ -1283,25 +1283,25 @@  discard block
 block discarded – undo
1283 1283
 			'type' => 'wp_editor',
1284 1284
 			'value' => EEH_Formatter::admin_format_content($this->_category->category_desc),
1285 1285
 			'class' => 'my_editor_custom',
1286
-			'wpeditor_args' => array( 'media_buttons' => FALSE )
1286
+			'wpeditor_args' => array('media_buttons' => FALSE)
1287 1287
 		);
1288
-		$_wp_editor = $this->_generate_admin_form_fields( $editor_args, 'array' );
1288
+		$_wp_editor = $this->_generate_admin_form_fields($editor_args, 'array');
1289 1289
 
1290
-		$all_terms = get_terms( array('espresso_venue_categories' ), array( 'hide_empty' => 0, 'exclude' => array( $this->_category->id ) ) );
1290
+		$all_terms = get_terms(array('espresso_venue_categories'), array('hide_empty' => 0, 'exclude' => array($this->_category->id)));
1291 1291
 
1292 1292
 		//setup category select for term parents.
1293 1293
 		$category_select_values[] = array(
1294 1294
 			'text' => __('No Parent', 'event_espresso'),
1295 1295
 			'id' => 0
1296 1296
 			);
1297
-		foreach ( $all_terms as $term ) {
1297
+		foreach ($all_terms as $term) {
1298 1298
 			$category_select_values[] = array(
1299 1299
 				'text' => $term->name,
1300 1300
 				'id' => $term->term_id
1301 1301
 				);
1302 1302
 		}
1303 1303
 
1304
-		$category_select = EEH_Form_Fields::select_input( 'category_parent', $category_select_values, $this->_category->parent );
1304
+		$category_select = EEH_Form_Fields::select_input('category_parent', $category_select_values, $this->_category->parent);
1305 1305
 		$template_args = array(
1306 1306
 			'category' => $this->_category,
1307 1307
 			'category_select' => $category_select,
@@ -1310,15 +1310,15 @@  discard block
 block discarded – undo
1310 1310
 			'disable' => '',
1311 1311
 			'disabled_message' =>FALSE
1312 1312
 			);
1313
-		$template = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
1314
-		return EEH_Template::display_template($template, $template_args, TRUE );
1313
+		$template = EVENTS_TEMPLATE_PATH.'event_category_details.template.php';
1314
+		return EEH_Template::display_template($template, $template_args, TRUE);
1315 1315
 	}
1316 1316
 
1317 1317
 
1318 1318
 	protected function _delete_categories() {
1319
-		$cat_ids = isset( $this->_req_data['VEN_CAT_ID'] ) ? (array) $this->_req_data['VEN_CAT_ID'] : (array) $this->_req_data['category_id'];
1319
+		$cat_ids = isset($this->_req_data['VEN_CAT_ID']) ? (array) $this->_req_data['VEN_CAT_ID'] : (array) $this->_req_data['category_id'];
1320 1320
 
1321
-		foreach ( $cat_ids as $cat_id ) {
1321
+		foreach ($cat_ids as $cat_id) {
1322 1322
 			$this->_delete_category($cat_id);
1323 1323
 		}
1324 1324
 
@@ -1326,7 +1326,7 @@  discard block
 block discarded – undo
1326 1326
 		$query_args = array(
1327 1327
 			'action' => 'category_list'
1328 1328
 			);
1329
-		$this->_redirect_after_action(0,'','',$query_args);
1329
+		$this->_redirect_after_action(0, '', '', $query_args);
1330 1330
 
1331 1331
 	}
1332 1332
 
@@ -1335,58 +1335,58 @@  discard block
 block discarded – undo
1335 1335
 
1336 1336
 
1337 1337
 	protected function _delete_category($cat_id) {
1338
-		$cat_id = absint( $cat_id );
1339
-		wp_delete_term( $cat_id, 'espresso_venue_categories' );
1338
+		$cat_id = absint($cat_id);
1339
+		wp_delete_term($cat_id, 'espresso_venue_categories');
1340 1340
 	}
1341 1341
 
1342 1342
 
1343 1343
 
1344 1344
 	protected function _insert_or_update_category($new_category) {
1345 1345
 
1346
-		$cat_id = $new_category ? $this->_insert_category() : $this->_insert_category( TRUE );
1346
+		$cat_id = $new_category ? $this->_insert_category() : $this->_insert_category(TRUE);
1347 1347
 		$success = 0; //we already have a success message so lets not send another.
1348
-		if ( $cat_id ) {
1348
+		if ($cat_id) {
1349 1349
 			$query_args = array(
1350 1350
 				'action'     => 'edit_category',
1351 1351
 				'VEN_CAT_ID' => $cat_id
1352 1352
 			);
1353 1353
 		} else {
1354
-			$query_args = array( 'action' => 'add_category' );
1354
+			$query_args = array('action' => 'add_category');
1355 1355
 		}
1356
-		$this->_redirect_after_action( $success, '','', $query_args, TRUE );
1356
+		$this->_redirect_after_action($success, '', '', $query_args, TRUE);
1357 1357
 
1358 1358
 	}
1359 1359
 
1360 1360
 
1361 1361
 
1362
-	private function _insert_category( $update = FALSE ) {
1362
+	private function _insert_category($update = FALSE) {
1363 1363
 		$cat_id = $update ? $this->_req_data['VEN_CAT_ID'] : '';
1364
-		$category_name= isset( $this->_req_data['category_name'] ) ? $this->_req_data['category_name'] : '';
1365
-		$category_desc= isset( $this->_req_data['category_desc'] ) ? $this->_req_data['category_desc'] : '';
1366
-		$category_parent = isset( $this->_req_data['category_parent'] ) ? $this->_req_data['category_parent'] : 0;
1364
+		$category_name = isset($this->_req_data['category_name']) ? $this->_req_data['category_name'] : '';
1365
+		$category_desc = isset($this->_req_data['category_desc']) ? $this->_req_data['category_desc'] : '';
1366
+		$category_parent = isset($this->_req_data['category_parent']) ? $this->_req_data['category_parent'] : 0;
1367 1367
 
1368
-		if ( empty( $category_name ) ) {
1369
-			$msg = __( 'You must add a name for the category.', 'event_espresso' );
1370
-			EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
1368
+		if (empty($category_name)) {
1369
+			$msg = __('You must add a name for the category.', 'event_espresso');
1370
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1371 1371
 			return false;
1372 1372
 		}
1373 1373
 
1374 1374
 
1375
-		$term_args=array(
1375
+		$term_args = array(
1376 1376
 			'name'=>$category_name,
1377 1377
 			'description'=>$category_desc,
1378 1378
 			'parent'=>$category_parent
1379 1379
 		);
1380 1380
 
1381
-		$insert_ids = $update ? wp_update_term( $cat_id, 'espresso_venue_categories', $term_args ) :wp_insert_term( $category_name, 'espresso_venue_categories', $term_args );
1381
+		$insert_ids = $update ? wp_update_term($cat_id, 'espresso_venue_categories', $term_args) : wp_insert_term($category_name, 'espresso_venue_categories', $term_args);
1382 1382
 
1383
-		if ( !is_array( $insert_ids ) ) {
1384
-			$msg = __( 'An error occurred and the category has not been saved to the database.', 'event_espresso' );
1385
-			EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
1383
+		if ( ! is_array($insert_ids)) {
1384
+			$msg = __('An error occurred and the category has not been saved to the database.', 'event_espresso');
1385
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1386 1386
 		} else {
1387 1387
 			$cat_id = $insert_ids['term_id'];
1388
-			$msg = sprintf ( __('The category %s was successfully created', 'event_espresso'), $category_name );
1389
-			EE_Error::add_success( $msg );
1388
+			$msg = sprintf(__('The category %s was successfully created', 'event_espresso'), $category_name);
1389
+			EE_Error::add_success($msg);
1390 1390
 		}
1391 1391
 
1392 1392
 		return $cat_id;
@@ -1406,11 +1406,11 @@  discard block
 block discarded – undo
1406 1406
 			'category_ids' => $this->_req_data['VEN_CAT_ID']
1407 1407
 			);
1408 1408
 
1409
-		$this->_req_data = array_merge( $this->_req_data, $new_request_args );
1409
+		$this->_req_data = array_merge($this->_req_data, $new_request_args);
1410 1410
 
1411
-		if ( is_readable( EE_CLASSES . 'EE_Export.class.php') ) {
1412
-			require_once( EE_CLASSES . 'EE_Export.class.php');
1413
-			$EE_Export = EE_Export::instance( $this->_req_data );
1411
+		if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
1412
+			require_once(EE_CLASSES.'EE_Export.class.php');
1413
+			$EE_Export = EE_Export::instance($this->_req_data);
1414 1414
 			$EE_Export->export();
1415 1415
 		}
1416 1416
 
@@ -1422,7 +1422,7 @@  discard block
 block discarded – undo
1422 1422
 
1423 1423
 	protected function _import_categories() {
1424 1424
 
1425
-		require_once(EE_CLASSES . 'EE_Import.class.php');
1425
+		require_once(EE_CLASSES.'EE_Import.class.php');
1426 1426
 		EE_Import::instance()->import();
1427 1427
 
1428 1428
 	}
@@ -1430,29 +1430,29 @@  discard block
 block discarded – undo
1430 1430
 
1431 1431
 
1432 1432
 
1433
-	public function get_categories( $per_page = 10, $current_page = 1, $count = FALSE ) {
1433
+	public function get_categories($per_page = 10, $current_page = 1, $count = FALSE) {
1434 1434
 
1435 1435
 		//testing term stuff
1436
-		$orderby = isset( $this->_req_data['orderby'] ) ? $this->_req_data['orderby'] : 'Term.term_id';
1437
-		$order = isset( $this->_req_data['order'] ) ? $this->_req_data['order'] : 'DESC';
1438
-		$limit = ($current_page-1)*$per_page;
1439
-		$where = array( 'taxonomy' => 'espresso_venue_categories' );
1440
-		if ( isset( $this->_req_data['s'] ) ) {
1441
-			$sstr = '%' . $this->_req_data['s'] . '%';
1436
+		$orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'Term.term_id';
1437
+		$order = isset($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
1438
+		$limit = ($current_page - 1) * $per_page;
1439
+		$where = array('taxonomy' => 'espresso_venue_categories');
1440
+		if (isset($this->_req_data['s'])) {
1441
+			$sstr = '%'.$this->_req_data['s'].'%';
1442 1442
 			$where['OR'] = array(
1443
-				'Term.name' => array( 'LIKE', $sstr),
1444
-				'description' => array( 'LIKE', $sstr )
1443
+				'Term.name' => array('LIKE', $sstr),
1444
+				'description' => array('LIKE', $sstr)
1445 1445
 				);
1446 1446
 		}
1447 1447
 
1448 1448
 		$query_params = array(
1449 1449
 			$where,
1450
-			'order_by' => array( $orderby => $order ),
1451
-			'limit' => $limit . ',' . $per_page,
1450
+			'order_by' => array($orderby => $order),
1451
+			'limit' => $limit.','.$per_page,
1452 1452
 			'force_join' => array('Term')
1453 1453
 			);
1454 1454
 
1455
-		$categories = $count ? EEM_Term_Taxonomy::instance()->count( $query_params, 'term_id' ) :EEM_Term_Taxonomy::instance()->get_all( $query_params );
1455
+		$categories = $count ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id') : EEM_Term_Taxonomy::instance()->get_all($query_params);
1456 1456
 
1457 1457
 		return $categories;
1458 1458
 	}
Please login to merge, or discard this patch.
admin_pages/registrations/EE_Registrations_List_Table.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -227,7 +227,7 @@
 block discarded – undo
227 227
      *    _get_table_filters
228 228
      *
229 229
      * @access protected
230
-     * @return array
230
+     * @return string[]
231 231
      */
232 232
     protected function _get_table_filters()
233 233
     {
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
         );
158 158
         $this->_primary_column = '_REG_ID';
159 159
         $this->_sortable_columns = array(
160
-            '_REG_date'     => array('_REG_date' => true),   //true means its already sorted
160
+            '_REG_date'     => array('_REG_date' => true), //true means its already sorted
161 161
             'ATT_fname'     => array('ATT_fname' => false),
162 162
             'event_name'    => array('event_name' => false),
163 163
             'DTT_EVT_start' => array('DTT_EVT_start' => false),
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
     {
180 180
         $class = parent::_get_row_class($item);
181 181
         //add status class
182
-        $class .= ' ee-status-strip reg-status-' . $item->status_ID();
182
+        $class .= ' ee-status-strip reg-status-'.$item->status_ID();
183 183
         if ($this->_has_checkbox_column) {
184 184
             $class .= ' has-checkbox-column';
185 185
         }
@@ -327,11 +327,11 @@  discard block
 block discarded – undo
327 327
         //setup date query.
328 328
         $beginning_string = EEM_Registration::instance()
329 329
                                             ->convert_datetime_for_query('REG_date',
330
-                                                $this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start,
330
+                                                $this_year_r.'-'.$this_month_r.'-01'.' '.$time_start,
331 331
                                                 'Y-m-d H:i:s');
332 332
         $end_string = EEM_Registration::instance()
333 333
                                       ->convert_datetime_for_query('REG_date',
334
-                                          $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
334
+                                          $this_year_r.'-'.$this_month_r.'-'.$days_this_month.' '.$time_end,
335 335
                                           'Y-m-d H:i:s');
336 336
         $_where['REG_date'] = array(
337 337
             'BETWEEN',
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
             'BETWEEN',
365 365
             array(
366 366
                 EEM_Registration::instance()
367
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_start, 'Y-m-d H:i:s'),
367
+                                ->convert_datetime_for_query('REG_date', $current_date.$time_start, 'Y-m-d H:i:s'),
368 368
                 EEM_Registration::instance()
369
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_end, 'Y-m-d H:i:s'),
369
+                                ->convert_datetime_for_query('REG_date', $current_date.$time_end, 'Y-m-d H:i:s'),
370 370
             ),
371 371
         );
372 372
         $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
@@ -410,8 +410,8 @@  discard block
 block discarded – undo
410 410
         $content .= '<div class="show-on-mobile-view-only">';
411 411
         $content .= '<br>';
412 412
         $content .= $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
413
-        $content .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
414
-        $content .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
413
+        $content .= '&nbsp;'.sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
414
+        $content .= '<br>'.sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
415 415
         $content .= '</div>';
416 416
         return $content;
417 417
     }
@@ -482,10 +482,10 @@  discard block
 block discarded – undo
482 482
                   . $event_name
483 483
                   . '</a>' : $event_name;
484 484
             $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('event_id' => $EVT_ID), REG_ADMIN_URL);
485
-            $actions['event_filter'] = '<a href="' . $edit_event_url . '" title="';
485
+            $actions['event_filter'] = '<a href="'.$edit_event_url.'" title="';
486 486
             $actions['event_filter'] .= sprintf(esc_attr__('Filter this list to only show registrations for %s',
487 487
                 'event_espresso'), $event_name);
488
-            $actions['event_filter'] .= '">' . __('View Registrations', 'event_espresso') . '</a>';
488
+            $actions['event_filter'] .= '">'.__('View Registrations', 'event_espresso').'</a>';
489 489
         } else {
490 490
             $edit_event = $event_name;
491 491
             $actions['event_filter'] = '';
@@ -551,12 +551,12 @@  discard block
 block discarded – undo
551 551
         $t = $item->get_first_related('Transaction');
552 552
         $payment_count = $t instanceof EE_Transaction ? $t->count_related('Payment') : 0;
553 553
         //append group count to name
554
-        $link .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
554
+        $link .= '&nbsp;'.sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
555 555
         //append reg_code
556
-        $link .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
556
+        $link .= '<br>'.sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
557 557
         //reg status text for accessibility
558
-        $link .= '<br><span class="ee-status-text-small">' . EEH_Template::pretty_status($item->status_ID(), false,
559
-                'sentence') . '</span>';
558
+        $link .= '<br><span class="ee-status-text-small">'.EEH_Template::pretty_status($item->status_ID(), false,
559
+                'sentence').'</span>';
560 560
         //trash/restore/delete actions
561 561
         $actions = array();
562 562
         if ($this->_view !== 'trash'
@@ -568,8 +568,8 @@  discard block
 block discarded – undo
568 568
                 'action'  => 'trash_registrations',
569 569
                 '_REG_ID' => $item->ID(),
570 570
             ), REG_ADMIN_URL);
571
-            $actions['trash'] = '<a href="' . $trash_lnk_url . '" title="' . esc_attr__('Trash Registration',
572
-                    'event_espresso') . '">' . __('Trash', 'event_espresso') . '</a>';
571
+            $actions['trash'] = '<a href="'.$trash_lnk_url.'" title="'.esc_attr__('Trash Registration',
572
+                    'event_espresso').'">'.__('Trash', 'event_espresso').'</a>';
573 573
         } elseif ($this->_view === 'trash') {
574 574
             // restore registration link
575 575
             if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
@@ -579,8 +579,8 @@  discard block
 block discarded – undo
579 579
                     'action'  => 'restore_registrations',
580 580
                     '_REG_ID' => $item->ID(),
581 581
                 ), REG_ADMIN_URL);
582
-                $actions['restore'] = '<a href="' . $restore_lnk_url . '" title="' . esc_attr__('Restore Registration',
583
-                        'event_espresso') . '">' . __('Restore', 'event_espresso') . '</a>';
582
+                $actions['restore'] = '<a href="'.$restore_lnk_url.'" title="'.esc_attr__('Restore Registration',
583
+                        'event_espresso').'">'.__('Restore', 'event_espresso').'</a>';
584 584
             }
585 585
             if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
586 586
                 'espresso_registrations_ee_delete_registrations', $item->ID())
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
                                                                               . $ticket->name()
649 649
                                                                               . '</span><br />' : '';
650 650
         if ($item->final_price() > 0) {
651
-            $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
651
+            $content .= '<span class="reg-pad-rght">'.$item->pretty_final_price().'</span>';
652 652
         } else {
653 653
             // free event
654 654
             $content .= '<span class="reg-overview-free-event-spn reg-pad-rght">'
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
             : '<span class="TKT_name">'
676 676
               . $ticket->name()
677 677
               . '</span><br />';
678
-        $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
678
+        $content .= '<span class="reg-pad-rght">'.$item->pretty_final_price().'</span>';
679 679
         return $content;
680 680
     }
681 681
 
@@ -693,10 +693,10 @@  discard block
 block discarded – undo
693 693
         $payment_method = $item->payment_method();
694 694
         $payment_method_name = $payment_method instanceof EE_Payment_Method ? $payment_method->admin_name()
695 695
             : __('Unknown', 'event_espresso');
696
-        $content = '<span class="reg-pad-rght">' . $item->pretty_paid() . '</span>';
696
+        $content = '<span class="reg-pad-rght">'.$item->pretty_paid().'</span>';
697 697
         if ($item->paid() > 0) {
698
-            $content .= '<br><span class="ee-status-text-small">' . sprintf(__('...via %s', 'event_espresso'),
699
-                    $payment_method_name) . '</span>';
698
+            $content .= '<br><span class="ee-status-text-small">'.sprintf(__('...via %s', 'event_espresso'),
699
+                    $payment_method_name).'</span>';
700 700
         }
701 701
         return $content;
702 702
     }
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
                   . esc_attr__('View Transaction', 'event_espresso')
729 729
                   . '">'
730 730
                   . $item->transaction()->pretty_total()
731
-                  . '</a></span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_total() . '</span>';
731
+                  . '</a></span>' : '<span class="reg-pad-rght">'.$item->transaction()->pretty_total().'</span>';
732 732
         } else {
733 733
             return __("None", "event_espresso");
734 734
         }
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
                       . esc_attr__('View Transaction', 'event_espresso')
766 766
                       . '">'
767 767
                       . $item->transaction()->pretty_paid()
768
-                      . '</a><span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_paid() . '</span>';
768
+                      . '</a><span>' : '<span class="reg-pad-rght">'.$item->transaction()->pretty_paid().'</span>';
769 769
             }
770 770
         }
771 771
         return '&nbsp;';
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
         $actions['view_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
806 806
             'espresso_registrations_view_registration', $item->ID()) ? '
807 807
 			<li>
808
-			<a href="' . $view_lnk_url . '" title="' . esc_attr__('View Registration Details', 'event_espresso') . '" class="tiny-text">
808
+			<a href="' . $view_lnk_url.'" title="'.esc_attr__('View Registration Details', 'event_espresso').'" class="tiny-text">
809 809
 				<div class="dashicons dashicons-clipboard"></div>
810 810
 			</a>
811 811
 			</li>' : '';
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
             'espresso_registrations_edit_attendee')
814 814
                                && $attendee instanceof EE_Attendee ? '
815 815
 			<li>
816
-			<a href="' . $edit_lnk_url . '" title="' . esc_attr__('Edit Contact Details', 'event_espresso') . '" class="tiny-text">
816
+			<a href="' . $edit_lnk_url.'" title="'.esc_attr__('Edit Contact Details', 'event_espresso').'" class="tiny-text">
817 817
 				<div class="ee-icon ee-icon-user-edit ee-icon-size-16"></div>
818 818
 			</a>
819 819
 			</li>' : '';
Please login to merge, or discard this patch.
Indentation   +818 added lines, -818 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -26,847 +26,847 @@  discard block
 block discarded – undo
26 26
 
27 27
 
28 28
 
29
-    private $_status;
30
-
31
-
32
-
33
-    /**
34
-     * An array of transaction details for the related transaction to the registration being processed.
35
-     * This is set via the _set_related_details method.
36
-     *
37
-     * @var array
38
-     */
39
-    protected $_transaction_details = array();
40
-
41
-
42
-
43
-    /**
44
-     * An array of event details for the related event to the registration being processed.
45
-     * This is set via the _set_related_details method.
46
-     *
47
-     * @var array
48
-     */
49
-    protected $_event_details = array();
50
-
51
-
52
-
53
-    /**
54
-     * @param \Registrations_Admin_Page $admin_page
55
-     */
56
-    public function __construct(Registrations_Admin_Page $admin_page)
57
-    {
58
-        if ( ! empty($_GET['event_id'])) {
59
-            $extra_query_args = array();
60
-            foreach ($admin_page->get_views() as $key => $view_details) {
61
-                $extra_query_args[$view_details['slug']] = array('event_id' => $_GET['event_id']);
62
-            }
63
-            $this->_views = $admin_page->get_list_table_view_RLs($extra_query_args);
64
-        }
65
-        parent::__construct($admin_page);
66
-        $this->_status = $this->_admin_page->get_registration_status_array();
67
-    }
68
-
69
-
70
-
71
-    /**
72
-     *    _setup_data
73
-     *
74
-     * @access protected
75
-     * @return void
76
-     */
77
-    protected function _setup_data()
78
-    {
79
-        $this->_data = $this->_admin_page->get_registrations($this->_per_page);
80
-        $this->_all_data_count = $this->_admin_page->get_registrations($this->_per_page, true, false, false);
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     *    _set_properties
87
-     *
88
-     * @access protected
89
-     * @return void
90
-     */
91
-    protected function _set_properties()
92
-    {
93
-        $this->_wp_list_args = array(
94
-            'singular' => __('registration', 'event_espresso'),
95
-            'plural'   => __('registrations', 'event_espresso'),
96
-            'ajax'     => true,
97
-            'screen'   => $this->_admin_page->get_current_screen()->id,
98
-        );
99
-        $ID_column_name = __('ID', 'event_espresso');
100
-        $ID_column_name .= ' : <span class="show-on-mobile-view-only" style="float:none">';
101
-        $ID_column_name .= __('Registrant Name', 'event_espresso');
102
-        $ID_column_name .= '</span> ';
103
-        if (isset($_GET['event_id'])) {
104
-            $this->_columns = array(
105
-                'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
106
-                '_REG_ID'          => $ID_column_name,
107
-                'ATT_fname'        => __('Name', 'event_espresso'),
108
-                'ATT_email'        => __('Email', 'event_espresso'),
109
-                '_REG_date'        => __('Reg Date', 'event_espresso'),
110
-                'PRC_amount'       => __('TKT Price', 'event_espresso'),
111
-                '_REG_final_price' => __('Final Price', 'event_espresso'),
112
-                'TXN_total'        => __('Total Txn', 'event_espresso'),
113
-                'TXN_paid'         => __('Paid', 'event_espresso'),
114
-                'actions'          => __('Actions', 'event_espresso'),
115
-            );
116
-            $this->_bottom_buttons = array(
117
-                'report' => array(
118
-                    'route'         => 'registrations_report',
119
-                    'extra_request' => array(
120
-                        'EVT_ID'     => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
121
-                        'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
122
-                    ),
123
-                ),
124
-            );
125
-        } else {
126
-            $this->_columns = array(
127
-                'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
128
-                '_REG_ID'          => $ID_column_name,
129
-                'ATT_fname'        => __('Name', 'event_espresso'),
130
-                '_REG_date'        => __('TXN Date', 'event_espresso'),
131
-                'event_name'       => __('Event', 'event_espresso'),
132
-                'DTT_EVT_start'    => __('Event Date', 'event_espresso'),
133
-                '_REG_final_price' => __('Price', 'event_espresso'),
134
-                '_REG_paid'        => __('Paid', 'event_espresso'),
135
-                'actions'          => __('Actions', 'event_espresso'),
136
-            );
137
-            $this->_bottom_buttons = array(
138
-                'report_all' => array(
139
-                    'route'         => 'registrations_report',
140
-                    'extra_request' => array(
141
-                        'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
142
-                    ),
143
-                ),
144
-            );
145
-        }
146
-        $this->_primary_column = '_REG_ID';
147
-        $this->_sortable_columns = array(
148
-            '_REG_date'     => array('_REG_date' => true),   //true means its already sorted
149
-            'ATT_fname'     => array('ATT_fname' => false),
150
-            'event_name'    => array('event_name' => false),
151
-            'DTT_EVT_start' => array('DTT_EVT_start' => false),
152
-            '_REG_ID'       => array('_REG_ID' => false),
153
-        );
154
-        $this->_hidden_columns = array();
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * This simply sets up the row class for the table rows.
161
-     * Allows for easier overriding of child methods for setting up sorting.
162
-     *
163
-     * @param  EE_Registration $item the current item
164
-     * @return string
165
-     */
166
-    protected function _get_row_class($item)
167
-    {
168
-        $class = parent::_get_row_class($item);
169
-        //add status class
170
-        $class .= ' ee-status-strip reg-status-' . $item->status_ID();
171
-        if ($this->_has_checkbox_column) {
172
-            $class .= ' has-checkbox-column';
173
-        }
174
-        return $class;
175
-    }
176
-
177
-
178
-
179
-    /**
180
-     * Set the $_transaction_details property if not set yet.
181
-     *
182
-     * @param EE_Registration $registration
183
-     * @throws \EE_Error
184
-     */
185
-    protected function _set_related_details(EE_Registration $registration)
186
-    {
187
-        $transaction = $registration->get_first_related('Transaction');
188
-        $status = $transaction instanceof EE_Transaction ? $transaction->status_ID()
189
-            : EEM_Transaction::failed_status_code;
190
-        $this->_transaction_details = array(
191
-            'transaction' => $transaction,
192
-            'status'      => $status,
193
-            'id'          => $transaction instanceof EE_Transaction ? $transaction->ID() : 0,
194
-            'title_attr'  => sprintf(__('View Transaction Details (%s)', 'event_espresso'),
195
-                EEH_Template::pretty_status($status, false, 'sentence')),
196
-        );
197
-        try {
198
-            $event = $registration->event();
199
-        } catch (\EventEspresso\core\exceptions\EntityNotFoundException $e) {
200
-            $event = null;
201
-        }
202
-        $status = $event instanceof EE_Event ? $event->get_active_status() : EE_Datetime::inactive;
203
-        $this->_event_details = array(
204
-            'event'      => $event,
205
-            'status'     => $status,
206
-            'id'         => $event instanceof EE_Event ? $event->ID() : 0,
207
-            'title_attr' => sprintf(__('Edit Event (%s)', 'event_espresso'),
208
-                EEH_Template::pretty_status($status, false, 'sentence')),
209
-        );
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     *    _get_table_filters
216
-     *
217
-     * @access protected
218
-     * @return array
219
-     */
220
-    protected function _get_table_filters()
221
-    {
222
-        $filters = array();
223
-        //todo we're currently using old functions here. We need to move things into the Events_Admin_Page() class as methods.
224
-        $cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
225
-        $cur_category = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
226
-        $reg_status = isset($this->_req_data['_reg_status']) ? $this->_req_data['_reg_status'] : '';
227
-        $filters[] = EEH_Form_Fields::generate_registration_months_dropdown($cur_date, $reg_status, $cur_category);
228
-        $filters[] = EEH_Form_Fields::generate_event_category_dropdown($cur_category);
229
-        $status = array();
230
-        $status[] = array('id' => 0, 'text' => __('Select Status', 'event_espresso'));
231
-        foreach ($this->_status as $key => $value) {
232
-            $status[] = array('id' => $key, 'text' => $value);
233
-        }
234
-        if ($this->_view !== 'incomplete') {
235
-            $filters[] = EEH_Form_Fields::select_input('_reg_status', $status,
236
-                isset($this->_req_data['_reg_status']) ? strtoupper(sanitize_key($this->_req_data['_reg_status']))
237
-                    : '');
238
-        }
239
-        if (isset($this->_req_data['event_id'])) {
240
-            $filters[] = EEH_Form_Fields::hidden_input('event_id', $this->_req_data['event_id'], 'reg_event_id');
241
-        }
242
-        return $filters;
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     *    _add_view_counts
249
-     *
250
-     * @access protected
251
-     * @return void
252
-     * @throws \EE_Error
253
-     */
254
-    protected function _add_view_counts()
255
-    {
256
-        $this->_views['all']['count'] = $this->_total_registrations();
257
-        $this->_views['month']['count'] = $this->_total_registrations_this_month();
258
-        $this->_views['today']['count'] = $this->_total_registrations_today();
259
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
260
-            'espresso_registrations_trash_registrations')
261
-        ) {
262
-            $this->_views['incomplete']['count'] = $this->_total_registrations('incomplete');
263
-            $this->_views['trash']['count'] = $this->_total_registrations('trash');
264
-        }
265
-    }
266
-
267
-
268
-
269
-    /**
270
-     * _total_registrations
271
-     *
272
-     * @access protected
273
-     * @param string $view
274
-     * @return int
275
-     * @throws \EE_Error
276
-     */
277
-    protected function _total_registrations($view = '')
278
-    {
279
-        $_where = array();
280
-        $EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
281
-        if ($EVT_ID) {
282
-            $_where['EVT_ID'] = $EVT_ID;
283
-        }
284
-        switch ($view) {
285
-            case 'trash' :
286
-                return EEM_Registration::instance()->count_deleted(array($_where));
287
-                break;
288
-            case 'incomplete' :
289
-                $_where['STS_ID'] = EEM_Registration::status_id_incomplete;
290
-                break;
291
-            default :
292
-                $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
293
-        }
294
-        return EEM_Registration::instance()->count(array($_where));
295
-    }
296
-
297
-
298
-
299
-    /**
300
-     * _total_registrations_this_month
301
-     *
302
-     * @access protected
303
-     * @return int
304
-     * @throws \EE_Error
305
-     */
306
-    protected function _total_registrations_this_month()
307
-    {
308
-        $EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
309
-        $_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
310
-        $this_year_r = date('Y', current_time('timestamp'));
311
-        $time_start = ' 00:00:00';
312
-        $time_end = ' 23:59:59';
313
-        $this_month_r = date('m', current_time('timestamp'));
314
-        $days_this_month = date('t', current_time('timestamp'));
315
-        //setup date query.
316
-        $beginning_string = EEM_Registration::instance()
317
-                                            ->convert_datetime_for_query('REG_date',
318
-                                                $this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start,
319
-                                                'Y-m-d H:i:s');
320
-        $end_string = EEM_Registration::instance()
321
-                                      ->convert_datetime_for_query('REG_date',
322
-                                          $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
323
-                                          'Y-m-d H:i:s');
324
-        $_where['REG_date'] = array(
325
-            'BETWEEN',
326
-            array(
327
-                $beginning_string,
328
-                $end_string,
329
-            ),
330
-        );
331
-        $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
332
-        return EEM_Registration::instance()->count(array($_where));
333
-    }
334
-
335
-
336
-
337
-    /**
338
-     * _total_registrations_today
339
-     *
340
-     * @access protected
341
-     * @return int
342
-     * @throws \EE_Error
343
-     */
344
-    protected function _total_registrations_today()
345
-    {
346
-        $EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
347
-        $_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
348
-        $current_date = date('Y-m-d', current_time('timestamp'));
349
-        $time_start = ' 00:00:00';
350
-        $time_end = ' 23:59:59';
351
-        $_where['REG_date'] = array(
352
-            'BETWEEN',
353
-            array(
354
-                EEM_Registration::instance()
355
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_start, 'Y-m-d H:i:s'),
356
-                EEM_Registration::instance()
357
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_end, 'Y-m-d H:i:s'),
358
-            ),
359
-        );
360
-        $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
361
-        return EEM_Registration::instance()->count(array($_where));
362
-    }
363
-
364
-
365
-
366
-    /**
367
-     * column_cb
368
-     *
369
-     * @access public
370
-     * @param \EE_Registration $item
371
-     * @return string
372
-     * @throws \EE_Error
373
-     */
374
-    public function column_cb($item)
375
-    {
376
-        /** checkbox/lock **/
377
-        $transaction = $item->get_first_related('Transaction');
378
-        $payment_count = $transaction instanceof EE_Transaction ? $transaction->count_related('Payment') : 0;
379
-        return $payment_count > 0 ? sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID())
380
-                                    . '<span class="ee-lock-icon"></span>'
381
-            : sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID());
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * column__REG_ID
388
-     *
389
-     * @access public
390
-     * @param \EE_Registration $item
391
-     * @return string
392
-     * @throws \EE_Error
393
-     */
394
-    public function column__REG_ID(EE_Registration $item)
395
-    {
396
-        $attendee = $item->attendee();
397
-        $content = $item->ID();
398
-        $content .= '<div class="show-on-mobile-view-only">';
399
-        $content .= '<br>';
400
-        $content .= $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
401
-        $content .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
402
-        $content .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
403
-        $content .= '</div>';
404
-        return $content;
405
-    }
406
-
407
-
408
-
409
-    /**
410
-     * column__REG_date
411
-     *
412
-     * @access public
413
-     * @param \EE_Registration $item
414
-     * @return string
415
-     * @throws \EE_Error
416
-     */
417
-    public function column__REG_date(EE_Registration $item)
418
-    {
419
-        $this->_set_related_details($item);
420
-        //Build row actions
421
-        $view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
422
-            'action' => 'view_transaction',
423
-            'TXN_ID' => $this->_transaction_details['id'],
424
-        ), TXN_ADMIN_URL);
425
-        $view_link = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
426
-            'espresso_transactions_view_transaction') ? '<a class="ee-status-color-'
427
-                                                        . $this->_transaction_details['status']
428
-                                                        . '" href="'
429
-                                                        . $view_lnk_url
430
-                                                        . '" title="'
431
-                                                        . esc_attr($this->_transaction_details['title_attr'])
432
-                                                        . '">'
433
-                                                        . $item->get_i18n_datetime('REG_date')
434
-                                                        . '</a>' : $item->get_i18n_datetime('REG_date');
435
-        $view_link .= '<br><span class="ee-status-text-small">'
436
-                      . EEH_Template::pretty_status($this->_transaction_details['status'], false, 'sentence')
437
-                      . '</span>';
438
-        return $view_link;
439
-    }
440
-
441
-
442
-
443
-    /**
444
-     * column_event_name
445
-     *
446
-     * @access public
447
-     * @param \EE_Registration $item
448
-     * @return string
449
-     * @throws \EE_Error
450
-     */
451
-    public function column_event_name(EE_Registration $item)
452
-    {
453
-        $this->_set_related_details($item);
454
-        // page=espresso_events&action=edit_event&EVT_ID=2&edit_event_nonce=cf3a7e5b62
455
-        $EVT_ID = $item->event_ID();
456
-        $event_name = $item->event_name();
457
-        $event_name = $event_name ? $event_name : __("No Associated Event", 'event_espresso');
458
-        $event_name = wp_trim_words($event_name, 30, '...');
459
-        if ($EVT_ID) {
460
-            $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'edit', 'post' => $EVT_ID),
461
-                EVENTS_ADMIN_URL);
462
-            $edit_event = EE_Registry::instance()->CAP->current_user_can('ee_edit_event', 'edit_event', $EVT_ID)
463
-                ? '<a class="ee-status-color-'
464
-                  . $this->_event_details['status']
465
-                  . '" href="'
466
-                  . $edit_event_url
467
-                  . '" title="'
468
-                  . esc_attr($this->_event_details['title_attr'])
469
-                  . '">'
470
-                  . $event_name
471
-                  . '</a>' : $event_name;
472
-            $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('event_id' => $EVT_ID), REG_ADMIN_URL);
473
-            $actions['event_filter'] = '<a href="' . $edit_event_url . '" title="';
474
-            $actions['event_filter'] .= sprintf(esc_attr__('Filter this list to only show registrations for %s',
475
-                'event_espresso'), $event_name);
476
-            $actions['event_filter'] .= '">' . __('View Registrations', 'event_espresso') . '</a>';
477
-        } else {
478
-            $edit_event = $event_name;
479
-            $actions['event_filter'] = '';
480
-        }
481
-        return sprintf('%1$s %2$s', $edit_event, $this->row_actions($actions));
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     * column_DTT_EVT_start
488
-     *
489
-     * @access public
490
-     * @param \EE_Registration $item
491
-     * @return string
492
-     * @throws \EE_Error
493
-     */
494
-    public function column_DTT_EVT_start(EE_Registration $item)
495
-    {
496
-        $datetime_strings = array();
497
-        $ticket = $item->ticket(true);
498
-        if ($ticket instanceof EE_Ticket) {
499
-            $remove_defaults = array('default_where_conditions' => 'none');
500
-            $datetimes = $ticket->datetimes($remove_defaults);
501
-            foreach ($datetimes as $datetime) {
502
-                $datetime_strings[] = $datetime->get_i18n_datetime('DTT_EVT_start');
503
-            }
504
-            return implode("<br />", $datetime_strings);
505
-        } else {
506
-            return __('There is no ticket on this registration', 'event_espresso');
507
-        }
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * column_ATT_fname
514
-     *
515
-     * @access public
516
-     * @param \EE_Registration $item
517
-     * @return string
518
-     * @throws \EE_Error
519
-     */
520
-    public function column_ATT_fname(EE_Registration $item)
521
-    {
522
-        $attendee = $item->attendee();
523
-        $edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
524
-            'action'  => 'view_registration',
525
-            '_REG_ID' => $item->ID(),
526
-        ), REG_ADMIN_URL);
527
-        $attendee_name = $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
528
-        $link = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
529
-            'espresso_registrations_view_registration', $item->ID()) ? '<a href="'
530
-                                                                       . $edit_lnk_url
531
-                                                                       . '" title="'
532
-                                                                       . esc_attr__('View Registration Details',
533
-                'event_espresso')
534
-                                                                       . '">'
535
-                                                                       . $attendee_name
536
-                                                                       . '</a>' : $attendee_name;
537
-        $link .= $item->count() === 1
538
-            ? '&nbsp;<sup><div class="dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8"></div></sup>' : '';
539
-        $t = $item->get_first_related('Transaction');
540
-        $payment_count = $t instanceof EE_Transaction ? $t->count_related('Payment') : 0;
541
-        //append group count to name
542
-        $link .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
543
-        //append reg_code
544
-        $link .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
545
-        //reg status text for accessibility
546
-        $link .= '<br><span class="ee-status-text-small">' . EEH_Template::pretty_status($item->status_ID(), false,
547
-                'sentence') . '</span>';
548
-        //trash/restore/delete actions
549
-        $actions = array();
550
-        if ($this->_view !== 'trash'
551
-            && $payment_count === 0
552
-            && EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
553
-                'espresso_registrations_trash_registrations', $item->ID())
554
-        ) {
555
-            $trash_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
556
-                'action'  => 'trash_registrations',
557
-                '_REG_ID' => $item->ID(),
558
-            ), REG_ADMIN_URL);
559
-            $actions['trash'] = '<a href="' . $trash_lnk_url . '" title="' . esc_attr__('Trash Registration',
560
-                    'event_espresso') . '">' . __('Trash', 'event_espresso') . '</a>';
561
-        } elseif ($this->_view === 'trash') {
562
-            // restore registration link
563
-            if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
564
-                'espresso_registrations_restore_registrations', $item->ID())
565
-            ) {
566
-                $restore_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
567
-                    'action'  => 'restore_registrations',
568
-                    '_REG_ID' => $item->ID(),
569
-                ), REG_ADMIN_URL);
570
-                $actions['restore'] = '<a href="' . $restore_lnk_url . '" title="' . esc_attr__('Restore Registration',
571
-                        'event_espresso') . '">' . __('Restore', 'event_espresso') . '</a>';
572
-            }
573
-            if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
574
-                'espresso_registrations_ee_delete_registrations', $item->ID())
575
-            ) {
576
-                $delete_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
577
-                    'action'  => 'delete_registrations',
578
-                    '_REG_ID' => $item->ID(),
579
-                ), REG_ADMIN_URL);
580
-                $actions['delete'] = '<a href="'
581
-                                     . $delete_lnk_url
582
-                                     . '" title="'
583
-                                     . esc_attr__('Delete Registration Permanently', 'event_espresso')
584
-                                     . '">'
585
-                                     . __('Delete', 'event_espresso')
586
-                                     . '</a>';
587
-            }
588
-        }
589
-        return sprintf('%1$s %2$s', $link, $this->row_actions($actions));
590
-    }
591
-
592
-
593
-
594
-    /**
595
-     * column_ATT_email
596
-     *
597
-     * @access public
598
-     * @param \EE_Registration $item
599
-     * @return string
600
-     * @throws \EE_Error
601
-     */
602
-    public function column_ATT_email(EE_Registration $item)
603
-    {
604
-        $attendee = $item->get_first_related('Attendee');
605
-        return ! $attendee instanceof EE_Attendee ? __('No attached contact record.', 'event_espresso')
606
-            : $attendee->email();
607
-    }
608
-
609
-
610
-
611
-    /**
612
-     * column__REG_count
613
-     *
614
-     * @access public
615
-     * @param \EE_Registration $item
616
-     * @return string
617
-     */
618
-    public function column__REG_count(EE_Registration $item)
619
-    {
620
-        return sprintf(__('%1$s / %2$s', 'event_espresso'), $item->count(), $item->group_size());
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * column_PRC_amount
627
-     *
628
-     * @access public
629
-     * @param \EE_Registration $item
630
-     * @return string
631
-     */
632
-    public function column_PRC_amount(EE_Registration $item)
633
-    {
634
-        $ticket = $item->ticket();
635
-        $content = isset($_GET['event_id']) && $ticket instanceof EE_Ticket ? '<span class="TKT_name">'
636
-                                                                              . $ticket->name()
637
-                                                                              . '</span><br />' : '';
638
-        if ($item->final_price() > 0) {
639
-            $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
640
-        } else {
641
-            // free event
642
-            $content .= '<span class="reg-overview-free-event-spn reg-pad-rght">'
643
-                        . __('free', 'event_espresso')
644
-                        . '</span>';
645
-        }
646
-        return $content;
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * column__REG_final_price
653
-     *
654
-     * @access public
655
-     * @param \EE_Registration $item
656
-     * @return string
657
-     */
658
-    public function column__REG_final_price(EE_Registration $item)
659
-    {
660
-        $ticket = $item->ticket();
661
-        $content = isset($_GET['event_id']) || ! $ticket instanceof EE_Ticket
662
-            ? ''
663
-            : '<span class="TKT_name">'
664
-              . $ticket->name()
665
-              . '</span><br />';
666
-        $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
667
-        return $content;
668
-    }
669
-
670
-
671
-
672
-    /**
673
-     * column__REG_paid
674
-     *
675
-     * @access public
676
-     * @param \EE_Registration $item
677
-     * @return string
678
-     */
679
-    public function column__REG_paid(EE_Registration $item)
680
-    {
681
-        $payment_method = $item->payment_method();
682
-        $payment_method_name = $payment_method instanceof EE_Payment_Method ? $payment_method->admin_name()
683
-            : __('Unknown', 'event_espresso');
684
-        $content = '<span class="reg-pad-rght">' . $item->pretty_paid() . '</span>';
685
-        if ($item->paid() > 0) {
686
-            $content .= '<br><span class="ee-status-text-small">' . sprintf(__('...via %s', 'event_espresso'),
687
-                    $payment_method_name) . '</span>';
688
-        }
689
-        return $content;
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     * column_TXN_total
696
-     *
697
-     * @access public
698
-     * @param \EE_Registration $item
699
-     * @return string
700
-     * @throws \EE_Error
701
-     */
702
-    public function column_TXN_total(EE_Registration $item)
703
-    {
704
-        if ($item->transaction()) {
705
-            $view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
706
-                'action' => 'view_transaction',
707
-                'TXN_ID' => $item->transaction_ID(),
708
-            ), TXN_ADMIN_URL);
709
-            return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
710
-                'espresso_transactions_view_transaction', $item->transaction_ID())
711
-                ? '<span class="reg-pad-rght"><a class="status-'
712
-                  . $item->transaction()->status_ID()
713
-                  . '" href="'
714
-                  . $view_txn_lnk_url
715
-                  . '"  title="'
716
-                  . esc_attr__('View Transaction', 'event_espresso')
717
-                  . '">'
718
-                  . $item->transaction()->pretty_total()
719
-                  . '</a></span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_total() . '</span>';
720
-        } else {
721
-            return __("None", "event_espresso");
722
-        }
723
-    }
724
-
725
-
726
-
727
-    /**
728
-     * column_TXN_paid
729
-     *
730
-     * @access public
731
-     * @param \EE_Registration $item
732
-     * @return string
733
-     * @throws \EE_Error
734
-     */
735
-    public function column_TXN_paid(EE_Registration $item)
736
-    {
737
-        if ($item->count() === 1) {
738
-            $transaction = $item->transaction() ? $item->transaction() : EE_Transaction::new_instance();
739
-            if ($transaction->paid() >= $transaction->total()) {
740
-                return '<span class="reg-pad-rght"><div class="dashicons dashicons-yes green-icon"></div></span>';
741
-            } else {
742
-                $view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
743
-                    'action' => 'view_transaction',
744
-                    'TXN_ID' => $item->transaction_ID(),
745
-                ), TXN_ADMIN_URL);
746
-                return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
747
-                    'espresso_transactions_view_transaction', $item->transaction_ID())
748
-                    ? '<span class="reg-pad-rght"><a class="status-'
749
-                      . $transaction->status_ID()
750
-                      . '" href="'
751
-                      . $view_txn_lnk_url
752
-                      . '"  title="'
753
-                      . esc_attr__('View Transaction', 'event_espresso')
754
-                      . '">'
755
-                      . $item->transaction()->pretty_paid()
756
-                      . '</a><span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_paid() . '</span>';
757
-            }
758
-        }
759
-        return '&nbsp;';
760
-    }
761
-
762
-
763
-
764
-    /**
765
-     * column_actions
766
-     *
767
-     * @access public
768
-     * @param \EE_Registration $item
769
-     * @return string
770
-     * @throws \EE_Error
771
-     */
772
-    public function column_actions(EE_Registration $item)
773
-    {
774
-        $actions = array();
775
-        $attendee = $item->attendee();
776
-        $this->_set_related_details($item);
777
-        //Build row actions
778
-        $view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
779
-            'action'  => 'view_registration',
780
-            '_REG_ID' => $item->ID(),
781
-        ), REG_ADMIN_URL);
782
-        $edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
783
-            'action' => 'edit_attendee',
784
-            'post'   => $item->attendee_ID(),
785
-        ), REG_ADMIN_URL);
786
-        // page=attendees&event_admin_reports=resend_email&registration_id=43653465634&event_id=2&form_action=resend_email
787
-        //$resend_reg_lnk_url_params = array( 'action'=>'resend_registration', '_REG_ID'=>$item->REG_ID );
788
-        $resend_reg_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
789
-            'action'  => 'resend_registration',
790
-            '_REG_ID' => $item->ID(),
791
-        ), REG_ADMIN_URL, true);
792
-        //Build row actions
793
-        $actions['view_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
794
-            'espresso_registrations_view_registration', $item->ID()) ? '
29
+	private $_status;
30
+
31
+
32
+
33
+	/**
34
+	 * An array of transaction details for the related transaction to the registration being processed.
35
+	 * This is set via the _set_related_details method.
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected $_transaction_details = array();
40
+
41
+
42
+
43
+	/**
44
+	 * An array of event details for the related event to the registration being processed.
45
+	 * This is set via the _set_related_details method.
46
+	 *
47
+	 * @var array
48
+	 */
49
+	protected $_event_details = array();
50
+
51
+
52
+
53
+	/**
54
+	 * @param \Registrations_Admin_Page $admin_page
55
+	 */
56
+	public function __construct(Registrations_Admin_Page $admin_page)
57
+	{
58
+		if ( ! empty($_GET['event_id'])) {
59
+			$extra_query_args = array();
60
+			foreach ($admin_page->get_views() as $key => $view_details) {
61
+				$extra_query_args[$view_details['slug']] = array('event_id' => $_GET['event_id']);
62
+			}
63
+			$this->_views = $admin_page->get_list_table_view_RLs($extra_query_args);
64
+		}
65
+		parent::__construct($admin_page);
66
+		$this->_status = $this->_admin_page->get_registration_status_array();
67
+	}
68
+
69
+
70
+
71
+	/**
72
+	 *    _setup_data
73
+	 *
74
+	 * @access protected
75
+	 * @return void
76
+	 */
77
+	protected function _setup_data()
78
+	{
79
+		$this->_data = $this->_admin_page->get_registrations($this->_per_page);
80
+		$this->_all_data_count = $this->_admin_page->get_registrations($this->_per_page, true, false, false);
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 *    _set_properties
87
+	 *
88
+	 * @access protected
89
+	 * @return void
90
+	 */
91
+	protected function _set_properties()
92
+	{
93
+		$this->_wp_list_args = array(
94
+			'singular' => __('registration', 'event_espresso'),
95
+			'plural'   => __('registrations', 'event_espresso'),
96
+			'ajax'     => true,
97
+			'screen'   => $this->_admin_page->get_current_screen()->id,
98
+		);
99
+		$ID_column_name = __('ID', 'event_espresso');
100
+		$ID_column_name .= ' : <span class="show-on-mobile-view-only" style="float:none">';
101
+		$ID_column_name .= __('Registrant Name', 'event_espresso');
102
+		$ID_column_name .= '</span> ';
103
+		if (isset($_GET['event_id'])) {
104
+			$this->_columns = array(
105
+				'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
106
+				'_REG_ID'          => $ID_column_name,
107
+				'ATT_fname'        => __('Name', 'event_espresso'),
108
+				'ATT_email'        => __('Email', 'event_espresso'),
109
+				'_REG_date'        => __('Reg Date', 'event_espresso'),
110
+				'PRC_amount'       => __('TKT Price', 'event_espresso'),
111
+				'_REG_final_price' => __('Final Price', 'event_espresso'),
112
+				'TXN_total'        => __('Total Txn', 'event_espresso'),
113
+				'TXN_paid'         => __('Paid', 'event_espresso'),
114
+				'actions'          => __('Actions', 'event_espresso'),
115
+			);
116
+			$this->_bottom_buttons = array(
117
+				'report' => array(
118
+					'route'         => 'registrations_report',
119
+					'extra_request' => array(
120
+						'EVT_ID'     => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
121
+						'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
122
+					),
123
+				),
124
+			);
125
+		} else {
126
+			$this->_columns = array(
127
+				'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
128
+				'_REG_ID'          => $ID_column_name,
129
+				'ATT_fname'        => __('Name', 'event_espresso'),
130
+				'_REG_date'        => __('TXN Date', 'event_espresso'),
131
+				'event_name'       => __('Event', 'event_espresso'),
132
+				'DTT_EVT_start'    => __('Event Date', 'event_espresso'),
133
+				'_REG_final_price' => __('Price', 'event_espresso'),
134
+				'_REG_paid'        => __('Paid', 'event_espresso'),
135
+				'actions'          => __('Actions', 'event_espresso'),
136
+			);
137
+			$this->_bottom_buttons = array(
138
+				'report_all' => array(
139
+					'route'         => 'registrations_report',
140
+					'extra_request' => array(
141
+						'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
142
+					),
143
+				),
144
+			);
145
+		}
146
+		$this->_primary_column = '_REG_ID';
147
+		$this->_sortable_columns = array(
148
+			'_REG_date'     => array('_REG_date' => true),   //true means its already sorted
149
+			'ATT_fname'     => array('ATT_fname' => false),
150
+			'event_name'    => array('event_name' => false),
151
+			'DTT_EVT_start' => array('DTT_EVT_start' => false),
152
+			'_REG_ID'       => array('_REG_ID' => false),
153
+		);
154
+		$this->_hidden_columns = array();
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * This simply sets up the row class for the table rows.
161
+	 * Allows for easier overriding of child methods for setting up sorting.
162
+	 *
163
+	 * @param  EE_Registration $item the current item
164
+	 * @return string
165
+	 */
166
+	protected function _get_row_class($item)
167
+	{
168
+		$class = parent::_get_row_class($item);
169
+		//add status class
170
+		$class .= ' ee-status-strip reg-status-' . $item->status_ID();
171
+		if ($this->_has_checkbox_column) {
172
+			$class .= ' has-checkbox-column';
173
+		}
174
+		return $class;
175
+	}
176
+
177
+
178
+
179
+	/**
180
+	 * Set the $_transaction_details property if not set yet.
181
+	 *
182
+	 * @param EE_Registration $registration
183
+	 * @throws \EE_Error
184
+	 */
185
+	protected function _set_related_details(EE_Registration $registration)
186
+	{
187
+		$transaction = $registration->get_first_related('Transaction');
188
+		$status = $transaction instanceof EE_Transaction ? $transaction->status_ID()
189
+			: EEM_Transaction::failed_status_code;
190
+		$this->_transaction_details = array(
191
+			'transaction' => $transaction,
192
+			'status'      => $status,
193
+			'id'          => $transaction instanceof EE_Transaction ? $transaction->ID() : 0,
194
+			'title_attr'  => sprintf(__('View Transaction Details (%s)', 'event_espresso'),
195
+				EEH_Template::pretty_status($status, false, 'sentence')),
196
+		);
197
+		try {
198
+			$event = $registration->event();
199
+		} catch (\EventEspresso\core\exceptions\EntityNotFoundException $e) {
200
+			$event = null;
201
+		}
202
+		$status = $event instanceof EE_Event ? $event->get_active_status() : EE_Datetime::inactive;
203
+		$this->_event_details = array(
204
+			'event'      => $event,
205
+			'status'     => $status,
206
+			'id'         => $event instanceof EE_Event ? $event->ID() : 0,
207
+			'title_attr' => sprintf(__('Edit Event (%s)', 'event_espresso'),
208
+				EEH_Template::pretty_status($status, false, 'sentence')),
209
+		);
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 *    _get_table_filters
216
+	 *
217
+	 * @access protected
218
+	 * @return array
219
+	 */
220
+	protected function _get_table_filters()
221
+	{
222
+		$filters = array();
223
+		//todo we're currently using old functions here. We need to move things into the Events_Admin_Page() class as methods.
224
+		$cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
225
+		$cur_category = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
226
+		$reg_status = isset($this->_req_data['_reg_status']) ? $this->_req_data['_reg_status'] : '';
227
+		$filters[] = EEH_Form_Fields::generate_registration_months_dropdown($cur_date, $reg_status, $cur_category);
228
+		$filters[] = EEH_Form_Fields::generate_event_category_dropdown($cur_category);
229
+		$status = array();
230
+		$status[] = array('id' => 0, 'text' => __('Select Status', 'event_espresso'));
231
+		foreach ($this->_status as $key => $value) {
232
+			$status[] = array('id' => $key, 'text' => $value);
233
+		}
234
+		if ($this->_view !== 'incomplete') {
235
+			$filters[] = EEH_Form_Fields::select_input('_reg_status', $status,
236
+				isset($this->_req_data['_reg_status']) ? strtoupper(sanitize_key($this->_req_data['_reg_status']))
237
+					: '');
238
+		}
239
+		if (isset($this->_req_data['event_id'])) {
240
+			$filters[] = EEH_Form_Fields::hidden_input('event_id', $this->_req_data['event_id'], 'reg_event_id');
241
+		}
242
+		return $filters;
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 *    _add_view_counts
249
+	 *
250
+	 * @access protected
251
+	 * @return void
252
+	 * @throws \EE_Error
253
+	 */
254
+	protected function _add_view_counts()
255
+	{
256
+		$this->_views['all']['count'] = $this->_total_registrations();
257
+		$this->_views['month']['count'] = $this->_total_registrations_this_month();
258
+		$this->_views['today']['count'] = $this->_total_registrations_today();
259
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
260
+			'espresso_registrations_trash_registrations')
261
+		) {
262
+			$this->_views['incomplete']['count'] = $this->_total_registrations('incomplete');
263
+			$this->_views['trash']['count'] = $this->_total_registrations('trash');
264
+		}
265
+	}
266
+
267
+
268
+
269
+	/**
270
+	 * _total_registrations
271
+	 *
272
+	 * @access protected
273
+	 * @param string $view
274
+	 * @return int
275
+	 * @throws \EE_Error
276
+	 */
277
+	protected function _total_registrations($view = '')
278
+	{
279
+		$_where = array();
280
+		$EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
281
+		if ($EVT_ID) {
282
+			$_where['EVT_ID'] = $EVT_ID;
283
+		}
284
+		switch ($view) {
285
+			case 'trash' :
286
+				return EEM_Registration::instance()->count_deleted(array($_where));
287
+				break;
288
+			case 'incomplete' :
289
+				$_where['STS_ID'] = EEM_Registration::status_id_incomplete;
290
+				break;
291
+			default :
292
+				$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
293
+		}
294
+		return EEM_Registration::instance()->count(array($_where));
295
+	}
296
+
297
+
298
+
299
+	/**
300
+	 * _total_registrations_this_month
301
+	 *
302
+	 * @access protected
303
+	 * @return int
304
+	 * @throws \EE_Error
305
+	 */
306
+	protected function _total_registrations_this_month()
307
+	{
308
+		$EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
309
+		$_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
310
+		$this_year_r = date('Y', current_time('timestamp'));
311
+		$time_start = ' 00:00:00';
312
+		$time_end = ' 23:59:59';
313
+		$this_month_r = date('m', current_time('timestamp'));
314
+		$days_this_month = date('t', current_time('timestamp'));
315
+		//setup date query.
316
+		$beginning_string = EEM_Registration::instance()
317
+											->convert_datetime_for_query('REG_date',
318
+												$this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start,
319
+												'Y-m-d H:i:s');
320
+		$end_string = EEM_Registration::instance()
321
+									  ->convert_datetime_for_query('REG_date',
322
+										  $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
323
+										  'Y-m-d H:i:s');
324
+		$_where['REG_date'] = array(
325
+			'BETWEEN',
326
+			array(
327
+				$beginning_string,
328
+				$end_string,
329
+			),
330
+		);
331
+		$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
332
+		return EEM_Registration::instance()->count(array($_where));
333
+	}
334
+
335
+
336
+
337
+	/**
338
+	 * _total_registrations_today
339
+	 *
340
+	 * @access protected
341
+	 * @return int
342
+	 * @throws \EE_Error
343
+	 */
344
+	protected function _total_registrations_today()
345
+	{
346
+		$EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
347
+		$_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
348
+		$current_date = date('Y-m-d', current_time('timestamp'));
349
+		$time_start = ' 00:00:00';
350
+		$time_end = ' 23:59:59';
351
+		$_where['REG_date'] = array(
352
+			'BETWEEN',
353
+			array(
354
+				EEM_Registration::instance()
355
+								->convert_datetime_for_query('REG_date', $current_date . $time_start, 'Y-m-d H:i:s'),
356
+				EEM_Registration::instance()
357
+								->convert_datetime_for_query('REG_date', $current_date . $time_end, 'Y-m-d H:i:s'),
358
+			),
359
+		);
360
+		$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
361
+		return EEM_Registration::instance()->count(array($_where));
362
+	}
363
+
364
+
365
+
366
+	/**
367
+	 * column_cb
368
+	 *
369
+	 * @access public
370
+	 * @param \EE_Registration $item
371
+	 * @return string
372
+	 * @throws \EE_Error
373
+	 */
374
+	public function column_cb($item)
375
+	{
376
+		/** checkbox/lock **/
377
+		$transaction = $item->get_first_related('Transaction');
378
+		$payment_count = $transaction instanceof EE_Transaction ? $transaction->count_related('Payment') : 0;
379
+		return $payment_count > 0 ? sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID())
380
+									. '<span class="ee-lock-icon"></span>'
381
+			: sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID());
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * column__REG_ID
388
+	 *
389
+	 * @access public
390
+	 * @param \EE_Registration $item
391
+	 * @return string
392
+	 * @throws \EE_Error
393
+	 */
394
+	public function column__REG_ID(EE_Registration $item)
395
+	{
396
+		$attendee = $item->attendee();
397
+		$content = $item->ID();
398
+		$content .= '<div class="show-on-mobile-view-only">';
399
+		$content .= '<br>';
400
+		$content .= $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
401
+		$content .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
402
+		$content .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
403
+		$content .= '</div>';
404
+		return $content;
405
+	}
406
+
407
+
408
+
409
+	/**
410
+	 * column__REG_date
411
+	 *
412
+	 * @access public
413
+	 * @param \EE_Registration $item
414
+	 * @return string
415
+	 * @throws \EE_Error
416
+	 */
417
+	public function column__REG_date(EE_Registration $item)
418
+	{
419
+		$this->_set_related_details($item);
420
+		//Build row actions
421
+		$view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
422
+			'action' => 'view_transaction',
423
+			'TXN_ID' => $this->_transaction_details['id'],
424
+		), TXN_ADMIN_URL);
425
+		$view_link = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
426
+			'espresso_transactions_view_transaction') ? '<a class="ee-status-color-'
427
+														. $this->_transaction_details['status']
428
+														. '" href="'
429
+														. $view_lnk_url
430
+														. '" title="'
431
+														. esc_attr($this->_transaction_details['title_attr'])
432
+														. '">'
433
+														. $item->get_i18n_datetime('REG_date')
434
+														. '</a>' : $item->get_i18n_datetime('REG_date');
435
+		$view_link .= '<br><span class="ee-status-text-small">'
436
+					  . EEH_Template::pretty_status($this->_transaction_details['status'], false, 'sentence')
437
+					  . '</span>';
438
+		return $view_link;
439
+	}
440
+
441
+
442
+
443
+	/**
444
+	 * column_event_name
445
+	 *
446
+	 * @access public
447
+	 * @param \EE_Registration $item
448
+	 * @return string
449
+	 * @throws \EE_Error
450
+	 */
451
+	public function column_event_name(EE_Registration $item)
452
+	{
453
+		$this->_set_related_details($item);
454
+		// page=espresso_events&action=edit_event&EVT_ID=2&edit_event_nonce=cf3a7e5b62
455
+		$EVT_ID = $item->event_ID();
456
+		$event_name = $item->event_name();
457
+		$event_name = $event_name ? $event_name : __("No Associated Event", 'event_espresso');
458
+		$event_name = wp_trim_words($event_name, 30, '...');
459
+		if ($EVT_ID) {
460
+			$edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'edit', 'post' => $EVT_ID),
461
+				EVENTS_ADMIN_URL);
462
+			$edit_event = EE_Registry::instance()->CAP->current_user_can('ee_edit_event', 'edit_event', $EVT_ID)
463
+				? '<a class="ee-status-color-'
464
+				  . $this->_event_details['status']
465
+				  . '" href="'
466
+				  . $edit_event_url
467
+				  . '" title="'
468
+				  . esc_attr($this->_event_details['title_attr'])
469
+				  . '">'
470
+				  . $event_name
471
+				  . '</a>' : $event_name;
472
+			$edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('event_id' => $EVT_ID), REG_ADMIN_URL);
473
+			$actions['event_filter'] = '<a href="' . $edit_event_url . '" title="';
474
+			$actions['event_filter'] .= sprintf(esc_attr__('Filter this list to only show registrations for %s',
475
+				'event_espresso'), $event_name);
476
+			$actions['event_filter'] .= '">' . __('View Registrations', 'event_espresso') . '</a>';
477
+		} else {
478
+			$edit_event = $event_name;
479
+			$actions['event_filter'] = '';
480
+		}
481
+		return sprintf('%1$s %2$s', $edit_event, $this->row_actions($actions));
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 * column_DTT_EVT_start
488
+	 *
489
+	 * @access public
490
+	 * @param \EE_Registration $item
491
+	 * @return string
492
+	 * @throws \EE_Error
493
+	 */
494
+	public function column_DTT_EVT_start(EE_Registration $item)
495
+	{
496
+		$datetime_strings = array();
497
+		$ticket = $item->ticket(true);
498
+		if ($ticket instanceof EE_Ticket) {
499
+			$remove_defaults = array('default_where_conditions' => 'none');
500
+			$datetimes = $ticket->datetimes($remove_defaults);
501
+			foreach ($datetimes as $datetime) {
502
+				$datetime_strings[] = $datetime->get_i18n_datetime('DTT_EVT_start');
503
+			}
504
+			return implode("<br />", $datetime_strings);
505
+		} else {
506
+			return __('There is no ticket on this registration', 'event_espresso');
507
+		}
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * column_ATT_fname
514
+	 *
515
+	 * @access public
516
+	 * @param \EE_Registration $item
517
+	 * @return string
518
+	 * @throws \EE_Error
519
+	 */
520
+	public function column_ATT_fname(EE_Registration $item)
521
+	{
522
+		$attendee = $item->attendee();
523
+		$edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
524
+			'action'  => 'view_registration',
525
+			'_REG_ID' => $item->ID(),
526
+		), REG_ADMIN_URL);
527
+		$attendee_name = $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
528
+		$link = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
529
+			'espresso_registrations_view_registration', $item->ID()) ? '<a href="'
530
+																	   . $edit_lnk_url
531
+																	   . '" title="'
532
+																	   . esc_attr__('View Registration Details',
533
+				'event_espresso')
534
+																	   . '">'
535
+																	   . $attendee_name
536
+																	   . '</a>' : $attendee_name;
537
+		$link .= $item->count() === 1
538
+			? '&nbsp;<sup><div class="dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8"></div></sup>' : '';
539
+		$t = $item->get_first_related('Transaction');
540
+		$payment_count = $t instanceof EE_Transaction ? $t->count_related('Payment') : 0;
541
+		//append group count to name
542
+		$link .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
543
+		//append reg_code
544
+		$link .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
545
+		//reg status text for accessibility
546
+		$link .= '<br><span class="ee-status-text-small">' . EEH_Template::pretty_status($item->status_ID(), false,
547
+				'sentence') . '</span>';
548
+		//trash/restore/delete actions
549
+		$actions = array();
550
+		if ($this->_view !== 'trash'
551
+			&& $payment_count === 0
552
+			&& EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
553
+				'espresso_registrations_trash_registrations', $item->ID())
554
+		) {
555
+			$trash_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
556
+				'action'  => 'trash_registrations',
557
+				'_REG_ID' => $item->ID(),
558
+			), REG_ADMIN_URL);
559
+			$actions['trash'] = '<a href="' . $trash_lnk_url . '" title="' . esc_attr__('Trash Registration',
560
+					'event_espresso') . '">' . __('Trash', 'event_espresso') . '</a>';
561
+		} elseif ($this->_view === 'trash') {
562
+			// restore registration link
563
+			if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
564
+				'espresso_registrations_restore_registrations', $item->ID())
565
+			) {
566
+				$restore_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
567
+					'action'  => 'restore_registrations',
568
+					'_REG_ID' => $item->ID(),
569
+				), REG_ADMIN_URL);
570
+				$actions['restore'] = '<a href="' . $restore_lnk_url . '" title="' . esc_attr__('Restore Registration',
571
+						'event_espresso') . '">' . __('Restore', 'event_espresso') . '</a>';
572
+			}
573
+			if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
574
+				'espresso_registrations_ee_delete_registrations', $item->ID())
575
+			) {
576
+				$delete_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
577
+					'action'  => 'delete_registrations',
578
+					'_REG_ID' => $item->ID(),
579
+				), REG_ADMIN_URL);
580
+				$actions['delete'] = '<a href="'
581
+									 . $delete_lnk_url
582
+									 . '" title="'
583
+									 . esc_attr__('Delete Registration Permanently', 'event_espresso')
584
+									 . '">'
585
+									 . __('Delete', 'event_espresso')
586
+									 . '</a>';
587
+			}
588
+		}
589
+		return sprintf('%1$s %2$s', $link, $this->row_actions($actions));
590
+	}
591
+
592
+
593
+
594
+	/**
595
+	 * column_ATT_email
596
+	 *
597
+	 * @access public
598
+	 * @param \EE_Registration $item
599
+	 * @return string
600
+	 * @throws \EE_Error
601
+	 */
602
+	public function column_ATT_email(EE_Registration $item)
603
+	{
604
+		$attendee = $item->get_first_related('Attendee');
605
+		return ! $attendee instanceof EE_Attendee ? __('No attached contact record.', 'event_espresso')
606
+			: $attendee->email();
607
+	}
608
+
609
+
610
+
611
+	/**
612
+	 * column__REG_count
613
+	 *
614
+	 * @access public
615
+	 * @param \EE_Registration $item
616
+	 * @return string
617
+	 */
618
+	public function column__REG_count(EE_Registration $item)
619
+	{
620
+		return sprintf(__('%1$s / %2$s', 'event_espresso'), $item->count(), $item->group_size());
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * column_PRC_amount
627
+	 *
628
+	 * @access public
629
+	 * @param \EE_Registration $item
630
+	 * @return string
631
+	 */
632
+	public function column_PRC_amount(EE_Registration $item)
633
+	{
634
+		$ticket = $item->ticket();
635
+		$content = isset($_GET['event_id']) && $ticket instanceof EE_Ticket ? '<span class="TKT_name">'
636
+																			  . $ticket->name()
637
+																			  . '</span><br />' : '';
638
+		if ($item->final_price() > 0) {
639
+			$content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
640
+		} else {
641
+			// free event
642
+			$content .= '<span class="reg-overview-free-event-spn reg-pad-rght">'
643
+						. __('free', 'event_espresso')
644
+						. '</span>';
645
+		}
646
+		return $content;
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * column__REG_final_price
653
+	 *
654
+	 * @access public
655
+	 * @param \EE_Registration $item
656
+	 * @return string
657
+	 */
658
+	public function column__REG_final_price(EE_Registration $item)
659
+	{
660
+		$ticket = $item->ticket();
661
+		$content = isset($_GET['event_id']) || ! $ticket instanceof EE_Ticket
662
+			? ''
663
+			: '<span class="TKT_name">'
664
+			  . $ticket->name()
665
+			  . '</span><br />';
666
+		$content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
667
+		return $content;
668
+	}
669
+
670
+
671
+
672
+	/**
673
+	 * column__REG_paid
674
+	 *
675
+	 * @access public
676
+	 * @param \EE_Registration $item
677
+	 * @return string
678
+	 */
679
+	public function column__REG_paid(EE_Registration $item)
680
+	{
681
+		$payment_method = $item->payment_method();
682
+		$payment_method_name = $payment_method instanceof EE_Payment_Method ? $payment_method->admin_name()
683
+			: __('Unknown', 'event_espresso');
684
+		$content = '<span class="reg-pad-rght">' . $item->pretty_paid() . '</span>';
685
+		if ($item->paid() > 0) {
686
+			$content .= '<br><span class="ee-status-text-small">' . sprintf(__('...via %s', 'event_espresso'),
687
+					$payment_method_name) . '</span>';
688
+		}
689
+		return $content;
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 * column_TXN_total
696
+	 *
697
+	 * @access public
698
+	 * @param \EE_Registration $item
699
+	 * @return string
700
+	 * @throws \EE_Error
701
+	 */
702
+	public function column_TXN_total(EE_Registration $item)
703
+	{
704
+		if ($item->transaction()) {
705
+			$view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
706
+				'action' => 'view_transaction',
707
+				'TXN_ID' => $item->transaction_ID(),
708
+			), TXN_ADMIN_URL);
709
+			return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
710
+				'espresso_transactions_view_transaction', $item->transaction_ID())
711
+				? '<span class="reg-pad-rght"><a class="status-'
712
+				  . $item->transaction()->status_ID()
713
+				  . '" href="'
714
+				  . $view_txn_lnk_url
715
+				  . '"  title="'
716
+				  . esc_attr__('View Transaction', 'event_espresso')
717
+				  . '">'
718
+				  . $item->transaction()->pretty_total()
719
+				  . '</a></span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_total() . '</span>';
720
+		} else {
721
+			return __("None", "event_espresso");
722
+		}
723
+	}
724
+
725
+
726
+
727
+	/**
728
+	 * column_TXN_paid
729
+	 *
730
+	 * @access public
731
+	 * @param \EE_Registration $item
732
+	 * @return string
733
+	 * @throws \EE_Error
734
+	 */
735
+	public function column_TXN_paid(EE_Registration $item)
736
+	{
737
+		if ($item->count() === 1) {
738
+			$transaction = $item->transaction() ? $item->transaction() : EE_Transaction::new_instance();
739
+			if ($transaction->paid() >= $transaction->total()) {
740
+				return '<span class="reg-pad-rght"><div class="dashicons dashicons-yes green-icon"></div></span>';
741
+			} else {
742
+				$view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
743
+					'action' => 'view_transaction',
744
+					'TXN_ID' => $item->transaction_ID(),
745
+				), TXN_ADMIN_URL);
746
+				return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
747
+					'espresso_transactions_view_transaction', $item->transaction_ID())
748
+					? '<span class="reg-pad-rght"><a class="status-'
749
+					  . $transaction->status_ID()
750
+					  . '" href="'
751
+					  . $view_txn_lnk_url
752
+					  . '"  title="'
753
+					  . esc_attr__('View Transaction', 'event_espresso')
754
+					  . '">'
755
+					  . $item->transaction()->pretty_paid()
756
+					  . '</a><span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_paid() . '</span>';
757
+			}
758
+		}
759
+		return '&nbsp;';
760
+	}
761
+
762
+
763
+
764
+	/**
765
+	 * column_actions
766
+	 *
767
+	 * @access public
768
+	 * @param \EE_Registration $item
769
+	 * @return string
770
+	 * @throws \EE_Error
771
+	 */
772
+	public function column_actions(EE_Registration $item)
773
+	{
774
+		$actions = array();
775
+		$attendee = $item->attendee();
776
+		$this->_set_related_details($item);
777
+		//Build row actions
778
+		$view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
779
+			'action'  => 'view_registration',
780
+			'_REG_ID' => $item->ID(),
781
+		), REG_ADMIN_URL);
782
+		$edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
783
+			'action' => 'edit_attendee',
784
+			'post'   => $item->attendee_ID(),
785
+		), REG_ADMIN_URL);
786
+		// page=attendees&event_admin_reports=resend_email&registration_id=43653465634&event_id=2&form_action=resend_email
787
+		//$resend_reg_lnk_url_params = array( 'action'=>'resend_registration', '_REG_ID'=>$item->REG_ID );
788
+		$resend_reg_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
789
+			'action'  => 'resend_registration',
790
+			'_REG_ID' => $item->ID(),
791
+		), REG_ADMIN_URL, true);
792
+		//Build row actions
793
+		$actions['view_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
794
+			'espresso_registrations_view_registration', $item->ID()) ? '
795 795
 			<li>
796 796
 			<a href="' . $view_lnk_url . '" title="' . esc_attr__('View Registration Details', 'event_espresso') . '" class="tiny-text">
797 797
 				<div class="dashicons dashicons-clipboard"></div>
798 798
 			</a>
799 799
 			</li>' : '';
800
-        $actions['edit_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_contacts',
801
-            'espresso_registrations_edit_attendee')
802
-                               && $attendee instanceof EE_Attendee ? '
800
+		$actions['edit_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_contacts',
801
+			'espresso_registrations_edit_attendee')
802
+							   && $attendee instanceof EE_Attendee ? '
803 803
 			<li>
804 804
 			<a href="' . $edit_lnk_url . '" title="' . esc_attr__('Edit Contact Details', 'event_espresso') . '" class="tiny-text">
805 805
 				<div class="ee-icon ee-icon-user-edit ee-icon-size-16"></div>
806 806
 			</a>
807 807
 			</li>' : '';
808
-        $actions['resend_reg_lnk'] = $attendee instanceof EE_Attendee
809
-                                     && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
810
-            'espresso_registrations_resend_registration', $item->ID()) ? '
808
+		$actions['resend_reg_lnk'] = $attendee instanceof EE_Attendee
809
+									 && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
810
+			'espresso_registrations_resend_registration', $item->ID()) ? '
811 811
 			<li>
812 812
 			<a href="'
813
-                                                                         . $resend_reg_lnk_url
814
-                                                                         . '" title="'
815
-                                                                         . esc_attr__('Resend Registration Details',
816
-                'event_espresso')
817
-                                                                         . '" class="tiny-text">
813
+																		 . $resend_reg_lnk_url
814
+																		 . '" title="'
815
+																		 . esc_attr__('Resend Registration Details',
816
+				'event_espresso')
817
+																		 . '" class="tiny-text">
818 818
 				<div class="dashicons dashicons-email-alt"></div>
819 819
 			</a>
820 820
 			</li>' : '';
821
-        // page=transactions&action=view_transaction&txn=256&_wpnonce=6414da4dbb
822
-        $view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
823
-            'action' => 'view_transaction',
824
-            'TXN_ID' => $this->_transaction_details['id'],
825
-        ), TXN_ADMIN_URL);
826
-        $actions['view_txn_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
827
-            'espresso_transactions_view_transaction', $this->_transaction_details['id']) ? '
821
+		// page=transactions&action=view_transaction&txn=256&_wpnonce=6414da4dbb
822
+		$view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
823
+			'action' => 'view_transaction',
824
+			'TXN_ID' => $this->_transaction_details['id'],
825
+		), TXN_ADMIN_URL);
826
+		$actions['view_txn_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
827
+			'espresso_transactions_view_transaction', $this->_transaction_details['id']) ? '
828 828
 			<li>
829 829
 			<a class="ee-status-color-'
830
-                                                                                           . $this->_transaction_details['status']
831
-                                                                                           . ' tiny-text" href="'
832
-                                                                                           . $view_txn_lnk_url
833
-                                                                                           . '"  title="'
834
-                                                                                           . $this->_transaction_details['title_attr']
835
-                                                                                           . '">
830
+																						   . $this->_transaction_details['status']
831
+																						   . ' tiny-text" href="'
832
+																						   . $view_txn_lnk_url
833
+																						   . '"  title="'
834
+																						   . $this->_transaction_details['title_attr']
835
+																						   . '">
836 836
 				<div class="dashicons dashicons-cart"></div>
837 837
 			</a>
838 838
 			</li>' : '';
839
-        //invoice link
840
-        $actions['dl_invoice_lnk'] = '';
841
-        $dl_invoice_lnk_url = $item->invoice_url();
842
-        //only show invoice link if message type is active.
843
-        if ($attendee instanceof EE_Attendee
844
-            && $item->is_primary_registrant()
845
-            && EEH_MSG_Template::is_mt_active('invoice')
846
-        ) {
847
-            $actions['dl_invoice_lnk'] = '
839
+		//invoice link
840
+		$actions['dl_invoice_lnk'] = '';
841
+		$dl_invoice_lnk_url = $item->invoice_url();
842
+		//only show invoice link if message type is active.
843
+		if ($attendee instanceof EE_Attendee
844
+			&& $item->is_primary_registrant()
845
+			&& EEH_MSG_Template::is_mt_active('invoice')
846
+		) {
847
+			$actions['dl_invoice_lnk'] = '
848 848
 		<li>
849 849
 			<a title="'
850
-                                         . esc_attr__('View Transaction Invoice', 'event_espresso')
851
-                                         . '" target="_blank" href="'
852
-                                         . $dl_invoice_lnk_url
853
-                                         . '" class="tiny-text">
850
+										 . esc_attr__('View Transaction Invoice', 'event_espresso')
851
+										 . '" target="_blank" href="'
852
+										 . $dl_invoice_lnk_url
853
+										 . '" class="tiny-text">
854 854
 				<span class="dashicons dashicons-media-spreadsheet ee-icon-size-18"></span>
855 855
 			</a>
856 856
 		</li>';
857
-        }
858
-        $actions['filtered_messages_link'] = '';
859
-        //message list table link (filtered by REG_ID
860
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
861
-            $actions['filtered_messages_link'] = '<li>'
862
-                                                 . EEH_MSG_Template::get_message_action_link('see_notifications_for',
863
-                    null, array(
864
-                        '_REG_ID' => $item->ID(),
865
-                    ))
866
-                                                 . '</li>';
867
-        }
868
-        $actions = apply_filters('FHEE__EE_Registrations_List_Table__column_actions__actions', $actions, $item, $this);
869
-        return $this->_action_string(implode('', $actions), $item, 'ul', 'reg-overview-actions-ul');
870
-    }
857
+		}
858
+		$actions['filtered_messages_link'] = '';
859
+		//message list table link (filtered by REG_ID
860
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
861
+			$actions['filtered_messages_link'] = '<li>'
862
+												 . EEH_MSG_Template::get_message_action_link('see_notifications_for',
863
+					null, array(
864
+						'_REG_ID' => $item->ID(),
865
+					))
866
+												 . '</li>';
867
+		}
868
+		$actions = apply_filters('FHEE__EE_Registrations_List_Table__column_actions__actions', $actions, $item, $this);
869
+		return $this->_action_string(implode('', $actions), $item, 'ul', 'reg-overview-actions-ul');
870
+	}
871 871
 
872 872
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +16 added lines, -14 removed lines patch added patch discarded remove patch
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
861 861
      * foreign key to the WP_User table)
862 862
      *
863
-     * @return string|boolean string on success, boolean false when there is no
863
+     * @return string|false string on success, boolean false when there is no
864 864
      * foreign key to the WP_User table
865 865
      */
866 866
     public function wp_user_field_name()
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
      *
967 967
      * @param array  $query_params      like EEM_Base::get_all's $query_params
968 968
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
969
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
969
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
970 970
      *                                  fields on the model, and the models we joined to in the query. However, you can
971 971
      *                                  override this and set the select to "*", or a specific column name, like
972 972
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1358,7 +1358,7 @@  discard block
 block discarded – undo
1358 1358
      * @param string $field_name The name of the field the formats are being retrieved for.
1359 1359
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1360 1360
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1361
-     * @return array formats in an array with the date format first, and the time format last.
1361
+     * @return string[] formats in an array with the date format first, and the time format last.
1362 1362
      */
1363 1363
     public function get_formats_for($field_name, $pretty = false)
1364 1364
     {
@@ -1391,7 +1391,7 @@  discard block
 block discarded – undo
1391 1391
      *                                 be returned.
1392 1392
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1393 1393
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1394
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1394
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1395 1395
      *                                 exception is triggered.
1396 1396
      */
1397 1397
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1723,7 +1723,7 @@  discard block
 block discarded – undo
1723 1723
      * Wrapper for EEM_Base::delete_permanently()
1724 1724
      *
1725 1725
      * @param mixed $id
1726
-     * @return boolean whether the row got deleted or not
1726
+     * @return integer whether the row got deleted or not
1727 1727
      * @throws \EE_Error
1728 1728
      */
1729 1729
     public function delete_permanently_by_ID($id)
@@ -1743,7 +1743,7 @@  discard block
 block discarded – undo
1743 1743
      * Wrapper for EEM_Base::delete()
1744 1744
      *
1745 1745
      * @param mixed $id
1746
-     * @return boolean whether the row got deleted or not
1746
+     * @return integer whether the row got deleted or not
1747 1747
      * @throws \EE_Error
1748 1748
      */
1749 1749
     public function delete_by_ID($id)
@@ -2193,7 +2193,7 @@  discard block
 block discarded – undo
2193 2193
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2194 2194
      * EEM_Base::$_db_verification_level
2195 2195
      *
2196
-     * @param $wpdb_method
2196
+     * @param string $wpdb_method
2197 2197
      * @param $arguments_to_provide
2198 2198
      * @return string
2199 2199
      */
@@ -2317,6 +2317,7 @@  discard block
 block discarded – undo
2317 2317
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2318 2318
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2319 2319
      *                             because these will be inserted in any new rows created as well.
2320
+     * @param EE_Base_Class $id_or_obj
2320 2321
      */
2321 2322
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2322 2323
     {
@@ -2327,7 +2328,7 @@  discard block
 block discarded – undo
2327 2328
 
2328 2329
 
2329 2330
     /**
2330
-     * @param mixed           $id_or_obj
2331
+     * @param EE_Base_Class           $id_or_obj
2331 2332
      * @param string          $relationName
2332 2333
      * @param array           $where_query_params
2333 2334
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2368,7 +2369,7 @@  discard block
 block discarded – undo
2368 2369
      * However, if the model objects can't be deleted because of blocking related model objects, then
2369 2370
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2370 2371
      *
2371
-     * @param EE_Base_Class|int|string $id_or_obj
2372
+     * @param EE_Base_Class $id_or_obj
2372 2373
      * @param string                   $model_name
2373 2374
      * @param array                    $query_params
2374 2375
      * @return int how many deleted
@@ -2389,7 +2390,7 @@  discard block
 block discarded – undo
2389 2390
      * the model objects can't be hard deleted because of blocking related model objects,
2390 2391
      * just does a soft-delete on them instead.
2391 2392
      *
2392
-     * @param EE_Base_Class|int|string $id_or_obj
2393
+     * @param EE_Base_Class $id_or_obj
2393 2394
      * @param string                   $model_name
2394 2395
      * @param array                    $query_params
2395 2396
      * @return int how many deleted
@@ -2446,6 +2447,7 @@  discard block
 block discarded – undo
2446 2447
      * @param string $model_name   like 'Event', or 'Registration'
2447 2448
      * @param array  $query_params like EEM_Base::get_all's
2448 2449
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2450
+     * @param EE_Base_Class $id_or_obj
2449 2451
      * @return float
2450 2452
      * @throws \EE_Error
2451 2453
      */
@@ -2909,7 +2911,7 @@  discard block
 block discarded – undo
2909 2911
      * Finds all the fields that correspond to the given table
2910 2912
      *
2911 2913
      * @param string $table_alias , array key in EEM_Base::_tables
2912
-     * @return EE_Model_Field_Base[]
2914
+     * @return EE_Model_Field_Base
2913 2915
      */
2914 2916
     public function _get_fields_for_table($table_alias)
2915 2917
     {
@@ -4354,7 +4356,7 @@  discard block
 block discarded – undo
4354 4356
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4355 4357
      * Eg, on EE_Answer that would be ANS_ID field object
4356 4358
      *
4357
-     * @param $field_obj
4359
+     * @param EE_Model_Field_Base $field_obj
4358 4360
      * @return boolean
4359 4361
      */
4360 4362
     public function is_primary_key_field($field_obj)
@@ -4465,7 +4467,7 @@  discard block
 block discarded – undo
4465 4467
      * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4466 4468
      *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4467 4469
      *                            Either one works
4468
-     * @return EE_Table_Base
4470
+     * @return string
4469 4471
      */
4470 4472
     public function get_table_for_alias($table_alias)
4471 4473
     {
@@ -5075,7 +5077,7 @@  discard block
 block discarded – undo
5075 5077
     /**
5076 5078
      * Read comments for assume_values_already_prepared_by_model_object()
5077 5079
      *
5078
-     * @return int
5080
+     * @return boolean
5079 5081
      */
5080 5082
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5081 5083
     {
Please login to merge, or discard this patch.
Indentation   +5564 added lines, -5564 removed lines patch added patch discarded remove patch
@@ -29,5572 +29,5572 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-
447
-
448
-    /**
449
-     * About all child constructors:
450
-     * they should define the _tables, _fields and _model_relations arrays.
451
-     * Should ALWAYS be called after child constructor.
452
-     * In order to make the child constructors to be as simple as possible, this parent constructor
453
-     * finalizes constructing all the object's attributes.
454
-     * Generally, rather than requiring a child to code
455
-     * $this->_tables = array(
456
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
-     *        ...);
458
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
-     * each EE_Table has a function to set the table's alias after the constructor, using
460
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
-     * do something similar.
462
-     *
463
-     * @param null $timezone
464
-     * @throws \EE_Error
465
-     */
466
-    protected function __construct($timezone = null)
467
-    {
468
-        // check that the model has not been loaded too soon
469
-        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
471
-                sprintf(
472
-                    __('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.',
473
-                        'event_espresso'),
474
-                    get_class($this)
475
-                )
476
-            );
477
-        }
478
-        /**
479
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
-         */
481
-        if (empty(EEM_Base::$_model_query_blog_id)) {
482
-            EEM_Base::set_model_query_blog_id();
483
-        }
484
-        /**
485
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
-         * just use EE_Register_Model_Extension
487
-         *
488
-         * @var EE_Table_Base[] $_tables
489
-         */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
-        foreach ($this->_tables as $table_alias => $table_obj) {
492
-            /** @var $table_obj EE_Table_Base */
493
-            $table_obj->_construct_finalize_with_alias($table_alias);
494
-            if ($table_obj instanceof EE_Secondary_Table) {
495
-                /** @var $table_obj EE_Secondary_Table */
496
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
-            }
498
-        }
499
-        /**
500
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
-         * EE_Register_Model_Extension
502
-         *
503
-         * @param EE_Model_Field_Base[] $_fields
504
-         */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
-        $this->_invalidate_field_caches();
507
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
508
-            if ( ! array_key_exists($table_alias, $this->_tables)) {
509
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
-            }
512
-            foreach ($fields_for_table as $field_name => $field_obj) {
513
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
-                //primary key field base has a slightly different _construct_finalize
515
-                /** @var $field_obj EE_Model_Field_Base */
516
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
-            }
518
-        }
519
-        // everything is related to Extra_Meta
520
-        if (get_class($this) !== 'EEM_Extra_Meta') {
521
-            //make extra meta related to everything, but don't block deleting things just
522
-            //because they have related extra meta info. For now just orphan those extra meta
523
-            //in the future we should automatically delete them
524
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
-        }
526
-        //and change logs
527
-        if (get_class($this) !== 'EEM_Change_Log') {
528
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
-        }
530
-        /**
531
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
-         * EE_Register_Model_Extension
533
-         *
534
-         * @param EE_Model_Relation_Base[] $_model_relations
535
-         */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
-            $this->_model_relations);
538
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
539
-            /** @var $relation_obj EE_Model_Relation_Base */
540
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
-        }
542
-        foreach ($this->_indexes as $index_name => $index_obj) {
543
-            /** @var $index_obj EE_Index */
544
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
-        }
546
-        $this->set_timezone($timezone);
547
-        //finalize default where condition strategy, or set default
548
-        if ( ! $this->_default_where_conditions_strategy) {
549
-            //nothing was set during child constructor, so set default
550
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
-        }
552
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
553
-        if ( ! $this->_minimum_where_conditions_strategy) {
554
-            //nothing was set during child constructor, so set default
555
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
-        }
557
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
559
-        //to indicate to NOT set it, set it to the logical default
560
-        if ($this->_caps_slug === null) {
561
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
-        }
563
-        //initialize the standard cap restriction generators if none were specified by the child constructor
564
-        if ($this->_cap_restriction_generators !== false) {
565
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
-                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
568
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
-                        new EE_Restriction_Generator_Protected(),
570
-                        $cap_context,
571
-                        $this
572
-                    );
573
-                }
574
-            }
575
-        }
576
-        //if there are cap restriction generators, use them to make the default cap restrictions
577
-        if ($this->_cap_restriction_generators !== false) {
578
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
-                if ( ! $generator_object) {
580
-                    continue;
581
-                }
582
-                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
-                    throw new EE_Error(
584
-                        sprintf(
585
-                            __('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.',
586
-                                'event_espresso'),
587
-                            $context,
588
-                            $this->get_this_model_name()
589
-                        )
590
-                    );
591
-                }
592
-                $action = $this->cap_action_for_context($context);
593
-                if ( ! $generator_object->construction_finalized()) {
594
-                    $generator_object->_construct_finalize($this, $action);
595
-                }
596
-            }
597
-        }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * Generates the cap restrictions for the given context, or if they were
605
-     * already generated just gets what's cached
606
-     *
607
-     * @param string $context one of EEM_Base::valid_cap_contexts()
608
-     * @return EE_Default_Where_Conditions[]
609
-     */
610
-    protected function _generate_cap_restrictions($context)
611
-    {
612
-        if (isset($this->_cap_restriction_generators[$context])
613
-            && $this->_cap_restriction_generators[$context]
614
-               instanceof
615
-               EE_Restriction_Generator_Base
616
-        ) {
617
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
-        } else {
619
-            return array();
620
-        }
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * Used to set the $_model_query_blog_id static property.
627
-     *
628
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
-     *                      value for get_current_blog_id() will be used.
630
-     */
631
-    public static function set_model_query_blog_id($blog_id = 0)
632
-    {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
-    }
635
-
636
-
637
-
638
-    /**
639
-     * Returns whatever is set as the internal $model_query_blog_id.
640
-     *
641
-     * @return int
642
-     */
643
-    public static function get_model_query_blog_id()
644
-    {
645
-        return EEM_Base::$_model_query_blog_id;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     *        This function is a singleton method used to instantiate the Espresso_model object
652
-     *
653
-     * @access public
654
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
-     *                         timezone in the 'timezone_string' wp option)
658
-     * @return static (as in the concrete child class)
659
-     */
660
-    public static function instance($timezone = null)
661
-    {
662
-        // check if instance of Espresso_model already exists
663
-        if ( ! static::$_instance instanceof static) {
664
-            // instantiate Espresso_model
665
-            static::$_instance = new static($timezone);
666
-        }
667
-        //we might have a timezone set, let set_timezone decide what to do with it
668
-        static::$_instance->set_timezone($timezone);
669
-        // Espresso_model object
670
-        return static::$_instance;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * resets the model and returns it
677
-     *
678
-     * @param null | string $timezone
679
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
-     * all its properties reset; if it wasn't instantiated, returns null)
681
-     */
682
-    public static function reset($timezone = null)
683
-    {
684
-        if (static::$_instance instanceof EEM_Base) {
685
-            //let's try to NOT swap out the current instance for a new one
686
-            //because if someone has a reference to it, we can't remove their reference
687
-            //so it's best to keep using the same reference, but change the original object
688
-            //reset all its properties to their original values as defined in the class
689
-            $r = new ReflectionClass(get_class(static::$_instance));
690
-            $static_properties = $r->getStaticProperties();
691
-            foreach ($r->getDefaultProperties() as $property => $value) {
692
-                //don't set instance to null like it was originally,
693
-                //but it's static anyways, and we're ignoring static properties (for now at least)
694
-                if ( ! isset($static_properties[$property])) {
695
-                    static::$_instance->{$property} = $value;
696
-                }
697
-            }
698
-            //and then directly call its constructor again, like we would if we
699
-            //were creating a new one
700
-            static::$_instance->__construct($timezone);
701
-            return self::instance();
702
-        }
703
-        return null;
704
-    }
705
-
706
-
707
-
708
-    /**
709
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
-     *
711
-     * @param  boolean $translated return localized strings or JUST the array.
712
-     * @return array
713
-     * @throws \EE_Error
714
-     */
715
-    public function status_array($translated = false)
716
-    {
717
-        if ( ! array_key_exists('Status', $this->_model_relations)) {
718
-            return array();
719
-        }
720
-        $model_name = $this->get_this_model_name();
721
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
-        $status_array = array();
724
-        foreach ($stati as $status) {
725
-            $status_array[$status->ID()] = $status->get('STS_code');
726
-        }
727
-        return $translated
728
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
-            : $status_array;
730
-    }
731
-
732
-
733
-
734
-    /**
735
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
-     *
737
-     * @param array $query_params             {
738
-     * @var array $0 (where) array {
739
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
-     *                                        conditions based on related models (and even
743
-     *                                        models-related-to-related-models) prepend the model's name onto the field
744
-     *                                        name. Eg,
745
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
750
-     *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
751
-     *                                        "Venue.VNU_ID", you could have
752
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
753
-     *                                        events are related to Registrations, which are related to Attendees). You
754
-     *                                        can take it even further with
755
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
756
-     *                                        (from the default of '='), change the value to an numerically-indexed
757
-     *                                        array, where the first item in the list is the operator. eg: array(
758
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
759
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
760
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
761
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
762
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
763
-     *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
764
-     *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
765
-     *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
766
-     *                                        all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
767
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
768
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
769
-     *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
770
-     *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
771
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
772
-     *                                        SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to
773
-     *                                        place two or more where conditions applying to the same field. eg:
774
-     *                                        array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus
775
-     *                                        removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*'
776
-     *                                        character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the
777
-     *                                        previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
778
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
779
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
780
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
781
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
782
-     *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
783
-     *                                        the OFFSET, the 2nd is the LIMIT
784
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
785
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
786
-     *                                        => array( 'table_alias', array(1,2) ) ).
787
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
788
-     *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
789
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
790
-     *                                        'where' conditions, these fields can be on related models. Eg
791
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
792
-     *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
793
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
794
-     *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
795
-     *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
796
-     *                                        want to order by the primary key. Eg,
797
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
798
-     *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
799
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
800
-     *                                        wp_esp_registration ORDER BY REG_ID ASC"
801
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
802
-     *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
803
-     *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
804
-     *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
805
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
806
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
807
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
808
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
809
-     *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
810
-     *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
811
-     *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
812
-     *                                        (ie, the current model has a foreign key to them, like how Registration
813
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
814
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
815
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
816
-     *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
817
-     *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
818
-     *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
819
-     *                                        (default), set to 'all'.
820
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
821
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
822
-     *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
823
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
824
-     *                                        }
825
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
826
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
827
-     *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
828
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
829
-     *                                        EEM_Transaction::instance()->get_all( array( array(
830
-     *                                        'OR'=>array(
831
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
832
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
833
-     *                                        )
834
-     *                                        ),
835
-     *                                        'limit'=>10,
836
-     *                                        'group_by'=>'TXN_ID'
837
-     *                                        ));
838
-     *                                        get all the answers to the question titled "shirt size" for event with id
839
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
840
-     *                                        'Question.QST_display_text'=>'shirt size',
841
-     *                                        'Registration.Event.EVT_ID'=>12
842
-     *                                        ),
843
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
844
-     *                                        ));
845
-     * @throws \EE_Error
846
-     */
847
-    public function get_all($query_params = array())
848
-    {
849
-        if (isset($query_params['limit'])
850
-            && ! isset($query_params['group_by'])
851
-        ) {
852
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
853
-        }
854
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
855
-    }
856
-
857
-
858
-
859
-    /**
860
-     * Modifies the query parameters so we only get back model objects
861
-     * that "belong" to the current user
862
-     *
863
-     * @param array $query_params @see EEM_Base::get_all()
864
-     * @return array like EEM_Base::get_all
865
-     */
866
-    public function alter_query_params_to_only_include_mine($query_params = array())
867
-    {
868
-        $wp_user_field_name = $this->wp_user_field_name();
869
-        if ($wp_user_field_name) {
870
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
871
-        }
872
-        return $query_params;
873
-    }
874
-
875
-
876
-
877
-    /**
878
-     * Returns the name of the field's name that points to the WP_User table
879
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
880
-     * foreign key to the WP_User table)
881
-     *
882
-     * @return string|boolean string on success, boolean false when there is no
883
-     * foreign key to the WP_User table
884
-     */
885
-    public function wp_user_field_name()
886
-    {
887
-        try {
888
-            if ( ! empty($this->_model_chain_to_wp_user)) {
889
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890
-                $last_model_name = end($models_to_follow_to_wp_users);
891
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
893
-            } else {
894
-                $model_with_fk_to_wp_users = $this;
895
-                $model_chain_to_wp_user = '';
896
-            }
897
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
899
-        } catch (EE_Error $e) {
900
-            return false;
901
-        }
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
908
-     * (or transiently-related model) has a foreign key to the wp_users table;
909
-     * useful for finding if model objects of this type are 'owned' by the current user.
910
-     * This is an empty string when the foreign key is on this model and when it isn't,
911
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
912
-     * (or transiently-related model)
913
-     *
914
-     * @return string
915
-     */
916
-    public function model_chain_to_wp_user()
917
-    {
918
-        return $this->_model_chain_to_wp_user;
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
925
-     * like how registrations don't have a foreign key to wp_users, but the
926
-     * events they are for are), or is unrelated to wp users.
927
-     * generally available
928
-     *
929
-     * @return boolean
930
-     */
931
-    public function is_owned()
932
-    {
933
-        if ($this->model_chain_to_wp_user()) {
934
-            return true;
935
-        } else {
936
-            try {
937
-                $this->get_foreign_key_to('WP_User');
938
-                return true;
939
-            } catch (EE_Error $e) {
940
-                return false;
941
-            }
942
-        }
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
949
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
950
-     * the model)
951
-     *
952
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
953
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
954
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
955
-     *                                  fields on the model, and the models we joined to in the query. However, you can
956
-     *                                  override this and set the select to "*", or a specific column name, like
957
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
958
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
959
-     *                                  the aliases used to refer to this selection, and values are to be
960
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
961
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
962
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
963
-     * @throws \EE_Error
964
-     */
965
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
966
-    {
967
-        // remember the custom selections, if any, and type cast as array
968
-        // (unless $columns_to_select is an object, then just set as an empty array)
969
-        // Note: (array) 'some string' === array( 'some string' )
970
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
971
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
972
-        $select_expressions = $columns_to_select !== null
973
-            ? $this->_construct_select_from_input($columns_to_select)
974
-            : $this->_construct_default_select_sql($model_query_info);
975
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
976
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
977
-    }
978
-
979
-
980
-
981
-    /**
982
-     * Gets an array of rows from the database just like $wpdb->get_results would,
983
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
984
-     * take care of joins, field preparation etc.
985
-     *
986
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
987
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
-     *                                  fields on the model, and the models we joined to in the query. However, you can
990
-     *                                  override this and set the select to "*", or a specific column name, like
991
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
-     *                                  the aliases used to refer to this selection, and values are to be
994
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
-     * @throws \EE_Error
998
-     */
999
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1000
-    {
1001
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * For creating a custom select statement
1008
-     *
1009
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1010
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1011
-     *                                 SQL, and 1=>is the datatype
1012
-     * @throws EE_Error
1013
-     * @return string
1014
-     */
1015
-    private function _construct_select_from_input($columns_to_select)
1016
-    {
1017
-        if (is_array($columns_to_select)) {
1018
-            $select_sql_array = array();
1019
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1020
-                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1021
-                    throw new EE_Error(
1022
-                        sprintf(
1023
-                            __(
1024
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1025
-                                "event_espresso"
1026
-                            ),
1027
-                            $selection_and_datatype,
1028
-                            $alias
1029
-                        )
1030
-                    );
1031
-                }
1032
-                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1033
-                    throw new EE_Error(
1034
-                        sprintf(
1035
-                            __(
1036
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1037
-                                "event_espresso"
1038
-                            ),
1039
-                            $selection_and_datatype[1],
1040
-                            $selection_and_datatype[0],
1041
-                            $alias,
1042
-                            implode(",", $this->_valid_wpdb_data_types)
1043
-                        )
1044
-                    );
1045
-                }
1046
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1047
-            }
1048
-            $columns_to_select_string = implode(", ", $select_sql_array);
1049
-        } else {
1050
-            $columns_to_select_string = $columns_to_select;
1051
-        }
1052
-        return $columns_to_select_string;
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1059
-     *
1060
-     * @return string
1061
-     * @throws \EE_Error
1062
-     */
1063
-    public function primary_key_name()
1064
-    {
1065
-        return $this->get_primary_key_field()->get_name();
1066
-    }
1067
-
1068
-
1069
-
1070
-    /**
1071
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1072
-     * If there is no primary key on this model, $id is treated as primary key string
1073
-     *
1074
-     * @param mixed $id int or string, depending on the type of the model's primary key
1075
-     * @return EE_Base_Class
1076
-     */
1077
-    public function get_one_by_ID($id)
1078
-    {
1079
-        if ($this->get_from_entity_map($id)) {
1080
-            return $this->get_from_entity_map($id);
1081
-        }
1082
-        return $this->get_one(
1083
-            $this->alter_query_params_to_restrict_by_ID(
1084
-                $id,
1085
-                array('default_where_conditions' => 'minimum')
1086
-            )
1087
-        );
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * Alters query parameters to only get items with this ID are returned.
1094
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1095
-     * or could just be a simple primary key ID
1096
-     *
1097
-     * @param int   $id
1098
-     * @param array $query_params
1099
-     * @return array of normal query params, @see EEM_Base::get_all
1100
-     * @throws \EE_Error
1101
-     */
1102
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1103
-    {
1104
-        if ( ! isset($query_params[0])) {
1105
-            $query_params[0] = array();
1106
-        }
1107
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1108
-        if ($conditions_from_id === null) {
1109
-            $query_params[0][$this->primary_key_name()] = $id;
1110
-        } else {
1111
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1112
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1113
-        }
1114
-        return $query_params;
1115
-    }
1116
-
1117
-
1118
-
1119
-    /**
1120
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1121
-     * array. If no item is found, null is returned.
1122
-     *
1123
-     * @param array $query_params like EEM_Base's $query_params variable.
1124
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1125
-     * @throws \EE_Error
1126
-     */
1127
-    public function get_one($query_params = array())
1128
-    {
1129
-        if ( ! is_array($query_params)) {
1130
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1131
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1132
-                    gettype($query_params)), '4.6.0');
1133
-            $query_params = array();
1134
-        }
1135
-        $query_params['limit'] = 1;
1136
-        $items = $this->get_all($query_params);
1137
-        if (empty($items)) {
1138
-            return null;
1139
-        } else {
1140
-            return array_shift($items);
1141
-        }
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Returns the next x number of items in sequence from the given value as
1148
-     * found in the database matching the given query conditions.
1149
-     *
1150
-     * @param mixed $current_field_value    Value used for the reference point.
1151
-     * @param null  $field_to_order_by      What field is used for the
1152
-     *                                      reference point.
1153
-     * @param int   $limit                  How many to return.
1154
-     * @param array $query_params           Extra conditions on the query.
1155
-     * @param null  $columns_to_select      If left null, then an array of
1156
-     *                                      EE_Base_Class objects is returned,
1157
-     *                                      otherwise you can indicate just the
1158
-     *                                      columns you want returned.
1159
-     * @return EE_Base_Class[]|array
1160
-     * @throws \EE_Error
1161
-     */
1162
-    public function next_x(
1163
-        $current_field_value,
1164
-        $field_to_order_by = null,
1165
-        $limit = 1,
1166
-        $query_params = array(),
1167
-        $columns_to_select = null
1168
-    ) {
1169
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1170
-            $columns_to_select);
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Returns the previous x number of items in sequence from the given value
1177
-     * as found in the database matching the given query conditions.
1178
-     *
1179
-     * @param mixed $current_field_value    Value used for the reference point.
1180
-     * @param null  $field_to_order_by      What field is used for the
1181
-     *                                      reference point.
1182
-     * @param int   $limit                  How many to return.
1183
-     * @param array $query_params           Extra conditions on the query.
1184
-     * @param null  $columns_to_select      If left null, then an array of
1185
-     *                                      EE_Base_Class objects is returned,
1186
-     *                                      otherwise you can indicate just the
1187
-     *                                      columns you want returned.
1188
-     * @return EE_Base_Class[]|array
1189
-     * @throws \EE_Error
1190
-     */
1191
-    public function previous_x(
1192
-        $current_field_value,
1193
-        $field_to_order_by = null,
1194
-        $limit = 1,
1195
-        $query_params = array(),
1196
-        $columns_to_select = null
1197
-    ) {
1198
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1199
-            $columns_to_select);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Returns the next item in sequence from the given value as found in the
1206
-     * database matching the given query conditions.
1207
-     *
1208
-     * @param mixed $current_field_value    Value used for the reference point.
1209
-     * @param null  $field_to_order_by      What field is used for the
1210
-     *                                      reference point.
1211
-     * @param array $query_params           Extra conditions on the query.
1212
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1213
-     *                                      object is returned, otherwise you
1214
-     *                                      can indicate just the columns you
1215
-     *                                      want and a single array indexed by
1216
-     *                                      the columns will be returned.
1217
-     * @return EE_Base_Class|null|array()
1218
-     * @throws \EE_Error
1219
-     */
1220
-    public function next(
1221
-        $current_field_value,
1222
-        $field_to_order_by = null,
1223
-        $query_params = array(),
1224
-        $columns_to_select = null
1225
-    ) {
1226
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1227
-            $columns_to_select);
1228
-        return empty($results) ? null : reset($results);
1229
-    }
1230
-
1231
-
1232
-
1233
-    /**
1234
-     * Returns the previous item in sequence from the given value as found in
1235
-     * the database matching the given query conditions.
1236
-     *
1237
-     * @param mixed $current_field_value    Value used for the reference point.
1238
-     * @param null  $field_to_order_by      What field is used for the
1239
-     *                                      reference point.
1240
-     * @param array $query_params           Extra conditions on the query.
1241
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1242
-     *                                      object is returned, otherwise you
1243
-     *                                      can indicate just the columns you
1244
-     *                                      want and a single array indexed by
1245
-     *                                      the columns will be returned.
1246
-     * @return EE_Base_Class|null|array()
1247
-     * @throws EE_Error
1248
-     */
1249
-    public function previous(
1250
-        $current_field_value,
1251
-        $field_to_order_by = null,
1252
-        $query_params = array(),
1253
-        $columns_to_select = null
1254
-    ) {
1255
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1256
-            $columns_to_select);
1257
-        return empty($results) ? null : reset($results);
1258
-    }
1259
-
1260
-
1261
-
1262
-    /**
1263
-     * Returns the a consecutive number of items in sequence from the given
1264
-     * value as found in the database matching the given query conditions.
1265
-     *
1266
-     * @param mixed  $current_field_value   Value used for the reference point.
1267
-     * @param string $operand               What operand is used for the sequence.
1268
-     * @param string $field_to_order_by     What field is used for the reference point.
1269
-     * @param int    $limit                 How many to return.
1270
-     * @param array  $query_params          Extra conditions on the query.
1271
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the columns you want returned.
1273
-     * @return EE_Base_Class[]|array
1274
-     * @throws EE_Error
1275
-     */
1276
-    protected function _get_consecutive(
1277
-        $current_field_value,
1278
-        $operand = '>',
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1285
-        if (empty($field_to_order_by)) {
1286
-            if ($this->has_primary_key_field()) {
1287
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1288
-            } else {
1289
-                if (WP_DEBUG) {
1290
-                    throw new EE_Error(__('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).',
1291
-                        'event_espresso'));
1292
-                }
1293
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1294
-                return array();
1295
-            }
1296
-        }
1297
-        if ( ! is_array($query_params)) {
1298
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1299
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1300
-                    gettype($query_params)), '4.6.0');
1301
-            $query_params = array();
1302
-        }
1303
-        //let's add the where query param for consecutive look up.
1304
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305
-        $query_params['limit'] = $limit;
1306
-        //set direction
1307
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1308
-        $query_params['order_by'] = $operand === '>'
1309
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1310
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1311
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1312
-        if (empty($columns_to_select)) {
1313
-            return $this->get_all($query_params);
1314
-        } else {
1315
-            //getting just the fields
1316
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1317
-        }
1318
-    }
1319
-
1320
-
1321
-
1322
-    /**
1323
-     * This sets the _timezone property after model object has been instantiated.
1324
-     *
1325
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1326
-     */
1327
-    public function set_timezone($timezone)
1328
-    {
1329
-        if ($timezone !== null) {
1330
-            $this->_timezone = $timezone;
1331
-        }
1332
-        //note we need to loop through relations and set the timezone on those objects as well.
1333
-        foreach ($this->_model_relations as $relation) {
1334
-            $relation->set_timezone($timezone);
1335
-        }
1336
-        //and finally we do the same for any datetime fields
1337
-        foreach ($this->_fields as $field) {
1338
-            if ($field instanceof EE_Datetime_Field) {
1339
-                $field->set_timezone($timezone);
1340
-            }
1341
-        }
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * This just returns whatever is set for the current timezone.
1348
-     *
1349
-     * @access public
1350
-     * @return string
1351
-     */
1352
-    public function get_timezone()
1353
-    {
1354
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1355
-        if (empty($this->_timezone)) {
1356
-            foreach ($this->_fields as $field) {
1357
-                if ($field instanceof EE_Datetime_Field) {
1358
-                    $this->set_timezone($field->get_timezone());
1359
-                    break;
1360
-                }
1361
-            }
1362
-        }
1363
-        //if timezone STILL empty then return the default timezone for the site.
1364
-        if (empty($this->_timezone)) {
1365
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1366
-        }
1367
-        return $this->_timezone;
1368
-    }
1369
-
1370
-
1371
-
1372
-    /**
1373
-     * This returns the date formats set for the given field name and also ensures that
1374
-     * $this->_timezone property is set correctly.
1375
-     *
1376
-     * @since 4.6.x
1377
-     * @param string $field_name The name of the field the formats are being retrieved for.
1378
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1379
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1380
-     * @return array formats in an array with the date format first, and the time format last.
1381
-     */
1382
-    public function get_formats_for($field_name, $pretty = false)
1383
-    {
1384
-        $field_settings = $this->field_settings_for($field_name);
1385
-        //if not a valid EE_Datetime_Field then throw error
1386
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1387
-            throw new EE_Error(sprintf(__('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.',
1388
-                'event_espresso'), $field_name));
1389
-        }
1390
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1391
-        //the field.
1392
-        $this->_timezone = $field_settings->get_timezone();
1393
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1394
-    }
1395
-
1396
-
1397
-
1398
-    /**
1399
-     * This returns the current time in a format setup for a query on this model.
1400
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1401
-     * it will return:
1402
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1403
-     *  NOW
1404
-     *  - or a unix timestamp (equivalent to time())
1405
-     *
1406
-     * @since 4.6.x
1407
-     * @param string $field_name       The field the current time is needed for.
1408
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1409
-     *                                 formatted string matching the set format for the field in the set timezone will
1410
-     *                                 be returned.
1411
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1412
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1413
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1414
-     *                                 exception is triggered.
1415
-     */
1416
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1417
-    {
1418
-        $formats = $this->get_formats_for($field_name);
1419
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1420
-        if ($timestamp) {
1421
-            return $DateTime->format('U');
1422
-        }
1423
-        //not returning timestamp, so return formatted string in timezone.
1424
-        switch ($what) {
1425
-            case 'time' :
1426
-                return $DateTime->format($formats[1]);
1427
-                break;
1428
-            case 'date' :
1429
-                return $DateTime->format($formats[0]);
1430
-                break;
1431
-            default :
1432
-                return $DateTime->format(implode(' ', $formats));
1433
-                break;
1434
-        }
1435
-    }
1436
-
1437
-
1438
-
1439
-    /**
1440
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1441
-     * for the model are.  Returns a DateTime object.
1442
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1443
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1444
-     * ignored.
1445
-     *
1446
-     * @param string $field_name      The field being setup.
1447
-     * @param string $timestring      The date time string being used.
1448
-     * @param string $incoming_format The format for the time string.
1449
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1450
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1451
-     *                                format is
1452
-     *                                'U', this is ignored.
1453
-     * @return DateTime
1454
-     * @throws \EE_Error
1455
-     */
1456
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1457
-    {
1458
-        //just using this to ensure the timezone is set correctly internally
1459
-        $this->get_formats_for($field_name);
1460
-        //load EEH_DTT_Helper
1461
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1462
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1463
-        return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1464
-    }
1465
-
1466
-
1467
-
1468
-    /**
1469
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1470
-     *
1471
-     * @return EE_Table_Base[]
1472
-     */
1473
-    public function get_tables()
1474
-    {
1475
-        return $this->_tables;
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1482
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1483
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1484
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1485
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1486
-     * model object with EVT_ID = 1
1487
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1488
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1489
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1490
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1491
-     * are not specified)
1492
-     *
1493
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1494
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1495
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1496
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1497
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1498
-     *                                         ID=34, we'd use this method as follows:
1499
-     *                                         EEM_Transaction::instance()->update(
1500
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1501
-     *                                         array(array('TXN_ID'=>34)));
1502
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1503
-     *                                         in client code into what's expected to be stored on each field. Eg,
1504
-     *                                         consider updating Question's QST_admin_label field is of type
1505
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1506
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1507
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1508
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1509
-     *                                         TRUE, it is assumed that you've already called
1510
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1511
-     *                                         malicious javascript. However, if
1512
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1513
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1514
-     *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1515
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1516
-     *                                         in this model's entity map according to $fields_n_values that match
1517
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1518
-     *                                         by setting this to FALSE, but be aware that model objects being used
1519
-     *                                         could get out-of-sync with the database
1520
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1521
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1525
-    {
1526
-        if ( ! is_array($query_params)) {
1527
-            EE_Error::doing_it_wrong('EEM_Base::update',
1528
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1529
-                    gettype($query_params)), '4.6.0');
1530
-            $query_params = array();
1531
-        }
1532
-        /**
1533
-         * Action called before a model update call has been made.
1534
-         *
1535
-         * @param EEM_Base $model
1536
-         * @param array    $fields_n_values the updated fields and their new values
1537
-         * @param array    $query_params    @see EEM_Base::get_all()
1538
-         */
1539
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1540
-        /**
1541
-         * Filters the fields about to be updated given the query parameters. You can provide the
1542
-         * $query_params to $this->get_all() to find exactly which records will be updated
1543
-         *
1544
-         * @param array    $fields_n_values fields and their new values
1545
-         * @param EEM_Base $model           the model being queried
1546
-         * @param array    $query_params    see EEM_Base::get_all()
1547
-         */
1548
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549
-            $query_params);
1550
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1551
-        //to do that, for each table, verify that it's PK isn't null.
1552
-        $tables = $this->get_tables();
1553
-        //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
1554
-        //NOTE: we should make this code more efficient by NOT querying twice
1555
-        //before the real update, but that needs to first go through ALPHA testing
1556
-        //as it's dangerous. says Mike August 8 2014
1557
-        //we want to make sure the default_where strategy is ignored
1558
-        $this->_ignore_where_strategy = true;
1559
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560
-        foreach ($wpdb_select_results as $wpdb_result) {
1561
-            // type cast stdClass as array
1562
-            $wpdb_result = (array)$wpdb_result;
1563
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564
-            if ($this->has_primary_key_field()) {
1565
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1566
-            } else {
1567
-                //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)
1568
-                $main_table_pk_value = null;
1569
-            }
1570
-            //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
1571
-            //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
1572
-            if (count($tables) > 1) {
1573
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1574
-                //in that table, and so we'll want to insert one
1575
-                foreach ($tables as $table_obj) {
1576
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1577
-                    //if there is no private key for this table on the results, it means there's no entry
1578
-                    //in this table, right? so insert a row in the current table, using any fields available
1579
-                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1580
-                            && $wpdb_result[$this_table_pk_column])
1581
-                    ) {
1582
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1583
-                            $main_table_pk_value);
1584
-                        //if we died here, report the error
1585
-                        if ( ! $success) {
1586
-                            return false;
1587
-                        }
1588
-                    }
1589
-                }
1590
-            }
1591
-            //				//and now check that if we have cached any models by that ID on the model, that
1592
-            //				//they also get updated properly
1593
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1594
-            //				if( $model_object ){
1595
-            //					foreach( $fields_n_values as $field => $value ){
1596
-            //						$model_object->set($field, $value);
1597
-            //let's make sure default_where strategy is followed now
1598
-            $this->_ignore_where_strategy = false;
1599
-        }
1600
-        //if we want to keep model objects in sync, AND
1601
-        //if this wasn't called from a model object (to update itself)
1602
-        //then we want to make sure we keep all the existing
1603
-        //model objects in sync with the db
1604
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1605
-            if ($this->has_primary_key_field()) {
1606
-                $model_objs_affected_ids = $this->get_col($query_params);
1607
-            } else {
1608
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1609
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1610
-                $model_objs_affected_ids = array();
1611
-                foreach ($models_affected_key_columns as $row) {
1612
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1613
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1614
-                }
1615
-            }
1616
-            if ( ! $model_objs_affected_ids) {
1617
-                //wait wait wait- if nothing was affected let's stop here
1618
-                return 0;
1619
-            }
1620
-            foreach ($model_objs_affected_ids as $id) {
1621
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1622
-                if ($model_obj_in_entity_map) {
1623
-                    foreach ($fields_n_values as $field => $new_value) {
1624
-                        $model_obj_in_entity_map->set($field, $new_value);
1625
-                    }
1626
-                }
1627
-            }
1628
-            //if there is a primary key on this model, we can now do a slight optimization
1629
-            if ($this->has_primary_key_field()) {
1630
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1631
-                $query_params = array(
1632
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1633
-                    'limit'                    => count($model_objs_affected_ids),
1634
-                    'default_where_conditions' => 'none',
1635
-                );
1636
-            }
1637
-        }
1638
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1639
-        $SQL = "UPDATE "
1640
-               . $model_query_info->get_full_join_sql()
1641
-               . " SET "
1642
-               . $this->_construct_update_sql($fields_n_values)
1643
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645
-        /**
1646
-         * Action called after a model update call has been made.
1647
-         *
1648
-         * @param EEM_Base $model
1649
-         * @param array    $fields_n_values the updated fields and their new values
1650
-         * @param array    $query_params    @see EEM_Base::get_all()
1651
-         * @param int      $rows_affected
1652
-         */
1653
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
-        return $rows_affected;//how many supposedly got updated
1655
-    }
1656
-
1657
-
1658
-
1659
-    /**
1660
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1661
-     * are teh values of the field specified (or by default the primary key field)
1662
-     * that matched the query params. Note that you should pass the name of the
1663
-     * model FIELD, not the database table's column name.
1664
-     *
1665
-     * @param array  $query_params @see EEM_Base::get_all()
1666
-     * @param string $field_to_select
1667
-     * @return array just like $wpdb->get_col()
1668
-     * @throws \EE_Error
1669
-     */
1670
-    public function get_col($query_params = array(), $field_to_select = null)
1671
-    {
1672
-        if ($field_to_select) {
1673
-            $field = $this->field_settings_for($field_to_select);
1674
-        } elseif ($this->has_primary_key_field()) {
1675
-            $field = $this->get_primary_key_field();
1676
-        } else {
1677
-            //no primary key, just grab the first column
1678
-            $field = reset($this->field_settings());
1679
-        }
1680
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1681
-        $select_expressions = $field->get_qualified_column();
1682
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1683
-        return $this->_do_wpdb_query('get_col', array($SQL));
1684
-    }
1685
-
1686
-
1687
-
1688
-    /**
1689
-     * Returns a single column value for a single row from the database
1690
-     *
1691
-     * @param array  $query_params    @see EEM_Base::get_all()
1692
-     * @param string $field_to_select @see EEM_Base::get_col()
1693
-     * @return string
1694
-     * @throws \EE_Error
1695
-     */
1696
-    public function get_var($query_params = array(), $field_to_select = null)
1697
-    {
1698
-        $query_params['limit'] = 1;
1699
-        $col = $this->get_col($query_params, $field_to_select);
1700
-        if ( ! empty($col)) {
1701
-            return reset($col);
1702
-        } else {
1703
-            return null;
1704
-        }
1705
-    }
1706
-
1707
-
1708
-
1709
-    /**
1710
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1711
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1712
-     * injection, but currently no further filtering is done
1713
-     *
1714
-     * @global      $wpdb
1715
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1716
-     *                               be updated to in the DB
1717
-     * @return string of SQL
1718
-     * @throws \EE_Error
1719
-     */
1720
-    public function _construct_update_sql($fields_n_values)
1721
-    {
1722
-        /** @type WPDB $wpdb */
1723
-        global $wpdb;
1724
-        $cols_n_values = array();
1725
-        foreach ($fields_n_values as $field_name => $value) {
1726
-            $field_obj = $this->field_settings_for($field_name);
1727
-            //if the value is NULL, we want to assign the value to that.
1728
-            //wpdb->prepare doesn't really handle that properly
1729
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730
-            $value_sql = $prepared_value === null ? 'NULL'
1731
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1733
-        }
1734
-        return implode(",", $cols_n_values);
1735
-    }
1736
-
1737
-
1738
-
1739
-    /**
1740
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1741
-     * Performs a HARD delete, meaning the database row should always be removed,
1742
-     * not just have a flag field on it switched
1743
-     * Wrapper for EEM_Base::delete_permanently()
1744
-     *
1745
-     * @param mixed $id
1746
-     * @return boolean whether the row got deleted or not
1747
-     * @throws \EE_Error
1748
-     */
1749
-    public function delete_permanently_by_ID($id)
1750
-    {
1751
-        return $this->delete_permanently(
1752
-            array(
1753
-                array($this->get_primary_key_field()->get_name() => $id),
1754
-                'limit' => 1,
1755
-            )
1756
-        );
1757
-    }
1758
-
1759
-
1760
-
1761
-    /**
1762
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1763
-     * Wrapper for EEM_Base::delete()
1764
-     *
1765
-     * @param mixed $id
1766
-     * @return boolean whether the row got deleted or not
1767
-     * @throws \EE_Error
1768
-     */
1769
-    public function delete_by_ID($id)
1770
-    {
1771
-        return $this->delete(
1772
-            array(
1773
-                array($this->get_primary_key_field()->get_name() => $id),
1774
-                'limit' => 1,
1775
-            )
1776
-        );
1777
-    }
1778
-
1779
-
1780
-
1781
-    /**
1782
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1783
-     * meaning if the model has a field that indicates its been "trashed" or
1784
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1785
-     *
1786
-     * @see EEM_Base::delete_permanently
1787
-     * @param array   $query_params
1788
-     * @param boolean $allow_blocking
1789
-     * @return int how many rows got deleted
1790
-     * @throws \EE_Error
1791
-     */
1792
-    public function delete($query_params, $allow_blocking = true)
1793
-    {
1794
-        return $this->delete_permanently($query_params, $allow_blocking);
1795
-    }
1796
-
1797
-
1798
-
1799
-    /**
1800
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1801
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1802
-     * as archived, not actually deleted
1803
-     *
1804
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1805
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1806
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1807
-     *                                deletes regardless of other objects which may depend on it. Its generally
1808
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1809
-     *                                DB
1810
-     * @return int how many rows got deleted
1811
-     * @throws \EE_Error
1812
-     */
1813
-    public function delete_permanently($query_params, $allow_blocking = true)
1814
-    {
1815
-        /**
1816
-         * Action called just before performing a real deletion query. You can use the
1817
-         * model and its $query_params to find exactly which items will be deleted
1818
-         *
1819
-         * @param EEM_Base $model
1820
-         * @param array    $query_params   @see EEM_Base::get_all()
1821
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1822
-         *                                 to block (prevent) this deletion
1823
-         */
1824
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1825
-        //some MySQL databases may be running safe mode, which may restrict
1826
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1827
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1828
-        //to delete them
1829
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1830
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1831
-        if ($deletion_where) {
1832
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1833
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1834
-            $table_aliases = array_keys($this->_tables);
1835
-            $SQL = "DELETE "
1836
-                   . implode(", ", $table_aliases)
1837
-                   . " FROM "
1838
-                   . $model_query_info->get_full_join_sql()
1839
-                   . " WHERE "
1840
-                   . $deletion_where;
1841
-            //		/echo "delete sql:$SQL";
1842
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1843
-        } else {
1844
-            $rows_deleted = 0;
1845
-        }
1846
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1847
-        if ($this->has_primary_key_field()) {
1848
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1849
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1850
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1851
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1852
-                }
1853
-            }
1854
-        }
1855
-        /**
1856
-         * Action called just after performing a real deletion query. Although at this point the
1857
-         * items should have been deleted
1858
-         *
1859
-         * @param EEM_Base $model
1860
-         * @param array    $query_params @see EEM_Base::get_all()
1861
-         * @param int      $rows_deleted
1862
-         */
1863
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
-        return $rows_deleted;//how many supposedly got deleted
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Checks all the relations that throw error messages when there are blocking related objects
1871
-     * for related model objects. If there are any related model objects on those relations,
1872
-     * adds an EE_Error, and return true
1873
-     *
1874
-     * @param EE_Base_Class|int $this_model_obj_or_id
1875
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1876
-     *                                                 should be ignored when determining whether there are related
1877
-     *                                                 model objects which block this model object's deletion. Useful
1878
-     *                                                 if you know A is related to B and are considering deleting A,
1879
-     *                                                 but want to see if A has any other objects blocking its deletion
1880
-     *                                                 before removing the relation between A and B
1881
-     * @return boolean
1882
-     * @throws \EE_Error
1883
-     */
1884
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1885
-    {
1886
-        //first, if $ignore_this_model_obj was supplied, get its model
1887
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1888
-            $ignored_model = $ignore_this_model_obj->get_model();
1889
-        } else {
1890
-            $ignored_model = null;
1891
-        }
1892
-        //now check all the relations of $this_model_obj_or_id and see if there
1893
-        //are any related model objects blocking it?
1894
-        $is_blocked = false;
1895
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1896
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1897
-                //if $ignore_this_model_obj was supplied, then for the query
1898
-                //on that model needs to be told to ignore $ignore_this_model_obj
1899
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1900
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1901
-                        array(
1902
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1903
-                                '!=',
1904
-                                $ignore_this_model_obj->ID(),
1905
-                            ),
1906
-                        ),
1907
-                    ));
1908
-                } else {
1909
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1910
-                }
1911
-                if ($related_model_objects) {
1912
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1913
-                    $is_blocked = true;
1914
-                }
1915
-            }
1916
-        }
1917
-        return $is_blocked;
1918
-    }
1919
-
1920
-
1921
-
1922
-    /**
1923
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1924
-     * well.
1925
-     *
1926
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1927
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1928
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
1929
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
1930
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
1931
-     *                                      easily corrupt your DB
1932
-     * @throws EE_Error
1933
-     * @return string    everything that comes after the WHERE statement.
1934
-     */
1935
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1936
-    {
1937
-        if ($this->has_primary_key_field()) {
1938
-            $primary_table = $this->_get_main_table();
1939
-            $other_tables = $this->_get_other_tables();
1940
-            $deletes = $query = array();
1941
-            foreach ($objects_for_deletion as $delete_object) {
1942
-                //before we mark this object for deletion,
1943
-                //make sure there's no related objects blocking its deletion (if we're checking)
1944
-                if (
1945
-                    $allow_blocking
1946
-                    && $this->delete_is_blocked_by_related_models(
1947
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
1948
-                    )
1949
-                ) {
1950
-                    continue;
1951
-                }
1952
-                //primary table deletes
1953
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1954
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1955
-                }
1956
-                //other tables
1957
-                if ( ! empty($other_tables)) {
1958
-                    foreach ($other_tables as $ot) {
1959
-                        //first check if we've got the foreign key column here.
1960
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1961
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1962
-                        }
1963
-                        // wait! it's entirely possible that we'll have a the primary key
1964
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
1965
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1966
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1967
-                        }
1968
-                        // finally, it is possible that the fk for this table is found
1969
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
1970
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1971
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1972
-                        }
1973
-                    }
1974
-                }
1975
-            }
1976
-            //we should have deletes now, so let's just go through and setup the where statement
1977
-            foreach ($deletes as $column => $values) {
1978
-                //make sure we have unique $values;
1979
-                $values = array_unique($values);
1980
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
1981
-            }
1982
-            return ! empty($query) ? implode(' AND ', $query) : '';
1983
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
1984
-            $ways_to_identify_a_row = array();
1985
-            $fields = $this->get_combined_primary_key_fields();
1986
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1987
-            foreach ($objects_for_deletion as $delete_object) {
1988
-                $values_for_each_cpk_for_a_row = array();
1989
-                foreach ($fields as $cpk_field) {
1990
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
1991
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1992
-                                                           . "="
1993
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
1994
-                    }
1995
-                }
1996
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1997
-            }
1998
-            return implode(" OR ", $ways_to_identify_a_row);
1999
-        } else {
2000
-            //so there's no primary key and no combined key...
2001
-            //sorry, can't help you
2002
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2003
-                "event_espresso"), get_class($this)));
2004
-        }
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2011
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2012
-     * column
2013
-     *
2014
-     * @param array  $query_params   like EEM_Base::get_all's
2015
-     * @param string $field_to_count field on model to count by (not column name)
2016
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2017
-     *                               that by the setting $distinct to TRUE;
2018
-     * @return int
2019
-     * @throws \EE_Error
2020
-     */
2021
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2022
-    {
2023
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2024
-        if ($field_to_count) {
2025
-            $field_obj = $this->field_settings_for($field_to_count);
2026
-            $column_to_count = $field_obj->get_qualified_column();
2027
-        } elseif ($this->has_primary_key_field()) {
2028
-            $pk_field_obj = $this->get_primary_key_field();
2029
-            $column_to_count = $pk_field_obj->get_qualified_column();
2030
-        } else {
2031
-            //there's no primary key
2032
-            //if we're counting distinct items, and there's no primary key,
2033
-            //we need to list out the columns for distinction;
2034
-            //otherwise we can just use star
2035
-            if ($distinct) {
2036
-                $columns_to_use = array();
2037
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2038
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2039
-                }
2040
-                $column_to_count = implode(',', $columns_to_use);
2041
-            } else {
2042
-                $column_to_count = '*';
2043
-            }
2044
-        }
2045
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2048
-    }
2049
-
2050
-
2051
-
2052
-    /**
2053
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2054
-     *
2055
-     * @param array  $query_params like EEM_Base::get_all
2056
-     * @param string $field_to_sum name of field (array key in $_fields array)
2057
-     * @return float
2058
-     * @throws \EE_Error
2059
-     */
2060
-    public function sum($query_params, $field_to_sum = null)
2061
-    {
2062
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2063
-        if ($field_to_sum) {
2064
-            $field_obj = $this->field_settings_for($field_to_sum);
2065
-        } else {
2066
-            $field_obj = $this->get_primary_key_field();
2067
-        }
2068
-        $column_to_count = $field_obj->get_qualified_column();
2069
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2070
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071
-        $data_type = $field_obj->get_wpdb_data_type();
2072
-        if ($data_type === '%d' || $data_type === '%s') {
2073
-            return (float)$return_value;
2074
-        } else {//must be %f
2075
-            return (float)$return_value;
2076
-        }
2077
-    }
2078
-
2079
-
2080
-
2081
-    /**
2082
-     * Just calls the specified method on $wpdb with the given arguments
2083
-     * Consolidates a little extra error handling code
2084
-     *
2085
-     * @param string $wpdb_method
2086
-     * @param array  $arguments_to_provide
2087
-     * @throws EE_Error
2088
-     * @global wpdb  $wpdb
2089
-     * @return mixed
2090
-     */
2091
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2092
-    {
2093
-        //if we're in maintenance mode level 2, DON'T run any queries
2094
-        //because level 2 indicates the database needs updating and
2095
-        //is probably out of sync with the code
2096
-        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2097
-            throw new EE_Error(sprintf(__("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.",
2098
-                "event_espresso")));
2099
-        }
2100
-        /** @type WPDB $wpdb */
2101
-        global $wpdb;
2102
-        if ( ! method_exists($wpdb, $wpdb_method)) {
2103
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2104
-                'event_espresso'), $wpdb_method));
2105
-        }
2106
-        if (WP_DEBUG) {
2107
-            $old_show_errors_value = $wpdb->show_errors;
2108
-            $wpdb->show_errors(false);
2109
-        }
2110
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2111
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2112
-        if (WP_DEBUG) {
2113
-            $wpdb->show_errors($old_show_errors_value);
2114
-            if ( ! empty($wpdb->last_error)) {
2115
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2116
-            } elseif ($result === false) {
2117
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2118
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2119
-            }
2120
-        } elseif ($result === false) {
2121
-            EE_Error::add_error(
2122
-                sprintf(
2123
-                    __('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"',
2124
-                        'event_espresso'),
2125
-                    $wpdb_method,
2126
-                    var_export($arguments_to_provide, true),
2127
-                    $wpdb->last_error
2128
-                ),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-        return $result;
2135
-    }
2136
-
2137
-
2138
-
2139
-    /**
2140
-     * Attempts to run the indicated WPDB method with the provided arguments,
2141
-     * and if there's an error tries to verify the DB is correct. Uses
2142
-     * the static property EEM_Base::$_db_verification_level to determine whether
2143
-     * we should try to fix the EE core db, the addons, or just give up
2144
-     *
2145
-     * @param string $wpdb_method
2146
-     * @param array  $arguments_to_provide
2147
-     * @return mixed
2148
-     */
2149
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2150
-    {
2151
-        /** @type WPDB $wpdb */
2152
-        global $wpdb;
2153
-        $wpdb->last_error = null;
2154
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2155
-        // was there an error running the query? but we don't care on new activations
2156
-        // (we're going to setup the DB anyway on new activations)
2157
-        if (($result === false || ! empty($wpdb->last_error))
2158
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2159
-        ) {
2160
-            switch (EEM_Base::$_db_verification_level) {
2161
-                case EEM_Base::db_verified_none :
2162
-                    // let's double-check core's DB
2163
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2164
-                    break;
2165
-                case EEM_Base::db_verified_core :
2166
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2167
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2168
-                    break;
2169
-                case EEM_Base::db_verified_addons :
2170
-                    // ummmm... you in trouble
2171
-                    return $result;
2172
-                    break;
2173
-            }
2174
-            if ( ! empty($error_message)) {
2175
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2176
-                trigger_error($error_message);
2177
-            }
2178
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2179
-        }
2180
-        return $result;
2181
-    }
2182
-
2183
-
2184
-
2185
-    /**
2186
-     * Verifies the EE core database is up-to-date and records that we've done it on
2187
-     * EEM_Base::$_db_verification_level
2188
-     *
2189
-     * @param string $wpdb_method
2190
-     * @param array  $arguments_to_provide
2191
-     * @return string
2192
-     */
2193
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2194
-    {
2195
-        /** @type WPDB $wpdb */
2196
-        global $wpdb;
2197
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2198
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2199
-        $error_message = sprintf(
2200
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2201
-                'event_espresso'),
2202
-            $wpdb->last_error,
2203
-            $wpdb_method,
2204
-            json_encode($arguments_to_provide)
2205
-        );
2206
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2207
-        return $error_message;
2208
-    }
2209
-
2210
-
2211
-
2212
-    /**
2213
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2214
-     * EEM_Base::$_db_verification_level
2215
-     *
2216
-     * @param $wpdb_method
2217
-     * @param $arguments_to_provide
2218
-     * @return string
2219
-     */
2220
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2221
-    {
2222
-        /** @type WPDB $wpdb */
2223
-        global $wpdb;
2224
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2225
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2226
-        $error_message = sprintf(
2227
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2228
-                'event_espresso'),
2229
-            $wpdb->last_error,
2230
-            $wpdb_method,
2231
-            json_encode($arguments_to_provide)
2232
-        );
2233
-        EE_System::instance()->initialize_addons();
2234
-        return $error_message;
2235
-    }
2236
-
2237
-
2238
-
2239
-    /**
2240
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2241
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2242
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2243
-     * ..."
2244
-     *
2245
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2246
-     * @return string
2247
-     */
2248
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249
-    {
2250
-        return " FROM " . $model_query_info->get_full_join_sql() .
2251
-               $model_query_info->get_where_sql() .
2252
-               $model_query_info->get_group_by_sql() .
2253
-               $model_query_info->get_having_sql() .
2254
-               $model_query_info->get_order_by_sql() .
2255
-               $model_query_info->get_limit_sql();
2256
-    }
2257
-
2258
-
2259
-
2260
-    /**
2261
-     * Set to easily debug the next X queries ran from this model.
2262
-     *
2263
-     * @param int $count
2264
-     */
2265
-    public function show_next_x_db_queries($count = 1)
2266
-    {
2267
-        $this->_show_next_x_db_queries = $count;
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * @param $sql_query
2274
-     */
2275
-    public function show_db_query_if_previously_requested($sql_query)
2276
-    {
2277
-        if ($this->_show_next_x_db_queries > 0) {
2278
-            echo $sql_query;
2279
-            $this->_show_next_x_db_queries--;
2280
-        }
2281
-    }
2282
-
2283
-
2284
-
2285
-    /**
2286
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2287
-     * There are the 3 cases:
2288
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2289
-     * $otherModelObject has no ID, it is first saved.
2290
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2291
-     * has no ID, it is first saved.
2292
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2293
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2294
-     * join table
2295
-     *
2296
-     * @param        EE_Base_Class                     /int $thisModelObject
2297
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2298
-     * @param string $relationName                     , key in EEM_Base::_relations
2299
-     *                                                 an attendee to a group, you also want to specify which role they
2300
-     *                                                 will have in that group. So you would use this parameter to
2301
-     *                                                 specify array('role-column-name'=>'role-id')
2302
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2303
-     *                                                 to for relation to methods that allow you to further specify
2304
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2305
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2306
-     *                                                 because these will be inserted in any new rows created as well.
2307
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2308
-     * @throws \EE_Error
2309
-     */
2310
-    public function add_relationship_to(
2311
-        $id_or_obj,
2312
-        $other_model_id_or_obj,
2313
-        $relationName,
2314
-        $extra_join_model_fields_n_values = array()
2315
-    ) {
2316
-        $relation_obj = $this->related_settings_for($relationName);
2317
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2318
-    }
2319
-
2320
-
2321
-
2322
-    /**
2323
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2324
-     * There are the 3 cases:
2325
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2326
-     * error
2327
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2328
-     * an error
2329
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2330
-     *
2331
-     * @param        EE_Base_Class /int $id_or_obj
2332
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2333
-     * @param string $relationName key in EEM_Base::_relations
2334
-     * @return boolean of success
2335
-     * @throws \EE_Error
2336
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2337
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2338
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2339
-     *                             because these will be inserted in any new rows created as well.
2340
-     */
2341
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2342
-    {
2343
-        $relation_obj = $this->related_settings_for($relationName);
2344
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2345
-    }
2346
-
2347
-
2348
-
2349
-    /**
2350
-     * @param mixed           $id_or_obj
2351
-     * @param string          $relationName
2352
-     * @param array           $where_query_params
2353
-     * @param EE_Base_Class[] objects to which relations were removed
2354
-     * @return \EE_Base_Class[]
2355
-     * @throws \EE_Error
2356
-     */
2357
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2358
-    {
2359
-        $relation_obj = $this->related_settings_for($relationName);
2360
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2361
-    }
2362
-
2363
-
2364
-
2365
-    /**
2366
-     * Gets all the related items of the specified $model_name, using $query_params.
2367
-     * Note: by default, we remove the "default query params"
2368
-     * because we want to get even deleted items etc.
2369
-     *
2370
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2371
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2372
-     * @param array  $query_params like EEM_Base::get_all
2373
-     * @return EE_Base_Class[]
2374
-     * @throws \EE_Error
2375
-     */
2376
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2377
-    {
2378
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2379
-        $relation_settings = $this->related_settings_for($model_name);
2380
-        return $relation_settings->get_all_related($model_obj, $query_params);
2381
-    }
2382
-
2383
-
2384
-
2385
-    /**
2386
-     * Deletes all the model objects across the relation indicated by $model_name
2387
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2388
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2389
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2390
-     *
2391
-     * @param EE_Base_Class|int|string $id_or_obj
2392
-     * @param string                   $model_name
2393
-     * @param array                    $query_params
2394
-     * @return int how many deleted
2395
-     * @throws \EE_Error
2396
-     */
2397
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2398
-    {
2399
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2400
-        $relation_settings = $this->related_settings_for($model_name);
2401
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2402
-    }
2403
-
2404
-
2405
-
2406
-    /**
2407
-     * Hard deletes all the model objects across the relation indicated by $model_name
2408
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2409
-     * the model objects can't be hard deleted because of blocking related model objects,
2410
-     * just does a soft-delete on them instead.
2411
-     *
2412
-     * @param EE_Base_Class|int|string $id_or_obj
2413
-     * @param string                   $model_name
2414
-     * @param array                    $query_params
2415
-     * @return int how many deleted
2416
-     * @throws \EE_Error
2417
-     */
2418
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2419
-    {
2420
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2421
-        $relation_settings = $this->related_settings_for($model_name);
2422
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2423
-    }
2424
-
2425
-
2426
-
2427
-    /**
2428
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2429
-     * unless otherwise specified in the $query_params
2430
-     *
2431
-     * @param        int             /EE_Base_Class $id_or_obj
2432
-     * @param string $model_name     like 'Event', or 'Registration'
2433
-     * @param array  $query_params   like EEM_Base::get_all's
2434
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2435
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2436
-     *                               that by the setting $distinct to TRUE;
2437
-     * @return int
2438
-     * @throws \EE_Error
2439
-     */
2440
-    public function count_related(
2441
-        $id_or_obj,
2442
-        $model_name,
2443
-        $query_params = array(),
2444
-        $field_to_count = null,
2445
-        $distinct = false
2446
-    ) {
2447
-        $related_model = $this->get_related_model_obj($model_name);
2448
-        //we're just going to use the query params on the related model's normal get_all query,
2449
-        //except add a condition to say to match the current mod
2450
-        if ( ! isset($query_params['default_where_conditions'])) {
2451
-            $query_params['default_where_conditions'] = 'none';
2452
-        }
2453
-        $this_model_name = $this->get_this_model_name();
2454
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2456
-        return $related_model->count($query_params, $field_to_count, $distinct);
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2463
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2464
-     *
2465
-     * @param        int           /EE_Base_Class $id_or_obj
2466
-     * @param string $model_name   like 'Event', or 'Registration'
2467
-     * @param array  $query_params like EEM_Base::get_all's
2468
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2469
-     * @return float
2470
-     * @throws \EE_Error
2471
-     */
2472
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2473
-    {
2474
-        $related_model = $this->get_related_model_obj($model_name);
2475
-        if ( ! is_array($query_params)) {
2476
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2477
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2478
-                    gettype($query_params)), '4.6.0');
2479
-            $query_params = array();
2480
-        }
2481
-        //we're just going to use the query params on the related model's normal get_all query,
2482
-        //except add a condition to say to match the current mod
2483
-        if ( ! isset($query_params['default_where_conditions'])) {
2484
-            $query_params['default_where_conditions'] = 'none';
2485
-        }
2486
-        $this_model_name = $this->get_this_model_name();
2487
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2489
-        return $related_model->sum($query_params, $field_to_sum);
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2496
-     * $modelObject
2497
-     *
2498
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2499
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2500
-     * @param array               $query_params     like EEM_Base::get_all's
2501
-     * @return EE_Base_Class
2502
-     * @throws \EE_Error
2503
-     */
2504
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2505
-    {
2506
-        $query_params['limit'] = 1;
2507
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2508
-        if ($results) {
2509
-            return array_shift($results);
2510
-        } else {
2511
-            return null;
2512
-        }
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2519
-     *
2520
-     * @return string
2521
-     */
2522
-    public function get_this_model_name()
2523
-    {
2524
-        return str_replace("EEM_", "", get_class($this));
2525
-    }
2526
-
2527
-
2528
-
2529
-    /**
2530
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2531
-     *
2532
-     * @return EE_Any_Foreign_Model_Name_Field
2533
-     * @throws EE_Error
2534
-     */
2535
-    public function get_field_containing_related_model_name()
2536
-    {
2537
-        foreach ($this->field_settings(true) as $field) {
2538
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2539
-                $field_with_model_name = $field;
2540
-            }
2541
-        }
2542
-        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2543
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2544
-                $this->get_this_model_name()));
2545
-        }
2546
-        return $field_with_model_name;
2547
-    }
2548
-
2549
-
2550
-
2551
-    /**
2552
-     * Inserts a new entry into the database, for each table.
2553
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2554
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2555
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2556
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2557
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2558
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2559
-     *
2560
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2561
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2562
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2563
-     *                              of EEM_Base)
2564
-     * @return int new primary key on main table that got inserted
2565
-     * @throws EE_Error
2566
-     */
2567
-    public function insert($field_n_values)
2568
-    {
2569
-        /**
2570
-         * Filters the fields and their values before inserting an item using the models
2571
-         *
2572
-         * @param array    $fields_n_values keys are the fields and values are their new values
2573
-         * @param EEM_Base $model           the model used
2574
-         */
2575
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2577
-            $main_table = $this->_get_main_table();
2578
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2579
-            if ($new_id !== false) {
2580
-                foreach ($this->_get_other_tables() as $other_table) {
2581
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2582
-                }
2583
-            }
2584
-            /**
2585
-             * Done just after attempting to insert a new model object
2586
-             *
2587
-             * @param EEM_Base   $model           used
2588
-             * @param array      $fields_n_values fields and their values
2589
-             * @param int|string the              ID of the newly-inserted model object
2590
-             */
2591
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2592
-            return $new_id;
2593
-        } else {
2594
-            return false;
2595
-        }
2596
-    }
2597
-
2598
-
2599
-
2600
-    /**
2601
-     * Checks that the result would satisfy the unique indexes on this model
2602
-     *
2603
-     * @param array  $field_n_values
2604
-     * @param string $action
2605
-     * @return boolean
2606
-     * @throws \EE_Error
2607
-     */
2608
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2609
-    {
2610
-        foreach ($this->unique_indexes() as $index_name => $index) {
2611
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2612
-            if ($this->exists(array($uniqueness_where_params))) {
2613
-                EE_Error::add_error(
2614
-                    sprintf(
2615
-                        __(
2616
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2617
-                            "event_espresso"
2618
-                        ),
2619
-                        $action,
2620
-                        $this->_get_class_name(),
2621
-                        $index_name,
2622
-                        implode(",", $index->field_names()),
2623
-                        http_build_query($uniqueness_where_params)
2624
-                    ),
2625
-                    __FILE__,
2626
-                    __FUNCTION__,
2627
-                    __LINE__
2628
-                );
2629
-                return false;
2630
-            }
2631
-        }
2632
-        return true;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Checks the database for an item that conflicts (ie, if this item were
2639
-     * saved to the DB would break some uniqueness requirement, like a primary key
2640
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2641
-     * can be either an EE_Base_Class or an array of fields n values
2642
-     *
2643
-     * @param EE_Base_Class|array $obj_or_fields_array
2644
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2645
-     *                                                 when looking for conflicts
2646
-     *                                                 (ie, if false, we ignore the model object's primary key
2647
-     *                                                 when finding "conflicts". If true, it's also considered).
2648
-     *                                                 Only works for INT primary key,
2649
-     *                                                 STRING primary keys cannot be ignored
2650
-     * @throws EE_Error
2651
-     * @return EE_Base_Class|array
2652
-     */
2653
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2654
-    {
2655
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2656
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2657
-        } elseif (is_array($obj_or_fields_array)) {
2658
-            $fields_n_values = $obj_or_fields_array;
2659
-        } else {
2660
-            throw new EE_Error(
2661
-                sprintf(
2662
-                    __(
2663
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2664
-                        "event_espresso"
2665
-                    ),
2666
-                    get_class($this),
2667
-                    $obj_or_fields_array
2668
-                )
2669
-            );
2670
-        }
2671
-        $query_params = array();
2672
-        if ($this->has_primary_key_field()
2673
-            && ($include_primary_key
2674
-                || $this->get_primary_key_field()
2675
-                   instanceof
2676
-                   EE_Primary_Key_String_Field)
2677
-            && isset($fields_n_values[$this->primary_key_name()])
2678
-        ) {
2679
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2680
-        }
2681
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2684
-        }
2685
-        //if there is nothing to base this search on, then we shouldn't find anything
2686
-        if (empty($query_params)) {
2687
-            return array();
2688
-        } else {
2689
-            return $this->get_one($query_params);
2690
-        }
2691
-    }
2692
-
2693
-
2694
-
2695
-    /**
2696
-     * Like count, but is optimized and returns a boolean instead of an int
2697
-     *
2698
-     * @param array $query_params
2699
-     * @return boolean
2700
-     * @throws \EE_Error
2701
-     */
2702
-    public function exists($query_params)
2703
-    {
2704
-        $query_params['limit'] = 1;
2705
-        return $this->count($query_params) > 0;
2706
-    }
2707
-
2708
-
2709
-
2710
-    /**
2711
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2712
-     *
2713
-     * @param int|string $id
2714
-     * @return boolean
2715
-     * @throws \EE_Error
2716
-     */
2717
-    public function exists_by_ID($id)
2718
-    {
2719
-        return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2726
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2727
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2728
-     * on the main table)
2729
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2730
-     * cases where we want to call it directly rather than via insert().
2731
-     *
2732
-     * @access   protected
2733
-     * @param EE_Table_Base $table
2734
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2735
-     *                                       float
2736
-     * @param int           $new_id          for now we assume only int keys
2737
-     * @throws EE_Error
2738
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2739
-     * @return int ID of new row inserted, or FALSE on failure
2740
-     */
2741
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2742
-    {
2743
-        global $wpdb;
2744
-        $insertion_col_n_values = array();
2745
-        $format_for_insertion = array();
2746
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2747
-        foreach ($fields_on_table as $field_name => $field_obj) {
2748
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2749
-            if ($field_obj->is_auto_increment()) {
2750
-                continue;
2751
-            }
2752
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2753
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2754
-            if ($prepared_value !== null) {
2755
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2756
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2757
-            }
2758
-        }
2759
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2760
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2761
-            //so add the fk to the main table as a column
2762
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2764
-        }
2765
-        //insert the new entry
2766
-        $result = $this->_do_wpdb_query('insert',
2767
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2768
-        if ($result === false) {
2769
-            return false;
2770
-        }
2771
-        //ok, now what do we return for the ID of the newly-inserted thing?
2772
-        if ($this->has_primary_key_field()) {
2773
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2774
-                return $wpdb->insert_id;
2775
-            } else {
2776
-                //it's not an auto-increment primary key, so
2777
-                //it must have been supplied
2778
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2779
-            }
2780
-        } else {
2781
-            //we can't return a  primary key because there is none. instead return
2782
-            //a unique string indicating this model
2783
-            return $this->get_index_primary_key_string($fields_n_values);
2784
-        }
2785
-    }
2786
-
2787
-
2788
-
2789
-    /**
2790
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2791
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2792
-     * and there is no default, we pass it along. WPDB will take care of it)
2793
-     *
2794
-     * @param EE_Model_Field_Base $field_obj
2795
-     * @param array               $fields_n_values
2796
-     * @return mixed string|int|float depending on what the table column will be expecting
2797
-     * @throws \EE_Error
2798
-     */
2799
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2800
-    {
2801
-        //if this field doesn't allow nullable, don't allow it
2802
-        if ( ! $field_obj->is_nullable()
2803
-             && (
2804
-                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2805
-        ) {
2806
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2807
-        }
2808
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2809
-            : null;
2810
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2811
-    }
2812
-
2813
-
2814
-
2815
-    /**
2816
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2817
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2818
-     * the field's prepare_for_set() method.
2819
-     *
2820
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2821
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2822
-     *                                   top of file)
2823
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2824
-     *                                   $value is a custom selection
2825
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2826
-     */
2827
-    private function _prepare_value_for_use_in_db($value, $field)
2828
-    {
2829
-        if ($field && $field instanceof EE_Model_Field_Base) {
2830
-            switch ($this->_values_already_prepared_by_model_object) {
2831
-                /** @noinspection PhpMissingBreakStatementInspection */
2832
-                case self::not_prepared_by_model_object:
2833
-                    $value = $field->prepare_for_set($value);
2834
-                //purposefully left out "return"
2835
-                case self::prepared_by_model_object:
2836
-                    $value = $field->prepare_for_use_in_db($value);
2837
-                case self::prepared_for_use_in_db:
2838
-                    //leave the value alone
2839
-            }
2840
-            return $value;
2841
-        } else {
2842
-            return $value;
2843
-        }
2844
-    }
2845
-
2846
-
2847
-
2848
-    /**
2849
-     * Returns the main table on this model
2850
-     *
2851
-     * @return EE_Primary_Table
2852
-     * @throws EE_Error
2853
-     */
2854
-    protected function _get_main_table()
2855
-    {
2856
-        foreach ($this->_tables as $table) {
2857
-            if ($table instanceof EE_Primary_Table) {
2858
-                return $table;
2859
-            }
2860
-        }
2861
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2862
-            'event_espresso'), get_class($this)));
2863
-    }
2864
-
2865
-
2866
-
2867
-    /**
2868
-     * table
2869
-     * returns EE_Primary_Table table name
2870
-     *
2871
-     * @return string
2872
-     * @throws \EE_Error
2873
-     */
2874
-    public function table()
2875
-    {
2876
-        return $this->_get_main_table()->get_table_name();
2877
-    }
2878
-
2879
-
2880
-
2881
-    /**
2882
-     * table
2883
-     * returns first EE_Secondary_Table table name
2884
-     *
2885
-     * @return string
2886
-     */
2887
-    public function second_table()
2888
-    {
2889
-        // grab second table from tables array
2890
-        $second_table = end($this->_tables);
2891
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2892
-    }
2893
-
2894
-
2895
-
2896
-    /**
2897
-     * get_table_obj_by_alias
2898
-     * returns table name given it's alias
2899
-     *
2900
-     * @param string $table_alias
2901
-     * @return EE_Primary_Table | EE_Secondary_Table
2902
-     */
2903
-    public function get_table_obj_by_alias($table_alias = '')
2904
-    {
2905
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2906
-    }
2907
-
2908
-
2909
-
2910
-    /**
2911
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2912
-     *
2913
-     * @return EE_Secondary_Table[]
2914
-     */
2915
-    protected function _get_other_tables()
2916
-    {
2917
-        $other_tables = array();
2918
-        foreach ($this->_tables as $table_alias => $table) {
2919
-            if ($table instanceof EE_Secondary_Table) {
2920
-                $other_tables[$table_alias] = $table;
2921
-            }
2922
-        }
2923
-        return $other_tables;
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Finds all the fields that correspond to the given table
2930
-     *
2931
-     * @param string $table_alias , array key in EEM_Base::_tables
2932
-     * @return EE_Model_Field_Base[]
2933
-     */
2934
-    public function _get_fields_for_table($table_alias)
2935
-    {
2936
-        return $this->_fields[$table_alias];
2937
-    }
2938
-
2939
-
2940
-
2941
-    /**
2942
-     * Recurses through all the where parameters, and finds all the related models we'll need
2943
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2944
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2945
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2946
-     * related Registration, Transaction, and Payment models.
2947
-     *
2948
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2949
-     * @return EE_Model_Query_Info_Carrier
2950
-     * @throws \EE_Error
2951
-     */
2952
-    public function _extract_related_models_from_query($query_params)
2953
-    {
2954
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
2955
-        if (array_key_exists(0, $query_params)) {
2956
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2957
-        }
2958
-        if (array_key_exists('group_by', $query_params)) {
2959
-            if (is_array($query_params['group_by'])) {
2960
-                $this->_extract_related_models_from_sub_params_array_values(
2961
-                    $query_params['group_by'],
2962
-                    $query_info_carrier,
2963
-                    'group_by'
2964
-                );
2965
-            } elseif ( ! empty ($query_params['group_by'])) {
2966
-                $this->_extract_related_model_info_from_query_param(
2967
-                    $query_params['group_by'],
2968
-                    $query_info_carrier,
2969
-                    'group_by'
2970
-                );
2971
-            }
2972
-        }
2973
-        if (array_key_exists('having', $query_params)) {
2974
-            $this->_extract_related_models_from_sub_params_array_keys(
2975
-                $query_params[0],
2976
-                $query_info_carrier,
2977
-                'having'
2978
-            );
2979
-        }
2980
-        if (array_key_exists('order_by', $query_params)) {
2981
-            if (is_array($query_params['order_by'])) {
2982
-                $this->_extract_related_models_from_sub_params_array_keys(
2983
-                    $query_params['order_by'],
2984
-                    $query_info_carrier,
2985
-                    'order_by'
2986
-                );
2987
-            } elseif ( ! empty($query_params['order_by'])) {
2988
-                $this->_extract_related_model_info_from_query_param(
2989
-                    $query_params['order_by'],
2990
-                    $query_info_carrier,
2991
-                    'order_by'
2992
-                );
2993
-            }
2994
-        }
2995
-        if (array_key_exists('force_join', $query_params)) {
2996
-            $this->_extract_related_models_from_sub_params_array_values(
2997
-                $query_params['force_join'],
2998
-                $query_info_carrier,
2999
-                'force_join'
3000
-            );
3001
-        }
3002
-        return $query_info_carrier;
3003
-    }
3004
-
3005
-
3006
-
3007
-    /**
3008
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3009
-     *
3010
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3011
-     *                                                      $query_params['having']
3012
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3013
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3014
-     * @throws EE_Error
3015
-     * @return \EE_Model_Query_Info_Carrier
3016
-     */
3017
-    private function _extract_related_models_from_sub_params_array_keys(
3018
-        $sub_query_params,
3019
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3020
-        $query_param_type
3021
-    ) {
3022
-        if ( ! empty($sub_query_params)) {
3023
-            $sub_query_params = (array)$sub_query_params;
3024
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3027
-                    $query_param_type);
3028
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3029
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3030
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3031
-                //of array('Registration.TXN_ID'=>23)
3032
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3033
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3034
-                    if ( ! is_array($possibly_array_of_params)) {
3035
-                        throw new EE_Error(sprintf(__("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'))",
3036
-                            "event_espresso"),
3037
-                            $param, $possibly_array_of_params));
3038
-                    } else {
3039
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3040
-                            $model_query_info_carrier, $query_param_type);
3041
-                    }
3042
-                } elseif ($query_param_type === 0 //ie WHERE
3043
-                          && is_array($possibly_array_of_params)
3044
-                          && isset($possibly_array_of_params[2])
3045
-                          && $possibly_array_of_params[2] == true
3046
-                ) {
3047
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3048
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3049
-                    //from which we should extract query parameters!
3050
-                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3051
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3052
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3053
-                    }
3054
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3055
-                        $model_query_info_carrier, $query_param_type);
3056
-                }
3057
-            }
3058
-        }
3059
-        return $model_query_info_carrier;
3060
-    }
3061
-
3062
-
3063
-
3064
-    /**
3065
-     * For extracting related models from forced_joins, where the array values contain the info about what
3066
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3067
-     *
3068
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3069
-     *                                                      $query_params['having']
3070
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3071
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3072
-     * @throws EE_Error
3073
-     * @return \EE_Model_Query_Info_Carrier
3074
-     */
3075
-    private function _extract_related_models_from_sub_params_array_values(
3076
-        $sub_query_params,
3077
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3078
-        $query_param_type
3079
-    ) {
3080
-        if ( ! empty($sub_query_params)) {
3081
-            if ( ! is_array($sub_query_params)) {
3082
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3083
-                    $sub_query_params));
3084
-            }
3085
-            foreach ($sub_query_params as $param) {
3086
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3087
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3088
-                    $query_param_type);
3089
-            }
3090
-        }
3091
-        return $model_query_info_carrier;
3092
-    }
3093
-
3094
-
3095
-
3096
-    /**
3097
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3098
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3099
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3100
-     * but use them in a different order. Eg, we need to know what models we are querying
3101
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3102
-     * other models before we can finalize the where clause SQL.
3103
-     *
3104
-     * @param array $query_params
3105
-     * @throws EE_Error
3106
-     * @return EE_Model_Query_Info_Carrier
3107
-     */
3108
-    public function _create_model_query_info_carrier($query_params)
3109
-    {
3110
-        if ( ! is_array($query_params)) {
3111
-            EE_Error::doing_it_wrong(
3112
-                'EEM_Base::_create_model_query_info_carrier',
3113
-                sprintf(
3114
-                    __(
3115
-                        '$query_params should be an array, you passed a variable of type %s',
3116
-                        'event_espresso'
3117
-                    ),
3118
-                    gettype($query_params)
3119
-                ),
3120
-                '4.6.0'
3121
-            );
3122
-            $query_params = array();
3123
-        }
3124
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3125
-        //first check if we should alter the query to account for caps or not
3126
-        //because the caps might require us to do extra joins
3127
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3128
-            $query_params[0] = $where_query_params = array_replace_recursive(
3129
-                $where_query_params,
3130
-                $this->caps_where_conditions(
3131
-                    $query_params['caps']
3132
-                )
3133
-            );
3134
-        }
3135
-        $query_object = $this->_extract_related_models_from_query($query_params);
3136
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3137
-        foreach ($where_query_params as $key => $value) {
3138
-            if (is_int($key)) {
3139
-                throw new EE_Error(
3140
-                    sprintf(
3141
-                        __(
3142
-                            "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.",
3143
-                            "event_espresso"
3144
-                        ),
3145
-                        $key,
3146
-                        var_export($value, true),
3147
-                        var_export($query_params, true),
3148
-                        get_class($this)
3149
-                    )
3150
-                );
3151
-            }
3152
-        }
3153
-        if (
3154
-            array_key_exists('default_where_conditions', $query_params)
3155
-            && ! empty($query_params['default_where_conditions'])
3156
-        ) {
3157
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3158
-        } else {
3159
-            $use_default_where_conditions = 'all';
3160
-        }
3161
-        $where_query_params = array_merge(
3162
-            $this->_get_default_where_conditions_for_models_in_query(
3163
-                $query_object,
3164
-                $use_default_where_conditions,
3165
-                $where_query_params
3166
-            ),
3167
-            $where_query_params
3168
-        );
3169
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3170
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3171
-        // So we need to setup a subquery and use that for the main join.
3172
-        // Note for now this only works on the primary table for the model.
3173
-        // So for instance, you could set the limit array like this:
3174
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3175
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3176
-            $query_object->set_main_model_join_sql(
3177
-                $this->_construct_limit_join_select(
3178
-                    $query_params['on_join_limit'][0],
3179
-                    $query_params['on_join_limit'][1]
3180
-                )
3181
-            );
3182
-        }
3183
-        //set limit
3184
-        if (array_key_exists('limit', $query_params)) {
3185
-            if (is_array($query_params['limit'])) {
3186
-                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3187
-                    $e = sprintf(
3188
-                        __(
3189
-                            "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)",
3190
-                            "event_espresso"
3191
-                        ),
3192
-                        http_build_query($query_params['limit'])
3193
-                    );
3194
-                    throw new EE_Error($e . "|" . $e);
3195
-                }
3196
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3198
-            } elseif ( ! empty ($query_params['limit'])) {
3199
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3200
-            }
3201
-        }
3202
-        //set order by
3203
-        if (array_key_exists('order_by', $query_params)) {
3204
-            if (is_array($query_params['order_by'])) {
3205
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3206
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3207
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3208
-                if (array_key_exists('order', $query_params)) {
3209
-                    throw new EE_Error(
3210
-                        sprintf(
3211
-                            __(
3212
-                                "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 ",
3213
-                                "event_espresso"
3214
-                            ),
3215
-                            get_class($this),
3216
-                            implode(", ", array_keys($query_params['order_by'])),
3217
-                            implode(", ", $query_params['order_by']),
3218
-                            $query_params['order']
3219
-                        )
3220
-                    );
3221
-                }
3222
-                $this->_extract_related_models_from_sub_params_array_keys(
3223
-                    $query_params['order_by'],
3224
-                    $query_object,
3225
-                    'order_by'
3226
-                );
3227
-                //assume it's an array of fields to order by
3228
-                $order_array = array();
3229
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230
-                    $order = $this->_extract_order($order);
3231
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3232
-                }
3233
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3234
-            } elseif ( ! empty ($query_params['order_by'])) {
3235
-                $this->_extract_related_model_info_from_query_param(
3236
-                    $query_params['order_by'],
3237
-                    $query_object,
3238
-                    'order',
3239
-                    $query_params['order_by']
3240
-                );
3241
-                $order = isset($query_params['order'])
3242
-                    ? $this->_extract_order($query_params['order'])
3243
-                    : 'DESC';
3244
-                $query_object->set_order_by_sql(
3245
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3246
-                );
3247
-            }
3248
-        }
3249
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3250
-        if ( ! array_key_exists('order_by', $query_params)
3251
-             && array_key_exists('order', $query_params)
3252
-             && ! empty($query_params['order'])
3253
-        ) {
3254
-            $pk_field = $this->get_primary_key_field();
3255
-            $order = $this->_extract_order($query_params['order']);
3256
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3257
-        }
3258
-        //set group by
3259
-        if (array_key_exists('group_by', $query_params)) {
3260
-            if (is_array($query_params['group_by'])) {
3261
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3262
-                $group_by_array = array();
3263
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265
-                }
3266
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3267
-            } elseif ( ! empty ($query_params['group_by'])) {
3268
-                $query_object->set_group_by_sql(
3269
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3270
-                );
3271
-            }
3272
-        }
3273
-        //set having
3274
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3275
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3276
-        }
3277
-        //now, just verify they didn't pass anything wack
3278
-        foreach ($query_params as $query_key => $query_value) {
3279
-            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3280
-                throw new EE_Error(
3281
-                    sprintf(
3282
-                        __(
3283
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3284
-                            'event_espresso'
3285
-                        ),
3286
-                        $query_key,
3287
-                        get_class($this),
3288
-                        //						print_r( $this->_allowed_query_params, TRUE )
3289
-                        implode(',', $this->_allowed_query_params)
3290
-                    )
3291
-                );
3292
-            }
3293
-        }
3294
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3295
-        if (empty($main_model_join_sql)) {
3296
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3297
-        }
3298
-        return $query_object;
3299
-    }
3300
-
3301
-
3302
-
3303
-    /**
3304
-     * Gets the where conditions that should be imposed on the query based on the
3305
-     * context (eg reading frontend, backend, edit or delete).
3306
-     *
3307
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3308
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3309
-     * @throws \EE_Error
3310
-     */
3311
-    public function caps_where_conditions($context = self::caps_read)
3312
-    {
3313
-        EEM_Base::verify_is_valid_cap_context($context);
3314
-        $cap_where_conditions = array();
3315
-        $cap_restrictions = $this->caps_missing($context);
3316
-        /**
3317
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3318
-         */
3319
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3320
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3321
-                $restriction_if_no_cap->get_default_where_conditions());
3322
-        }
3323
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3324
-            $cap_restrictions);
3325
-    }
3326
-
3327
-
3328
-
3329
-    /**
3330
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3331
-     * otherwise throws an exception
3332
-     *
3333
-     * @param string $should_be_order_string
3334
-     * @return string either ASC, asc, DESC or desc
3335
-     * @throws EE_Error
3336
-     */
3337
-    private function _extract_order($should_be_order_string)
3338
-    {
3339
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3340
-            return $should_be_order_string;
3341
-        } else {
3342
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3343
-                "event_espresso"), get_class($this), $should_be_order_string));
3344
-        }
3345
-    }
3346
-
3347
-
3348
-
3349
-    /**
3350
-     * Looks at all the models which are included in this query, and asks each
3351
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3352
-     * so they can be merged
3353
-     *
3354
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3355
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3356
-     *                                                                  'none' means NO default where conditions will
3357
-     *                                                                  be used AT ALL during this query.
3358
-     *                                                                  'other_models_only' means default where
3359
-     *                                                                  conditions from other models will be used, but
3360
-     *                                                                  not for this primary model. 'all', the default,
3361
-     *                                                                  means default where conditions will apply as
3362
-     *                                                                  normal
3363
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3364
-     * @throws EE_Error
3365
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3366
-     */
3367
-    private function _get_default_where_conditions_for_models_in_query(
3368
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3369
-        $use_default_where_conditions = 'all',
3370
-        $where_query_params = array()
3371
-    ) {
3372
-        $allowed_used_default_where_conditions_values = array(
3373
-            'all',
3374
-            'this_model_only',
3375
-            'other_models_only',
3376
-            'minimum',
3377
-            'none',
3378
-        );
3379
-        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3380
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3381
-                "event_espresso"), $use_default_where_conditions,
3382
-                implode(", ", $allowed_used_default_where_conditions_values)));
3383
-        }
3384
-        $universal_query_params = array();
3385
-        if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3386
-            $universal_query_params = $this->_get_default_where_conditions();
3387
-        } else if ($use_default_where_conditions === 'minimum') {
3388
-            $universal_query_params = $this->_get_minimum_where_conditions();
3389
-        }
3390
-        if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3391
-            foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3392
-                $related_model = $this->get_related_model_obj($model_name);
3393
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3394
-                $overrides = $this->_override_defaults_or_make_null_friendly(
3395
-                    $related_model_universal_where_params,
3396
-                    $where_query_params,
3397
-                    $related_model,
3398
-                    $model_relation_path
3399
-                );
3400
-                $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3401
-                    $universal_query_params,
3402
-                    $overrides
3403
-                );
3404
-            }
3405
-        }
3406
-        return $universal_query_params;
3407
-    }
3408
-
3409
-
3410
-
3411
-    /**
3412
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3413
-     * then we also add a special where condition which allows for that model's primary key
3414
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3415
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3416
-     *
3417
-     * @param array    $default_where_conditions
3418
-     * @param array    $provided_where_conditions
3419
-     * @param EEM_Base $model
3420
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3421
-     * @return array like EEM_Base::get_all's $query_params[0]
3422
-     * @throws \EE_Error
3423
-     */
3424
-    private function _override_defaults_or_make_null_friendly(
3425
-        $default_where_conditions,
3426
-        $provided_where_conditions,
3427
-        $model,
3428
-        $model_relation_path
3429
-    ) {
3430
-        $null_friendly_where_conditions = array();
3431
-        $none_overridden = true;
3432
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3433
-        foreach ($default_where_conditions as $key => $val) {
3434
-            if (isset($provided_where_conditions[$key])) {
3435
-                $none_overridden = false;
3436
-            } else {
3437
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3438
-            }
3439
-        }
3440
-        if ($none_overridden && $default_where_conditions) {
3441
-            if ($model->has_primary_key_field()) {
3442
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3443
-                                                                                . "."
3444
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3445
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+
447
+
448
+	/**
449
+	 * About all child constructors:
450
+	 * they should define the _tables, _fields and _model_relations arrays.
451
+	 * Should ALWAYS be called after child constructor.
452
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
453
+	 * finalizes constructing all the object's attributes.
454
+	 * Generally, rather than requiring a child to code
455
+	 * $this->_tables = array(
456
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
+	 *        ...);
458
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
+	 * each EE_Table has a function to set the table's alias after the constructor, using
460
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
+	 * do something similar.
462
+	 *
463
+	 * @param null $timezone
464
+	 * @throws \EE_Error
465
+	 */
466
+	protected function __construct($timezone = null)
467
+	{
468
+		// check that the model has not been loaded too soon
469
+		if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
+			throw new EE_Error (
471
+				sprintf(
472
+					__('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.',
473
+						'event_espresso'),
474
+					get_class($this)
475
+				)
476
+			);
477
+		}
478
+		/**
479
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
+		 */
481
+		if (empty(EEM_Base::$_model_query_blog_id)) {
482
+			EEM_Base::set_model_query_blog_id();
483
+		}
484
+		/**
485
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
+		 * just use EE_Register_Model_Extension
487
+		 *
488
+		 * @var EE_Table_Base[] $_tables
489
+		 */
490
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
+		foreach ($this->_tables as $table_alias => $table_obj) {
492
+			/** @var $table_obj EE_Table_Base */
493
+			$table_obj->_construct_finalize_with_alias($table_alias);
494
+			if ($table_obj instanceof EE_Secondary_Table) {
495
+				/** @var $table_obj EE_Secondary_Table */
496
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
+			}
498
+		}
499
+		/**
500
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
+		 * EE_Register_Model_Extension
502
+		 *
503
+		 * @param EE_Model_Field_Base[] $_fields
504
+		 */
505
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
+		$this->_invalidate_field_caches();
507
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
508
+			if ( ! array_key_exists($table_alias, $this->_tables)) {
509
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
+			}
512
+			foreach ($fields_for_table as $field_name => $field_obj) {
513
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
+				//primary key field base has a slightly different _construct_finalize
515
+				/** @var $field_obj EE_Model_Field_Base */
516
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
+			}
518
+		}
519
+		// everything is related to Extra_Meta
520
+		if (get_class($this) !== 'EEM_Extra_Meta') {
521
+			//make extra meta related to everything, but don't block deleting things just
522
+			//because they have related extra meta info. For now just orphan those extra meta
523
+			//in the future we should automatically delete them
524
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
+		}
526
+		//and change logs
527
+		if (get_class($this) !== 'EEM_Change_Log') {
528
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
+		}
530
+		/**
531
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
+		 * EE_Register_Model_Extension
533
+		 *
534
+		 * @param EE_Model_Relation_Base[] $_model_relations
535
+		 */
536
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
+			$this->_model_relations);
538
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
539
+			/** @var $relation_obj EE_Model_Relation_Base */
540
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
+		}
542
+		foreach ($this->_indexes as $index_name => $index_obj) {
543
+			/** @var $index_obj EE_Index */
544
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
+		}
546
+		$this->set_timezone($timezone);
547
+		//finalize default where condition strategy, or set default
548
+		if ( ! $this->_default_where_conditions_strategy) {
549
+			//nothing was set during child constructor, so set default
550
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
+		}
552
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
553
+		if ( ! $this->_minimum_where_conditions_strategy) {
554
+			//nothing was set during child constructor, so set default
555
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
+		}
557
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
559
+		//to indicate to NOT set it, set it to the logical default
560
+		if ($this->_caps_slug === null) {
561
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
+		}
563
+		//initialize the standard cap restriction generators if none were specified by the child constructor
564
+		if ($this->_cap_restriction_generators !== false) {
565
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
+				if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
568
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
+						new EE_Restriction_Generator_Protected(),
570
+						$cap_context,
571
+						$this
572
+					);
573
+				}
574
+			}
575
+		}
576
+		//if there are cap restriction generators, use them to make the default cap restrictions
577
+		if ($this->_cap_restriction_generators !== false) {
578
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
+				if ( ! $generator_object) {
580
+					continue;
581
+				}
582
+				if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
+					throw new EE_Error(
584
+						sprintf(
585
+							__('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.',
586
+								'event_espresso'),
587
+							$context,
588
+							$this->get_this_model_name()
589
+						)
590
+					);
591
+				}
592
+				$action = $this->cap_action_for_context($context);
593
+				if ( ! $generator_object->construction_finalized()) {
594
+					$generator_object->_construct_finalize($this, $action);
595
+				}
596
+			}
597
+		}
598
+		do_action('AHEE__' . get_class($this) . '__construct__end');
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * Generates the cap restrictions for the given context, or if they were
605
+	 * already generated just gets what's cached
606
+	 *
607
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
608
+	 * @return EE_Default_Where_Conditions[]
609
+	 */
610
+	protected function _generate_cap_restrictions($context)
611
+	{
612
+		if (isset($this->_cap_restriction_generators[$context])
613
+			&& $this->_cap_restriction_generators[$context]
614
+			   instanceof
615
+			   EE_Restriction_Generator_Base
616
+		) {
617
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
+		} else {
619
+			return array();
620
+		}
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * Used to set the $_model_query_blog_id static property.
627
+	 *
628
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
+	 *                      value for get_current_blog_id() will be used.
630
+	 */
631
+	public static function set_model_query_blog_id($blog_id = 0)
632
+	{
633
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
+	}
635
+
636
+
637
+
638
+	/**
639
+	 * Returns whatever is set as the internal $model_query_blog_id.
640
+	 *
641
+	 * @return int
642
+	 */
643
+	public static function get_model_query_blog_id()
644
+	{
645
+		return EEM_Base::$_model_query_blog_id;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 *        This function is a singleton method used to instantiate the Espresso_model object
652
+	 *
653
+	 * @access public
654
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
+	 *                         timezone in the 'timezone_string' wp option)
658
+	 * @return static (as in the concrete child class)
659
+	 */
660
+	public static function instance($timezone = null)
661
+	{
662
+		// check if instance of Espresso_model already exists
663
+		if ( ! static::$_instance instanceof static) {
664
+			// instantiate Espresso_model
665
+			static::$_instance = new static($timezone);
666
+		}
667
+		//we might have a timezone set, let set_timezone decide what to do with it
668
+		static::$_instance->set_timezone($timezone);
669
+		// Espresso_model object
670
+		return static::$_instance;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * resets the model and returns it
677
+	 *
678
+	 * @param null | string $timezone
679
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
+	 * all its properties reset; if it wasn't instantiated, returns null)
681
+	 */
682
+	public static function reset($timezone = null)
683
+	{
684
+		if (static::$_instance instanceof EEM_Base) {
685
+			//let's try to NOT swap out the current instance for a new one
686
+			//because if someone has a reference to it, we can't remove their reference
687
+			//so it's best to keep using the same reference, but change the original object
688
+			//reset all its properties to their original values as defined in the class
689
+			$r = new ReflectionClass(get_class(static::$_instance));
690
+			$static_properties = $r->getStaticProperties();
691
+			foreach ($r->getDefaultProperties() as $property => $value) {
692
+				//don't set instance to null like it was originally,
693
+				//but it's static anyways, and we're ignoring static properties (for now at least)
694
+				if ( ! isset($static_properties[$property])) {
695
+					static::$_instance->{$property} = $value;
696
+				}
697
+			}
698
+			//and then directly call its constructor again, like we would if we
699
+			//were creating a new one
700
+			static::$_instance->__construct($timezone);
701
+			return self::instance();
702
+		}
703
+		return null;
704
+	}
705
+
706
+
707
+
708
+	/**
709
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
+	 *
711
+	 * @param  boolean $translated return localized strings or JUST the array.
712
+	 * @return array
713
+	 * @throws \EE_Error
714
+	 */
715
+	public function status_array($translated = false)
716
+	{
717
+		if ( ! array_key_exists('Status', $this->_model_relations)) {
718
+			return array();
719
+		}
720
+		$model_name = $this->get_this_model_name();
721
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
+		$status_array = array();
724
+		foreach ($stati as $status) {
725
+			$status_array[$status->ID()] = $status->get('STS_code');
726
+		}
727
+		return $translated
728
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
+			: $status_array;
730
+	}
731
+
732
+
733
+
734
+	/**
735
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
+	 *
737
+	 * @param array $query_params             {
738
+	 * @var array $0 (where) array {
739
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
+	 *                                        conditions based on related models (and even
743
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
744
+	 *                                        name. Eg,
745
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
750
+	 *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
751
+	 *                                        "Venue.VNU_ID", you could have
752
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
753
+	 *                                        events are related to Registrations, which are related to Attendees). You
754
+	 *                                        can take it even further with
755
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
756
+	 *                                        (from the default of '='), change the value to an numerically-indexed
757
+	 *                                        array, where the first item in the list is the operator. eg: array(
758
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
759
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
760
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
761
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
762
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
763
+	 *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
764
+	 *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
765
+	 *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
766
+	 *                                        all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
767
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
768
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
769
+	 *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
770
+	 *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
771
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
772
+	 *                                        SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to
773
+	 *                                        place two or more where conditions applying to the same field. eg:
774
+	 *                                        array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus
775
+	 *                                        removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*'
776
+	 *                                        character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the
777
+	 *                                        previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
778
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
779
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
780
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
781
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
782
+	 *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
783
+	 *                                        the OFFSET, the 2nd is the LIMIT
784
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
785
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
786
+	 *                                        => array( 'table_alias', array(1,2) ) ).
787
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
788
+	 *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
789
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
790
+	 *                                        'where' conditions, these fields can be on related models. Eg
791
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
792
+	 *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
793
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
794
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
795
+	 *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
796
+	 *                                        want to order by the primary key. Eg,
797
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
798
+	 *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
799
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
800
+	 *                                        wp_esp_registration ORDER BY REG_ID ASC"
801
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
802
+	 *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
803
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
804
+	 *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
805
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
806
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
807
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
808
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
809
+	 *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
810
+	 *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
811
+	 *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
812
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
813
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
814
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
815
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
816
+	 *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
817
+	 *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
818
+	 *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
819
+	 *                                        (default), set to 'all'.
820
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
821
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
822
+	 *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
823
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
824
+	 *                                        }
825
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
826
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
827
+	 *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
828
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
829
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
830
+	 *                                        'OR'=>array(
831
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
832
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
833
+	 *                                        )
834
+	 *                                        ),
835
+	 *                                        'limit'=>10,
836
+	 *                                        'group_by'=>'TXN_ID'
837
+	 *                                        ));
838
+	 *                                        get all the answers to the question titled "shirt size" for event with id
839
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
840
+	 *                                        'Question.QST_display_text'=>'shirt size',
841
+	 *                                        'Registration.Event.EVT_ID'=>12
842
+	 *                                        ),
843
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
844
+	 *                                        ));
845
+	 * @throws \EE_Error
846
+	 */
847
+	public function get_all($query_params = array())
848
+	{
849
+		if (isset($query_params['limit'])
850
+			&& ! isset($query_params['group_by'])
851
+		) {
852
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
853
+		}
854
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
855
+	}
856
+
857
+
858
+
859
+	/**
860
+	 * Modifies the query parameters so we only get back model objects
861
+	 * that "belong" to the current user
862
+	 *
863
+	 * @param array $query_params @see EEM_Base::get_all()
864
+	 * @return array like EEM_Base::get_all
865
+	 */
866
+	public function alter_query_params_to_only_include_mine($query_params = array())
867
+	{
868
+		$wp_user_field_name = $this->wp_user_field_name();
869
+		if ($wp_user_field_name) {
870
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
871
+		}
872
+		return $query_params;
873
+	}
874
+
875
+
876
+
877
+	/**
878
+	 * Returns the name of the field's name that points to the WP_User table
879
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
880
+	 * foreign key to the WP_User table)
881
+	 *
882
+	 * @return string|boolean string on success, boolean false when there is no
883
+	 * foreign key to the WP_User table
884
+	 */
885
+	public function wp_user_field_name()
886
+	{
887
+		try {
888
+			if ( ! empty($this->_model_chain_to_wp_user)) {
889
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890
+				$last_model_name = end($models_to_follow_to_wp_users);
891
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
893
+			} else {
894
+				$model_with_fk_to_wp_users = $this;
895
+				$model_chain_to_wp_user = '';
896
+			}
897
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
899
+		} catch (EE_Error $e) {
900
+			return false;
901
+		}
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
908
+	 * (or transiently-related model) has a foreign key to the wp_users table;
909
+	 * useful for finding if model objects of this type are 'owned' by the current user.
910
+	 * This is an empty string when the foreign key is on this model and when it isn't,
911
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
912
+	 * (or transiently-related model)
913
+	 *
914
+	 * @return string
915
+	 */
916
+	public function model_chain_to_wp_user()
917
+	{
918
+		return $this->_model_chain_to_wp_user;
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
925
+	 * like how registrations don't have a foreign key to wp_users, but the
926
+	 * events they are for are), or is unrelated to wp users.
927
+	 * generally available
928
+	 *
929
+	 * @return boolean
930
+	 */
931
+	public function is_owned()
932
+	{
933
+		if ($this->model_chain_to_wp_user()) {
934
+			return true;
935
+		} else {
936
+			try {
937
+				$this->get_foreign_key_to('WP_User');
938
+				return true;
939
+			} catch (EE_Error $e) {
940
+				return false;
941
+			}
942
+		}
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
949
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
950
+	 * the model)
951
+	 *
952
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
953
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
954
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
955
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
956
+	 *                                  override this and set the select to "*", or a specific column name, like
957
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
958
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
959
+	 *                                  the aliases used to refer to this selection, and values are to be
960
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
961
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
962
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
963
+	 * @throws \EE_Error
964
+	 */
965
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
966
+	{
967
+		// remember the custom selections, if any, and type cast as array
968
+		// (unless $columns_to_select is an object, then just set as an empty array)
969
+		// Note: (array) 'some string' === array( 'some string' )
970
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
971
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
972
+		$select_expressions = $columns_to_select !== null
973
+			? $this->_construct_select_from_input($columns_to_select)
974
+			: $this->_construct_default_select_sql($model_query_info);
975
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
976
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
977
+	}
978
+
979
+
980
+
981
+	/**
982
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
983
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
984
+	 * take care of joins, field preparation etc.
985
+	 *
986
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
987
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
990
+	 *                                  override this and set the select to "*", or a specific column name, like
991
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
+	 *                                  the aliases used to refer to this selection, and values are to be
994
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
+	 * @throws \EE_Error
998
+	 */
999
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1000
+	{
1001
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * For creating a custom select statement
1008
+	 *
1009
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1010
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1011
+	 *                                 SQL, and 1=>is the datatype
1012
+	 * @throws EE_Error
1013
+	 * @return string
1014
+	 */
1015
+	private function _construct_select_from_input($columns_to_select)
1016
+	{
1017
+		if (is_array($columns_to_select)) {
1018
+			$select_sql_array = array();
1019
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1020
+				if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1021
+					throw new EE_Error(
1022
+						sprintf(
1023
+							__(
1024
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1025
+								"event_espresso"
1026
+							),
1027
+							$selection_and_datatype,
1028
+							$alias
1029
+						)
1030
+					);
1031
+				}
1032
+				if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1033
+					throw new EE_Error(
1034
+						sprintf(
1035
+							__(
1036
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1037
+								"event_espresso"
1038
+							),
1039
+							$selection_and_datatype[1],
1040
+							$selection_and_datatype[0],
1041
+							$alias,
1042
+							implode(",", $this->_valid_wpdb_data_types)
1043
+						)
1044
+					);
1045
+				}
1046
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1047
+			}
1048
+			$columns_to_select_string = implode(", ", $select_sql_array);
1049
+		} else {
1050
+			$columns_to_select_string = $columns_to_select;
1051
+		}
1052
+		return $columns_to_select_string;
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1059
+	 *
1060
+	 * @return string
1061
+	 * @throws \EE_Error
1062
+	 */
1063
+	public function primary_key_name()
1064
+	{
1065
+		return $this->get_primary_key_field()->get_name();
1066
+	}
1067
+
1068
+
1069
+
1070
+	/**
1071
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1072
+	 * If there is no primary key on this model, $id is treated as primary key string
1073
+	 *
1074
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1075
+	 * @return EE_Base_Class
1076
+	 */
1077
+	public function get_one_by_ID($id)
1078
+	{
1079
+		if ($this->get_from_entity_map($id)) {
1080
+			return $this->get_from_entity_map($id);
1081
+		}
1082
+		return $this->get_one(
1083
+			$this->alter_query_params_to_restrict_by_ID(
1084
+				$id,
1085
+				array('default_where_conditions' => 'minimum')
1086
+			)
1087
+		);
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * Alters query parameters to only get items with this ID are returned.
1094
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1095
+	 * or could just be a simple primary key ID
1096
+	 *
1097
+	 * @param int   $id
1098
+	 * @param array $query_params
1099
+	 * @return array of normal query params, @see EEM_Base::get_all
1100
+	 * @throws \EE_Error
1101
+	 */
1102
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1103
+	{
1104
+		if ( ! isset($query_params[0])) {
1105
+			$query_params[0] = array();
1106
+		}
1107
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1108
+		if ($conditions_from_id === null) {
1109
+			$query_params[0][$this->primary_key_name()] = $id;
1110
+		} else {
1111
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1112
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1113
+		}
1114
+		return $query_params;
1115
+	}
1116
+
1117
+
1118
+
1119
+	/**
1120
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1121
+	 * array. If no item is found, null is returned.
1122
+	 *
1123
+	 * @param array $query_params like EEM_Base's $query_params variable.
1124
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1125
+	 * @throws \EE_Error
1126
+	 */
1127
+	public function get_one($query_params = array())
1128
+	{
1129
+		if ( ! is_array($query_params)) {
1130
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1131
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1132
+					gettype($query_params)), '4.6.0');
1133
+			$query_params = array();
1134
+		}
1135
+		$query_params['limit'] = 1;
1136
+		$items = $this->get_all($query_params);
1137
+		if (empty($items)) {
1138
+			return null;
1139
+		} else {
1140
+			return array_shift($items);
1141
+		}
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Returns the next x number of items in sequence from the given value as
1148
+	 * found in the database matching the given query conditions.
1149
+	 *
1150
+	 * @param mixed $current_field_value    Value used for the reference point.
1151
+	 * @param null  $field_to_order_by      What field is used for the
1152
+	 *                                      reference point.
1153
+	 * @param int   $limit                  How many to return.
1154
+	 * @param array $query_params           Extra conditions on the query.
1155
+	 * @param null  $columns_to_select      If left null, then an array of
1156
+	 *                                      EE_Base_Class objects is returned,
1157
+	 *                                      otherwise you can indicate just the
1158
+	 *                                      columns you want returned.
1159
+	 * @return EE_Base_Class[]|array
1160
+	 * @throws \EE_Error
1161
+	 */
1162
+	public function next_x(
1163
+		$current_field_value,
1164
+		$field_to_order_by = null,
1165
+		$limit = 1,
1166
+		$query_params = array(),
1167
+		$columns_to_select = null
1168
+	) {
1169
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1170
+			$columns_to_select);
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Returns the previous x number of items in sequence from the given value
1177
+	 * as found in the database matching the given query conditions.
1178
+	 *
1179
+	 * @param mixed $current_field_value    Value used for the reference point.
1180
+	 * @param null  $field_to_order_by      What field is used for the
1181
+	 *                                      reference point.
1182
+	 * @param int   $limit                  How many to return.
1183
+	 * @param array $query_params           Extra conditions on the query.
1184
+	 * @param null  $columns_to_select      If left null, then an array of
1185
+	 *                                      EE_Base_Class objects is returned,
1186
+	 *                                      otherwise you can indicate just the
1187
+	 *                                      columns you want returned.
1188
+	 * @return EE_Base_Class[]|array
1189
+	 * @throws \EE_Error
1190
+	 */
1191
+	public function previous_x(
1192
+		$current_field_value,
1193
+		$field_to_order_by = null,
1194
+		$limit = 1,
1195
+		$query_params = array(),
1196
+		$columns_to_select = null
1197
+	) {
1198
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1199
+			$columns_to_select);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Returns the next item in sequence from the given value as found in the
1206
+	 * database matching the given query conditions.
1207
+	 *
1208
+	 * @param mixed $current_field_value    Value used for the reference point.
1209
+	 * @param null  $field_to_order_by      What field is used for the
1210
+	 *                                      reference point.
1211
+	 * @param array $query_params           Extra conditions on the query.
1212
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1213
+	 *                                      object is returned, otherwise you
1214
+	 *                                      can indicate just the columns you
1215
+	 *                                      want and a single array indexed by
1216
+	 *                                      the columns will be returned.
1217
+	 * @return EE_Base_Class|null|array()
1218
+	 * @throws \EE_Error
1219
+	 */
1220
+	public function next(
1221
+		$current_field_value,
1222
+		$field_to_order_by = null,
1223
+		$query_params = array(),
1224
+		$columns_to_select = null
1225
+	) {
1226
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1227
+			$columns_to_select);
1228
+		return empty($results) ? null : reset($results);
1229
+	}
1230
+
1231
+
1232
+
1233
+	/**
1234
+	 * Returns the previous item in sequence from the given value as found in
1235
+	 * the database matching the given query conditions.
1236
+	 *
1237
+	 * @param mixed $current_field_value    Value used for the reference point.
1238
+	 * @param null  $field_to_order_by      What field is used for the
1239
+	 *                                      reference point.
1240
+	 * @param array $query_params           Extra conditions on the query.
1241
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1242
+	 *                                      object is returned, otherwise you
1243
+	 *                                      can indicate just the columns you
1244
+	 *                                      want and a single array indexed by
1245
+	 *                                      the columns will be returned.
1246
+	 * @return EE_Base_Class|null|array()
1247
+	 * @throws EE_Error
1248
+	 */
1249
+	public function previous(
1250
+		$current_field_value,
1251
+		$field_to_order_by = null,
1252
+		$query_params = array(),
1253
+		$columns_to_select = null
1254
+	) {
1255
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1256
+			$columns_to_select);
1257
+		return empty($results) ? null : reset($results);
1258
+	}
1259
+
1260
+
1261
+
1262
+	/**
1263
+	 * Returns the a consecutive number of items in sequence from the given
1264
+	 * value as found in the database matching the given query conditions.
1265
+	 *
1266
+	 * @param mixed  $current_field_value   Value used for the reference point.
1267
+	 * @param string $operand               What operand is used for the sequence.
1268
+	 * @param string $field_to_order_by     What field is used for the reference point.
1269
+	 * @param int    $limit                 How many to return.
1270
+	 * @param array  $query_params          Extra conditions on the query.
1271
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the columns you want returned.
1273
+	 * @return EE_Base_Class[]|array
1274
+	 * @throws EE_Error
1275
+	 */
1276
+	protected function _get_consecutive(
1277
+		$current_field_value,
1278
+		$operand = '>',
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1285
+		if (empty($field_to_order_by)) {
1286
+			if ($this->has_primary_key_field()) {
1287
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1288
+			} else {
1289
+				if (WP_DEBUG) {
1290
+					throw new EE_Error(__('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).',
1291
+						'event_espresso'));
1292
+				}
1293
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1294
+				return array();
1295
+			}
1296
+		}
1297
+		if ( ! is_array($query_params)) {
1298
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1299
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1300
+					gettype($query_params)), '4.6.0');
1301
+			$query_params = array();
1302
+		}
1303
+		//let's add the where query param for consecutive look up.
1304
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305
+		$query_params['limit'] = $limit;
1306
+		//set direction
1307
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1308
+		$query_params['order_by'] = $operand === '>'
1309
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1310
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1311
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1312
+		if (empty($columns_to_select)) {
1313
+			return $this->get_all($query_params);
1314
+		} else {
1315
+			//getting just the fields
1316
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1317
+		}
1318
+	}
1319
+
1320
+
1321
+
1322
+	/**
1323
+	 * This sets the _timezone property after model object has been instantiated.
1324
+	 *
1325
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1326
+	 */
1327
+	public function set_timezone($timezone)
1328
+	{
1329
+		if ($timezone !== null) {
1330
+			$this->_timezone = $timezone;
1331
+		}
1332
+		//note we need to loop through relations and set the timezone on those objects as well.
1333
+		foreach ($this->_model_relations as $relation) {
1334
+			$relation->set_timezone($timezone);
1335
+		}
1336
+		//and finally we do the same for any datetime fields
1337
+		foreach ($this->_fields as $field) {
1338
+			if ($field instanceof EE_Datetime_Field) {
1339
+				$field->set_timezone($timezone);
1340
+			}
1341
+		}
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * This just returns whatever is set for the current timezone.
1348
+	 *
1349
+	 * @access public
1350
+	 * @return string
1351
+	 */
1352
+	public function get_timezone()
1353
+	{
1354
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1355
+		if (empty($this->_timezone)) {
1356
+			foreach ($this->_fields as $field) {
1357
+				if ($field instanceof EE_Datetime_Field) {
1358
+					$this->set_timezone($field->get_timezone());
1359
+					break;
1360
+				}
1361
+			}
1362
+		}
1363
+		//if timezone STILL empty then return the default timezone for the site.
1364
+		if (empty($this->_timezone)) {
1365
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1366
+		}
1367
+		return $this->_timezone;
1368
+	}
1369
+
1370
+
1371
+
1372
+	/**
1373
+	 * This returns the date formats set for the given field name and also ensures that
1374
+	 * $this->_timezone property is set correctly.
1375
+	 *
1376
+	 * @since 4.6.x
1377
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1378
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1379
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1380
+	 * @return array formats in an array with the date format first, and the time format last.
1381
+	 */
1382
+	public function get_formats_for($field_name, $pretty = false)
1383
+	{
1384
+		$field_settings = $this->field_settings_for($field_name);
1385
+		//if not a valid EE_Datetime_Field then throw error
1386
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1387
+			throw new EE_Error(sprintf(__('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.',
1388
+				'event_espresso'), $field_name));
1389
+		}
1390
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1391
+		//the field.
1392
+		$this->_timezone = $field_settings->get_timezone();
1393
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1394
+	}
1395
+
1396
+
1397
+
1398
+	/**
1399
+	 * This returns the current time in a format setup for a query on this model.
1400
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1401
+	 * it will return:
1402
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1403
+	 *  NOW
1404
+	 *  - or a unix timestamp (equivalent to time())
1405
+	 *
1406
+	 * @since 4.6.x
1407
+	 * @param string $field_name       The field the current time is needed for.
1408
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1409
+	 *                                 formatted string matching the set format for the field in the set timezone will
1410
+	 *                                 be returned.
1411
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1412
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1413
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1414
+	 *                                 exception is triggered.
1415
+	 */
1416
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1417
+	{
1418
+		$formats = $this->get_formats_for($field_name);
1419
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1420
+		if ($timestamp) {
1421
+			return $DateTime->format('U');
1422
+		}
1423
+		//not returning timestamp, so return formatted string in timezone.
1424
+		switch ($what) {
1425
+			case 'time' :
1426
+				return $DateTime->format($formats[1]);
1427
+				break;
1428
+			case 'date' :
1429
+				return $DateTime->format($formats[0]);
1430
+				break;
1431
+			default :
1432
+				return $DateTime->format(implode(' ', $formats));
1433
+				break;
1434
+		}
1435
+	}
1436
+
1437
+
1438
+
1439
+	/**
1440
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1441
+	 * for the model are.  Returns a DateTime object.
1442
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1443
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1444
+	 * ignored.
1445
+	 *
1446
+	 * @param string $field_name      The field being setup.
1447
+	 * @param string $timestring      The date time string being used.
1448
+	 * @param string $incoming_format The format for the time string.
1449
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1450
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1451
+	 *                                format is
1452
+	 *                                'U', this is ignored.
1453
+	 * @return DateTime
1454
+	 * @throws \EE_Error
1455
+	 */
1456
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1457
+	{
1458
+		//just using this to ensure the timezone is set correctly internally
1459
+		$this->get_formats_for($field_name);
1460
+		//load EEH_DTT_Helper
1461
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1462
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1463
+		return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1464
+	}
1465
+
1466
+
1467
+
1468
+	/**
1469
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1470
+	 *
1471
+	 * @return EE_Table_Base[]
1472
+	 */
1473
+	public function get_tables()
1474
+	{
1475
+		return $this->_tables;
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1482
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1483
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1484
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1485
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1486
+	 * model object with EVT_ID = 1
1487
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1488
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1489
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1490
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1491
+	 * are not specified)
1492
+	 *
1493
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1494
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1495
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1496
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1497
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1498
+	 *                                         ID=34, we'd use this method as follows:
1499
+	 *                                         EEM_Transaction::instance()->update(
1500
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1501
+	 *                                         array(array('TXN_ID'=>34)));
1502
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1503
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1504
+	 *                                         consider updating Question's QST_admin_label field is of type
1505
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1506
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1507
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1508
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1509
+	 *                                         TRUE, it is assumed that you've already called
1510
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1511
+	 *                                         malicious javascript. However, if
1512
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1513
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1514
+	 *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1515
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1516
+	 *                                         in this model's entity map according to $fields_n_values that match
1517
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1518
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1519
+	 *                                         could get out-of-sync with the database
1520
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1521
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1525
+	{
1526
+		if ( ! is_array($query_params)) {
1527
+			EE_Error::doing_it_wrong('EEM_Base::update',
1528
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1529
+					gettype($query_params)), '4.6.0');
1530
+			$query_params = array();
1531
+		}
1532
+		/**
1533
+		 * Action called before a model update call has been made.
1534
+		 *
1535
+		 * @param EEM_Base $model
1536
+		 * @param array    $fields_n_values the updated fields and their new values
1537
+		 * @param array    $query_params    @see EEM_Base::get_all()
1538
+		 */
1539
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1540
+		/**
1541
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1542
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1543
+		 *
1544
+		 * @param array    $fields_n_values fields and their new values
1545
+		 * @param EEM_Base $model           the model being queried
1546
+		 * @param array    $query_params    see EEM_Base::get_all()
1547
+		 */
1548
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549
+			$query_params);
1550
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1551
+		//to do that, for each table, verify that it's PK isn't null.
1552
+		$tables = $this->get_tables();
1553
+		//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
1554
+		//NOTE: we should make this code more efficient by NOT querying twice
1555
+		//before the real update, but that needs to first go through ALPHA testing
1556
+		//as it's dangerous. says Mike August 8 2014
1557
+		//we want to make sure the default_where strategy is ignored
1558
+		$this->_ignore_where_strategy = true;
1559
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560
+		foreach ($wpdb_select_results as $wpdb_result) {
1561
+			// type cast stdClass as array
1562
+			$wpdb_result = (array)$wpdb_result;
1563
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564
+			if ($this->has_primary_key_field()) {
1565
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1566
+			} else {
1567
+				//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)
1568
+				$main_table_pk_value = null;
1569
+			}
1570
+			//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
1571
+			//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
1572
+			if (count($tables) > 1) {
1573
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1574
+				//in that table, and so we'll want to insert one
1575
+				foreach ($tables as $table_obj) {
1576
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1577
+					//if there is no private key for this table on the results, it means there's no entry
1578
+					//in this table, right? so insert a row in the current table, using any fields available
1579
+					if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1580
+							&& $wpdb_result[$this_table_pk_column])
1581
+					) {
1582
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1583
+							$main_table_pk_value);
1584
+						//if we died here, report the error
1585
+						if ( ! $success) {
1586
+							return false;
1587
+						}
1588
+					}
1589
+				}
1590
+			}
1591
+			//				//and now check that if we have cached any models by that ID on the model, that
1592
+			//				//they also get updated properly
1593
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1594
+			//				if( $model_object ){
1595
+			//					foreach( $fields_n_values as $field => $value ){
1596
+			//						$model_object->set($field, $value);
1597
+			//let's make sure default_where strategy is followed now
1598
+			$this->_ignore_where_strategy = false;
1599
+		}
1600
+		//if we want to keep model objects in sync, AND
1601
+		//if this wasn't called from a model object (to update itself)
1602
+		//then we want to make sure we keep all the existing
1603
+		//model objects in sync with the db
1604
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1605
+			if ($this->has_primary_key_field()) {
1606
+				$model_objs_affected_ids = $this->get_col($query_params);
1607
+			} else {
1608
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1609
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1610
+				$model_objs_affected_ids = array();
1611
+				foreach ($models_affected_key_columns as $row) {
1612
+					$combined_index_key = $this->get_index_primary_key_string($row);
1613
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1614
+				}
1615
+			}
1616
+			if ( ! $model_objs_affected_ids) {
1617
+				//wait wait wait- if nothing was affected let's stop here
1618
+				return 0;
1619
+			}
1620
+			foreach ($model_objs_affected_ids as $id) {
1621
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1622
+				if ($model_obj_in_entity_map) {
1623
+					foreach ($fields_n_values as $field => $new_value) {
1624
+						$model_obj_in_entity_map->set($field, $new_value);
1625
+					}
1626
+				}
1627
+			}
1628
+			//if there is a primary key on this model, we can now do a slight optimization
1629
+			if ($this->has_primary_key_field()) {
1630
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1631
+				$query_params = array(
1632
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1633
+					'limit'                    => count($model_objs_affected_ids),
1634
+					'default_where_conditions' => 'none',
1635
+				);
1636
+			}
1637
+		}
1638
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1639
+		$SQL = "UPDATE "
1640
+			   . $model_query_info->get_full_join_sql()
1641
+			   . " SET "
1642
+			   . $this->_construct_update_sql($fields_n_values)
1643
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645
+		/**
1646
+		 * Action called after a model update call has been made.
1647
+		 *
1648
+		 * @param EEM_Base $model
1649
+		 * @param array    $fields_n_values the updated fields and their new values
1650
+		 * @param array    $query_params    @see EEM_Base::get_all()
1651
+		 * @param int      $rows_affected
1652
+		 */
1653
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
+		return $rows_affected;//how many supposedly got updated
1655
+	}
1656
+
1657
+
1658
+
1659
+	/**
1660
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1661
+	 * are teh values of the field specified (or by default the primary key field)
1662
+	 * that matched the query params. Note that you should pass the name of the
1663
+	 * model FIELD, not the database table's column name.
1664
+	 *
1665
+	 * @param array  $query_params @see EEM_Base::get_all()
1666
+	 * @param string $field_to_select
1667
+	 * @return array just like $wpdb->get_col()
1668
+	 * @throws \EE_Error
1669
+	 */
1670
+	public function get_col($query_params = array(), $field_to_select = null)
1671
+	{
1672
+		if ($field_to_select) {
1673
+			$field = $this->field_settings_for($field_to_select);
1674
+		} elseif ($this->has_primary_key_field()) {
1675
+			$field = $this->get_primary_key_field();
1676
+		} else {
1677
+			//no primary key, just grab the first column
1678
+			$field = reset($this->field_settings());
1679
+		}
1680
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1681
+		$select_expressions = $field->get_qualified_column();
1682
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1683
+		return $this->_do_wpdb_query('get_col', array($SQL));
1684
+	}
1685
+
1686
+
1687
+
1688
+	/**
1689
+	 * Returns a single column value for a single row from the database
1690
+	 *
1691
+	 * @param array  $query_params    @see EEM_Base::get_all()
1692
+	 * @param string $field_to_select @see EEM_Base::get_col()
1693
+	 * @return string
1694
+	 * @throws \EE_Error
1695
+	 */
1696
+	public function get_var($query_params = array(), $field_to_select = null)
1697
+	{
1698
+		$query_params['limit'] = 1;
1699
+		$col = $this->get_col($query_params, $field_to_select);
1700
+		if ( ! empty($col)) {
1701
+			return reset($col);
1702
+		} else {
1703
+			return null;
1704
+		}
1705
+	}
1706
+
1707
+
1708
+
1709
+	/**
1710
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1711
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1712
+	 * injection, but currently no further filtering is done
1713
+	 *
1714
+	 * @global      $wpdb
1715
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1716
+	 *                               be updated to in the DB
1717
+	 * @return string of SQL
1718
+	 * @throws \EE_Error
1719
+	 */
1720
+	public function _construct_update_sql($fields_n_values)
1721
+	{
1722
+		/** @type WPDB $wpdb */
1723
+		global $wpdb;
1724
+		$cols_n_values = array();
1725
+		foreach ($fields_n_values as $field_name => $value) {
1726
+			$field_obj = $this->field_settings_for($field_name);
1727
+			//if the value is NULL, we want to assign the value to that.
1728
+			//wpdb->prepare doesn't really handle that properly
1729
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730
+			$value_sql = $prepared_value === null ? 'NULL'
1731
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1733
+		}
1734
+		return implode(",", $cols_n_values);
1735
+	}
1736
+
1737
+
1738
+
1739
+	/**
1740
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1741
+	 * Performs a HARD delete, meaning the database row should always be removed,
1742
+	 * not just have a flag field on it switched
1743
+	 * Wrapper for EEM_Base::delete_permanently()
1744
+	 *
1745
+	 * @param mixed $id
1746
+	 * @return boolean whether the row got deleted or not
1747
+	 * @throws \EE_Error
1748
+	 */
1749
+	public function delete_permanently_by_ID($id)
1750
+	{
1751
+		return $this->delete_permanently(
1752
+			array(
1753
+				array($this->get_primary_key_field()->get_name() => $id),
1754
+				'limit' => 1,
1755
+			)
1756
+		);
1757
+	}
1758
+
1759
+
1760
+
1761
+	/**
1762
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1763
+	 * Wrapper for EEM_Base::delete()
1764
+	 *
1765
+	 * @param mixed $id
1766
+	 * @return boolean whether the row got deleted or not
1767
+	 * @throws \EE_Error
1768
+	 */
1769
+	public function delete_by_ID($id)
1770
+	{
1771
+		return $this->delete(
1772
+			array(
1773
+				array($this->get_primary_key_field()->get_name() => $id),
1774
+				'limit' => 1,
1775
+			)
1776
+		);
1777
+	}
1778
+
1779
+
1780
+
1781
+	/**
1782
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1783
+	 * meaning if the model has a field that indicates its been "trashed" or
1784
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1785
+	 *
1786
+	 * @see EEM_Base::delete_permanently
1787
+	 * @param array   $query_params
1788
+	 * @param boolean $allow_blocking
1789
+	 * @return int how many rows got deleted
1790
+	 * @throws \EE_Error
1791
+	 */
1792
+	public function delete($query_params, $allow_blocking = true)
1793
+	{
1794
+		return $this->delete_permanently($query_params, $allow_blocking);
1795
+	}
1796
+
1797
+
1798
+
1799
+	/**
1800
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1801
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1802
+	 * as archived, not actually deleted
1803
+	 *
1804
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1805
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1806
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1807
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1808
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1809
+	 *                                DB
1810
+	 * @return int how many rows got deleted
1811
+	 * @throws \EE_Error
1812
+	 */
1813
+	public function delete_permanently($query_params, $allow_blocking = true)
1814
+	{
1815
+		/**
1816
+		 * Action called just before performing a real deletion query. You can use the
1817
+		 * model and its $query_params to find exactly which items will be deleted
1818
+		 *
1819
+		 * @param EEM_Base $model
1820
+		 * @param array    $query_params   @see EEM_Base::get_all()
1821
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1822
+		 *                                 to block (prevent) this deletion
1823
+		 */
1824
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1825
+		//some MySQL databases may be running safe mode, which may restrict
1826
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1827
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1828
+		//to delete them
1829
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1830
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1831
+		if ($deletion_where) {
1832
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1833
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1834
+			$table_aliases = array_keys($this->_tables);
1835
+			$SQL = "DELETE "
1836
+				   . implode(", ", $table_aliases)
1837
+				   . " FROM "
1838
+				   . $model_query_info->get_full_join_sql()
1839
+				   . " WHERE "
1840
+				   . $deletion_where;
1841
+			//		/echo "delete sql:$SQL";
1842
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1843
+		} else {
1844
+			$rows_deleted = 0;
1845
+		}
1846
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1847
+		if ($this->has_primary_key_field()) {
1848
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1849
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1850
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1851
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1852
+				}
1853
+			}
1854
+		}
1855
+		/**
1856
+		 * Action called just after performing a real deletion query. Although at this point the
1857
+		 * items should have been deleted
1858
+		 *
1859
+		 * @param EEM_Base $model
1860
+		 * @param array    $query_params @see EEM_Base::get_all()
1861
+		 * @param int      $rows_deleted
1862
+		 */
1863
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
+		return $rows_deleted;//how many supposedly got deleted
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Checks all the relations that throw error messages when there are blocking related objects
1871
+	 * for related model objects. If there are any related model objects on those relations,
1872
+	 * adds an EE_Error, and return true
1873
+	 *
1874
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1875
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1876
+	 *                                                 should be ignored when determining whether there are related
1877
+	 *                                                 model objects which block this model object's deletion. Useful
1878
+	 *                                                 if you know A is related to B and are considering deleting A,
1879
+	 *                                                 but want to see if A has any other objects blocking its deletion
1880
+	 *                                                 before removing the relation between A and B
1881
+	 * @return boolean
1882
+	 * @throws \EE_Error
1883
+	 */
1884
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1885
+	{
1886
+		//first, if $ignore_this_model_obj was supplied, get its model
1887
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1888
+			$ignored_model = $ignore_this_model_obj->get_model();
1889
+		} else {
1890
+			$ignored_model = null;
1891
+		}
1892
+		//now check all the relations of $this_model_obj_or_id and see if there
1893
+		//are any related model objects blocking it?
1894
+		$is_blocked = false;
1895
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1896
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1897
+				//if $ignore_this_model_obj was supplied, then for the query
1898
+				//on that model needs to be told to ignore $ignore_this_model_obj
1899
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1900
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1901
+						array(
1902
+							$ignored_model->get_primary_key_field()->get_name() => array(
1903
+								'!=',
1904
+								$ignore_this_model_obj->ID(),
1905
+							),
1906
+						),
1907
+					));
1908
+				} else {
1909
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1910
+				}
1911
+				if ($related_model_objects) {
1912
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1913
+					$is_blocked = true;
1914
+				}
1915
+			}
1916
+		}
1917
+		return $is_blocked;
1918
+	}
1919
+
1920
+
1921
+
1922
+	/**
1923
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1924
+	 * well.
1925
+	 *
1926
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1927
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1928
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
1929
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
1930
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
1931
+	 *                                      easily corrupt your DB
1932
+	 * @throws EE_Error
1933
+	 * @return string    everything that comes after the WHERE statement.
1934
+	 */
1935
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1936
+	{
1937
+		if ($this->has_primary_key_field()) {
1938
+			$primary_table = $this->_get_main_table();
1939
+			$other_tables = $this->_get_other_tables();
1940
+			$deletes = $query = array();
1941
+			foreach ($objects_for_deletion as $delete_object) {
1942
+				//before we mark this object for deletion,
1943
+				//make sure there's no related objects blocking its deletion (if we're checking)
1944
+				if (
1945
+					$allow_blocking
1946
+					&& $this->delete_is_blocked_by_related_models(
1947
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
1948
+					)
1949
+				) {
1950
+					continue;
1951
+				}
1952
+				//primary table deletes
1953
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1954
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1955
+				}
1956
+				//other tables
1957
+				if ( ! empty($other_tables)) {
1958
+					foreach ($other_tables as $ot) {
1959
+						//first check if we've got the foreign key column here.
1960
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1961
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1962
+						}
1963
+						// wait! it's entirely possible that we'll have a the primary key
1964
+						// for this table in here, if it's a foreign key for one of the other secondary tables
1965
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1966
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1967
+						}
1968
+						// finally, it is possible that the fk for this table is found
1969
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
1970
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1971
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1972
+						}
1973
+					}
1974
+				}
1975
+			}
1976
+			//we should have deletes now, so let's just go through and setup the where statement
1977
+			foreach ($deletes as $column => $values) {
1978
+				//make sure we have unique $values;
1979
+				$values = array_unique($values);
1980
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
1981
+			}
1982
+			return ! empty($query) ? implode(' AND ', $query) : '';
1983
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
1984
+			$ways_to_identify_a_row = array();
1985
+			$fields = $this->get_combined_primary_key_fields();
1986
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1987
+			foreach ($objects_for_deletion as $delete_object) {
1988
+				$values_for_each_cpk_for_a_row = array();
1989
+				foreach ($fields as $cpk_field) {
1990
+					if ($cpk_field instanceof EE_Model_Field_Base) {
1991
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1992
+														   . "="
1993
+														   . $delete_object[$cpk_field->get_qualified_column()];
1994
+					}
1995
+				}
1996
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1997
+			}
1998
+			return implode(" OR ", $ways_to_identify_a_row);
1999
+		} else {
2000
+			//so there's no primary key and no combined key...
2001
+			//sorry, can't help you
2002
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2003
+				"event_espresso"), get_class($this)));
2004
+		}
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2011
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2012
+	 * column
2013
+	 *
2014
+	 * @param array  $query_params   like EEM_Base::get_all's
2015
+	 * @param string $field_to_count field on model to count by (not column name)
2016
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2017
+	 *                               that by the setting $distinct to TRUE;
2018
+	 * @return int
2019
+	 * @throws \EE_Error
2020
+	 */
2021
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2022
+	{
2023
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2024
+		if ($field_to_count) {
2025
+			$field_obj = $this->field_settings_for($field_to_count);
2026
+			$column_to_count = $field_obj->get_qualified_column();
2027
+		} elseif ($this->has_primary_key_field()) {
2028
+			$pk_field_obj = $this->get_primary_key_field();
2029
+			$column_to_count = $pk_field_obj->get_qualified_column();
2030
+		} else {
2031
+			//there's no primary key
2032
+			//if we're counting distinct items, and there's no primary key,
2033
+			//we need to list out the columns for distinction;
2034
+			//otherwise we can just use star
2035
+			if ($distinct) {
2036
+				$columns_to_use = array();
2037
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2038
+					$columns_to_use[] = $field_obj->get_qualified_column();
2039
+				}
2040
+				$column_to_count = implode(',', $columns_to_use);
2041
+			} else {
2042
+				$column_to_count = '*';
2043
+			}
2044
+		}
2045
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2048
+	}
2049
+
2050
+
2051
+
2052
+	/**
2053
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2054
+	 *
2055
+	 * @param array  $query_params like EEM_Base::get_all
2056
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2057
+	 * @return float
2058
+	 * @throws \EE_Error
2059
+	 */
2060
+	public function sum($query_params, $field_to_sum = null)
2061
+	{
2062
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2063
+		if ($field_to_sum) {
2064
+			$field_obj = $this->field_settings_for($field_to_sum);
2065
+		} else {
2066
+			$field_obj = $this->get_primary_key_field();
2067
+		}
2068
+		$column_to_count = $field_obj->get_qualified_column();
2069
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2070
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071
+		$data_type = $field_obj->get_wpdb_data_type();
2072
+		if ($data_type === '%d' || $data_type === '%s') {
2073
+			return (float)$return_value;
2074
+		} else {//must be %f
2075
+			return (float)$return_value;
2076
+		}
2077
+	}
2078
+
2079
+
2080
+
2081
+	/**
2082
+	 * Just calls the specified method on $wpdb with the given arguments
2083
+	 * Consolidates a little extra error handling code
2084
+	 *
2085
+	 * @param string $wpdb_method
2086
+	 * @param array  $arguments_to_provide
2087
+	 * @throws EE_Error
2088
+	 * @global wpdb  $wpdb
2089
+	 * @return mixed
2090
+	 */
2091
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2092
+	{
2093
+		//if we're in maintenance mode level 2, DON'T run any queries
2094
+		//because level 2 indicates the database needs updating and
2095
+		//is probably out of sync with the code
2096
+		if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2097
+			throw new EE_Error(sprintf(__("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.",
2098
+				"event_espresso")));
2099
+		}
2100
+		/** @type WPDB $wpdb */
2101
+		global $wpdb;
2102
+		if ( ! method_exists($wpdb, $wpdb_method)) {
2103
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2104
+				'event_espresso'), $wpdb_method));
2105
+		}
2106
+		if (WP_DEBUG) {
2107
+			$old_show_errors_value = $wpdb->show_errors;
2108
+			$wpdb->show_errors(false);
2109
+		}
2110
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2111
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2112
+		if (WP_DEBUG) {
2113
+			$wpdb->show_errors($old_show_errors_value);
2114
+			if ( ! empty($wpdb->last_error)) {
2115
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2116
+			} elseif ($result === false) {
2117
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2118
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2119
+			}
2120
+		} elseif ($result === false) {
2121
+			EE_Error::add_error(
2122
+				sprintf(
2123
+					__('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"',
2124
+						'event_espresso'),
2125
+					$wpdb_method,
2126
+					var_export($arguments_to_provide, true),
2127
+					$wpdb->last_error
2128
+				),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+		return $result;
2135
+	}
2136
+
2137
+
2138
+
2139
+	/**
2140
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2141
+	 * and if there's an error tries to verify the DB is correct. Uses
2142
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2143
+	 * we should try to fix the EE core db, the addons, or just give up
2144
+	 *
2145
+	 * @param string $wpdb_method
2146
+	 * @param array  $arguments_to_provide
2147
+	 * @return mixed
2148
+	 */
2149
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2150
+	{
2151
+		/** @type WPDB $wpdb */
2152
+		global $wpdb;
2153
+		$wpdb->last_error = null;
2154
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2155
+		// was there an error running the query? but we don't care on new activations
2156
+		// (we're going to setup the DB anyway on new activations)
2157
+		if (($result === false || ! empty($wpdb->last_error))
2158
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2159
+		) {
2160
+			switch (EEM_Base::$_db_verification_level) {
2161
+				case EEM_Base::db_verified_none :
2162
+					// let's double-check core's DB
2163
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2164
+					break;
2165
+				case EEM_Base::db_verified_core :
2166
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2167
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2168
+					break;
2169
+				case EEM_Base::db_verified_addons :
2170
+					// ummmm... you in trouble
2171
+					return $result;
2172
+					break;
2173
+			}
2174
+			if ( ! empty($error_message)) {
2175
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2176
+				trigger_error($error_message);
2177
+			}
2178
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2179
+		}
2180
+		return $result;
2181
+	}
2182
+
2183
+
2184
+
2185
+	/**
2186
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2187
+	 * EEM_Base::$_db_verification_level
2188
+	 *
2189
+	 * @param string $wpdb_method
2190
+	 * @param array  $arguments_to_provide
2191
+	 * @return string
2192
+	 */
2193
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2194
+	{
2195
+		/** @type WPDB $wpdb */
2196
+		global $wpdb;
2197
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2198
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2199
+		$error_message = sprintf(
2200
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2201
+				'event_espresso'),
2202
+			$wpdb->last_error,
2203
+			$wpdb_method,
2204
+			json_encode($arguments_to_provide)
2205
+		);
2206
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2207
+		return $error_message;
2208
+	}
2209
+
2210
+
2211
+
2212
+	/**
2213
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2214
+	 * EEM_Base::$_db_verification_level
2215
+	 *
2216
+	 * @param $wpdb_method
2217
+	 * @param $arguments_to_provide
2218
+	 * @return string
2219
+	 */
2220
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2221
+	{
2222
+		/** @type WPDB $wpdb */
2223
+		global $wpdb;
2224
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2225
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2226
+		$error_message = sprintf(
2227
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2228
+				'event_espresso'),
2229
+			$wpdb->last_error,
2230
+			$wpdb_method,
2231
+			json_encode($arguments_to_provide)
2232
+		);
2233
+		EE_System::instance()->initialize_addons();
2234
+		return $error_message;
2235
+	}
2236
+
2237
+
2238
+
2239
+	/**
2240
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2241
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2242
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2243
+	 * ..."
2244
+	 *
2245
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2246
+	 * @return string
2247
+	 */
2248
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249
+	{
2250
+		return " FROM " . $model_query_info->get_full_join_sql() .
2251
+			   $model_query_info->get_where_sql() .
2252
+			   $model_query_info->get_group_by_sql() .
2253
+			   $model_query_info->get_having_sql() .
2254
+			   $model_query_info->get_order_by_sql() .
2255
+			   $model_query_info->get_limit_sql();
2256
+	}
2257
+
2258
+
2259
+
2260
+	/**
2261
+	 * Set to easily debug the next X queries ran from this model.
2262
+	 *
2263
+	 * @param int $count
2264
+	 */
2265
+	public function show_next_x_db_queries($count = 1)
2266
+	{
2267
+		$this->_show_next_x_db_queries = $count;
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * @param $sql_query
2274
+	 */
2275
+	public function show_db_query_if_previously_requested($sql_query)
2276
+	{
2277
+		if ($this->_show_next_x_db_queries > 0) {
2278
+			echo $sql_query;
2279
+			$this->_show_next_x_db_queries--;
2280
+		}
2281
+	}
2282
+
2283
+
2284
+
2285
+	/**
2286
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2287
+	 * There are the 3 cases:
2288
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2289
+	 * $otherModelObject has no ID, it is first saved.
2290
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2291
+	 * has no ID, it is first saved.
2292
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2293
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2294
+	 * join table
2295
+	 *
2296
+	 * @param        EE_Base_Class                     /int $thisModelObject
2297
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2298
+	 * @param string $relationName                     , key in EEM_Base::_relations
2299
+	 *                                                 an attendee to a group, you also want to specify which role they
2300
+	 *                                                 will have in that group. So you would use this parameter to
2301
+	 *                                                 specify array('role-column-name'=>'role-id')
2302
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2303
+	 *                                                 to for relation to methods that allow you to further specify
2304
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2305
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2306
+	 *                                                 because these will be inserted in any new rows created as well.
2307
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2308
+	 * @throws \EE_Error
2309
+	 */
2310
+	public function add_relationship_to(
2311
+		$id_or_obj,
2312
+		$other_model_id_or_obj,
2313
+		$relationName,
2314
+		$extra_join_model_fields_n_values = array()
2315
+	) {
2316
+		$relation_obj = $this->related_settings_for($relationName);
2317
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2318
+	}
2319
+
2320
+
2321
+
2322
+	/**
2323
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2324
+	 * There are the 3 cases:
2325
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2326
+	 * error
2327
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2328
+	 * an error
2329
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2330
+	 *
2331
+	 * @param        EE_Base_Class /int $id_or_obj
2332
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2333
+	 * @param string $relationName key in EEM_Base::_relations
2334
+	 * @return boolean of success
2335
+	 * @throws \EE_Error
2336
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2337
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2338
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2339
+	 *                             because these will be inserted in any new rows created as well.
2340
+	 */
2341
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2342
+	{
2343
+		$relation_obj = $this->related_settings_for($relationName);
2344
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2345
+	}
2346
+
2347
+
2348
+
2349
+	/**
2350
+	 * @param mixed           $id_or_obj
2351
+	 * @param string          $relationName
2352
+	 * @param array           $where_query_params
2353
+	 * @param EE_Base_Class[] objects to which relations were removed
2354
+	 * @return \EE_Base_Class[]
2355
+	 * @throws \EE_Error
2356
+	 */
2357
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2358
+	{
2359
+		$relation_obj = $this->related_settings_for($relationName);
2360
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2361
+	}
2362
+
2363
+
2364
+
2365
+	/**
2366
+	 * Gets all the related items of the specified $model_name, using $query_params.
2367
+	 * Note: by default, we remove the "default query params"
2368
+	 * because we want to get even deleted items etc.
2369
+	 *
2370
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2371
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2372
+	 * @param array  $query_params like EEM_Base::get_all
2373
+	 * @return EE_Base_Class[]
2374
+	 * @throws \EE_Error
2375
+	 */
2376
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2377
+	{
2378
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2379
+		$relation_settings = $this->related_settings_for($model_name);
2380
+		return $relation_settings->get_all_related($model_obj, $query_params);
2381
+	}
2382
+
2383
+
2384
+
2385
+	/**
2386
+	 * Deletes all the model objects across the relation indicated by $model_name
2387
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2388
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2389
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2390
+	 *
2391
+	 * @param EE_Base_Class|int|string $id_or_obj
2392
+	 * @param string                   $model_name
2393
+	 * @param array                    $query_params
2394
+	 * @return int how many deleted
2395
+	 * @throws \EE_Error
2396
+	 */
2397
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2398
+	{
2399
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2400
+		$relation_settings = $this->related_settings_for($model_name);
2401
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2402
+	}
2403
+
2404
+
2405
+
2406
+	/**
2407
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2408
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2409
+	 * the model objects can't be hard deleted because of blocking related model objects,
2410
+	 * just does a soft-delete on them instead.
2411
+	 *
2412
+	 * @param EE_Base_Class|int|string $id_or_obj
2413
+	 * @param string                   $model_name
2414
+	 * @param array                    $query_params
2415
+	 * @return int how many deleted
2416
+	 * @throws \EE_Error
2417
+	 */
2418
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2419
+	{
2420
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2421
+		$relation_settings = $this->related_settings_for($model_name);
2422
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2423
+	}
2424
+
2425
+
2426
+
2427
+	/**
2428
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2429
+	 * unless otherwise specified in the $query_params
2430
+	 *
2431
+	 * @param        int             /EE_Base_Class $id_or_obj
2432
+	 * @param string $model_name     like 'Event', or 'Registration'
2433
+	 * @param array  $query_params   like EEM_Base::get_all's
2434
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2435
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2436
+	 *                               that by the setting $distinct to TRUE;
2437
+	 * @return int
2438
+	 * @throws \EE_Error
2439
+	 */
2440
+	public function count_related(
2441
+		$id_or_obj,
2442
+		$model_name,
2443
+		$query_params = array(),
2444
+		$field_to_count = null,
2445
+		$distinct = false
2446
+	) {
2447
+		$related_model = $this->get_related_model_obj($model_name);
2448
+		//we're just going to use the query params on the related model's normal get_all query,
2449
+		//except add a condition to say to match the current mod
2450
+		if ( ! isset($query_params['default_where_conditions'])) {
2451
+			$query_params['default_where_conditions'] = 'none';
2452
+		}
2453
+		$this_model_name = $this->get_this_model_name();
2454
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2456
+		return $related_model->count($query_params, $field_to_count, $distinct);
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2463
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2464
+	 *
2465
+	 * @param        int           /EE_Base_Class $id_or_obj
2466
+	 * @param string $model_name   like 'Event', or 'Registration'
2467
+	 * @param array  $query_params like EEM_Base::get_all's
2468
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2469
+	 * @return float
2470
+	 * @throws \EE_Error
2471
+	 */
2472
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2473
+	{
2474
+		$related_model = $this->get_related_model_obj($model_name);
2475
+		if ( ! is_array($query_params)) {
2476
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2477
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2478
+					gettype($query_params)), '4.6.0');
2479
+			$query_params = array();
2480
+		}
2481
+		//we're just going to use the query params on the related model's normal get_all query,
2482
+		//except add a condition to say to match the current mod
2483
+		if ( ! isset($query_params['default_where_conditions'])) {
2484
+			$query_params['default_where_conditions'] = 'none';
2485
+		}
2486
+		$this_model_name = $this->get_this_model_name();
2487
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2489
+		return $related_model->sum($query_params, $field_to_sum);
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2496
+	 * $modelObject
2497
+	 *
2498
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2499
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2500
+	 * @param array               $query_params     like EEM_Base::get_all's
2501
+	 * @return EE_Base_Class
2502
+	 * @throws \EE_Error
2503
+	 */
2504
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2505
+	{
2506
+		$query_params['limit'] = 1;
2507
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2508
+		if ($results) {
2509
+			return array_shift($results);
2510
+		} else {
2511
+			return null;
2512
+		}
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2519
+	 *
2520
+	 * @return string
2521
+	 */
2522
+	public function get_this_model_name()
2523
+	{
2524
+		return str_replace("EEM_", "", get_class($this));
2525
+	}
2526
+
2527
+
2528
+
2529
+	/**
2530
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2531
+	 *
2532
+	 * @return EE_Any_Foreign_Model_Name_Field
2533
+	 * @throws EE_Error
2534
+	 */
2535
+	public function get_field_containing_related_model_name()
2536
+	{
2537
+		foreach ($this->field_settings(true) as $field) {
2538
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2539
+				$field_with_model_name = $field;
2540
+			}
2541
+		}
2542
+		if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2543
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2544
+				$this->get_this_model_name()));
2545
+		}
2546
+		return $field_with_model_name;
2547
+	}
2548
+
2549
+
2550
+
2551
+	/**
2552
+	 * Inserts a new entry into the database, for each table.
2553
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2554
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2555
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2556
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2557
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2558
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2559
+	 *
2560
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2561
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2562
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2563
+	 *                              of EEM_Base)
2564
+	 * @return int new primary key on main table that got inserted
2565
+	 * @throws EE_Error
2566
+	 */
2567
+	public function insert($field_n_values)
2568
+	{
2569
+		/**
2570
+		 * Filters the fields and their values before inserting an item using the models
2571
+		 *
2572
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2573
+		 * @param EEM_Base $model           the model used
2574
+		 */
2575
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2577
+			$main_table = $this->_get_main_table();
2578
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2579
+			if ($new_id !== false) {
2580
+				foreach ($this->_get_other_tables() as $other_table) {
2581
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2582
+				}
2583
+			}
2584
+			/**
2585
+			 * Done just after attempting to insert a new model object
2586
+			 *
2587
+			 * @param EEM_Base   $model           used
2588
+			 * @param array      $fields_n_values fields and their values
2589
+			 * @param int|string the              ID of the newly-inserted model object
2590
+			 */
2591
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2592
+			return $new_id;
2593
+		} else {
2594
+			return false;
2595
+		}
2596
+	}
2597
+
2598
+
2599
+
2600
+	/**
2601
+	 * Checks that the result would satisfy the unique indexes on this model
2602
+	 *
2603
+	 * @param array  $field_n_values
2604
+	 * @param string $action
2605
+	 * @return boolean
2606
+	 * @throws \EE_Error
2607
+	 */
2608
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2609
+	{
2610
+		foreach ($this->unique_indexes() as $index_name => $index) {
2611
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2612
+			if ($this->exists(array($uniqueness_where_params))) {
2613
+				EE_Error::add_error(
2614
+					sprintf(
2615
+						__(
2616
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2617
+							"event_espresso"
2618
+						),
2619
+						$action,
2620
+						$this->_get_class_name(),
2621
+						$index_name,
2622
+						implode(",", $index->field_names()),
2623
+						http_build_query($uniqueness_where_params)
2624
+					),
2625
+					__FILE__,
2626
+					__FUNCTION__,
2627
+					__LINE__
2628
+				);
2629
+				return false;
2630
+			}
2631
+		}
2632
+		return true;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Checks the database for an item that conflicts (ie, if this item were
2639
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2640
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2641
+	 * can be either an EE_Base_Class or an array of fields n values
2642
+	 *
2643
+	 * @param EE_Base_Class|array $obj_or_fields_array
2644
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2645
+	 *                                                 when looking for conflicts
2646
+	 *                                                 (ie, if false, we ignore the model object's primary key
2647
+	 *                                                 when finding "conflicts". If true, it's also considered).
2648
+	 *                                                 Only works for INT primary key,
2649
+	 *                                                 STRING primary keys cannot be ignored
2650
+	 * @throws EE_Error
2651
+	 * @return EE_Base_Class|array
2652
+	 */
2653
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2654
+	{
2655
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2656
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2657
+		} elseif (is_array($obj_or_fields_array)) {
2658
+			$fields_n_values = $obj_or_fields_array;
2659
+		} else {
2660
+			throw new EE_Error(
2661
+				sprintf(
2662
+					__(
2663
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2664
+						"event_espresso"
2665
+					),
2666
+					get_class($this),
2667
+					$obj_or_fields_array
2668
+				)
2669
+			);
2670
+		}
2671
+		$query_params = array();
2672
+		if ($this->has_primary_key_field()
2673
+			&& ($include_primary_key
2674
+				|| $this->get_primary_key_field()
2675
+				   instanceof
2676
+				   EE_Primary_Key_String_Field)
2677
+			&& isset($fields_n_values[$this->primary_key_name()])
2678
+		) {
2679
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2680
+		}
2681
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2684
+		}
2685
+		//if there is nothing to base this search on, then we shouldn't find anything
2686
+		if (empty($query_params)) {
2687
+			return array();
2688
+		} else {
2689
+			return $this->get_one($query_params);
2690
+		}
2691
+	}
2692
+
2693
+
2694
+
2695
+	/**
2696
+	 * Like count, but is optimized and returns a boolean instead of an int
2697
+	 *
2698
+	 * @param array $query_params
2699
+	 * @return boolean
2700
+	 * @throws \EE_Error
2701
+	 */
2702
+	public function exists($query_params)
2703
+	{
2704
+		$query_params['limit'] = 1;
2705
+		return $this->count($query_params) > 0;
2706
+	}
2707
+
2708
+
2709
+
2710
+	/**
2711
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2712
+	 *
2713
+	 * @param int|string $id
2714
+	 * @return boolean
2715
+	 * @throws \EE_Error
2716
+	 */
2717
+	public function exists_by_ID($id)
2718
+	{
2719
+		return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2726
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2727
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2728
+	 * on the main table)
2729
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2730
+	 * cases where we want to call it directly rather than via insert().
2731
+	 *
2732
+	 * @access   protected
2733
+	 * @param EE_Table_Base $table
2734
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2735
+	 *                                       float
2736
+	 * @param int           $new_id          for now we assume only int keys
2737
+	 * @throws EE_Error
2738
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2739
+	 * @return int ID of new row inserted, or FALSE on failure
2740
+	 */
2741
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2742
+	{
2743
+		global $wpdb;
2744
+		$insertion_col_n_values = array();
2745
+		$format_for_insertion = array();
2746
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2747
+		foreach ($fields_on_table as $field_name => $field_obj) {
2748
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2749
+			if ($field_obj->is_auto_increment()) {
2750
+				continue;
2751
+			}
2752
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2753
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2754
+			if ($prepared_value !== null) {
2755
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2756
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2757
+			}
2758
+		}
2759
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2760
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2761
+			//so add the fk to the main table as a column
2762
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2764
+		}
2765
+		//insert the new entry
2766
+		$result = $this->_do_wpdb_query('insert',
2767
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2768
+		if ($result === false) {
2769
+			return false;
2770
+		}
2771
+		//ok, now what do we return for the ID of the newly-inserted thing?
2772
+		if ($this->has_primary_key_field()) {
2773
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2774
+				return $wpdb->insert_id;
2775
+			} else {
2776
+				//it's not an auto-increment primary key, so
2777
+				//it must have been supplied
2778
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2779
+			}
2780
+		} else {
2781
+			//we can't return a  primary key because there is none. instead return
2782
+			//a unique string indicating this model
2783
+			return $this->get_index_primary_key_string($fields_n_values);
2784
+		}
2785
+	}
2786
+
2787
+
2788
+
2789
+	/**
2790
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2791
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2792
+	 * and there is no default, we pass it along. WPDB will take care of it)
2793
+	 *
2794
+	 * @param EE_Model_Field_Base $field_obj
2795
+	 * @param array               $fields_n_values
2796
+	 * @return mixed string|int|float depending on what the table column will be expecting
2797
+	 * @throws \EE_Error
2798
+	 */
2799
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2800
+	{
2801
+		//if this field doesn't allow nullable, don't allow it
2802
+		if ( ! $field_obj->is_nullable()
2803
+			 && (
2804
+				 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2805
+		) {
2806
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2807
+		}
2808
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2809
+			: null;
2810
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2811
+	}
2812
+
2813
+
2814
+
2815
+	/**
2816
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2817
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2818
+	 * the field's prepare_for_set() method.
2819
+	 *
2820
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2821
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2822
+	 *                                   top of file)
2823
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2824
+	 *                                   $value is a custom selection
2825
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2826
+	 */
2827
+	private function _prepare_value_for_use_in_db($value, $field)
2828
+	{
2829
+		if ($field && $field instanceof EE_Model_Field_Base) {
2830
+			switch ($this->_values_already_prepared_by_model_object) {
2831
+				/** @noinspection PhpMissingBreakStatementInspection */
2832
+				case self::not_prepared_by_model_object:
2833
+					$value = $field->prepare_for_set($value);
2834
+				//purposefully left out "return"
2835
+				case self::prepared_by_model_object:
2836
+					$value = $field->prepare_for_use_in_db($value);
2837
+				case self::prepared_for_use_in_db:
2838
+					//leave the value alone
2839
+			}
2840
+			return $value;
2841
+		} else {
2842
+			return $value;
2843
+		}
2844
+	}
2845
+
2846
+
2847
+
2848
+	/**
2849
+	 * Returns the main table on this model
2850
+	 *
2851
+	 * @return EE_Primary_Table
2852
+	 * @throws EE_Error
2853
+	 */
2854
+	protected function _get_main_table()
2855
+	{
2856
+		foreach ($this->_tables as $table) {
2857
+			if ($table instanceof EE_Primary_Table) {
2858
+				return $table;
2859
+			}
2860
+		}
2861
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2862
+			'event_espresso'), get_class($this)));
2863
+	}
2864
+
2865
+
2866
+
2867
+	/**
2868
+	 * table
2869
+	 * returns EE_Primary_Table table name
2870
+	 *
2871
+	 * @return string
2872
+	 * @throws \EE_Error
2873
+	 */
2874
+	public function table()
2875
+	{
2876
+		return $this->_get_main_table()->get_table_name();
2877
+	}
2878
+
2879
+
2880
+
2881
+	/**
2882
+	 * table
2883
+	 * returns first EE_Secondary_Table table name
2884
+	 *
2885
+	 * @return string
2886
+	 */
2887
+	public function second_table()
2888
+	{
2889
+		// grab second table from tables array
2890
+		$second_table = end($this->_tables);
2891
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2892
+	}
2893
+
2894
+
2895
+
2896
+	/**
2897
+	 * get_table_obj_by_alias
2898
+	 * returns table name given it's alias
2899
+	 *
2900
+	 * @param string $table_alias
2901
+	 * @return EE_Primary_Table | EE_Secondary_Table
2902
+	 */
2903
+	public function get_table_obj_by_alias($table_alias = '')
2904
+	{
2905
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2906
+	}
2907
+
2908
+
2909
+
2910
+	/**
2911
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2912
+	 *
2913
+	 * @return EE_Secondary_Table[]
2914
+	 */
2915
+	protected function _get_other_tables()
2916
+	{
2917
+		$other_tables = array();
2918
+		foreach ($this->_tables as $table_alias => $table) {
2919
+			if ($table instanceof EE_Secondary_Table) {
2920
+				$other_tables[$table_alias] = $table;
2921
+			}
2922
+		}
2923
+		return $other_tables;
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Finds all the fields that correspond to the given table
2930
+	 *
2931
+	 * @param string $table_alias , array key in EEM_Base::_tables
2932
+	 * @return EE_Model_Field_Base[]
2933
+	 */
2934
+	public function _get_fields_for_table($table_alias)
2935
+	{
2936
+		return $this->_fields[$table_alias];
2937
+	}
2938
+
2939
+
2940
+
2941
+	/**
2942
+	 * Recurses through all the where parameters, and finds all the related models we'll need
2943
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2944
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2945
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2946
+	 * related Registration, Transaction, and Payment models.
2947
+	 *
2948
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2949
+	 * @return EE_Model_Query_Info_Carrier
2950
+	 * @throws \EE_Error
2951
+	 */
2952
+	public function _extract_related_models_from_query($query_params)
2953
+	{
2954
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2955
+		if (array_key_exists(0, $query_params)) {
2956
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2957
+		}
2958
+		if (array_key_exists('group_by', $query_params)) {
2959
+			if (is_array($query_params['group_by'])) {
2960
+				$this->_extract_related_models_from_sub_params_array_values(
2961
+					$query_params['group_by'],
2962
+					$query_info_carrier,
2963
+					'group_by'
2964
+				);
2965
+			} elseif ( ! empty ($query_params['group_by'])) {
2966
+				$this->_extract_related_model_info_from_query_param(
2967
+					$query_params['group_by'],
2968
+					$query_info_carrier,
2969
+					'group_by'
2970
+				);
2971
+			}
2972
+		}
2973
+		if (array_key_exists('having', $query_params)) {
2974
+			$this->_extract_related_models_from_sub_params_array_keys(
2975
+				$query_params[0],
2976
+				$query_info_carrier,
2977
+				'having'
2978
+			);
2979
+		}
2980
+		if (array_key_exists('order_by', $query_params)) {
2981
+			if (is_array($query_params['order_by'])) {
2982
+				$this->_extract_related_models_from_sub_params_array_keys(
2983
+					$query_params['order_by'],
2984
+					$query_info_carrier,
2985
+					'order_by'
2986
+				);
2987
+			} elseif ( ! empty($query_params['order_by'])) {
2988
+				$this->_extract_related_model_info_from_query_param(
2989
+					$query_params['order_by'],
2990
+					$query_info_carrier,
2991
+					'order_by'
2992
+				);
2993
+			}
2994
+		}
2995
+		if (array_key_exists('force_join', $query_params)) {
2996
+			$this->_extract_related_models_from_sub_params_array_values(
2997
+				$query_params['force_join'],
2998
+				$query_info_carrier,
2999
+				'force_join'
3000
+			);
3001
+		}
3002
+		return $query_info_carrier;
3003
+	}
3004
+
3005
+
3006
+
3007
+	/**
3008
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3009
+	 *
3010
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3011
+	 *                                                      $query_params['having']
3012
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3013
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3014
+	 * @throws EE_Error
3015
+	 * @return \EE_Model_Query_Info_Carrier
3016
+	 */
3017
+	private function _extract_related_models_from_sub_params_array_keys(
3018
+		$sub_query_params,
3019
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3020
+		$query_param_type
3021
+	) {
3022
+		if ( ! empty($sub_query_params)) {
3023
+			$sub_query_params = (array)$sub_query_params;
3024
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3027
+					$query_param_type);
3028
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3029
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3030
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3031
+				//of array('Registration.TXN_ID'=>23)
3032
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3033
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3034
+					if ( ! is_array($possibly_array_of_params)) {
3035
+						throw new EE_Error(sprintf(__("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'))",
3036
+							"event_espresso"),
3037
+							$param, $possibly_array_of_params));
3038
+					} else {
3039
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3040
+							$model_query_info_carrier, $query_param_type);
3041
+					}
3042
+				} elseif ($query_param_type === 0 //ie WHERE
3043
+						  && is_array($possibly_array_of_params)
3044
+						  && isset($possibly_array_of_params[2])
3045
+						  && $possibly_array_of_params[2] == true
3046
+				) {
3047
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3048
+					//indicating that $possible_array_of_params[1] is actually a field name,
3049
+					//from which we should extract query parameters!
3050
+					if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3051
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3052
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3053
+					}
3054
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3055
+						$model_query_info_carrier, $query_param_type);
3056
+				}
3057
+			}
3058
+		}
3059
+		return $model_query_info_carrier;
3060
+	}
3061
+
3062
+
3063
+
3064
+	/**
3065
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3066
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3067
+	 *
3068
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3069
+	 *                                                      $query_params['having']
3070
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3071
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3072
+	 * @throws EE_Error
3073
+	 * @return \EE_Model_Query_Info_Carrier
3074
+	 */
3075
+	private function _extract_related_models_from_sub_params_array_values(
3076
+		$sub_query_params,
3077
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3078
+		$query_param_type
3079
+	) {
3080
+		if ( ! empty($sub_query_params)) {
3081
+			if ( ! is_array($sub_query_params)) {
3082
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3083
+					$sub_query_params));
3084
+			}
3085
+			foreach ($sub_query_params as $param) {
3086
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3087
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3088
+					$query_param_type);
3089
+			}
3090
+		}
3091
+		return $model_query_info_carrier;
3092
+	}
3093
+
3094
+
3095
+
3096
+	/**
3097
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3098
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3099
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3100
+	 * but use them in a different order. Eg, we need to know what models we are querying
3101
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3102
+	 * other models before we can finalize the where clause SQL.
3103
+	 *
3104
+	 * @param array $query_params
3105
+	 * @throws EE_Error
3106
+	 * @return EE_Model_Query_Info_Carrier
3107
+	 */
3108
+	public function _create_model_query_info_carrier($query_params)
3109
+	{
3110
+		if ( ! is_array($query_params)) {
3111
+			EE_Error::doing_it_wrong(
3112
+				'EEM_Base::_create_model_query_info_carrier',
3113
+				sprintf(
3114
+					__(
3115
+						'$query_params should be an array, you passed a variable of type %s',
3116
+						'event_espresso'
3117
+					),
3118
+					gettype($query_params)
3119
+				),
3120
+				'4.6.0'
3121
+			);
3122
+			$query_params = array();
3123
+		}
3124
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3125
+		//first check if we should alter the query to account for caps or not
3126
+		//because the caps might require us to do extra joins
3127
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3128
+			$query_params[0] = $where_query_params = array_replace_recursive(
3129
+				$where_query_params,
3130
+				$this->caps_where_conditions(
3131
+					$query_params['caps']
3132
+				)
3133
+			);
3134
+		}
3135
+		$query_object = $this->_extract_related_models_from_query($query_params);
3136
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3137
+		foreach ($where_query_params as $key => $value) {
3138
+			if (is_int($key)) {
3139
+				throw new EE_Error(
3140
+					sprintf(
3141
+						__(
3142
+							"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.",
3143
+							"event_espresso"
3144
+						),
3145
+						$key,
3146
+						var_export($value, true),
3147
+						var_export($query_params, true),
3148
+						get_class($this)
3149
+					)
3150
+				);
3151
+			}
3152
+		}
3153
+		if (
3154
+			array_key_exists('default_where_conditions', $query_params)
3155
+			&& ! empty($query_params['default_where_conditions'])
3156
+		) {
3157
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3158
+		} else {
3159
+			$use_default_where_conditions = 'all';
3160
+		}
3161
+		$where_query_params = array_merge(
3162
+			$this->_get_default_where_conditions_for_models_in_query(
3163
+				$query_object,
3164
+				$use_default_where_conditions,
3165
+				$where_query_params
3166
+			),
3167
+			$where_query_params
3168
+		);
3169
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3170
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3171
+		// So we need to setup a subquery and use that for the main join.
3172
+		// Note for now this only works on the primary table for the model.
3173
+		// So for instance, you could set the limit array like this:
3174
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3175
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3176
+			$query_object->set_main_model_join_sql(
3177
+				$this->_construct_limit_join_select(
3178
+					$query_params['on_join_limit'][0],
3179
+					$query_params['on_join_limit'][1]
3180
+				)
3181
+			);
3182
+		}
3183
+		//set limit
3184
+		if (array_key_exists('limit', $query_params)) {
3185
+			if (is_array($query_params['limit'])) {
3186
+				if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3187
+					$e = sprintf(
3188
+						__(
3189
+							"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)",
3190
+							"event_espresso"
3191
+						),
3192
+						http_build_query($query_params['limit'])
3193
+					);
3194
+					throw new EE_Error($e . "|" . $e);
3195
+				}
3196
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3198
+			} elseif ( ! empty ($query_params['limit'])) {
3199
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3200
+			}
3201
+		}
3202
+		//set order by
3203
+		if (array_key_exists('order_by', $query_params)) {
3204
+			if (is_array($query_params['order_by'])) {
3205
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3206
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3207
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3208
+				if (array_key_exists('order', $query_params)) {
3209
+					throw new EE_Error(
3210
+						sprintf(
3211
+							__(
3212
+								"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 ",
3213
+								"event_espresso"
3214
+							),
3215
+							get_class($this),
3216
+							implode(", ", array_keys($query_params['order_by'])),
3217
+							implode(", ", $query_params['order_by']),
3218
+							$query_params['order']
3219
+						)
3220
+					);
3221
+				}
3222
+				$this->_extract_related_models_from_sub_params_array_keys(
3223
+					$query_params['order_by'],
3224
+					$query_object,
3225
+					'order_by'
3226
+				);
3227
+				//assume it's an array of fields to order by
3228
+				$order_array = array();
3229
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230
+					$order = $this->_extract_order($order);
3231
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3232
+				}
3233
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3234
+			} elseif ( ! empty ($query_params['order_by'])) {
3235
+				$this->_extract_related_model_info_from_query_param(
3236
+					$query_params['order_by'],
3237
+					$query_object,
3238
+					'order',
3239
+					$query_params['order_by']
3240
+				);
3241
+				$order = isset($query_params['order'])
3242
+					? $this->_extract_order($query_params['order'])
3243
+					: 'DESC';
3244
+				$query_object->set_order_by_sql(
3245
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3246
+				);
3247
+			}
3248
+		}
3249
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3250
+		if ( ! array_key_exists('order_by', $query_params)
3251
+			 && array_key_exists('order', $query_params)
3252
+			 && ! empty($query_params['order'])
3253
+		) {
3254
+			$pk_field = $this->get_primary_key_field();
3255
+			$order = $this->_extract_order($query_params['order']);
3256
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3257
+		}
3258
+		//set group by
3259
+		if (array_key_exists('group_by', $query_params)) {
3260
+			if (is_array($query_params['group_by'])) {
3261
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3262
+				$group_by_array = array();
3263
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265
+				}
3266
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3267
+			} elseif ( ! empty ($query_params['group_by'])) {
3268
+				$query_object->set_group_by_sql(
3269
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3270
+				);
3271
+			}
3272
+		}
3273
+		//set having
3274
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3275
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3276
+		}
3277
+		//now, just verify they didn't pass anything wack
3278
+		foreach ($query_params as $query_key => $query_value) {
3279
+			if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3280
+				throw new EE_Error(
3281
+					sprintf(
3282
+						__(
3283
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3284
+							'event_espresso'
3285
+						),
3286
+						$query_key,
3287
+						get_class($this),
3288
+						//						print_r( $this->_allowed_query_params, TRUE )
3289
+						implode(',', $this->_allowed_query_params)
3290
+					)
3291
+				);
3292
+			}
3293
+		}
3294
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3295
+		if (empty($main_model_join_sql)) {
3296
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3297
+		}
3298
+		return $query_object;
3299
+	}
3300
+
3301
+
3302
+
3303
+	/**
3304
+	 * Gets the where conditions that should be imposed on the query based on the
3305
+	 * context (eg reading frontend, backend, edit or delete).
3306
+	 *
3307
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3308
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3309
+	 * @throws \EE_Error
3310
+	 */
3311
+	public function caps_where_conditions($context = self::caps_read)
3312
+	{
3313
+		EEM_Base::verify_is_valid_cap_context($context);
3314
+		$cap_where_conditions = array();
3315
+		$cap_restrictions = $this->caps_missing($context);
3316
+		/**
3317
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3318
+		 */
3319
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3320
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3321
+				$restriction_if_no_cap->get_default_where_conditions());
3322
+		}
3323
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3324
+			$cap_restrictions);
3325
+	}
3326
+
3327
+
3328
+
3329
+	/**
3330
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3331
+	 * otherwise throws an exception
3332
+	 *
3333
+	 * @param string $should_be_order_string
3334
+	 * @return string either ASC, asc, DESC or desc
3335
+	 * @throws EE_Error
3336
+	 */
3337
+	private function _extract_order($should_be_order_string)
3338
+	{
3339
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3340
+			return $should_be_order_string;
3341
+		} else {
3342
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3343
+				"event_espresso"), get_class($this), $should_be_order_string));
3344
+		}
3345
+	}
3346
+
3347
+
3348
+
3349
+	/**
3350
+	 * Looks at all the models which are included in this query, and asks each
3351
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3352
+	 * so they can be merged
3353
+	 *
3354
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3355
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3356
+	 *                                                                  'none' means NO default where conditions will
3357
+	 *                                                                  be used AT ALL during this query.
3358
+	 *                                                                  'other_models_only' means default where
3359
+	 *                                                                  conditions from other models will be used, but
3360
+	 *                                                                  not for this primary model. 'all', the default,
3361
+	 *                                                                  means default where conditions will apply as
3362
+	 *                                                                  normal
3363
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3364
+	 * @throws EE_Error
3365
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3366
+	 */
3367
+	private function _get_default_where_conditions_for_models_in_query(
3368
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3369
+		$use_default_where_conditions = 'all',
3370
+		$where_query_params = array()
3371
+	) {
3372
+		$allowed_used_default_where_conditions_values = array(
3373
+			'all',
3374
+			'this_model_only',
3375
+			'other_models_only',
3376
+			'minimum',
3377
+			'none',
3378
+		);
3379
+		if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3380
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3381
+				"event_espresso"), $use_default_where_conditions,
3382
+				implode(", ", $allowed_used_default_where_conditions_values)));
3383
+		}
3384
+		$universal_query_params = array();
3385
+		if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3386
+			$universal_query_params = $this->_get_default_where_conditions();
3387
+		} else if ($use_default_where_conditions === 'minimum') {
3388
+			$universal_query_params = $this->_get_minimum_where_conditions();
3389
+		}
3390
+		if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3391
+			foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3392
+				$related_model = $this->get_related_model_obj($model_name);
3393
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3394
+				$overrides = $this->_override_defaults_or_make_null_friendly(
3395
+					$related_model_universal_where_params,
3396
+					$where_query_params,
3397
+					$related_model,
3398
+					$model_relation_path
3399
+				);
3400
+				$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3401
+					$universal_query_params,
3402
+					$overrides
3403
+				);
3404
+			}
3405
+		}
3406
+		return $universal_query_params;
3407
+	}
3408
+
3409
+
3410
+
3411
+	/**
3412
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3413
+	 * then we also add a special where condition which allows for that model's primary key
3414
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3415
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3416
+	 *
3417
+	 * @param array    $default_where_conditions
3418
+	 * @param array    $provided_where_conditions
3419
+	 * @param EEM_Base $model
3420
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3421
+	 * @return array like EEM_Base::get_all's $query_params[0]
3422
+	 * @throws \EE_Error
3423
+	 */
3424
+	private function _override_defaults_or_make_null_friendly(
3425
+		$default_where_conditions,
3426
+		$provided_where_conditions,
3427
+		$model,
3428
+		$model_relation_path
3429
+	) {
3430
+		$null_friendly_where_conditions = array();
3431
+		$none_overridden = true;
3432
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3433
+		foreach ($default_where_conditions as $key => $val) {
3434
+			if (isset($provided_where_conditions[$key])) {
3435
+				$none_overridden = false;
3436
+			} else {
3437
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3438
+			}
3439
+		}
3440
+		if ($none_overridden && $default_where_conditions) {
3441
+			if ($model->has_primary_key_field()) {
3442
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3443
+																				. "."
3444
+																				. $model->primary_key_name()] = array('IS NULL');
3445
+			}/*else{
3446 3446
 				//@todo NO PK, use other defaults
3447 3447
 			}*/
3448
-        }
3449
-        return $null_friendly_where_conditions;
3450
-    }
3451
-
3452
-
3453
-
3454
-    /**
3455
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3456
-     * default where conditions on all get_all, update, and delete queries done by this model.
3457
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3458
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3459
-     *
3460
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
-     */
3463
-    private function _get_default_where_conditions($model_relation_path = null)
3464
-    {
3465
-        if ($this->_ignore_where_strategy) {
3466
-            return array();
3467
-        }
3468
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
-    }
3470
-
3471
-
3472
-
3473
-    /**
3474
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3475
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3476
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3477
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3478
-     * Similar to _get_default_where_conditions
3479
-     *
3480
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3481
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3482
-     */
3483
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3484
-    {
3485
-        if ($this->_ignore_where_strategy) {
3486
-            return array();
3487
-        }
3488
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3489
-    }
3490
-
3491
-
3492
-
3493
-    /**
3494
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3495
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3496
-     *
3497
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3498
-     * @return string
3499
-     * @throws \EE_Error
3500
-     */
3501
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3502
-    {
3503
-        $selects = $this->_get_columns_to_select_for_this_model();
3504
-        foreach (
3505
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3506
-            $name_of_other_model_included
3507
-        ) {
3508
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3509
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3510
-            foreach ($other_model_selects as $key => $value) {
3511
-                $selects[] = $value;
3512
-            }
3513
-        }
3514
-        return implode(", ", $selects);
3515
-    }
3516
-
3517
-
3518
-
3519
-    /**
3520
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3521
-     * So that's going to be the columns for all the fields on the model
3522
-     *
3523
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3524
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3525
-     */
3526
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3527
-    {
3528
-        $fields = $this->field_settings();
3529
-        $selects = array();
3530
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3531
-            $this->get_this_model_name());
3532
-        foreach ($fields as $field_obj) {
3533
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3534
-                         . $field_obj->get_table_alias()
3535
-                         . "."
3536
-                         . $field_obj->get_table_column()
3537
-                         . " AS '"
3538
-                         . $table_alias_with_model_relation_chain_prefix
3539
-                         . $field_obj->get_table_alias()
3540
-                         . "."
3541
-                         . $field_obj->get_table_column()
3542
-                         . "'";
3543
-        }
3544
-        //make sure we are also getting the PKs of each table
3545
-        $tables = $this->get_tables();
3546
-        if (count($tables) > 1) {
3547
-            foreach ($tables as $table_obj) {
3548
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3549
-                                       . $table_obj->get_fully_qualified_pk_column();
3550
-                if ( ! in_array($qualified_pk_column, $selects)) {
3551
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3552
-                }
3553
-            }
3554
-        }
3555
-        return $selects;
3556
-    }
3557
-
3558
-
3559
-
3560
-    /**
3561
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3562
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3563
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3564
-     * SQL for joining, and the data types
3565
-     *
3566
-     * @param null|string                 $original_query_param
3567
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3568
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3569
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3570
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3571
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3572
-     *                                                          or 'Registration's
3573
-     * @param string                      $original_query_param what it originally was (eg
3574
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3575
-     *                                                          matches $query_param
3576
-     * @throws EE_Error
3577
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3578
-     */
3579
-    private function _extract_related_model_info_from_query_param(
3580
-        $query_param,
3581
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3582
-        $query_param_type,
3583
-        $original_query_param = null
3584
-    ) {
3585
-        if ($original_query_param === null) {
3586
-            $original_query_param = $query_param;
3587
-        }
3588
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3589
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3590
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3591
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3592
-        //check to see if we have a field on this model
3593
-        $this_model_fields = $this->field_settings(true);
3594
-        if (array_key_exists($query_param, $this_model_fields)) {
3595
-            if ($allow_fields) {
3596
-                return;
3597
-            } else {
3598
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3599
-                    "event_espresso"),
3600
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3601
-            }
3602
-        } //check if this is a special logic query param
3603
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3604
-            if ($allow_logic_query_params) {
3605
-                return;
3606
-            } else {
3607
-                throw new EE_Error(
3608
-                    sprintf(
3609
-                        __('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',
3610
-                            'event_espresso'),
3611
-                        implode('", "', $this->_logic_query_param_keys),
3612
-                        $query_param,
3613
-                        get_class($this),
3614
-                        '<br />',
3615
-                        "\t"
3616
-                        . ' $passed_in_query_info = <pre>'
3617
-                        . print_r($passed_in_query_info, true)
3618
-                        . '</pre>'
3619
-                        . "\n\t"
3620
-                        . ' $query_param_type = '
3621
-                        . $query_param_type
3622
-                        . "\n\t"
3623
-                        . ' $original_query_param = '
3624
-                        . $original_query_param
3625
-                    )
3626
-                );
3627
-            }
3628
-        } //check if it's a custom selection
3629
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3630
-            return;
3631
-        }
3632
-        //check if has a model name at the beginning
3633
-        //and
3634
-        //check if it's a field on a related model
3635
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3637
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3639
-                if ($query_param === '') {
3640
-                    //nothing left to $query_param
3641
-                    //we should actually end in a field name, not a model like this!
3642
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3643
-                        "event_espresso"),
3644
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3645
-                } else {
3646
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3647
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3648
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3649
-                    return;
3650
-                }
3651
-            } elseif ($query_param === $valid_related_model_name) {
3652
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3653
-                return;
3654
-            }
3655
-        }
3656
-        //ok so $query_param didn't start with a model name
3657
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3658
-        //it's wack, that's what it is
3659
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3660
-            "event_espresso"),
3661
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3662
-    }
3663
-
3664
-
3665
-
3666
-    /**
3667
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3668
-     * and store it on $passed_in_query_info
3669
-     *
3670
-     * @param string                      $model_name
3671
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3672
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3673
-     *                                                          model and $model_name. Eg, if we are querying Event,
3674
-     *                                                          and are adding a join to 'Payment' with the original
3675
-     *                                                          query param key
3676
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3677
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3678
-     *                                                          Payment wants to add default query params so that it
3679
-     *                                                          will know what models to prepend onto its default query
3680
-     *                                                          params or in case it wants to rename tables (in case
3681
-     *                                                          there are multiple joins to the same table)
3682
-     * @return void
3683
-     * @throws \EE_Error
3684
-     */
3685
-    private function _add_join_to_model(
3686
-        $model_name,
3687
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3688
-        $original_query_param
3689
-    ) {
3690
-        $relation_obj = $this->related_settings_for($model_name);
3691
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3692
-        //check if the relation is HABTM, because then we're essentially doing two joins
3693
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3694
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3695
-            $join_model_obj = $relation_obj->get_join_model();
3696
-            //replace the model specified with the join model for this relation chain, whi
3697
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3698
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3699
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3700
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3701
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3702
-            $passed_in_query_info->merge($new_query_info);
3703
-        }
3704
-        //now just join to the other table pointed to by the relation object, and add its data types
3705
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3706
-            array($model_relation_chain => $model_name),
3707
-            $relation_obj->get_join_statement($model_relation_chain));
3708
-        $passed_in_query_info->merge($new_query_info);
3709
-    }
3710
-
3711
-
3712
-
3713
-    /**
3714
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3715
-     *
3716
-     * @param array $where_params like EEM_Base::get_all
3717
-     * @return string of SQL
3718
-     * @throws \EE_Error
3719
-     */
3720
-    private function _construct_where_clause($where_params)
3721
-    {
3722
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723
-        if ($SQL) {
3724
-            return " WHERE " . $SQL;
3725
-        } else {
3726
-            return '';
3727
-        }
3728
-    }
3729
-
3730
-
3731
-
3732
-    /**
3733
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3734
-     * and should be passed HAVING parameters, not WHERE parameters
3735
-     *
3736
-     * @param array $having_params
3737
-     * @return string
3738
-     * @throws \EE_Error
3739
-     */
3740
-    private function _construct_having_clause($having_params)
3741
-    {
3742
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743
-        if ($SQL) {
3744
-            return " HAVING " . $SQL;
3745
-        } else {
3746
-            return '';
3747
-        }
3748
-    }
3749
-
3750
-
3751
-
3752
-    /**
3753
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3754
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3755
-     * EEM_Attendee.
3756
-     *
3757
-     * @param string $field_name
3758
-     * @param string $model_name
3759
-     * @return EE_Model_Field_Base
3760
-     * @throws EE_Error
3761
-     */
3762
-    protected function _get_field_on_model($field_name, $model_name)
3763
-    {
3764
-        $model_class = 'EEM_' . $model_name;
3765
-        $model_filepath = $model_class . ".model.php";
3766
-        if (is_readable($model_filepath)) {
3767
-            require_once($model_filepath);
3768
-            $model_instance = call_user_func($model_name . "::instance");
3769
-            /* @var $model_instance EEM_Base */
3770
-            return $model_instance->field_settings_for($field_name);
3771
-        } else {
3772
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3773
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3774
-        }
3775
-    }
3776
-
3777
-
3778
-
3779
-    /**
3780
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3781
-     * Event_Meta.meta_value = 'foo'))"
3782
-     *
3783
-     * @param array  $where_params see EEM_Base::get_all for documentation
3784
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3785
-     * @throws EE_Error
3786
-     * @return string of SQL
3787
-     */
3788
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3789
-    {
3790
-        $where_clauses = array();
3791
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3793
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3794
-                switch ($query_param) {
3795
-                    case 'not':
3796
-                    case 'NOT':
3797
-                        $where_clauses[] = "! ("
3798
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3799
-                                $glue)
3800
-                                           . ")";
3801
-                        break;
3802
-                    case 'and':
3803
-                    case 'AND':
3804
-                        $where_clauses[] = " ("
3805
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3806
-                                ' AND ')
3807
-                                           . ")";
3808
-                        break;
3809
-                    case 'or':
3810
-                    case 'OR':
3811
-                        $where_clauses[] = " ("
3812
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3813
-                                ' OR ')
3814
-                                           . ")";
3815
-                        break;
3816
-                }
3817
-            } else {
3818
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3819
-                //if it's not a normal field, maybe it's a custom selection?
3820
-                if ( ! $field_obj) {
3821
-                    if (isset($this->_custom_selections[$query_param][1])) {
3822
-                        $field_obj = $this->_custom_selections[$query_param][1];
3823
-                    } else {
3824
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3825
-                            "event_espresso"), $query_param));
3826
-                    }
3827
-                }
3828
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3830
-            }
3831
-        }
3832
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3833
-    }
3834
-
3835
-
3836
-
3837
-    /**
3838
-     * Takes the input parameter and extract the table name (alias) and column name
3839
-     *
3840
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3841
-     * @throws EE_Error
3842
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3843
-     */
3844
-    private function _deduce_column_name_from_query_param($query_param)
3845
-    {
3846
-        $field = $this->_deduce_field_from_query_param($query_param);
3847
-        if ($field) {
3848
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849
-                $query_param);
3850
-            return $table_alias_prefix . $field->get_qualified_column();
3851
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852
-            //maybe it's custom selection item?
3853
-            //if so, just use it as the "column name"
3854
-            return $query_param;
3855
-        } else {
3856
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3857
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3858
-        }
3859
-    }
3860
-
3861
-
3862
-
3863
-    /**
3864
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3865
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3866
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3867
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3868
-     *
3869
-     * @param string $condition_query_param_key
3870
-     * @return string
3871
-     */
3872
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3873
-    {
3874
-        $pos_of_star = strpos($condition_query_param_key, '*');
3875
-        if ($pos_of_star === false) {
3876
-            return $condition_query_param_key;
3877
-        } else {
3878
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3879
-            return $condition_query_param_sans_star;
3880
-        }
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3887
-     *
3888
-     * @param                            mixed      array | string    $op_and_value
3889
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3890
-     * @throws EE_Error
3891
-     * @return string
3892
-     */
3893
-    private function _construct_op_and_value($op_and_value, $field_obj)
3894
-    {
3895
-        if (is_array($op_and_value)) {
3896
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3897
-            if ( ! $operator) {
3898
-                $php_array_like_string = array();
3899
-                foreach ($op_and_value as $key => $value) {
3900
-                    $php_array_like_string[] = "$key=>$value";
3901
-                }
3902
-                throw new EE_Error(
3903
-                    sprintf(
3904
-                        __(
3905
-                            "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))",
3906
-                            "event_espresso"
3907
-                        ),
3908
-                        implode(",", $php_array_like_string)
3909
-                    )
3910
-                );
3911
-            }
3912
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3913
-        } else {
3914
-            $operator = '=';
3915
-            $value = $op_and_value;
3916
-        }
3917
-        //check to see if the value is actually another field
3918
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3920
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921
-            //in this case, the value should be an array, or at least a comma-separated list
3922
-            //it will need to handle a little differently
3923
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
3924
-            //note: $cleaned_value has already been run through $wpdb->prepare()
3925
-            return $operator . SP . $cleaned_value;
3926
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927
-            //the value should be an array with count of two.
3928
-            if (count($value) !== 2) {
3929
-                throw new EE_Error(
3930
-                    sprintf(
3931
-                        __(
3932
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3933
-                            'event_espresso'
3934
-                        ),
3935
-                        "BETWEEN"
3936
-                    )
3937
-                );
3938
-            }
3939
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
-            return $operator . SP . $cleaned_value;
3941
-        } elseif (in_array($operator, $this->_null_style_operators)) {
3942
-            if ($value !== null) {
3943
-                throw new EE_Error(
3944
-                    sprintf(
3945
-                        __(
3946
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3947
-                            "event_espresso"
3948
-                        ),
3949
-                        $value,
3950
-                        $operator
3951
-                    )
3952
-                );
3953
-            }
3954
-            return $operator;
3955
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
3956
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
3957
-            //remove other junk. So just treat it as a string.
3958
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3959
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3961
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962
-            throw new EE_Error(
3963
-                sprintf(
3964
-                    __(
3965
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3966
-                        'event_espresso'
3967
-                    ),
3968
-                    $operator,
3969
-                    $operator
3970
-                )
3971
-            );
3972
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3973
-            throw new EE_Error(
3974
-                sprintf(
3975
-                    __(
3976
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3977
-                        'event_espresso'
3978
-                    ),
3979
-                    $operator,
3980
-                    $operator
3981
-                )
3982
-            );
3983
-        } else {
3984
-            throw new EE_Error(
3985
-                sprintf(
3986
-                    __(
3987
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3988
-                        "event_espresso"
3989
-                    ),
3990
-                    http_build_query($op_and_value)
3991
-                )
3992
-            );
3993
-        }
3994
-    }
3995
-
3996
-
3997
-
3998
-    /**
3999
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4000
-     *
4001
-     * @param array                      $values
4002
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4003
-     *                                              '%s'
4004
-     * @return string
4005
-     * @throws \EE_Error
4006
-     */
4007
-    public function _construct_between_value($values, $field_obj)
4008
-    {
4009
-        $cleaned_values = array();
4010
-        foreach ($values as $value) {
4011
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012
-        }
4013
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4014
-    }
4015
-
4016
-
4017
-
4018
-    /**
4019
-     * Takes an array or a comma-separated list of $values and cleans them
4020
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4021
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4022
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4023
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4024
-     *
4025
-     * @param mixed                      $values    array or comma-separated string
4026
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4027
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4028
-     * @throws \EE_Error
4029
-     */
4030
-    public function _construct_in_value($values, $field_obj)
4031
-    {
4032
-        //check if the value is a CSV list
4033
-        if (is_string($values)) {
4034
-            //in which case, turn it into an array
4035
-            $values = explode(",", $values);
4036
-        }
4037
-        $cleaned_values = array();
4038
-        foreach ($values as $value) {
4039
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4040
-        }
4041
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4042
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4043
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4044
-        if (empty($cleaned_values)) {
4045
-            $all_fields = $this->field_settings();
4046
-            $a_field = array_shift($all_fields);
4047
-            $main_table = $this->_get_main_table();
4048
-            $cleaned_values[] = "SELECT "
4049
-                                . $a_field->get_table_column()
4050
-                                . " FROM "
4051
-                                . $main_table->get_table_name()
4052
-                                . " WHERE FALSE";
4053
-        }
4054
-        return "(" . implode(",", $cleaned_values) . ")";
4055
-    }
4056
-
4057
-
4058
-
4059
-    /**
4060
-     * @param mixed                      $value
4061
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4062
-     * @throws EE_Error
4063
-     * @return false|null|string
4064
-     */
4065
-    private function _wpdb_prepare_using_field($value, $field_obj)
4066
-    {
4067
-        /** @type WPDB $wpdb */
4068
-        global $wpdb;
4069
-        if ($field_obj instanceof EE_Model_Field_Base) {
4070
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4071
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4072
-        } else {//$field_obj should really just be a data type
4073
-            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4074
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4075
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4076
-            }
4077
-            return $wpdb->prepare($field_obj, $value);
4078
-        }
4079
-    }
4080
-
4081
-
4082
-
4083
-    /**
4084
-     * Takes the input parameter and finds the model field that it indicates.
4085
-     *
4086
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4087
-     * @throws EE_Error
4088
-     * @return EE_Model_Field_Base
4089
-     */
4090
-    protected function _deduce_field_from_query_param($query_param_name)
4091
-    {
4092
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4093
-        //which will help us find the database table and column
4094
-        $query_param_parts = explode(".", $query_param_name);
4095
-        if (empty($query_param_parts)) {
4096
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4097
-                'event_espresso'), $query_param_name));
4098
-        }
4099
-        $number_of_parts = count($query_param_parts);
4100
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4101
-        if ($number_of_parts === 1) {
4102
-            $field_name = $last_query_param_part;
4103
-            $model_obj = $this;
4104
-        } else {// $number_of_parts >= 2
4105
-            //the last part is the column name, and there are only 2parts. therefore...
4106
-            $field_name = $last_query_param_part;
4107
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4108
-        }
4109
-        try {
4110
-            return $model_obj->field_settings_for($field_name);
4111
-        } catch (EE_Error $e) {
4112
-            return null;
4113
-        }
4114
-    }
4115
-
4116
-
4117
-
4118
-    /**
4119
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4120
-     * alias and column which corresponds to it
4121
-     *
4122
-     * @param string $field_name
4123
-     * @throws EE_Error
4124
-     * @return string
4125
-     */
4126
-    public function _get_qualified_column_for_field($field_name)
4127
-    {
4128
-        $all_fields = $this->field_settings();
4129
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4130
-        if ($field) {
4131
-            return $field->get_qualified_column();
4132
-        } else {
4133
-            throw new EE_Error(sprintf(__("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.",
4134
-                'event_espresso'), $field_name, get_class($this)));
4135
-        }
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * constructs the select use on special limit joins
4142
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4143
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4144
-     * (as that is typically where the limits would be set).
4145
-     *
4146
-     * @param  string       $table_alias The table the select is being built for
4147
-     * @param  mixed|string $limit       The limit for this select
4148
-     * @return string                The final select join element for the query.
4149
-     */
4150
-    public function _construct_limit_join_select($table_alias, $limit)
4151
-    {
4152
-        $SQL = '';
4153
-        foreach ($this->_tables as $table_obj) {
4154
-            if ($table_obj instanceof EE_Primary_Table) {
4155
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4156
-                    ? $table_obj->get_select_join_limit($limit)
4157
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4158
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4159
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4160
-                    ? $table_obj->get_select_join_limit_join($limit)
4161
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4162
-            }
4163
-        }
4164
-        return $SQL;
4165
-    }
4166
-
4167
-
4168
-
4169
-    /**
4170
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4171
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4172
-     *
4173
-     * @return string SQL
4174
-     * @throws \EE_Error
4175
-     */
4176
-    public function _construct_internal_join()
4177
-    {
4178
-        $SQL = $this->_get_main_table()->get_table_sql();
4179
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4180
-        return $SQL;
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Constructs the SQL for joining all the tables on this model.
4187
-     * Normally $alias should be the primary table's alias, but in cases where
4188
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4189
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4190
-     * alias, this will construct SQL like:
4191
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4192
-     * With $alias being a secondary table's alias, this will construct SQL like:
4193
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4194
-     *
4195
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4196
-     * @return string
4197
-     */
4198
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4199
-    {
4200
-        $SQL = '';
4201
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4202
-        foreach ($this->_tables as $table_obj) {
4203
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4204
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4205
-                    //so we're joining to this table, meaning the table is already in
4206
-                    //the FROM statement, BUT the primary table isn't. So we want
4207
-                    //to add the inverse join sql
4208
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4209
-                } else {
4210
-                    //just add a regular JOIN to this table from the primary table
4211
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4212
-                }
4213
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4214
-        }
4215
-        return $SQL;
4216
-    }
4217
-
4218
-
4219
-
4220
-    /**
4221
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4222
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4223
-     * their data type (eg, '%s', '%d', etc)
4224
-     *
4225
-     * @return array
4226
-     */
4227
-    public function _get_data_types()
4228
-    {
4229
-        $data_types = array();
4230
-        foreach ($this->field_settings() as $field_obj) {
4231
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4232
-            /** @var $field_obj EE_Model_Field_Base */
4233
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4234
-        }
4235
-        return $data_types;
4236
-    }
4237
-
4238
-
4239
-
4240
-    /**
4241
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4242
-     *
4243
-     * @param string $model_name
4244
-     * @throws EE_Error
4245
-     * @return EEM_Base
4246
-     */
4247
-    public function get_related_model_obj($model_name)
4248
-    {
4249
-        $model_classname = "EEM_" . $model_name;
4250
-        if ( ! class_exists($model_classname)) {
4251
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4252
-                'event_espresso'), $model_name, $model_classname));
4253
-        }
4254
-        return call_user_func($model_classname . "::instance");
4255
-    }
4256
-
4257
-
4258
-
4259
-    /**
4260
-     * Returns the array of EE_ModelRelations for this model.
4261
-     *
4262
-     * @return EE_Model_Relation_Base[]
4263
-     */
4264
-    public function relation_settings()
4265
-    {
4266
-        return $this->_model_relations;
4267
-    }
4268
-
4269
-
4270
-
4271
-    /**
4272
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4273
-     * because without THOSE models, this model probably doesn't have much purpose.
4274
-     * (Eg, without an event, datetimes have little purpose.)
4275
-     *
4276
-     * @return EE_Belongs_To_Relation[]
4277
-     */
4278
-    public function belongs_to_relations()
4279
-    {
4280
-        $belongs_to_relations = array();
4281
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4282
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4283
-                $belongs_to_relations[$model_name] = $relation_obj;
4284
-            }
4285
-        }
4286
-        return $belongs_to_relations;
4287
-    }
4288
-
4289
-
4290
-
4291
-    /**
4292
-     * Returns the specified EE_Model_Relation, or throws an exception
4293
-     *
4294
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4295
-     * @throws EE_Error
4296
-     * @return EE_Model_Relation_Base
4297
-     */
4298
-    public function related_settings_for($relation_name)
4299
-    {
4300
-        $relatedModels = $this->relation_settings();
4301
-        if ( ! array_key_exists($relation_name, $relatedModels)) {
4302
-            throw new EE_Error(
4303
-                sprintf(
4304
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4305
-                        'event_espresso'),
4306
-                    $relation_name,
4307
-                    $this->_get_class_name(),
4308
-                    implode(', ', array_keys($relatedModels))
4309
-                )
4310
-            );
4311
-        }
4312
-        return $relatedModels[$relation_name];
4313
-    }
4314
-
4315
-
4316
-
4317
-    /**
4318
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4319
-     * fields
4320
-     *
4321
-     * @param string $fieldName
4322
-     * @throws EE_Error
4323
-     * @return EE_Model_Field_Base
4324
-     */
4325
-    public function field_settings_for($fieldName)
4326
-    {
4327
-        $fieldSettings = $this->field_settings(true);
4328
-        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4329
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4330
-                get_class($this)));
4331
-        }
4332
-        return $fieldSettings[$fieldName];
4333
-    }
4334
-
4335
-
4336
-
4337
-    /**
4338
-     * Checks if this field exists on this model
4339
-     *
4340
-     * @param string $fieldName a key in the model's _field_settings array
4341
-     * @return boolean
4342
-     */
4343
-    public function has_field($fieldName)
4344
-    {
4345
-        $fieldSettings = $this->field_settings(true);
4346
-        if (isset($fieldSettings[$fieldName])) {
4347
-            return true;
4348
-        } else {
4349
-            return false;
4350
-        }
4351
-    }
4352
-
4353
-
4354
-
4355
-    /**
4356
-     * Returns whether or not this model has a relation to the specified model
4357
-     *
4358
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4359
-     * @return boolean
4360
-     */
4361
-    public function has_relation($relation_name)
4362
-    {
4363
-        $relations = $this->relation_settings();
4364
-        if (isset($relations[$relation_name])) {
4365
-            return true;
4366
-        } else {
4367
-            return false;
4368
-        }
4369
-    }
4370
-
4371
-
4372
-
4373
-    /**
4374
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4375
-     * Eg, on EE_Answer that would be ANS_ID field object
4376
-     *
4377
-     * @param $field_obj
4378
-     * @return boolean
4379
-     */
4380
-    public function is_primary_key_field($field_obj)
4381
-    {
4382
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4383
-    }
4384
-
4385
-
4386
-
4387
-    /**
4388
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4389
-     * Eg, on EE_Answer that would be ANS_ID field object
4390
-     *
4391
-     * @return EE_Model_Field_Base
4392
-     * @throws EE_Error
4393
-     */
4394
-    public function get_primary_key_field()
4395
-    {
4396
-        if ($this->_primary_key_field === null) {
4397
-            foreach ($this->field_settings(true) as $field_obj) {
4398
-                if ($this->is_primary_key_field($field_obj)) {
4399
-                    $this->_primary_key_field = $field_obj;
4400
-                    break;
4401
-                }
4402
-            }
4403
-            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4404
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4405
-                    get_class($this)));
4406
-            }
4407
-        }
4408
-        return $this->_primary_key_field;
4409
-    }
4410
-
4411
-
4412
-
4413
-    /**
4414
-     * Returns whether or not not there is a primary key on this model.
4415
-     * Internally does some caching.
4416
-     *
4417
-     * @return boolean
4418
-     */
4419
-    public function has_primary_key_field()
4420
-    {
4421
-        if ($this->_has_primary_key_field === null) {
4422
-            try {
4423
-                $this->get_primary_key_field();
4424
-                $this->_has_primary_key_field = true;
4425
-            } catch (EE_Error $e) {
4426
-                $this->_has_primary_key_field = false;
4427
-            }
4428
-        }
4429
-        return $this->_has_primary_key_field;
4430
-    }
4431
-
4432
-
4433
-
4434
-    /**
4435
-     * Finds the first field of type $field_class_name.
4436
-     *
4437
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4438
-     *                                 EE_Foreign_Key_Field, etc
4439
-     * @return EE_Model_Field_Base or null if none is found
4440
-     */
4441
-    public function get_a_field_of_type($field_class_name)
4442
-    {
4443
-        foreach ($this->field_settings() as $field) {
4444
-            if ($field instanceof $field_class_name) {
4445
-                return $field;
4446
-            }
4447
-        }
4448
-        return null;
4449
-    }
4450
-
4451
-
4452
-
4453
-    /**
4454
-     * Gets a foreign key field pointing to model.
4455
-     *
4456
-     * @param string $model_name eg Event, Registration, not EEM_Event
4457
-     * @return EE_Foreign_Key_Field_Base
4458
-     * @throws EE_Error
4459
-     */
4460
-    public function get_foreign_key_to($model_name)
4461
-    {
4462
-        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4463
-            foreach ($this->field_settings() as $field) {
4464
-                if (
4465
-                    $field instanceof EE_Foreign_Key_Field_Base
4466
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4467
-                ) {
4468
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4469
-                    break;
4470
-                }
4471
-            }
4472
-            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4473
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4474
-                    'event_espresso'), $model_name, get_class($this)));
4475
-            }
4476
-        }
4477
-        return $this->_cache_foreign_key_to_fields[$model_name];
4478
-    }
4479
-
4480
-
4481
-
4482
-    /**
4483
-     * Gets the actual table for the table alias
4484
-     *
4485
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4486
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4487
-     *                            Either one works
4488
-     * @return EE_Table_Base
4489
-     */
4490
-    public function get_table_for_alias($table_alias)
4491
-    {
4492
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4493
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4494
-    }
4495
-
4496
-
4497
-
4498
-    /**
4499
-     * Returns a flat array of all field son this model, instead of organizing them
4500
-     * by table_alias as they are in the constructor.
4501
-     *
4502
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4503
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4504
-     */
4505
-    public function field_settings($include_db_only_fields = false)
4506
-    {
4507
-        if ($include_db_only_fields) {
4508
-            if ($this->_cached_fields === null) {
4509
-                $this->_cached_fields = array();
4510
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4511
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4512
-                        $this->_cached_fields[$field_name] = $field_obj;
4513
-                    }
4514
-                }
4515
-            }
4516
-            return $this->_cached_fields;
4517
-        } else {
4518
-            if ($this->_cached_fields_non_db_only === null) {
4519
-                $this->_cached_fields_non_db_only = array();
4520
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4521
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4522
-                        /** @var $field_obj EE_Model_Field_Base */
4523
-                        if ( ! $field_obj->is_db_only_field()) {
4524
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4525
-                        }
4526
-                    }
4527
-                }
4528
-            }
4529
-            return $this->_cached_fields_non_db_only;
4530
-        }
4531
-    }
4532
-
4533
-
4534
-
4535
-    /**
4536
-     *        cycle though array of attendees and create objects out of each item
4537
-     *
4538
-     * @access        private
4539
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4540
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4541
-     *                           numerically indexed)
4542
-     * @throws \EE_Error
4543
-     */
4544
-    protected function _create_objects($rows = array())
4545
-    {
4546
-        $array_of_objects = array();
4547
-        if (empty($rows)) {
4548
-            return array();
4549
-        }
4550
-        $count_if_model_has_no_primary_key = 0;
4551
-        $has_primary_key = $this->has_primary_key_field();
4552
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4553
-        foreach ((array)$rows as $row) {
4554
-            if (empty($row)) {
4555
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4556
-                return array();
4557
-            }
4558
-            //check if we've already set this object in the results array,
4559
-            //in which case there's no need to process it further (again)
4560
-            if ($has_primary_key) {
4561
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4562
-                    $row,
4563
-                    $primary_key_field->get_qualified_column(),
4564
-                    $primary_key_field->get_table_column()
4565
-                );
4566
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4567
-                    continue;
4568
-                }
4569
-            }
4570
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4571
-            if ( ! $classInstance) {
4572
-                throw new EE_Error(
4573
-                    sprintf(
4574
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4575
-                        $this->get_this_model_name(),
4576
-                        http_build_query($row)
4577
-                    )
4578
-                );
4579
-            }
4580
-            //set the timezone on the instantiated objects
4581
-            $classInstance->set_timezone($this->_timezone);
4582
-            //make sure if there is any timezone setting present that we set the timezone for the object
4583
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4584
-            $array_of_objects[$key] = $classInstance;
4585
-            //also, for all the relations of type BelongsTo, see if we can cache
4586
-            //those related models
4587
-            //(we could do this for other relations too, but if there are conditions
4588
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4589
-            //so it requires a little more thought than just caching them immediately...)
4590
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4591
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4592
-                    //check if this model's INFO is present. If so, cache it on the model
4593
-                    $other_model = $relation_obj->get_other_model();
4594
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4595
-                    //if we managed to make a model object from the results, cache it on the main model object
4596
-                    if ($other_model_obj_maybe) {
4597
-                        //set timezone on these other model objects if they are present
4598
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4599
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4600
-                    }
4601
-                }
4602
-            }
4603
-        }
4604
-        return $array_of_objects;
4605
-    }
4606
-
4607
-
4608
-
4609
-    /**
4610
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4611
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4612
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4613
-     * object (as set in the model_field!).
4614
-     *
4615
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4616
-     */
4617
-    public function create_default_object()
4618
-    {
4619
-        $this_model_fields_and_values = array();
4620
-        //setup the row using default values;
4621
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4622
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4623
-        }
4624
-        $className = $this->_get_class_name();
4625
-        $classInstance = EE_Registry::instance()
4626
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4627
-        return $classInstance;
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4634
-     *                             or an stdClass where each property is the name of a column,
4635
-     * @return EE_Base_Class
4636
-     * @throws \EE_Error
4637
-     */
4638
-    public function instantiate_class_from_array_or_object($cols_n_values)
4639
-    {
4640
-        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4641
-            $cols_n_values = get_object_vars($cols_n_values);
4642
-        }
4643
-        $primary_key = null;
4644
-        //make sure the array only has keys that are fields/columns on this model
4645
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4646
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4647
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4648
-        }
4649
-        $className = $this->_get_class_name();
4650
-        //check we actually found results that we can use to build our model object
4651
-        //if not, return null
4652
-        if ($this->has_primary_key_field()) {
4653
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4654
-                return null;
4655
-            }
4656
-        } else if ($this->unique_indexes()) {
4657
-            $first_column = reset($this_model_fields_n_values);
4658
-            if (empty($first_column)) {
4659
-                return null;
4660
-            }
4661
-        }
4662
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4663
-        if ($primary_key) {
4664
-            $classInstance = $this->get_from_entity_map($primary_key);
4665
-            if ( ! $classInstance) {
4666
-                $classInstance = EE_Registry::instance()
4667
-                                            ->load_class($className,
4668
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4669
-                // add this new object to the entity map
4670
-                $classInstance = $this->add_to_entity_map($classInstance);
4671
-            }
4672
-        } else {
4673
-            $classInstance = EE_Registry::instance()
4674
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4675
-                                            true, false);
4676
-        }
4677
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4678
-        $this->set_timezone($classInstance->get_timezone());
4679
-        return $classInstance;
4680
-    }
4681
-
4682
-
4683
-
4684
-    /**
4685
-     * Gets the model object from the  entity map if it exists
4686
-     *
4687
-     * @param int|string $id the ID of the model object
4688
-     * @return EE_Base_Class
4689
-     */
4690
-    public function get_from_entity_map($id)
4691
-    {
4692
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4693
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4694
-    }
4695
-
4696
-
4697
-
4698
-    /**
4699
-     * add_to_entity_map
4700
-     * Adds the object to the model's entity mappings
4701
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4702
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4703
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4704
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4705
-     *        then this method should be called immediately after the update query
4706
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4707
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4708
-     *
4709
-     * @param    EE_Base_Class $object
4710
-     * @throws EE_Error
4711
-     * @return \EE_Base_Class
4712
-     */
4713
-    public function add_to_entity_map(EE_Base_Class $object)
4714
-    {
4715
-        $className = $this->_get_class_name();
4716
-        if ( ! $object instanceof $className) {
4717
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4718
-                is_object($object) ? get_class($object) : $object, $className));
4719
-        }
4720
-        /** @var $object EE_Base_Class */
4721
-        if ( ! $object->ID()) {
4722
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4723
-                "event_espresso"), get_class($this)));
4724
-        }
4725
-        // double check it's not already there
4726
-        $classInstance = $this->get_from_entity_map($object->ID());
4727
-        if ($classInstance) {
4728
-            return $classInstance;
4729
-        } else {
4730
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4731
-            return $object;
4732
-        }
4733
-    }
4734
-
4735
-
4736
-
4737
-    /**
4738
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4739
-     * if no identifier is provided, then the entire entity map is emptied
4740
-     *
4741
-     * @param int|string $id the ID of the model object
4742
-     * @return boolean
4743
-     */
4744
-    public function clear_entity_map($id = null)
4745
-    {
4746
-        if (empty($id)) {
4747
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4748
-            return true;
4749
-        }
4750
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4751
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4752
-            return true;
4753
-        }
4754
-        return false;
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4761
-     * Given an array where keys are column (or column alias) names and values,
4762
-     * returns an array of their corresponding field names and database values
4763
-     *
4764
-     * @param array $cols_n_values
4765
-     * @return array
4766
-     */
4767
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4768
-    {
4769
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4770
-    }
4771
-
4772
-
4773
-
4774
-    /**
4775
-     * _deduce_fields_n_values_from_cols_n_values
4776
-     * Given an array where keys are column (or column alias) names and values,
4777
-     * returns an array of their corresponding field names and database values
4778
-     *
4779
-     * @param string $cols_n_values
4780
-     * @return array
4781
-     */
4782
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4783
-    {
4784
-        $this_model_fields_n_values = array();
4785
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4786
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4787
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4788
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4789
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4790
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4791
-                    if ( ! $field_obj->is_db_only_field()) {
4792
-                        //prepare field as if its coming from db
4793
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4794
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4795
-                    }
4796
-                }
4797
-            } else {
4798
-                //the table's rows existed. Use their values
4799
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4800
-                    if ( ! $field_obj->is_db_only_field()) {
4801
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4802
-                            $cols_n_values, $field_obj->get_qualified_column(),
4803
-                            $field_obj->get_table_column()
4804
-                        );
4805
-                    }
4806
-                }
4807
-            }
4808
-        }
4809
-        return $this_model_fields_n_values;
4810
-    }
4811
-
4812
-
4813
-
4814
-    /**
4815
-     * @param $cols_n_values
4816
-     * @param $qualified_column
4817
-     * @param $regular_column
4818
-     * @return null
4819
-     */
4820
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4821
-    {
4822
-        $value = null;
4823
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4824
-        //does the field on the model relate to this column retrieved from the db?
4825
-        //or is it a db-only field? (not relating to the model)
4826
-        if (isset($cols_n_values[$qualified_column])) {
4827
-            $value = $cols_n_values[$qualified_column];
4828
-        } elseif (isset($cols_n_values[$regular_column])) {
4829
-            $value = $cols_n_values[$regular_column];
4830
-        }
4831
-        return $value;
4832
-    }
4833
-
4834
-
4835
-
4836
-    /**
4837
-     * refresh_entity_map_from_db
4838
-     * Makes sure the model object in the entity map at $id assumes the values
4839
-     * of the database (opposite of EE_base_Class::save())
4840
-     *
4841
-     * @param int|string $id
4842
-     * @return EE_Base_Class
4843
-     * @throws \EE_Error
4844
-     */
4845
-    public function refresh_entity_map_from_db($id)
4846
-    {
4847
-        $obj_in_map = $this->get_from_entity_map($id);
4848
-        if ($obj_in_map) {
4849
-            $wpdb_results = $this->_get_all_wpdb_results(
4850
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4851
-            );
4852
-            if ($wpdb_results && is_array($wpdb_results)) {
4853
-                $one_row = reset($wpdb_results);
4854
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4855
-                    $obj_in_map->set_from_db($field_name, $db_value);
4856
-                }
4857
-                //clear the cache of related model objects
4858
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4859
-                    $obj_in_map->clear_cache($relation_name, null, true);
4860
-                }
4861
-            }
4862
-            return $obj_in_map;
4863
-        } else {
4864
-            return $this->get_one_by_ID($id);
4865
-        }
4866
-    }
4867
-
4868
-
4869
-
4870
-    /**
4871
-     * refresh_entity_map_with
4872
-     * Leaves the entry in the entity map alone, but updates it to match the provided
4873
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4874
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4875
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4876
-     *
4877
-     * @param int|string    $id
4878
-     * @param EE_Base_Class $replacing_model_obj
4879
-     * @return \EE_Base_Class
4880
-     * @throws \EE_Error
4881
-     */
4882
-    public function refresh_entity_map_with($id, $replacing_model_obj)
4883
-    {
4884
-        $obj_in_map = $this->get_from_entity_map($id);
4885
-        if ($obj_in_map) {
4886
-            if ($replacing_model_obj instanceof EE_Base_Class) {
4887
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4888
-                    $obj_in_map->set($field_name, $value);
4889
-                }
4890
-                //make the model object in the entity map's cache match the $replacing_model_obj
4891
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4892
-                    $obj_in_map->clear_cache($relation_name, null, true);
4893
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4894
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4895
-                    }
4896
-                }
4897
-            }
4898
-            return $obj_in_map;
4899
-        } else {
4900
-            $this->add_to_entity_map($replacing_model_obj);
4901
-            return $replacing_model_obj;
4902
-        }
4903
-    }
4904
-
4905
-
4906
-
4907
-    /**
4908
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4909
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4910
-     * require_once($this->_getClassName().".class.php");
4911
-     *
4912
-     * @return string
4913
-     */
4914
-    private function _get_class_name()
4915
-    {
4916
-        return "EE_" . $this->get_this_model_name();
4917
-    }
4918
-
4919
-
4920
-
4921
-    /**
4922
-     * Get the name of the items this model represents, for the quantity specified. Eg,
4923
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4924
-     * it would be 'Events'.
4925
-     *
4926
-     * @param int $quantity
4927
-     * @return string
4928
-     */
4929
-    public function item_name($quantity = 1)
4930
-    {
4931
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4932
-    }
4933
-
4934
-
4935
-
4936
-    /**
4937
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4938
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
4939
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
4940
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
4941
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
4942
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
4943
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
4944
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
4945
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
4946
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4947
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4948
-     *        return $previousReturnValue.$returnString;
4949
-     * }
4950
-     * require('EEM_Answer.model.php');
4951
-     * $answer=EEM_Answer::instance();
4952
-     * echo $answer->my_callback('monkeys',100);
4953
-     * //will output "you called my_callback! and passed args:monkeys,100"
4954
-     *
4955
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4956
-     * @param array  $args       array of original arguments passed to the function
4957
-     * @throws EE_Error
4958
-     * @return mixed whatever the plugin which calls add_filter decides
4959
-     */
4960
-    public function __call($methodName, $args)
4961
-    {
4962
-        $className = get_class($this);
4963
-        $tagName = "FHEE__{$className}__{$methodName}";
4964
-        if ( ! has_filter($tagName)) {
4965
-            throw new EE_Error(
4966
-                sprintf(
4967
-                    __('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 );',
4968
-                        'event_espresso'),
4969
-                    $methodName,
4970
-                    $className,
4971
-                    $tagName,
4972
-                    '<br />'
4973
-                )
4974
-            );
4975
-        }
4976
-        return apply_filters($tagName, null, $this, $args);
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4983
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4984
-     *
4985
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4986
-     *                                                       the EE_Base_Class object that corresponds to this Model,
4987
-     *                                                       the object's class name
4988
-     *                                                       or object's ID
4989
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
4990
-     *                                                       exists in the database. If it does not, we add it
4991
-     * @throws EE_Error
4992
-     * @return EE_Base_Class
4993
-     */
4994
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
4995
-    {
4996
-        $className = $this->_get_class_name();
4997
-        if ($base_class_obj_or_id instanceof $className) {
4998
-            $model_object = $base_class_obj_or_id;
4999
-        } else {
5000
-            $primary_key_field = $this->get_primary_key_field();
5001
-            if (
5002
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5003
-                && (
5004
-                    is_int($base_class_obj_or_id)
5005
-                    || is_string($base_class_obj_or_id)
5006
-                )
5007
-            ) {
5008
-                // assume it's an ID.
5009
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5010
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5011
-            } else if (
5012
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5013
-                && is_string($base_class_obj_or_id)
5014
-            ) {
5015
-                // assume its a string representation of the object
5016
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5017
-            } else {
5018
-                throw new EE_Error(
5019
-                    sprintf(
5020
-                        __(
5021
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5022
-                            'event_espresso'
5023
-                        ),
5024
-                        $base_class_obj_or_id,
5025
-                        $this->_get_class_name(),
5026
-                        print_r($base_class_obj_or_id, true)
5027
-                    )
5028
-                );
5029
-            }
5030
-        }
5031
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5032
-            $model_object->save();
5033
-        }
5034
-        return $model_object;
5035
-    }
5036
-
5037
-
5038
-
5039
-    /**
5040
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5041
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5042
-     * returns it ID.
5043
-     *
5044
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5045
-     * @return int|string depending on the type of this model object's ID
5046
-     * @throws EE_Error
5047
-     */
5048
-    public function ensure_is_ID($base_class_obj_or_id)
5049
-    {
5050
-        $className = $this->_get_class_name();
5051
-        if ($base_class_obj_or_id instanceof $className) {
5052
-            /** @var $base_class_obj_or_id EE_Base_Class */
5053
-            $id = $base_class_obj_or_id->ID();
5054
-        } elseif (is_int($base_class_obj_or_id)) {
5055
-            //assume it's an ID
5056
-            $id = $base_class_obj_or_id;
5057
-        } elseif (is_string($base_class_obj_or_id)) {
5058
-            //assume its a string representation of the object
5059
-            $id = $base_class_obj_or_id;
5060
-        } else {
5061
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5062
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5063
-                print_r($base_class_obj_or_id, true)));
5064
-        }
5065
-        return $id;
5066
-    }
5067
-
5068
-
5069
-
5070
-    /**
5071
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5072
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5073
-     * been sanitized and converted into the appropriate domain.
5074
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5075
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5076
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5077
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5078
-     * $EVT = EEM_Event::instance(); $old_setting =
5079
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5080
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5081
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5082
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5083
-     *
5084
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5085
-     * @return void
5086
-     */
5087
-    public function assume_values_already_prepared_by_model_object(
5088
-        $values_already_prepared = self::not_prepared_by_model_object
5089
-    ) {
5090
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5091
-    }
5092
-
5093
-
5094
-
5095
-    /**
5096
-     * Read comments for assume_values_already_prepared_by_model_object()
5097
-     *
5098
-     * @return int
5099
-     */
5100
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5101
-    {
5102
-        return $this->_values_already_prepared_by_model_object;
5103
-    }
5104
-
5105
-
5106
-
5107
-    /**
5108
-     * Gets all the indexes on this model
5109
-     *
5110
-     * @return EE_Index[]
5111
-     */
5112
-    public function indexes()
5113
-    {
5114
-        return $this->_indexes;
5115
-    }
5116
-
5117
-
5118
-
5119
-    /**
5120
-     * Gets all the Unique Indexes on this model
5121
-     *
5122
-     * @return EE_Unique_Index[]
5123
-     */
5124
-    public function unique_indexes()
5125
-    {
5126
-        $unique_indexes = array();
5127
-        foreach ($this->_indexes as $name => $index) {
5128
-            if ($index instanceof EE_Unique_Index) {
5129
-                $unique_indexes [$name] = $index;
5130
-            }
5131
-        }
5132
-        return $unique_indexes;
5133
-    }
5134
-
5135
-
5136
-
5137
-    /**
5138
-     * Gets all the fields which, when combined, make the primary key.
5139
-     * This is usually just an array with 1 element (the primary key), but in cases
5140
-     * where there is no primary key, it's a combination of fields as defined
5141
-     * on a primary index
5142
-     *
5143
-     * @return EE_Model_Field_Base[] indexed by the field's name
5144
-     * @throws \EE_Error
5145
-     */
5146
-    public function get_combined_primary_key_fields()
5147
-    {
5148
-        foreach ($this->indexes() as $index) {
5149
-            if ($index instanceof EE_Primary_Key_Index) {
5150
-                return $index->fields();
5151
-            }
5152
-        }
5153
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5154
-    }
5155
-
5156
-
5157
-
5158
-    /**
5159
-     * Used to build a primary key string (when the model has no primary key),
5160
-     * which can be used a unique string to identify this model object.
5161
-     *
5162
-     * @param array $cols_n_values keys are field names, values are their values
5163
-     * @return string
5164
-     * @throws \EE_Error
5165
-     */
5166
-    public function get_index_primary_key_string($cols_n_values)
5167
-    {
5168
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5169
-            $this->get_combined_primary_key_fields());
5170
-        return http_build_query($cols_n_values_for_primary_key_index);
5171
-    }
5172
-
5173
-
5174
-
5175
-    /**
5176
-     * Gets the field values from the primary key string
5177
-     *
5178
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5179
-     * @param string $index_primary_key_string
5180
-     * @return null|array
5181
-     * @throws \EE_Error
5182
-     */
5183
-    public function parse_index_primary_key_string($index_primary_key_string)
5184
-    {
5185
-        $key_fields = $this->get_combined_primary_key_fields();
5186
-        //check all of them are in the $id
5187
-        $key_vals_in_combined_pk = array();
5188
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5189
-        foreach ($key_fields as $key_field_name => $field_obj) {
5190
-            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5191
-                return null;
5192
-            }
5193
-        }
5194
-        return $key_vals_in_combined_pk;
5195
-    }
5196
-
5197
-
5198
-
5199
-    /**
5200
-     * verifies that an array of key-value pairs for model fields has a key
5201
-     * for each field comprising the primary key index
5202
-     *
5203
-     * @param array $key_vals
5204
-     * @return boolean
5205
-     * @throws \EE_Error
5206
-     */
5207
-    public function has_all_combined_primary_key_fields($key_vals)
5208
-    {
5209
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5210
-        foreach ($keys_it_should_have as $key) {
5211
-            if ( ! isset($key_vals[$key])) {
5212
-                return false;
5213
-            }
5214
-        }
5215
-        return true;
5216
-    }
5217
-
5218
-
5219
-
5220
-    /**
5221
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5222
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5223
-     *
5224
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5225
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5226
-     * @throws EE_Error
5227
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5228
-     *                                                              indexed)
5229
-     */
5230
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5231
-    {
5232
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5233
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5234
-        } elseif (is_array($model_object_or_attributes_array)) {
5235
-            $attributes_array = $model_object_or_attributes_array;
5236
-        } else {
5237
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5238
-                "event_espresso"), $model_object_or_attributes_array));
5239
-        }
5240
-        //even copies obviously won't have the same ID, so remove the primary key
5241
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5242
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5243
-            unset($attributes_array[$this->primary_key_name()]);
5244
-        }
5245
-        if (isset($query_params[0])) {
5246
-            $query_params[0] = array_merge($attributes_array, $query_params);
5247
-        } else {
5248
-            $query_params[0] = $attributes_array;
5249
-        }
5250
-        return $this->get_all($query_params);
5251
-    }
5252
-
5253
-
5254
-
5255
-    /**
5256
-     * Gets the first copy we find. See get_all_copies for more details
5257
-     *
5258
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5259
-     * @param array $query_params
5260
-     * @return EE_Base_Class
5261
-     * @throws \EE_Error
5262
-     */
5263
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5264
-    {
5265
-        if ( ! is_array($query_params)) {
5266
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5267
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5268
-                    gettype($query_params)), '4.6.0');
5269
-            $query_params = array();
5270
-        }
5271
-        $query_params['limit'] = 1;
5272
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5273
-        if (is_array($copies)) {
5274
-            return array_shift($copies);
5275
-        } else {
5276
-            return null;
5277
-        }
5278
-    }
5279
-
5280
-
5281
-
5282
-    /**
5283
-     * Updates the item with the specified id. Ignores default query parameters because
5284
-     * we have specified the ID, and its assumed we KNOW what we're doing
5285
-     *
5286
-     * @param array      $fields_n_values keys are field names, values are their new values
5287
-     * @param int|string $id              the value of the primary key to update
5288
-     * @return int number of rows updated
5289
-     * @throws \EE_Error
5290
-     */
5291
-    public function update_by_ID($fields_n_values, $id)
5292
-    {
5293
-        $query_params = array(
5294
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5295
-            'default_where_conditions' => 'other_models_only',
5296
-        );
5297
-        return $this->update($fields_n_values, $query_params);
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Changes an operator which was supplied to the models into one usable in SQL
5304
-     *
5305
-     * @param string $operator_supplied
5306
-     * @return string an operator which can be used in SQL
5307
-     * @throws EE_Error
5308
-     */
5309
-    private function _prepare_operator_for_sql($operator_supplied)
5310
-    {
5311
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5312
-            : null;
5313
-        if ($sql_operator) {
5314
-            return $sql_operator;
5315
-        } else {
5316
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5317
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5318
-        }
5319
-    }
5320
-
5321
-
5322
-
5323
-    /**
5324
-     * Gets an array where keys are the primary keys and values are their 'names'
5325
-     * (as determined by the model object's name() function, which is often overridden)
5326
-     *
5327
-     * @param array $query_params like get_all's
5328
-     * @return string[]
5329
-     * @throws \EE_Error
5330
-     */
5331
-    public function get_all_names($query_params = array())
5332
-    {
5333
-        $objs = $this->get_all($query_params);
5334
-        $names = array();
5335
-        foreach ($objs as $obj) {
5336
-            $names[$obj->ID()] = $obj->name();
5337
-        }
5338
-        return $names;
5339
-    }
5340
-
5341
-
5342
-
5343
-    /**
5344
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5345
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5346
-     * this is duplicated effort and reduces efficiency) you would be better to use
5347
-     * array_keys() on $model_objects.
5348
-     *
5349
-     * @param \EE_Base_Class[] $model_objects
5350
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5351
-     *                                               in the returned array
5352
-     * @return array
5353
-     * @throws \EE_Error
5354
-     */
5355
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5356
-    {
5357
-        if ( ! $this->has_primary_key_field()) {
5358
-            if (WP_DEBUG) {
5359
-                EE_Error::add_error(
5360
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5361
-                    __FILE__,
5362
-                    __FUNCTION__,
5363
-                    __LINE__
5364
-                );
5365
-            }
5366
-        }
5367
-        $IDs = array();
5368
-        foreach ($model_objects as $model_object) {
5369
-            $id = $model_object->ID();
5370
-            if ( ! $id) {
5371
-                if ($filter_out_empty_ids) {
5372
-                    continue;
5373
-                }
5374
-                if (WP_DEBUG) {
5375
-                    EE_Error::add_error(
5376
-                        __(
5377
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5378
-                            'event_espresso'
5379
-                        ),
5380
-                        __FILE__,
5381
-                        __FUNCTION__,
5382
-                        __LINE__
5383
-                    );
5384
-                }
5385
-            }
5386
-            $IDs[] = $id;
5387
-        }
5388
-        return $IDs;
5389
-    }
5390
-
5391
-
5392
-
5393
-    /**
5394
-     * Returns the string used in capabilities relating to this model. If there
5395
-     * are no capabilities that relate to this model returns false
5396
-     *
5397
-     * @return string|false
5398
-     */
5399
-    public function cap_slug()
5400
-    {
5401
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5402
-    }
5403
-
5404
-
5405
-
5406
-    /**
5407
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5408
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5409
-     * only returns the cap restrictions array in that context (ie, the array
5410
-     * at that key)
5411
-     *
5412
-     * @param string $context
5413
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5414
-     * @throws \EE_Error
5415
-     */
5416
-    public function cap_restrictions($context = EEM_Base::caps_read)
5417
-    {
5418
-        EEM_Base::verify_is_valid_cap_context($context);
5419
-        //check if we ought to run the restriction generator first
5420
-        if (
5421
-            isset($this->_cap_restriction_generators[$context])
5422
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5423
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5424
-        ) {
5425
-            $this->_cap_restrictions[$context] = array_merge(
5426
-                $this->_cap_restrictions[$context],
5427
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5428
-            );
5429
-        }
5430
-        //and make sure we've finalized the construction of each restriction
5431
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5432
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5433
-                $where_conditions_obj->_finalize_construct($this);
5434
-            }
5435
-        }
5436
-        return $this->_cap_restrictions[$context];
5437
-    }
5438
-
5439
-
5440
-
5441
-    /**
5442
-     * Indicating whether or not this model thinks its a wp core model
5443
-     *
5444
-     * @return boolean
5445
-     */
5446
-    public function is_wp_core_model()
5447
-    {
5448
-        return $this->_wp_core_model;
5449
-    }
5450
-
5451
-
5452
-
5453
-    /**
5454
-     * Gets all the caps that are missing which impose a restriction on
5455
-     * queries made in this context
5456
-     *
5457
-     * @param string $context one of EEM_Base::caps_ constants
5458
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5459
-     * @throws \EE_Error
5460
-     */
5461
-    public function caps_missing($context = EEM_Base::caps_read)
5462
-    {
5463
-        $missing_caps = array();
5464
-        $cap_restrictions = $this->cap_restrictions($context);
5465
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5466
-            if ( ! EE_Capabilities::instance()
5467
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5468
-            ) {
5469
-                $missing_caps[$cap] = $restriction_if_no_cap;
5470
-            }
5471
-        }
5472
-        return $missing_caps;
5473
-    }
5474
-
5475
-
5476
-
5477
-    /**
5478
-     * Gets the mapping from capability contexts to action strings used in capability names
5479
-     *
5480
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5481
-     * one of 'read', 'edit', or 'delete'
5482
-     */
5483
-    public function cap_contexts_to_cap_action_map()
5484
-    {
5485
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5486
-            $this);
5487
-    }
5488
-
5489
-
5490
-
5491
-    /**
5492
-     * Gets the action string for the specified capability context
5493
-     *
5494
-     * @param string $context
5495
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5496
-     * @throws \EE_Error
5497
-     */
5498
-    public function cap_action_for_context($context)
5499
-    {
5500
-        $mapping = $this->cap_contexts_to_cap_action_map();
5501
-        if (isset($mapping[$context])) {
5502
-            return $mapping[$context];
5503
-        }
5504
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5505
-            return $action;
5506
-        }
5507
-        throw new EE_Error(
5508
-            sprintf(
5509
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5510
-                $context,
5511
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5512
-            )
5513
-        );
5514
-    }
5515
-
5516
-
5517
-
5518
-    /**
5519
-     * Returns all the capability contexts which are valid when querying models
5520
-     *
5521
-     * @return array
5522
-     */
5523
-    static public function valid_cap_contexts()
5524
-    {
5525
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5526
-            self::caps_read,
5527
-            self::caps_read_admin,
5528
-            self::caps_edit,
5529
-            self::caps_delete,
5530
-        ));
5531
-    }
5532
-
5533
-
5534
-
5535
-    /**
5536
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5537
-     *
5538
-     * @param string $context
5539
-     * @return bool
5540
-     * @throws \EE_Error
5541
-     */
5542
-    static public function verify_is_valid_cap_context($context)
5543
-    {
5544
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5545
-        if (in_array($context, $valid_cap_contexts)) {
5546
-            return true;
5547
-        } else {
5548
-            throw new EE_Error(
5549
-                sprintf(
5550
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5551
-                        'event_espresso'),
5552
-                    $context,
5553
-                    'EEM_Base',
5554
-                    implode(',', $valid_cap_contexts)
5555
-                )
5556
-            );
5557
-        }
5558
-    }
5559
-
5560
-
5561
-
5562
-    /**
5563
-     * Clears all the models field caches. This is only useful when a sub-class
5564
-     * might have added a field or something and these caches might be invalidated
5565
-     */
5566
-    protected function _invalidate_field_caches()
5567
-    {
5568
-        $this->_cache_foreign_key_to_fields = array();
5569
-        $this->_cached_fields = null;
5570
-        $this->_cached_fields_non_db_only = null;
5571
-    }
5572
-
5573
-
5574
-
5575
-    /**
5576
-     * _instantiate_new_instance_from_db
5577
-     *
5578
-     * @param string $class_name
5579
-     * @param array  $arguments
5580
-     * @return \EE_Base_Class
5581
-     * @throws \Exception
5582
-     */
5583
-    public function _instantiate_new_instance_from_db($class_name, $arguments)
5584
-    {
5585
-        if ( ! class_exists($class_name)) {
5586
-            throw new EE_Error(
5587
-                sprintf(
5588
-                    __('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5589
-                    $class_name
5590
-                )
5591
-            );
5592
-        }
5593
-        return call_user_func_array(
5594
-            array($class_name, 'new_instance'),
5595
-            array((array)$arguments, $this->_timezone, array(), true)
5596
-        );
5597
-    }
3448
+		}
3449
+		return $null_friendly_where_conditions;
3450
+	}
3451
+
3452
+
3453
+
3454
+	/**
3455
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3456
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3457
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3458
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3459
+	 *
3460
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
+	 */
3463
+	private function _get_default_where_conditions($model_relation_path = null)
3464
+	{
3465
+		if ($this->_ignore_where_strategy) {
3466
+			return array();
3467
+		}
3468
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
+	}
3470
+
3471
+
3472
+
3473
+	/**
3474
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3475
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3476
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3477
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3478
+	 * Similar to _get_default_where_conditions
3479
+	 *
3480
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3481
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3482
+	 */
3483
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3484
+	{
3485
+		if ($this->_ignore_where_strategy) {
3486
+			return array();
3487
+		}
3488
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3489
+	}
3490
+
3491
+
3492
+
3493
+	/**
3494
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3495
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3496
+	 *
3497
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3498
+	 * @return string
3499
+	 * @throws \EE_Error
3500
+	 */
3501
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3502
+	{
3503
+		$selects = $this->_get_columns_to_select_for_this_model();
3504
+		foreach (
3505
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3506
+			$name_of_other_model_included
3507
+		) {
3508
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3509
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3510
+			foreach ($other_model_selects as $key => $value) {
3511
+				$selects[] = $value;
3512
+			}
3513
+		}
3514
+		return implode(", ", $selects);
3515
+	}
3516
+
3517
+
3518
+
3519
+	/**
3520
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3521
+	 * So that's going to be the columns for all the fields on the model
3522
+	 *
3523
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3524
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3525
+	 */
3526
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3527
+	{
3528
+		$fields = $this->field_settings();
3529
+		$selects = array();
3530
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3531
+			$this->get_this_model_name());
3532
+		foreach ($fields as $field_obj) {
3533
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3534
+						 . $field_obj->get_table_alias()
3535
+						 . "."
3536
+						 . $field_obj->get_table_column()
3537
+						 . " AS '"
3538
+						 . $table_alias_with_model_relation_chain_prefix
3539
+						 . $field_obj->get_table_alias()
3540
+						 . "."
3541
+						 . $field_obj->get_table_column()
3542
+						 . "'";
3543
+		}
3544
+		//make sure we are also getting the PKs of each table
3545
+		$tables = $this->get_tables();
3546
+		if (count($tables) > 1) {
3547
+			foreach ($tables as $table_obj) {
3548
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3549
+									   . $table_obj->get_fully_qualified_pk_column();
3550
+				if ( ! in_array($qualified_pk_column, $selects)) {
3551
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3552
+				}
3553
+			}
3554
+		}
3555
+		return $selects;
3556
+	}
3557
+
3558
+
3559
+
3560
+	/**
3561
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3562
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3563
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3564
+	 * SQL for joining, and the data types
3565
+	 *
3566
+	 * @param null|string                 $original_query_param
3567
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3568
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3569
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3570
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3571
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3572
+	 *                                                          or 'Registration's
3573
+	 * @param string                      $original_query_param what it originally was (eg
3574
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3575
+	 *                                                          matches $query_param
3576
+	 * @throws EE_Error
3577
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3578
+	 */
3579
+	private function _extract_related_model_info_from_query_param(
3580
+		$query_param,
3581
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3582
+		$query_param_type,
3583
+		$original_query_param = null
3584
+	) {
3585
+		if ($original_query_param === null) {
3586
+			$original_query_param = $query_param;
3587
+		}
3588
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3589
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3590
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3591
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3592
+		//check to see if we have a field on this model
3593
+		$this_model_fields = $this->field_settings(true);
3594
+		if (array_key_exists($query_param, $this_model_fields)) {
3595
+			if ($allow_fields) {
3596
+				return;
3597
+			} else {
3598
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3599
+					"event_espresso"),
3600
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3601
+			}
3602
+		} //check if this is a special logic query param
3603
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3604
+			if ($allow_logic_query_params) {
3605
+				return;
3606
+			} else {
3607
+				throw new EE_Error(
3608
+					sprintf(
3609
+						__('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',
3610
+							'event_espresso'),
3611
+						implode('", "', $this->_logic_query_param_keys),
3612
+						$query_param,
3613
+						get_class($this),
3614
+						'<br />',
3615
+						"\t"
3616
+						. ' $passed_in_query_info = <pre>'
3617
+						. print_r($passed_in_query_info, true)
3618
+						. '</pre>'
3619
+						. "\n\t"
3620
+						. ' $query_param_type = '
3621
+						. $query_param_type
3622
+						. "\n\t"
3623
+						. ' $original_query_param = '
3624
+						. $original_query_param
3625
+					)
3626
+				);
3627
+			}
3628
+		} //check if it's a custom selection
3629
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3630
+			return;
3631
+		}
3632
+		//check if has a model name at the beginning
3633
+		//and
3634
+		//check if it's a field on a related model
3635
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3637
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3639
+				if ($query_param === '') {
3640
+					//nothing left to $query_param
3641
+					//we should actually end in a field name, not a model like this!
3642
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3643
+						"event_espresso"),
3644
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3645
+				} else {
3646
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3647
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3648
+						$passed_in_query_info, $query_param_type, $original_query_param);
3649
+					return;
3650
+				}
3651
+			} elseif ($query_param === $valid_related_model_name) {
3652
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3653
+				return;
3654
+			}
3655
+		}
3656
+		//ok so $query_param didn't start with a model name
3657
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3658
+		//it's wack, that's what it is
3659
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3660
+			"event_espresso"),
3661
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3662
+	}
3663
+
3664
+
3665
+
3666
+	/**
3667
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3668
+	 * and store it on $passed_in_query_info
3669
+	 *
3670
+	 * @param string                      $model_name
3671
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3672
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3673
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3674
+	 *                                                          and are adding a join to 'Payment' with the original
3675
+	 *                                                          query param key
3676
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3677
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3678
+	 *                                                          Payment wants to add default query params so that it
3679
+	 *                                                          will know what models to prepend onto its default query
3680
+	 *                                                          params or in case it wants to rename tables (in case
3681
+	 *                                                          there are multiple joins to the same table)
3682
+	 * @return void
3683
+	 * @throws \EE_Error
3684
+	 */
3685
+	private function _add_join_to_model(
3686
+		$model_name,
3687
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3688
+		$original_query_param
3689
+	) {
3690
+		$relation_obj = $this->related_settings_for($model_name);
3691
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3692
+		//check if the relation is HABTM, because then we're essentially doing two joins
3693
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3694
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3695
+			$join_model_obj = $relation_obj->get_join_model();
3696
+			//replace the model specified with the join model for this relation chain, whi
3697
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3698
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3699
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3700
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3701
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3702
+			$passed_in_query_info->merge($new_query_info);
3703
+		}
3704
+		//now just join to the other table pointed to by the relation object, and add its data types
3705
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3706
+			array($model_relation_chain => $model_name),
3707
+			$relation_obj->get_join_statement($model_relation_chain));
3708
+		$passed_in_query_info->merge($new_query_info);
3709
+	}
3710
+
3711
+
3712
+
3713
+	/**
3714
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3715
+	 *
3716
+	 * @param array $where_params like EEM_Base::get_all
3717
+	 * @return string of SQL
3718
+	 * @throws \EE_Error
3719
+	 */
3720
+	private function _construct_where_clause($where_params)
3721
+	{
3722
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723
+		if ($SQL) {
3724
+			return " WHERE " . $SQL;
3725
+		} else {
3726
+			return '';
3727
+		}
3728
+	}
3729
+
3730
+
3731
+
3732
+	/**
3733
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3734
+	 * and should be passed HAVING parameters, not WHERE parameters
3735
+	 *
3736
+	 * @param array $having_params
3737
+	 * @return string
3738
+	 * @throws \EE_Error
3739
+	 */
3740
+	private function _construct_having_clause($having_params)
3741
+	{
3742
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743
+		if ($SQL) {
3744
+			return " HAVING " . $SQL;
3745
+		} else {
3746
+			return '';
3747
+		}
3748
+	}
3749
+
3750
+
3751
+
3752
+	/**
3753
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3754
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3755
+	 * EEM_Attendee.
3756
+	 *
3757
+	 * @param string $field_name
3758
+	 * @param string $model_name
3759
+	 * @return EE_Model_Field_Base
3760
+	 * @throws EE_Error
3761
+	 */
3762
+	protected function _get_field_on_model($field_name, $model_name)
3763
+	{
3764
+		$model_class = 'EEM_' . $model_name;
3765
+		$model_filepath = $model_class . ".model.php";
3766
+		if (is_readable($model_filepath)) {
3767
+			require_once($model_filepath);
3768
+			$model_instance = call_user_func($model_name . "::instance");
3769
+			/* @var $model_instance EEM_Base */
3770
+			return $model_instance->field_settings_for($field_name);
3771
+		} else {
3772
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3773
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3774
+		}
3775
+	}
3776
+
3777
+
3778
+
3779
+	/**
3780
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3781
+	 * Event_Meta.meta_value = 'foo'))"
3782
+	 *
3783
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3784
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3785
+	 * @throws EE_Error
3786
+	 * @return string of SQL
3787
+	 */
3788
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3789
+	{
3790
+		$where_clauses = array();
3791
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3793
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3794
+				switch ($query_param) {
3795
+					case 'not':
3796
+					case 'NOT':
3797
+						$where_clauses[] = "! ("
3798
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3799
+								$glue)
3800
+										   . ")";
3801
+						break;
3802
+					case 'and':
3803
+					case 'AND':
3804
+						$where_clauses[] = " ("
3805
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3806
+								' AND ')
3807
+										   . ")";
3808
+						break;
3809
+					case 'or':
3810
+					case 'OR':
3811
+						$where_clauses[] = " ("
3812
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3813
+								' OR ')
3814
+										   . ")";
3815
+						break;
3816
+				}
3817
+			} else {
3818
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3819
+				//if it's not a normal field, maybe it's a custom selection?
3820
+				if ( ! $field_obj) {
3821
+					if (isset($this->_custom_selections[$query_param][1])) {
3822
+						$field_obj = $this->_custom_selections[$query_param][1];
3823
+					} else {
3824
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3825
+							"event_espresso"), $query_param));
3826
+					}
3827
+				}
3828
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3830
+			}
3831
+		}
3832
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3833
+	}
3834
+
3835
+
3836
+
3837
+	/**
3838
+	 * Takes the input parameter and extract the table name (alias) and column name
3839
+	 *
3840
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3841
+	 * @throws EE_Error
3842
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3843
+	 */
3844
+	private function _deduce_column_name_from_query_param($query_param)
3845
+	{
3846
+		$field = $this->_deduce_field_from_query_param($query_param);
3847
+		if ($field) {
3848
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849
+				$query_param);
3850
+			return $table_alias_prefix . $field->get_qualified_column();
3851
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852
+			//maybe it's custom selection item?
3853
+			//if so, just use it as the "column name"
3854
+			return $query_param;
3855
+		} else {
3856
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3857
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3858
+		}
3859
+	}
3860
+
3861
+
3862
+
3863
+	/**
3864
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3865
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3866
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3867
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3868
+	 *
3869
+	 * @param string $condition_query_param_key
3870
+	 * @return string
3871
+	 */
3872
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3873
+	{
3874
+		$pos_of_star = strpos($condition_query_param_key, '*');
3875
+		if ($pos_of_star === false) {
3876
+			return $condition_query_param_key;
3877
+		} else {
3878
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3879
+			return $condition_query_param_sans_star;
3880
+		}
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3887
+	 *
3888
+	 * @param                            mixed      array | string    $op_and_value
3889
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3890
+	 * @throws EE_Error
3891
+	 * @return string
3892
+	 */
3893
+	private function _construct_op_and_value($op_and_value, $field_obj)
3894
+	{
3895
+		if (is_array($op_and_value)) {
3896
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3897
+			if ( ! $operator) {
3898
+				$php_array_like_string = array();
3899
+				foreach ($op_and_value as $key => $value) {
3900
+					$php_array_like_string[] = "$key=>$value";
3901
+				}
3902
+				throw new EE_Error(
3903
+					sprintf(
3904
+						__(
3905
+							"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))",
3906
+							"event_espresso"
3907
+						),
3908
+						implode(",", $php_array_like_string)
3909
+					)
3910
+				);
3911
+			}
3912
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3913
+		} else {
3914
+			$operator = '=';
3915
+			$value = $op_and_value;
3916
+		}
3917
+		//check to see if the value is actually another field
3918
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3920
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921
+			//in this case, the value should be an array, or at least a comma-separated list
3922
+			//it will need to handle a little differently
3923
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
3924
+			//note: $cleaned_value has already been run through $wpdb->prepare()
3925
+			return $operator . SP . $cleaned_value;
3926
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927
+			//the value should be an array with count of two.
3928
+			if (count($value) !== 2) {
3929
+				throw new EE_Error(
3930
+					sprintf(
3931
+						__(
3932
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3933
+							'event_espresso'
3934
+						),
3935
+						"BETWEEN"
3936
+					)
3937
+				);
3938
+			}
3939
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
+			return $operator . SP . $cleaned_value;
3941
+		} elseif (in_array($operator, $this->_null_style_operators)) {
3942
+			if ($value !== null) {
3943
+				throw new EE_Error(
3944
+					sprintf(
3945
+						__(
3946
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3947
+							"event_espresso"
3948
+						),
3949
+						$value,
3950
+						$operator
3951
+					)
3952
+				);
3953
+			}
3954
+			return $operator;
3955
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
3956
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3957
+			//remove other junk. So just treat it as a string.
3958
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3959
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3961
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962
+			throw new EE_Error(
3963
+				sprintf(
3964
+					__(
3965
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3966
+						'event_espresso'
3967
+					),
3968
+					$operator,
3969
+					$operator
3970
+				)
3971
+			);
3972
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3973
+			throw new EE_Error(
3974
+				sprintf(
3975
+					__(
3976
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3977
+						'event_espresso'
3978
+					),
3979
+					$operator,
3980
+					$operator
3981
+				)
3982
+			);
3983
+		} else {
3984
+			throw new EE_Error(
3985
+				sprintf(
3986
+					__(
3987
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3988
+						"event_espresso"
3989
+					),
3990
+					http_build_query($op_and_value)
3991
+				)
3992
+			);
3993
+		}
3994
+	}
3995
+
3996
+
3997
+
3998
+	/**
3999
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4000
+	 *
4001
+	 * @param array                      $values
4002
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4003
+	 *                                              '%s'
4004
+	 * @return string
4005
+	 * @throws \EE_Error
4006
+	 */
4007
+	public function _construct_between_value($values, $field_obj)
4008
+	{
4009
+		$cleaned_values = array();
4010
+		foreach ($values as $value) {
4011
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012
+		}
4013
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4014
+	}
4015
+
4016
+
4017
+
4018
+	/**
4019
+	 * Takes an array or a comma-separated list of $values and cleans them
4020
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4021
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4022
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4023
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4024
+	 *
4025
+	 * @param mixed                      $values    array or comma-separated string
4026
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4027
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4028
+	 * @throws \EE_Error
4029
+	 */
4030
+	public function _construct_in_value($values, $field_obj)
4031
+	{
4032
+		//check if the value is a CSV list
4033
+		if (is_string($values)) {
4034
+			//in which case, turn it into an array
4035
+			$values = explode(",", $values);
4036
+		}
4037
+		$cleaned_values = array();
4038
+		foreach ($values as $value) {
4039
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4040
+		}
4041
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4042
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4043
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4044
+		if (empty($cleaned_values)) {
4045
+			$all_fields = $this->field_settings();
4046
+			$a_field = array_shift($all_fields);
4047
+			$main_table = $this->_get_main_table();
4048
+			$cleaned_values[] = "SELECT "
4049
+								. $a_field->get_table_column()
4050
+								. " FROM "
4051
+								. $main_table->get_table_name()
4052
+								. " WHERE FALSE";
4053
+		}
4054
+		return "(" . implode(",", $cleaned_values) . ")";
4055
+	}
4056
+
4057
+
4058
+
4059
+	/**
4060
+	 * @param mixed                      $value
4061
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4062
+	 * @throws EE_Error
4063
+	 * @return false|null|string
4064
+	 */
4065
+	private function _wpdb_prepare_using_field($value, $field_obj)
4066
+	{
4067
+		/** @type WPDB $wpdb */
4068
+		global $wpdb;
4069
+		if ($field_obj instanceof EE_Model_Field_Base) {
4070
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4071
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4072
+		} else {//$field_obj should really just be a data type
4073
+			if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4074
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4075
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4076
+			}
4077
+			return $wpdb->prepare($field_obj, $value);
4078
+		}
4079
+	}
4080
+
4081
+
4082
+
4083
+	/**
4084
+	 * Takes the input parameter and finds the model field that it indicates.
4085
+	 *
4086
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4087
+	 * @throws EE_Error
4088
+	 * @return EE_Model_Field_Base
4089
+	 */
4090
+	protected function _deduce_field_from_query_param($query_param_name)
4091
+	{
4092
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4093
+		//which will help us find the database table and column
4094
+		$query_param_parts = explode(".", $query_param_name);
4095
+		if (empty($query_param_parts)) {
4096
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4097
+				'event_espresso'), $query_param_name));
4098
+		}
4099
+		$number_of_parts = count($query_param_parts);
4100
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4101
+		if ($number_of_parts === 1) {
4102
+			$field_name = $last_query_param_part;
4103
+			$model_obj = $this;
4104
+		} else {// $number_of_parts >= 2
4105
+			//the last part is the column name, and there are only 2parts. therefore...
4106
+			$field_name = $last_query_param_part;
4107
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4108
+		}
4109
+		try {
4110
+			return $model_obj->field_settings_for($field_name);
4111
+		} catch (EE_Error $e) {
4112
+			return null;
4113
+		}
4114
+	}
4115
+
4116
+
4117
+
4118
+	/**
4119
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4120
+	 * alias and column which corresponds to it
4121
+	 *
4122
+	 * @param string $field_name
4123
+	 * @throws EE_Error
4124
+	 * @return string
4125
+	 */
4126
+	public function _get_qualified_column_for_field($field_name)
4127
+	{
4128
+		$all_fields = $this->field_settings();
4129
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4130
+		if ($field) {
4131
+			return $field->get_qualified_column();
4132
+		} else {
4133
+			throw new EE_Error(sprintf(__("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.",
4134
+				'event_espresso'), $field_name, get_class($this)));
4135
+		}
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * constructs the select use on special limit joins
4142
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4143
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4144
+	 * (as that is typically where the limits would be set).
4145
+	 *
4146
+	 * @param  string       $table_alias The table the select is being built for
4147
+	 * @param  mixed|string $limit       The limit for this select
4148
+	 * @return string                The final select join element for the query.
4149
+	 */
4150
+	public function _construct_limit_join_select($table_alias, $limit)
4151
+	{
4152
+		$SQL = '';
4153
+		foreach ($this->_tables as $table_obj) {
4154
+			if ($table_obj instanceof EE_Primary_Table) {
4155
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4156
+					? $table_obj->get_select_join_limit($limit)
4157
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4158
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4159
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4160
+					? $table_obj->get_select_join_limit_join($limit)
4161
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4162
+			}
4163
+		}
4164
+		return $SQL;
4165
+	}
4166
+
4167
+
4168
+
4169
+	/**
4170
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4171
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4172
+	 *
4173
+	 * @return string SQL
4174
+	 * @throws \EE_Error
4175
+	 */
4176
+	public function _construct_internal_join()
4177
+	{
4178
+		$SQL = $this->_get_main_table()->get_table_sql();
4179
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4180
+		return $SQL;
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Constructs the SQL for joining all the tables on this model.
4187
+	 * Normally $alias should be the primary table's alias, but in cases where
4188
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4189
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4190
+	 * alias, this will construct SQL like:
4191
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4192
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4193
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4194
+	 *
4195
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4196
+	 * @return string
4197
+	 */
4198
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4199
+	{
4200
+		$SQL = '';
4201
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4202
+		foreach ($this->_tables as $table_obj) {
4203
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4204
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4205
+					//so we're joining to this table, meaning the table is already in
4206
+					//the FROM statement, BUT the primary table isn't. So we want
4207
+					//to add the inverse join sql
4208
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4209
+				} else {
4210
+					//just add a regular JOIN to this table from the primary table
4211
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4212
+				}
4213
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4214
+		}
4215
+		return $SQL;
4216
+	}
4217
+
4218
+
4219
+
4220
+	/**
4221
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4222
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4223
+	 * their data type (eg, '%s', '%d', etc)
4224
+	 *
4225
+	 * @return array
4226
+	 */
4227
+	public function _get_data_types()
4228
+	{
4229
+		$data_types = array();
4230
+		foreach ($this->field_settings() as $field_obj) {
4231
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4232
+			/** @var $field_obj EE_Model_Field_Base */
4233
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4234
+		}
4235
+		return $data_types;
4236
+	}
4237
+
4238
+
4239
+
4240
+	/**
4241
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4242
+	 *
4243
+	 * @param string $model_name
4244
+	 * @throws EE_Error
4245
+	 * @return EEM_Base
4246
+	 */
4247
+	public function get_related_model_obj($model_name)
4248
+	{
4249
+		$model_classname = "EEM_" . $model_name;
4250
+		if ( ! class_exists($model_classname)) {
4251
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4252
+				'event_espresso'), $model_name, $model_classname));
4253
+		}
4254
+		return call_user_func($model_classname . "::instance");
4255
+	}
4256
+
4257
+
4258
+
4259
+	/**
4260
+	 * Returns the array of EE_ModelRelations for this model.
4261
+	 *
4262
+	 * @return EE_Model_Relation_Base[]
4263
+	 */
4264
+	public function relation_settings()
4265
+	{
4266
+		return $this->_model_relations;
4267
+	}
4268
+
4269
+
4270
+
4271
+	/**
4272
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4273
+	 * because without THOSE models, this model probably doesn't have much purpose.
4274
+	 * (Eg, without an event, datetimes have little purpose.)
4275
+	 *
4276
+	 * @return EE_Belongs_To_Relation[]
4277
+	 */
4278
+	public function belongs_to_relations()
4279
+	{
4280
+		$belongs_to_relations = array();
4281
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4282
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4283
+				$belongs_to_relations[$model_name] = $relation_obj;
4284
+			}
4285
+		}
4286
+		return $belongs_to_relations;
4287
+	}
4288
+
4289
+
4290
+
4291
+	/**
4292
+	 * Returns the specified EE_Model_Relation, or throws an exception
4293
+	 *
4294
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4295
+	 * @throws EE_Error
4296
+	 * @return EE_Model_Relation_Base
4297
+	 */
4298
+	public function related_settings_for($relation_name)
4299
+	{
4300
+		$relatedModels = $this->relation_settings();
4301
+		if ( ! array_key_exists($relation_name, $relatedModels)) {
4302
+			throw new EE_Error(
4303
+				sprintf(
4304
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4305
+						'event_espresso'),
4306
+					$relation_name,
4307
+					$this->_get_class_name(),
4308
+					implode(', ', array_keys($relatedModels))
4309
+				)
4310
+			);
4311
+		}
4312
+		return $relatedModels[$relation_name];
4313
+	}
4314
+
4315
+
4316
+
4317
+	/**
4318
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4319
+	 * fields
4320
+	 *
4321
+	 * @param string $fieldName
4322
+	 * @throws EE_Error
4323
+	 * @return EE_Model_Field_Base
4324
+	 */
4325
+	public function field_settings_for($fieldName)
4326
+	{
4327
+		$fieldSettings = $this->field_settings(true);
4328
+		if ( ! array_key_exists($fieldName, $fieldSettings)) {
4329
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4330
+				get_class($this)));
4331
+		}
4332
+		return $fieldSettings[$fieldName];
4333
+	}
4334
+
4335
+
4336
+
4337
+	/**
4338
+	 * Checks if this field exists on this model
4339
+	 *
4340
+	 * @param string $fieldName a key in the model's _field_settings array
4341
+	 * @return boolean
4342
+	 */
4343
+	public function has_field($fieldName)
4344
+	{
4345
+		$fieldSettings = $this->field_settings(true);
4346
+		if (isset($fieldSettings[$fieldName])) {
4347
+			return true;
4348
+		} else {
4349
+			return false;
4350
+		}
4351
+	}
4352
+
4353
+
4354
+
4355
+	/**
4356
+	 * Returns whether or not this model has a relation to the specified model
4357
+	 *
4358
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4359
+	 * @return boolean
4360
+	 */
4361
+	public function has_relation($relation_name)
4362
+	{
4363
+		$relations = $this->relation_settings();
4364
+		if (isset($relations[$relation_name])) {
4365
+			return true;
4366
+		} else {
4367
+			return false;
4368
+		}
4369
+	}
4370
+
4371
+
4372
+
4373
+	/**
4374
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4375
+	 * Eg, on EE_Answer that would be ANS_ID field object
4376
+	 *
4377
+	 * @param $field_obj
4378
+	 * @return boolean
4379
+	 */
4380
+	public function is_primary_key_field($field_obj)
4381
+	{
4382
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4383
+	}
4384
+
4385
+
4386
+
4387
+	/**
4388
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4389
+	 * Eg, on EE_Answer that would be ANS_ID field object
4390
+	 *
4391
+	 * @return EE_Model_Field_Base
4392
+	 * @throws EE_Error
4393
+	 */
4394
+	public function get_primary_key_field()
4395
+	{
4396
+		if ($this->_primary_key_field === null) {
4397
+			foreach ($this->field_settings(true) as $field_obj) {
4398
+				if ($this->is_primary_key_field($field_obj)) {
4399
+					$this->_primary_key_field = $field_obj;
4400
+					break;
4401
+				}
4402
+			}
4403
+			if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4404
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4405
+					get_class($this)));
4406
+			}
4407
+		}
4408
+		return $this->_primary_key_field;
4409
+	}
4410
+
4411
+
4412
+
4413
+	/**
4414
+	 * Returns whether or not not there is a primary key on this model.
4415
+	 * Internally does some caching.
4416
+	 *
4417
+	 * @return boolean
4418
+	 */
4419
+	public function has_primary_key_field()
4420
+	{
4421
+		if ($this->_has_primary_key_field === null) {
4422
+			try {
4423
+				$this->get_primary_key_field();
4424
+				$this->_has_primary_key_field = true;
4425
+			} catch (EE_Error $e) {
4426
+				$this->_has_primary_key_field = false;
4427
+			}
4428
+		}
4429
+		return $this->_has_primary_key_field;
4430
+	}
4431
+
4432
+
4433
+
4434
+	/**
4435
+	 * Finds the first field of type $field_class_name.
4436
+	 *
4437
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4438
+	 *                                 EE_Foreign_Key_Field, etc
4439
+	 * @return EE_Model_Field_Base or null if none is found
4440
+	 */
4441
+	public function get_a_field_of_type($field_class_name)
4442
+	{
4443
+		foreach ($this->field_settings() as $field) {
4444
+			if ($field instanceof $field_class_name) {
4445
+				return $field;
4446
+			}
4447
+		}
4448
+		return null;
4449
+	}
4450
+
4451
+
4452
+
4453
+	/**
4454
+	 * Gets a foreign key field pointing to model.
4455
+	 *
4456
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4457
+	 * @return EE_Foreign_Key_Field_Base
4458
+	 * @throws EE_Error
4459
+	 */
4460
+	public function get_foreign_key_to($model_name)
4461
+	{
4462
+		if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4463
+			foreach ($this->field_settings() as $field) {
4464
+				if (
4465
+					$field instanceof EE_Foreign_Key_Field_Base
4466
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4467
+				) {
4468
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4469
+					break;
4470
+				}
4471
+			}
4472
+			if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4473
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4474
+					'event_espresso'), $model_name, get_class($this)));
4475
+			}
4476
+		}
4477
+		return $this->_cache_foreign_key_to_fields[$model_name];
4478
+	}
4479
+
4480
+
4481
+
4482
+	/**
4483
+	 * Gets the actual table for the table alias
4484
+	 *
4485
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4486
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4487
+	 *                            Either one works
4488
+	 * @return EE_Table_Base
4489
+	 */
4490
+	public function get_table_for_alias($table_alias)
4491
+	{
4492
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4493
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4494
+	}
4495
+
4496
+
4497
+
4498
+	/**
4499
+	 * Returns a flat array of all field son this model, instead of organizing them
4500
+	 * by table_alias as they are in the constructor.
4501
+	 *
4502
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4503
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4504
+	 */
4505
+	public function field_settings($include_db_only_fields = false)
4506
+	{
4507
+		if ($include_db_only_fields) {
4508
+			if ($this->_cached_fields === null) {
4509
+				$this->_cached_fields = array();
4510
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4511
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4512
+						$this->_cached_fields[$field_name] = $field_obj;
4513
+					}
4514
+				}
4515
+			}
4516
+			return $this->_cached_fields;
4517
+		} else {
4518
+			if ($this->_cached_fields_non_db_only === null) {
4519
+				$this->_cached_fields_non_db_only = array();
4520
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4521
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4522
+						/** @var $field_obj EE_Model_Field_Base */
4523
+						if ( ! $field_obj->is_db_only_field()) {
4524
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4525
+						}
4526
+					}
4527
+				}
4528
+			}
4529
+			return $this->_cached_fields_non_db_only;
4530
+		}
4531
+	}
4532
+
4533
+
4534
+
4535
+	/**
4536
+	 *        cycle though array of attendees and create objects out of each item
4537
+	 *
4538
+	 * @access        private
4539
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4540
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4541
+	 *                           numerically indexed)
4542
+	 * @throws \EE_Error
4543
+	 */
4544
+	protected function _create_objects($rows = array())
4545
+	{
4546
+		$array_of_objects = array();
4547
+		if (empty($rows)) {
4548
+			return array();
4549
+		}
4550
+		$count_if_model_has_no_primary_key = 0;
4551
+		$has_primary_key = $this->has_primary_key_field();
4552
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4553
+		foreach ((array)$rows as $row) {
4554
+			if (empty($row)) {
4555
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4556
+				return array();
4557
+			}
4558
+			//check if we've already set this object in the results array,
4559
+			//in which case there's no need to process it further (again)
4560
+			if ($has_primary_key) {
4561
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4562
+					$row,
4563
+					$primary_key_field->get_qualified_column(),
4564
+					$primary_key_field->get_table_column()
4565
+				);
4566
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4567
+					continue;
4568
+				}
4569
+			}
4570
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4571
+			if ( ! $classInstance) {
4572
+				throw new EE_Error(
4573
+					sprintf(
4574
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4575
+						$this->get_this_model_name(),
4576
+						http_build_query($row)
4577
+					)
4578
+				);
4579
+			}
4580
+			//set the timezone on the instantiated objects
4581
+			$classInstance->set_timezone($this->_timezone);
4582
+			//make sure if there is any timezone setting present that we set the timezone for the object
4583
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4584
+			$array_of_objects[$key] = $classInstance;
4585
+			//also, for all the relations of type BelongsTo, see if we can cache
4586
+			//those related models
4587
+			//(we could do this for other relations too, but if there are conditions
4588
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4589
+			//so it requires a little more thought than just caching them immediately...)
4590
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4591
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4592
+					//check if this model's INFO is present. If so, cache it on the model
4593
+					$other_model = $relation_obj->get_other_model();
4594
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4595
+					//if we managed to make a model object from the results, cache it on the main model object
4596
+					if ($other_model_obj_maybe) {
4597
+						//set timezone on these other model objects if they are present
4598
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4599
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4600
+					}
4601
+				}
4602
+			}
4603
+		}
4604
+		return $array_of_objects;
4605
+	}
4606
+
4607
+
4608
+
4609
+	/**
4610
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4611
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4612
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4613
+	 * object (as set in the model_field!).
4614
+	 *
4615
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4616
+	 */
4617
+	public function create_default_object()
4618
+	{
4619
+		$this_model_fields_and_values = array();
4620
+		//setup the row using default values;
4621
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4622
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4623
+		}
4624
+		$className = $this->_get_class_name();
4625
+		$classInstance = EE_Registry::instance()
4626
+									->load_class($className, array($this_model_fields_and_values), false, false);
4627
+		return $classInstance;
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4634
+	 *                             or an stdClass where each property is the name of a column,
4635
+	 * @return EE_Base_Class
4636
+	 * @throws \EE_Error
4637
+	 */
4638
+	public function instantiate_class_from_array_or_object($cols_n_values)
4639
+	{
4640
+		if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4641
+			$cols_n_values = get_object_vars($cols_n_values);
4642
+		}
4643
+		$primary_key = null;
4644
+		//make sure the array only has keys that are fields/columns on this model
4645
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4646
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4647
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4648
+		}
4649
+		$className = $this->_get_class_name();
4650
+		//check we actually found results that we can use to build our model object
4651
+		//if not, return null
4652
+		if ($this->has_primary_key_field()) {
4653
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4654
+				return null;
4655
+			}
4656
+		} else if ($this->unique_indexes()) {
4657
+			$first_column = reset($this_model_fields_n_values);
4658
+			if (empty($first_column)) {
4659
+				return null;
4660
+			}
4661
+		}
4662
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4663
+		if ($primary_key) {
4664
+			$classInstance = $this->get_from_entity_map($primary_key);
4665
+			if ( ! $classInstance) {
4666
+				$classInstance = EE_Registry::instance()
4667
+											->load_class($className,
4668
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4669
+				// add this new object to the entity map
4670
+				$classInstance = $this->add_to_entity_map($classInstance);
4671
+			}
4672
+		} else {
4673
+			$classInstance = EE_Registry::instance()
4674
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4675
+											true, false);
4676
+		}
4677
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4678
+		$this->set_timezone($classInstance->get_timezone());
4679
+		return $classInstance;
4680
+	}
4681
+
4682
+
4683
+
4684
+	/**
4685
+	 * Gets the model object from the  entity map if it exists
4686
+	 *
4687
+	 * @param int|string $id the ID of the model object
4688
+	 * @return EE_Base_Class
4689
+	 */
4690
+	public function get_from_entity_map($id)
4691
+	{
4692
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4693
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4694
+	}
4695
+
4696
+
4697
+
4698
+	/**
4699
+	 * add_to_entity_map
4700
+	 * Adds the object to the model's entity mappings
4701
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4702
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4703
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4704
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4705
+	 *        then this method should be called immediately after the update query
4706
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4707
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4708
+	 *
4709
+	 * @param    EE_Base_Class $object
4710
+	 * @throws EE_Error
4711
+	 * @return \EE_Base_Class
4712
+	 */
4713
+	public function add_to_entity_map(EE_Base_Class $object)
4714
+	{
4715
+		$className = $this->_get_class_name();
4716
+		if ( ! $object instanceof $className) {
4717
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4718
+				is_object($object) ? get_class($object) : $object, $className));
4719
+		}
4720
+		/** @var $object EE_Base_Class */
4721
+		if ( ! $object->ID()) {
4722
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4723
+				"event_espresso"), get_class($this)));
4724
+		}
4725
+		// double check it's not already there
4726
+		$classInstance = $this->get_from_entity_map($object->ID());
4727
+		if ($classInstance) {
4728
+			return $classInstance;
4729
+		} else {
4730
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4731
+			return $object;
4732
+		}
4733
+	}
4734
+
4735
+
4736
+
4737
+	/**
4738
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4739
+	 * if no identifier is provided, then the entire entity map is emptied
4740
+	 *
4741
+	 * @param int|string $id the ID of the model object
4742
+	 * @return boolean
4743
+	 */
4744
+	public function clear_entity_map($id = null)
4745
+	{
4746
+		if (empty($id)) {
4747
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4748
+			return true;
4749
+		}
4750
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4751
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4752
+			return true;
4753
+		}
4754
+		return false;
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4761
+	 * Given an array where keys are column (or column alias) names and values,
4762
+	 * returns an array of their corresponding field names and database values
4763
+	 *
4764
+	 * @param array $cols_n_values
4765
+	 * @return array
4766
+	 */
4767
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4768
+	{
4769
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4770
+	}
4771
+
4772
+
4773
+
4774
+	/**
4775
+	 * _deduce_fields_n_values_from_cols_n_values
4776
+	 * Given an array where keys are column (or column alias) names and values,
4777
+	 * returns an array of their corresponding field names and database values
4778
+	 *
4779
+	 * @param string $cols_n_values
4780
+	 * @return array
4781
+	 */
4782
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4783
+	{
4784
+		$this_model_fields_n_values = array();
4785
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4786
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4787
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4788
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4789
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4790
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4791
+					if ( ! $field_obj->is_db_only_field()) {
4792
+						//prepare field as if its coming from db
4793
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4794
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4795
+					}
4796
+				}
4797
+			} else {
4798
+				//the table's rows existed. Use their values
4799
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4800
+					if ( ! $field_obj->is_db_only_field()) {
4801
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4802
+							$cols_n_values, $field_obj->get_qualified_column(),
4803
+							$field_obj->get_table_column()
4804
+						);
4805
+					}
4806
+				}
4807
+			}
4808
+		}
4809
+		return $this_model_fields_n_values;
4810
+	}
4811
+
4812
+
4813
+
4814
+	/**
4815
+	 * @param $cols_n_values
4816
+	 * @param $qualified_column
4817
+	 * @param $regular_column
4818
+	 * @return null
4819
+	 */
4820
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4821
+	{
4822
+		$value = null;
4823
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4824
+		//does the field on the model relate to this column retrieved from the db?
4825
+		//or is it a db-only field? (not relating to the model)
4826
+		if (isset($cols_n_values[$qualified_column])) {
4827
+			$value = $cols_n_values[$qualified_column];
4828
+		} elseif (isset($cols_n_values[$regular_column])) {
4829
+			$value = $cols_n_values[$regular_column];
4830
+		}
4831
+		return $value;
4832
+	}
4833
+
4834
+
4835
+
4836
+	/**
4837
+	 * refresh_entity_map_from_db
4838
+	 * Makes sure the model object in the entity map at $id assumes the values
4839
+	 * of the database (opposite of EE_base_Class::save())
4840
+	 *
4841
+	 * @param int|string $id
4842
+	 * @return EE_Base_Class
4843
+	 * @throws \EE_Error
4844
+	 */
4845
+	public function refresh_entity_map_from_db($id)
4846
+	{
4847
+		$obj_in_map = $this->get_from_entity_map($id);
4848
+		if ($obj_in_map) {
4849
+			$wpdb_results = $this->_get_all_wpdb_results(
4850
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4851
+			);
4852
+			if ($wpdb_results && is_array($wpdb_results)) {
4853
+				$one_row = reset($wpdb_results);
4854
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4855
+					$obj_in_map->set_from_db($field_name, $db_value);
4856
+				}
4857
+				//clear the cache of related model objects
4858
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4859
+					$obj_in_map->clear_cache($relation_name, null, true);
4860
+				}
4861
+			}
4862
+			return $obj_in_map;
4863
+		} else {
4864
+			return $this->get_one_by_ID($id);
4865
+		}
4866
+	}
4867
+
4868
+
4869
+
4870
+	/**
4871
+	 * refresh_entity_map_with
4872
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
4873
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4874
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4875
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4876
+	 *
4877
+	 * @param int|string    $id
4878
+	 * @param EE_Base_Class $replacing_model_obj
4879
+	 * @return \EE_Base_Class
4880
+	 * @throws \EE_Error
4881
+	 */
4882
+	public function refresh_entity_map_with($id, $replacing_model_obj)
4883
+	{
4884
+		$obj_in_map = $this->get_from_entity_map($id);
4885
+		if ($obj_in_map) {
4886
+			if ($replacing_model_obj instanceof EE_Base_Class) {
4887
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4888
+					$obj_in_map->set($field_name, $value);
4889
+				}
4890
+				//make the model object in the entity map's cache match the $replacing_model_obj
4891
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4892
+					$obj_in_map->clear_cache($relation_name, null, true);
4893
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4894
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4895
+					}
4896
+				}
4897
+			}
4898
+			return $obj_in_map;
4899
+		} else {
4900
+			$this->add_to_entity_map($replacing_model_obj);
4901
+			return $replacing_model_obj;
4902
+		}
4903
+	}
4904
+
4905
+
4906
+
4907
+	/**
4908
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4909
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4910
+	 * require_once($this->_getClassName().".class.php");
4911
+	 *
4912
+	 * @return string
4913
+	 */
4914
+	private function _get_class_name()
4915
+	{
4916
+		return "EE_" . $this->get_this_model_name();
4917
+	}
4918
+
4919
+
4920
+
4921
+	/**
4922
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
4923
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4924
+	 * it would be 'Events'.
4925
+	 *
4926
+	 * @param int $quantity
4927
+	 * @return string
4928
+	 */
4929
+	public function item_name($quantity = 1)
4930
+	{
4931
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4932
+	}
4933
+
4934
+
4935
+
4936
+	/**
4937
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4938
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
4939
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
4940
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
4941
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
4942
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
4943
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
4944
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
4945
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
4946
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4947
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4948
+	 *        return $previousReturnValue.$returnString;
4949
+	 * }
4950
+	 * require('EEM_Answer.model.php');
4951
+	 * $answer=EEM_Answer::instance();
4952
+	 * echo $answer->my_callback('monkeys',100);
4953
+	 * //will output "you called my_callback! and passed args:monkeys,100"
4954
+	 *
4955
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4956
+	 * @param array  $args       array of original arguments passed to the function
4957
+	 * @throws EE_Error
4958
+	 * @return mixed whatever the plugin which calls add_filter decides
4959
+	 */
4960
+	public function __call($methodName, $args)
4961
+	{
4962
+		$className = get_class($this);
4963
+		$tagName = "FHEE__{$className}__{$methodName}";
4964
+		if ( ! has_filter($tagName)) {
4965
+			throw new EE_Error(
4966
+				sprintf(
4967
+					__('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 );',
4968
+						'event_espresso'),
4969
+					$methodName,
4970
+					$className,
4971
+					$tagName,
4972
+					'<br />'
4973
+				)
4974
+			);
4975
+		}
4976
+		return apply_filters($tagName, null, $this, $args);
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4983
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4984
+	 *
4985
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4986
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
4987
+	 *                                                       the object's class name
4988
+	 *                                                       or object's ID
4989
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
4990
+	 *                                                       exists in the database. If it does not, we add it
4991
+	 * @throws EE_Error
4992
+	 * @return EE_Base_Class
4993
+	 */
4994
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
4995
+	{
4996
+		$className = $this->_get_class_name();
4997
+		if ($base_class_obj_or_id instanceof $className) {
4998
+			$model_object = $base_class_obj_or_id;
4999
+		} else {
5000
+			$primary_key_field = $this->get_primary_key_field();
5001
+			if (
5002
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5003
+				&& (
5004
+					is_int($base_class_obj_or_id)
5005
+					|| is_string($base_class_obj_or_id)
5006
+				)
5007
+			) {
5008
+				// assume it's an ID.
5009
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5010
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5011
+			} else if (
5012
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5013
+				&& is_string($base_class_obj_or_id)
5014
+			) {
5015
+				// assume its a string representation of the object
5016
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5017
+			} else {
5018
+				throw new EE_Error(
5019
+					sprintf(
5020
+						__(
5021
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5022
+							'event_espresso'
5023
+						),
5024
+						$base_class_obj_or_id,
5025
+						$this->_get_class_name(),
5026
+						print_r($base_class_obj_or_id, true)
5027
+					)
5028
+				);
5029
+			}
5030
+		}
5031
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5032
+			$model_object->save();
5033
+		}
5034
+		return $model_object;
5035
+	}
5036
+
5037
+
5038
+
5039
+	/**
5040
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5041
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5042
+	 * returns it ID.
5043
+	 *
5044
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5045
+	 * @return int|string depending on the type of this model object's ID
5046
+	 * @throws EE_Error
5047
+	 */
5048
+	public function ensure_is_ID($base_class_obj_or_id)
5049
+	{
5050
+		$className = $this->_get_class_name();
5051
+		if ($base_class_obj_or_id instanceof $className) {
5052
+			/** @var $base_class_obj_or_id EE_Base_Class */
5053
+			$id = $base_class_obj_or_id->ID();
5054
+		} elseif (is_int($base_class_obj_or_id)) {
5055
+			//assume it's an ID
5056
+			$id = $base_class_obj_or_id;
5057
+		} elseif (is_string($base_class_obj_or_id)) {
5058
+			//assume its a string representation of the object
5059
+			$id = $base_class_obj_or_id;
5060
+		} else {
5061
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5062
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5063
+				print_r($base_class_obj_or_id, true)));
5064
+		}
5065
+		return $id;
5066
+	}
5067
+
5068
+
5069
+
5070
+	/**
5071
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5072
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5073
+	 * been sanitized and converted into the appropriate domain.
5074
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5075
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5076
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5077
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5078
+	 * $EVT = EEM_Event::instance(); $old_setting =
5079
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5080
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5081
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5082
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5083
+	 *
5084
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5085
+	 * @return void
5086
+	 */
5087
+	public function assume_values_already_prepared_by_model_object(
5088
+		$values_already_prepared = self::not_prepared_by_model_object
5089
+	) {
5090
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5091
+	}
5092
+
5093
+
5094
+
5095
+	/**
5096
+	 * Read comments for assume_values_already_prepared_by_model_object()
5097
+	 *
5098
+	 * @return int
5099
+	 */
5100
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5101
+	{
5102
+		return $this->_values_already_prepared_by_model_object;
5103
+	}
5104
+
5105
+
5106
+
5107
+	/**
5108
+	 * Gets all the indexes on this model
5109
+	 *
5110
+	 * @return EE_Index[]
5111
+	 */
5112
+	public function indexes()
5113
+	{
5114
+		return $this->_indexes;
5115
+	}
5116
+
5117
+
5118
+
5119
+	/**
5120
+	 * Gets all the Unique Indexes on this model
5121
+	 *
5122
+	 * @return EE_Unique_Index[]
5123
+	 */
5124
+	public function unique_indexes()
5125
+	{
5126
+		$unique_indexes = array();
5127
+		foreach ($this->_indexes as $name => $index) {
5128
+			if ($index instanceof EE_Unique_Index) {
5129
+				$unique_indexes [$name] = $index;
5130
+			}
5131
+		}
5132
+		return $unique_indexes;
5133
+	}
5134
+
5135
+
5136
+
5137
+	/**
5138
+	 * Gets all the fields which, when combined, make the primary key.
5139
+	 * This is usually just an array with 1 element (the primary key), but in cases
5140
+	 * where there is no primary key, it's a combination of fields as defined
5141
+	 * on a primary index
5142
+	 *
5143
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5144
+	 * @throws \EE_Error
5145
+	 */
5146
+	public function get_combined_primary_key_fields()
5147
+	{
5148
+		foreach ($this->indexes() as $index) {
5149
+			if ($index instanceof EE_Primary_Key_Index) {
5150
+				return $index->fields();
5151
+			}
5152
+		}
5153
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5154
+	}
5155
+
5156
+
5157
+
5158
+	/**
5159
+	 * Used to build a primary key string (when the model has no primary key),
5160
+	 * which can be used a unique string to identify this model object.
5161
+	 *
5162
+	 * @param array $cols_n_values keys are field names, values are their values
5163
+	 * @return string
5164
+	 * @throws \EE_Error
5165
+	 */
5166
+	public function get_index_primary_key_string($cols_n_values)
5167
+	{
5168
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5169
+			$this->get_combined_primary_key_fields());
5170
+		return http_build_query($cols_n_values_for_primary_key_index);
5171
+	}
5172
+
5173
+
5174
+
5175
+	/**
5176
+	 * Gets the field values from the primary key string
5177
+	 *
5178
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5179
+	 * @param string $index_primary_key_string
5180
+	 * @return null|array
5181
+	 * @throws \EE_Error
5182
+	 */
5183
+	public function parse_index_primary_key_string($index_primary_key_string)
5184
+	{
5185
+		$key_fields = $this->get_combined_primary_key_fields();
5186
+		//check all of them are in the $id
5187
+		$key_vals_in_combined_pk = array();
5188
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5189
+		foreach ($key_fields as $key_field_name => $field_obj) {
5190
+			if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5191
+				return null;
5192
+			}
5193
+		}
5194
+		return $key_vals_in_combined_pk;
5195
+	}
5196
+
5197
+
5198
+
5199
+	/**
5200
+	 * verifies that an array of key-value pairs for model fields has a key
5201
+	 * for each field comprising the primary key index
5202
+	 *
5203
+	 * @param array $key_vals
5204
+	 * @return boolean
5205
+	 * @throws \EE_Error
5206
+	 */
5207
+	public function has_all_combined_primary_key_fields($key_vals)
5208
+	{
5209
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5210
+		foreach ($keys_it_should_have as $key) {
5211
+			if ( ! isset($key_vals[$key])) {
5212
+				return false;
5213
+			}
5214
+		}
5215
+		return true;
5216
+	}
5217
+
5218
+
5219
+
5220
+	/**
5221
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5222
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5223
+	 *
5224
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5225
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5226
+	 * @throws EE_Error
5227
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5228
+	 *                                                              indexed)
5229
+	 */
5230
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5231
+	{
5232
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5233
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5234
+		} elseif (is_array($model_object_or_attributes_array)) {
5235
+			$attributes_array = $model_object_or_attributes_array;
5236
+		} else {
5237
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5238
+				"event_espresso"), $model_object_or_attributes_array));
5239
+		}
5240
+		//even copies obviously won't have the same ID, so remove the primary key
5241
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5242
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5243
+			unset($attributes_array[$this->primary_key_name()]);
5244
+		}
5245
+		if (isset($query_params[0])) {
5246
+			$query_params[0] = array_merge($attributes_array, $query_params);
5247
+		} else {
5248
+			$query_params[0] = $attributes_array;
5249
+		}
5250
+		return $this->get_all($query_params);
5251
+	}
5252
+
5253
+
5254
+
5255
+	/**
5256
+	 * Gets the first copy we find. See get_all_copies for more details
5257
+	 *
5258
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5259
+	 * @param array $query_params
5260
+	 * @return EE_Base_Class
5261
+	 * @throws \EE_Error
5262
+	 */
5263
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5264
+	{
5265
+		if ( ! is_array($query_params)) {
5266
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5267
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5268
+					gettype($query_params)), '4.6.0');
5269
+			$query_params = array();
5270
+		}
5271
+		$query_params['limit'] = 1;
5272
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5273
+		if (is_array($copies)) {
5274
+			return array_shift($copies);
5275
+		} else {
5276
+			return null;
5277
+		}
5278
+	}
5279
+
5280
+
5281
+
5282
+	/**
5283
+	 * Updates the item with the specified id. Ignores default query parameters because
5284
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5285
+	 *
5286
+	 * @param array      $fields_n_values keys are field names, values are their new values
5287
+	 * @param int|string $id              the value of the primary key to update
5288
+	 * @return int number of rows updated
5289
+	 * @throws \EE_Error
5290
+	 */
5291
+	public function update_by_ID($fields_n_values, $id)
5292
+	{
5293
+		$query_params = array(
5294
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5295
+			'default_where_conditions' => 'other_models_only',
5296
+		);
5297
+		return $this->update($fields_n_values, $query_params);
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Changes an operator which was supplied to the models into one usable in SQL
5304
+	 *
5305
+	 * @param string $operator_supplied
5306
+	 * @return string an operator which can be used in SQL
5307
+	 * @throws EE_Error
5308
+	 */
5309
+	private function _prepare_operator_for_sql($operator_supplied)
5310
+	{
5311
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5312
+			: null;
5313
+		if ($sql_operator) {
5314
+			return $sql_operator;
5315
+		} else {
5316
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5317
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5318
+		}
5319
+	}
5320
+
5321
+
5322
+
5323
+	/**
5324
+	 * Gets an array where keys are the primary keys and values are their 'names'
5325
+	 * (as determined by the model object's name() function, which is often overridden)
5326
+	 *
5327
+	 * @param array $query_params like get_all's
5328
+	 * @return string[]
5329
+	 * @throws \EE_Error
5330
+	 */
5331
+	public function get_all_names($query_params = array())
5332
+	{
5333
+		$objs = $this->get_all($query_params);
5334
+		$names = array();
5335
+		foreach ($objs as $obj) {
5336
+			$names[$obj->ID()] = $obj->name();
5337
+		}
5338
+		return $names;
5339
+	}
5340
+
5341
+
5342
+
5343
+	/**
5344
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5345
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5346
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5347
+	 * array_keys() on $model_objects.
5348
+	 *
5349
+	 * @param \EE_Base_Class[] $model_objects
5350
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5351
+	 *                                               in the returned array
5352
+	 * @return array
5353
+	 * @throws \EE_Error
5354
+	 */
5355
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5356
+	{
5357
+		if ( ! $this->has_primary_key_field()) {
5358
+			if (WP_DEBUG) {
5359
+				EE_Error::add_error(
5360
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5361
+					__FILE__,
5362
+					__FUNCTION__,
5363
+					__LINE__
5364
+				);
5365
+			}
5366
+		}
5367
+		$IDs = array();
5368
+		foreach ($model_objects as $model_object) {
5369
+			$id = $model_object->ID();
5370
+			if ( ! $id) {
5371
+				if ($filter_out_empty_ids) {
5372
+					continue;
5373
+				}
5374
+				if (WP_DEBUG) {
5375
+					EE_Error::add_error(
5376
+						__(
5377
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5378
+							'event_espresso'
5379
+						),
5380
+						__FILE__,
5381
+						__FUNCTION__,
5382
+						__LINE__
5383
+					);
5384
+				}
5385
+			}
5386
+			$IDs[] = $id;
5387
+		}
5388
+		return $IDs;
5389
+	}
5390
+
5391
+
5392
+
5393
+	/**
5394
+	 * Returns the string used in capabilities relating to this model. If there
5395
+	 * are no capabilities that relate to this model returns false
5396
+	 *
5397
+	 * @return string|false
5398
+	 */
5399
+	public function cap_slug()
5400
+	{
5401
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5402
+	}
5403
+
5404
+
5405
+
5406
+	/**
5407
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5408
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5409
+	 * only returns the cap restrictions array in that context (ie, the array
5410
+	 * at that key)
5411
+	 *
5412
+	 * @param string $context
5413
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5414
+	 * @throws \EE_Error
5415
+	 */
5416
+	public function cap_restrictions($context = EEM_Base::caps_read)
5417
+	{
5418
+		EEM_Base::verify_is_valid_cap_context($context);
5419
+		//check if we ought to run the restriction generator first
5420
+		if (
5421
+			isset($this->_cap_restriction_generators[$context])
5422
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5423
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5424
+		) {
5425
+			$this->_cap_restrictions[$context] = array_merge(
5426
+				$this->_cap_restrictions[$context],
5427
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5428
+			);
5429
+		}
5430
+		//and make sure we've finalized the construction of each restriction
5431
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5432
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5433
+				$where_conditions_obj->_finalize_construct($this);
5434
+			}
5435
+		}
5436
+		return $this->_cap_restrictions[$context];
5437
+	}
5438
+
5439
+
5440
+
5441
+	/**
5442
+	 * Indicating whether or not this model thinks its a wp core model
5443
+	 *
5444
+	 * @return boolean
5445
+	 */
5446
+	public function is_wp_core_model()
5447
+	{
5448
+		return $this->_wp_core_model;
5449
+	}
5450
+
5451
+
5452
+
5453
+	/**
5454
+	 * Gets all the caps that are missing which impose a restriction on
5455
+	 * queries made in this context
5456
+	 *
5457
+	 * @param string $context one of EEM_Base::caps_ constants
5458
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5459
+	 * @throws \EE_Error
5460
+	 */
5461
+	public function caps_missing($context = EEM_Base::caps_read)
5462
+	{
5463
+		$missing_caps = array();
5464
+		$cap_restrictions = $this->cap_restrictions($context);
5465
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5466
+			if ( ! EE_Capabilities::instance()
5467
+								  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5468
+			) {
5469
+				$missing_caps[$cap] = $restriction_if_no_cap;
5470
+			}
5471
+		}
5472
+		return $missing_caps;
5473
+	}
5474
+
5475
+
5476
+
5477
+	/**
5478
+	 * Gets the mapping from capability contexts to action strings used in capability names
5479
+	 *
5480
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5481
+	 * one of 'read', 'edit', or 'delete'
5482
+	 */
5483
+	public function cap_contexts_to_cap_action_map()
5484
+	{
5485
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5486
+			$this);
5487
+	}
5488
+
5489
+
5490
+
5491
+	/**
5492
+	 * Gets the action string for the specified capability context
5493
+	 *
5494
+	 * @param string $context
5495
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5496
+	 * @throws \EE_Error
5497
+	 */
5498
+	public function cap_action_for_context($context)
5499
+	{
5500
+		$mapping = $this->cap_contexts_to_cap_action_map();
5501
+		if (isset($mapping[$context])) {
5502
+			return $mapping[$context];
5503
+		}
5504
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5505
+			return $action;
5506
+		}
5507
+		throw new EE_Error(
5508
+			sprintf(
5509
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5510
+				$context,
5511
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5512
+			)
5513
+		);
5514
+	}
5515
+
5516
+
5517
+
5518
+	/**
5519
+	 * Returns all the capability contexts which are valid when querying models
5520
+	 *
5521
+	 * @return array
5522
+	 */
5523
+	static public function valid_cap_contexts()
5524
+	{
5525
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5526
+			self::caps_read,
5527
+			self::caps_read_admin,
5528
+			self::caps_edit,
5529
+			self::caps_delete,
5530
+		));
5531
+	}
5532
+
5533
+
5534
+
5535
+	/**
5536
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5537
+	 *
5538
+	 * @param string $context
5539
+	 * @return bool
5540
+	 * @throws \EE_Error
5541
+	 */
5542
+	static public function verify_is_valid_cap_context($context)
5543
+	{
5544
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5545
+		if (in_array($context, $valid_cap_contexts)) {
5546
+			return true;
5547
+		} else {
5548
+			throw new EE_Error(
5549
+				sprintf(
5550
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5551
+						'event_espresso'),
5552
+					$context,
5553
+					'EEM_Base',
5554
+					implode(',', $valid_cap_contexts)
5555
+				)
5556
+			);
5557
+		}
5558
+	}
5559
+
5560
+
5561
+
5562
+	/**
5563
+	 * Clears all the models field caches. This is only useful when a sub-class
5564
+	 * might have added a field or something and these caches might be invalidated
5565
+	 */
5566
+	protected function _invalidate_field_caches()
5567
+	{
5568
+		$this->_cache_foreign_key_to_fields = array();
5569
+		$this->_cached_fields = null;
5570
+		$this->_cached_fields_non_db_only = null;
5571
+	}
5572
+
5573
+
5574
+
5575
+	/**
5576
+	 * _instantiate_new_instance_from_db
5577
+	 *
5578
+	 * @param string $class_name
5579
+	 * @param array  $arguments
5580
+	 * @return \EE_Base_Class
5581
+	 * @throws \Exception
5582
+	 */
5583
+	public function _instantiate_new_instance_from_db($class_name, $arguments)
5584
+	{
5585
+		if ( ! class_exists($class_name)) {
5586
+			throw new EE_Error(
5587
+				sprintf(
5588
+					__('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5589
+					$class_name
5590
+				)
5591
+			);
5592
+		}
5593
+		return call_user_func_array(
5594
+			array($class_name, 'new_instance'),
5595
+			array((array)$arguments, $this->_timezone, array(), true)
5596
+		);
5597
+	}
5598 5598
 
5599 5599
 
5600 5600
 }
Please login to merge, or discard this patch.
Spacing   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
     {
468 468
         // check that the model has not been loaded too soon
469 469
         if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
470
+            throw new EE_Error(
471 471
                 sprintf(
472 472
                     __('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.',
473 473
                         'event_espresso'),
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
          *
488 488
          * @var EE_Table_Base[] $_tables
489 489
          */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
490
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
491 491
         foreach ($this->_tables as $table_alias => $table_obj) {
492 492
             /** @var $table_obj EE_Table_Base */
493 493
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
          *
503 503
          * @param EE_Model_Field_Base[] $_fields
504 504
          */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
505
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
506 506
         $this->_invalidate_field_caches();
507 507
         foreach ($this->_fields as $table_alias => $fields_for_table) {
508 508
             if ( ! array_key_exists($table_alias, $this->_tables)) {
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
          *
534 534
          * @param EE_Model_Relation_Base[] $_model_relations
535 535
          */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
536
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
537 537
             $this->_model_relations);
538 538
         foreach ($this->_model_relations as $model_name => $relation_obj) {
539 539
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
                 }
596 596
             }
597 597
         }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
598
+        do_action('AHEE__'.get_class($this).'__construct__end');
599 599
     }
600 600
 
601 601
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
      */
631 631
     public static function set_model_query_blog_id($blog_id = 0)
632 632
     {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
633
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
634 634
     }
635 635
 
636 636
 
@@ -889,13 +889,13 @@  discard block
 block discarded – undo
889 889
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890 890
                 $last_model_name = end($models_to_follow_to_wp_users);
891 891
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
892
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
893 893
             } else {
894 894
                 $model_with_fk_to_wp_users = $this;
895 895
                 $model_chain_to_wp_user = '';
896 896
             }
897 897
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
898
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
899 899
         } catch (EE_Error $e) {
900 900
             return false;
901 901
         }
@@ -967,12 +967,12 @@  discard block
 block discarded – undo
967 967
         // remember the custom selections, if any, and type cast as array
968 968
         // (unless $columns_to_select is an object, then just set as an empty array)
969 969
         // Note: (array) 'some string' === array( 'some string' )
970
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
970
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
971 971
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
972 972
         $select_expressions = $columns_to_select !== null
973 973
             ? $this->_construct_select_from_input($columns_to_select)
974 974
             : $this->_construct_default_select_sql($model_query_info);
975
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
975
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
976 976
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
977 977
     }
978 978
 
@@ -1304,7 +1304,7 @@  discard block
 block discarded – undo
1304 1304
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305 1305
         $query_params['limit'] = $limit;
1306 1306
         //set direction
1307
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1307
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1308 1308
         $query_params['order_by'] = $operand === '>'
1309 1309
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1310 1310
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1545,7 +1545,7 @@  discard block
 block discarded – undo
1545 1545
          * @param EEM_Base $model           the model being queried
1546 1546
          * @param array    $query_params    see EEM_Base::get_all()
1547 1547
          */
1548
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1548
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549 1549
             $query_params);
1550 1550
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1551 1551
         //to do that, for each table, verify that it's PK isn't null.
@@ -1559,7 +1559,7 @@  discard block
 block discarded – undo
1559 1559
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560 1560
         foreach ($wpdb_select_results as $wpdb_result) {
1561 1561
             // type cast stdClass as array
1562
-            $wpdb_result = (array)$wpdb_result;
1562
+            $wpdb_result = (array) $wpdb_result;
1563 1563
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564 1564
             if ($this->has_primary_key_field()) {
1565 1565
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1640,7 +1640,7 @@  discard block
 block discarded – undo
1640 1640
                . $model_query_info->get_full_join_sql()
1641 1641
                . " SET "
1642 1642
                . $this->_construct_update_sql($fields_n_values)
1643
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1643
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644 1644
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645 1645
         /**
1646 1646
          * Action called after a model update call has been made.
@@ -1651,7 +1651,7 @@  discard block
 block discarded – undo
1651 1651
          * @param int      $rows_affected
1652 1652
          */
1653 1653
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
-        return $rows_affected;//how many supposedly got updated
1654
+        return $rows_affected; //how many supposedly got updated
1655 1655
     }
1656 1656
 
1657 1657
 
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
         }
1680 1680
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1681 1681
         $select_expressions = $field->get_qualified_column();
1682
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1682
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1683 1683
         return $this->_do_wpdb_query('get_col', array($SQL));
1684 1684
     }
1685 1685
 
@@ -1729,7 +1729,7 @@  discard block
 block discarded – undo
1729 1729
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730 1730
             $value_sql = $prepared_value === null ? 'NULL'
1731 1731
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1732
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1733 1733
         }
1734 1734
         return implode(",", $cols_n_values);
1735 1735
     }
@@ -1861,7 +1861,7 @@  discard block
 block discarded – undo
1861 1861
          * @param int      $rows_deleted
1862 1862
          */
1863 1863
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
-        return $rows_deleted;//how many supposedly got deleted
1864
+        return $rows_deleted; //how many supposedly got deleted
1865 1865
     }
1866 1866
 
1867 1867
 
@@ -1977,7 +1977,7 @@  discard block
 block discarded – undo
1977 1977
             foreach ($deletes as $column => $values) {
1978 1978
                 //make sure we have unique $values;
1979 1979
                 $values = array_unique($values);
1980
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
1980
+                $query[] = $column.' IN('.implode(",", $values).')';
1981 1981
             }
1982 1982
             return ! empty($query) ? implode(' AND ', $query) : '';
1983 1983
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -1993,7 +1993,7 @@  discard block
 block discarded – undo
1993 1993
                                                            . $delete_object[$cpk_field->get_qualified_column()];
1994 1994
                     }
1995 1995
                 }
1996
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1996
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
1997 1997
             }
1998 1998
             return implode(" OR ", $ways_to_identify_a_row);
1999 1999
         } else {
@@ -2042,9 +2042,9 @@  discard block
 block discarded – undo
2042 2042
                 $column_to_count = '*';
2043 2043
             }
2044 2044
         }
2045
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2045
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2046
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2047
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2048 2048
     }
2049 2049
 
2050 2050
 
@@ -2066,13 +2066,13 @@  discard block
 block discarded – undo
2066 2066
             $field_obj = $this->get_primary_key_field();
2067 2067
         }
2068 2068
         $column_to_count = $field_obj->get_qualified_column();
2069
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2069
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2070 2070
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071 2071
         $data_type = $field_obj->get_wpdb_data_type();
2072 2072
         if ($data_type === '%d' || $data_type === '%s') {
2073
-            return (float)$return_value;
2073
+            return (float) $return_value;
2074 2074
         } else {//must be %f
2075
-            return (float)$return_value;
2075
+            return (float) $return_value;
2076 2076
         }
2077 2077
     }
2078 2078
 
@@ -2247,11 +2247,11 @@  discard block
 block discarded – undo
2247 2247
      */
2248 2248
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249 2249
     {
2250
-        return " FROM " . $model_query_info->get_full_join_sql() .
2251
-               $model_query_info->get_where_sql() .
2252
-               $model_query_info->get_group_by_sql() .
2253
-               $model_query_info->get_having_sql() .
2254
-               $model_query_info->get_order_by_sql() .
2250
+        return " FROM ".$model_query_info->get_full_join_sql().
2251
+               $model_query_info->get_where_sql().
2252
+               $model_query_info->get_group_by_sql().
2253
+               $model_query_info->get_having_sql().
2254
+               $model_query_info->get_order_by_sql().
2255 2255
                $model_query_info->get_limit_sql();
2256 2256
     }
2257 2257
 
@@ -2452,7 +2452,7 @@  discard block
 block discarded – undo
2452 2452
         }
2453 2453
         $this_model_name = $this->get_this_model_name();
2454 2454
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2455
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2456 2456
         return $related_model->count($query_params, $field_to_count, $distinct);
2457 2457
     }
2458 2458
 
@@ -2485,7 +2485,7 @@  discard block
 block discarded – undo
2485 2485
         }
2486 2486
         $this_model_name = $this->get_this_model_name();
2487 2487
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2488
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2489 2489
         return $related_model->sum($query_params, $field_to_sum);
2490 2490
     }
2491 2491
 
@@ -2572,7 +2572,7 @@  discard block
 block discarded – undo
2572 2572
          * @param array    $fields_n_values keys are the fields and values are their new values
2573 2573
          * @param EEM_Base $model           the model used
2574 2574
          */
2575
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2575
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576 2576
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2577 2577
             $main_table = $this->_get_main_table();
2578 2578
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2680,7 +2680,7 @@  discard block
 block discarded – undo
2680 2680
         }
2681 2681
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682 2682
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2683
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2684 2684
         }
2685 2685
         //if there is nothing to base this search on, then we shouldn't find anything
2686 2686
         if (empty($query_params)) {
@@ -2760,7 +2760,7 @@  discard block
 block discarded – undo
2760 2760
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2761 2761
             //so add the fk to the main table as a column
2762 2762
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2763
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2764 2764
         }
2765 2765
         //insert the new entry
2766 2766
         $result = $this->_do_wpdb_query('insert',
@@ -3020,7 +3020,7 @@  discard block
 block discarded – undo
3020 3020
         $query_param_type
3021 3021
     ) {
3022 3022
         if ( ! empty($sub_query_params)) {
3023
-            $sub_query_params = (array)$sub_query_params;
3023
+            $sub_query_params = (array) $sub_query_params;
3024 3024
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025 3025
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026 3026
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3191,12 +3191,12 @@  discard block
 block discarded – undo
3191 3191
                         ),
3192 3192
                         http_build_query($query_params['limit'])
3193 3193
                     );
3194
-                    throw new EE_Error($e . "|" . $e);
3194
+                    throw new EE_Error($e."|".$e);
3195 3195
                 }
3196 3196
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3197
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3198 3198
             } elseif ( ! empty ($query_params['limit'])) {
3199
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3199
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3200 3200
             }
3201 3201
         }
3202 3202
         //set order by
@@ -3228,9 +3228,9 @@  discard block
 block discarded – undo
3228 3228
                 $order_array = array();
3229 3229
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230 3230
                     $order = $this->_extract_order($order);
3231
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3231
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3232 3232
                 }
3233
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3233
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3234 3234
             } elseif ( ! empty ($query_params['order_by'])) {
3235 3235
                 $this->_extract_related_model_info_from_query_param(
3236 3236
                     $query_params['order_by'],
@@ -3242,7 +3242,7 @@  discard block
 block discarded – undo
3242 3242
                     ? $this->_extract_order($query_params['order'])
3243 3243
                     : 'DESC';
3244 3244
                 $query_object->set_order_by_sql(
3245
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3245
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3246 3246
                 );
3247 3247
             }
3248 3248
         }
@@ -3253,7 +3253,7 @@  discard block
 block discarded – undo
3253 3253
         ) {
3254 3254
             $pk_field = $this->get_primary_key_field();
3255 3255
             $order = $this->_extract_order($query_params['order']);
3256
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3256
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3257 3257
         }
3258 3258
         //set group by
3259 3259
         if (array_key_exists('group_by', $query_params)) {
@@ -3263,10 +3263,10 @@  discard block
 block discarded – undo
3263 3263
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264 3264
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265 3265
                 }
3266
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3266
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3267 3267
             } elseif ( ! empty ($query_params['group_by'])) {
3268 3268
                 $query_object->set_group_by_sql(
3269
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3269
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3270 3270
                 );
3271 3271
             }
3272 3272
         }
@@ -3429,7 +3429,7 @@  discard block
 block discarded – undo
3429 3429
     ) {
3430 3430
         $null_friendly_where_conditions = array();
3431 3431
         $none_overridden = true;
3432
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3432
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3433 3433
         foreach ($default_where_conditions as $key => $val) {
3434 3434
             if (isset($provided_where_conditions[$key])) {
3435 3435
                 $none_overridden = false;
@@ -3633,9 +3633,9 @@  discard block
 block discarded – undo
3633 3633
         //and
3634 3634
         //check if it's a field on a related model
3635 3635
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3636
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3637 3637
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3638
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3639 3639
                 if ($query_param === '') {
3640 3640
                     //nothing left to $query_param
3641 3641
                     //we should actually end in a field name, not a model like this!
@@ -3721,7 +3721,7 @@  discard block
 block discarded – undo
3721 3721
     {
3722 3722
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723 3723
         if ($SQL) {
3724
-            return " WHERE " . $SQL;
3724
+            return " WHERE ".$SQL;
3725 3725
         } else {
3726 3726
             return '';
3727 3727
         }
@@ -3741,7 +3741,7 @@  discard block
 block discarded – undo
3741 3741
     {
3742 3742
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743 3743
         if ($SQL) {
3744
-            return " HAVING " . $SQL;
3744
+            return " HAVING ".$SQL;
3745 3745
         } else {
3746 3746
             return '';
3747 3747
         }
@@ -3761,11 +3761,11 @@  discard block
 block discarded – undo
3761 3761
      */
3762 3762
     protected function _get_field_on_model($field_name, $model_name)
3763 3763
     {
3764
-        $model_class = 'EEM_' . $model_name;
3765
-        $model_filepath = $model_class . ".model.php";
3764
+        $model_class = 'EEM_'.$model_name;
3765
+        $model_filepath = $model_class.".model.php";
3766 3766
         if (is_readable($model_filepath)) {
3767 3767
             require_once($model_filepath);
3768
-            $model_instance = call_user_func($model_name . "::instance");
3768
+            $model_instance = call_user_func($model_name."::instance");
3769 3769
             /* @var $model_instance EEM_Base */
3770 3770
             return $model_instance->field_settings_for($field_name);
3771 3771
         } else {
@@ -3789,7 +3789,7 @@  discard block
 block discarded – undo
3789 3789
     {
3790 3790
         $where_clauses = array();
3791 3791
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3792
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3793 3793
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3794 3794
                 switch ($query_param) {
3795 3795
                     case 'not':
@@ -3826,7 +3826,7 @@  discard block
 block discarded – undo
3826 3826
                     }
3827 3827
                 }
3828 3828
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3829
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3830 3830
             }
3831 3831
         }
3832 3832
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -3847,7 +3847,7 @@  discard block
 block discarded – undo
3847 3847
         if ($field) {
3848 3848
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849 3849
                 $query_param);
3850
-            return $table_alias_prefix . $field->get_qualified_column();
3850
+            return $table_alias_prefix.$field->get_qualified_column();
3851 3851
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852 3852
             //maybe it's custom selection item?
3853 3853
             //if so, just use it as the "column name"
@@ -3916,13 +3916,13 @@  discard block
 block discarded – undo
3916 3916
         }
3917 3917
         //check to see if the value is actually another field
3918 3918
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3919
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
3920 3920
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921 3921
             //in this case, the value should be an array, or at least a comma-separated list
3922 3922
             //it will need to handle a little differently
3923 3923
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
3924 3924
             //note: $cleaned_value has already been run through $wpdb->prepare()
3925
-            return $operator . SP . $cleaned_value;
3925
+            return $operator.SP.$cleaned_value;
3926 3926
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927 3927
             //the value should be an array with count of two.
3928 3928
             if (count($value) !== 2) {
@@ -3937,7 +3937,7 @@  discard block
 block discarded – undo
3937 3937
                 );
3938 3938
             }
3939 3939
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
-            return $operator . SP . $cleaned_value;
3940
+            return $operator.SP.$cleaned_value;
3941 3941
         } elseif (in_array($operator, $this->_null_style_operators)) {
3942 3942
             if ($value !== null) {
3943 3943
                 throw new EE_Error(
@@ -3955,9 +3955,9 @@  discard block
 block discarded – undo
3955 3955
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
3956 3956
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
3957 3957
             //remove other junk. So just treat it as a string.
3958
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3958
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
3959 3959
         } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3960
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
3961 3961
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962 3962
             throw new EE_Error(
3963 3963
                 sprintf(
@@ -4010,7 +4010,7 @@  discard block
 block discarded – undo
4010 4010
         foreach ($values as $value) {
4011 4011
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012 4012
         }
4013
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4013
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4014 4014
     }
4015 4015
 
4016 4016
 
@@ -4051,7 +4051,7 @@  discard block
 block discarded – undo
4051 4051
                                 . $main_table->get_table_name()
4052 4052
                                 . " WHERE FALSE";
4053 4053
         }
4054
-        return "(" . implode(",", $cleaned_values) . ")";
4054
+        return "(".implode(",", $cleaned_values).")";
4055 4055
     }
4056 4056
 
4057 4057
 
@@ -4154,11 +4154,11 @@  discard block
 block discarded – undo
4154 4154
             if ($table_obj instanceof EE_Primary_Table) {
4155 4155
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4156 4156
                     ? $table_obj->get_select_join_limit($limit)
4157
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4157
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4158 4158
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4159 4159
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4160 4160
                     ? $table_obj->get_select_join_limit_join($limit)
4161
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4161
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4162 4162
             }
4163 4163
         }
4164 4164
         return $SQL;
@@ -4246,12 +4246,12 @@  discard block
 block discarded – undo
4246 4246
      */
4247 4247
     public function get_related_model_obj($model_name)
4248 4248
     {
4249
-        $model_classname = "EEM_" . $model_name;
4249
+        $model_classname = "EEM_".$model_name;
4250 4250
         if ( ! class_exists($model_classname)) {
4251 4251
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4252 4252
                 'event_espresso'), $model_name, $model_classname));
4253 4253
         }
4254
-        return call_user_func($model_classname . "::instance");
4254
+        return call_user_func($model_classname."::instance");
4255 4255
     }
4256 4256
 
4257 4257
 
@@ -4550,7 +4550,7 @@  discard block
 block discarded – undo
4550 4550
         $count_if_model_has_no_primary_key = 0;
4551 4551
         $has_primary_key = $this->has_primary_key_field();
4552 4552
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4553
-        foreach ((array)$rows as $row) {
4553
+        foreach ((array) $rows as $row) {
4554 4554
             if (empty($row)) {
4555 4555
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4556 4556
                 return array();
@@ -4913,7 +4913,7 @@  discard block
 block discarded – undo
4913 4913
      */
4914 4914
     private function _get_class_name()
4915 4915
     {
4916
-        return "EE_" . $this->get_this_model_name();
4916
+        return "EE_".$this->get_this_model_name();
4917 4917
     }
4918 4918
 
4919 4919
 
@@ -4928,7 +4928,7 @@  discard block
 block discarded – undo
4928 4928
      */
4929 4929
     public function item_name($quantity = 1)
4930 4930
     {
4931
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4931
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
4932 4932
     }
4933 4933
 
4934 4934
 
@@ -5464,7 +5464,7 @@  discard block
 block discarded – undo
5464 5464
         $cap_restrictions = $this->cap_restrictions($context);
5465 5465
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5466 5466
             if ( ! EE_Capabilities::instance()
5467
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5467
+                                  ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5468 5468
             ) {
5469 5469
                 $missing_caps[$cap] = $restriction_if_no_cap;
5470 5470
             }
@@ -5592,7 +5592,7 @@  discard block
 block discarded – undo
5592 5592
         }
5593 5593
         return call_user_func_array(
5594 5594
             array($class_name, 'new_instance'),
5595
-            array((array)$arguments, $this->_timezone, array(), true)
5595
+            array((array) $arguments, $this->_timezone, array(), true)
5596 5596
         );
5597 5597
     }
5598 5598
 
Please login to merge, or discard this patch.
core/helpers/EEH_Event_Query.helper.php 1 patch
Spacing   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	 */
86 86
 	public static function add_query_filters() {
87 87
 		//add query filters
88
-		add_action( 'pre_get_posts', array( 'EEH_Event_Query', 'filter_query_parts' ), 10, 1 );
88
+		add_action('pre_get_posts', array('EEH_Event_Query', 'filter_query_parts'), 10, 1);
89 89
 	}
90 90
 
91 91
 
@@ -97,8 +97,8 @@  discard block
 block discarded – undo
97 97
 	 * @param \WP_Query $WP_Query
98 98
 	 * @return bool
99 99
 	 */
100
-	public static function apply_query_filters( WP_Query $WP_Query ) {
101
-		return ( isset( $WP_Query->query, $WP_Query->query['post_type'] ) && $WP_Query->query['post_type'] == 'espresso_events' ) ||  apply_filters( 'FHEE__EEH_Event_Query__apply_query_filters', false ) ? true : false;
100
+	public static function apply_query_filters(WP_Query $WP_Query) {
101
+		return (isset($WP_Query->query, $WP_Query->query['post_type']) && $WP_Query->query['post_type'] == 'espresso_events') || apply_filters('FHEE__EEH_Event_Query__apply_query_filters', false) ? true : false;
102 102
 	}
103 103
 
104 104
 
@@ -108,15 +108,15 @@  discard block
 block discarded – undo
108 108
 	 * @access    public
109 109
 	 * @param \WP_Query $WP_Query
110 110
 	 */
111
-	public static function filter_query_parts( WP_Query $WP_Query ) {
111
+	public static function filter_query_parts(WP_Query $WP_Query) {
112 112
 		//ONLY add our filters if this isn't the main wp_query, because if this is the main wp_query we already have our cpt strategies take care of adding things in.
113
-		if ( $WP_Query instanceof WP_Query && ! $WP_Query->is_main_query() ) {
113
+		if ($WP_Query instanceof WP_Query && ! $WP_Query->is_main_query()) {
114 114
 			// build event list query
115
-			add_filter( 'posts_fields', array( 'EEH_Event_Query', 'posts_fields' ), 10, 2 );
116
-			add_filter( 'posts_join', array( 'EEH_Event_Query', 'posts_join' ), 10, 2 );
117
-			add_filter( 'posts_where', array( 'EEH_Event_Query', 'posts_where' ), 10, 2 );
118
-			add_filter( 'posts_orderby', array( 'EEH_Event_Query', 'posts_orderby' ), 10, 2 );
119
-			add_filter( 'posts_clauses_request', array( 'EEH_Event_Query', 'posts_clauses' ), 10, 2 );
115
+			add_filter('posts_fields', array('EEH_Event_Query', 'posts_fields'), 10, 2);
116
+			add_filter('posts_join', array('EEH_Event_Query', 'posts_join'), 10, 2);
117
+			add_filter('posts_where', array('EEH_Event_Query', 'posts_where'), 10, 2);
118
+			add_filter('posts_orderby', array('EEH_Event_Query', 'posts_orderby'), 10, 2);
119
+			add_filter('posts_clauses_request', array('EEH_Event_Query', 'posts_clauses'), 10, 2);
120 120
 		}
121 121
 	}
122 122
 
@@ -131,13 +131,13 @@  discard block
 block discarded – undo
131 131
 	 * @param string $orderby
132 132
 	 * @param string $sort
133 133
 	 */
134
-	public static function set_query_params( $month = '', $category = '', $show_expired = FALSE, $orderby = 'start_date', $sort = 'ASC' ) {
134
+	public static function set_query_params($month = '', $category = '', $show_expired = FALSE, $orderby = 'start_date', $sort = 'ASC') {
135 135
 		self::$_query_params = array();
136
-		EEH_Event_Query::$_event_query_month = EEH_Event_Query::_display_month( $month );
137
-		EEH_Event_Query::$_event_query_category = EEH_Event_Query::_event_category_slug( $category );
138
-		EEH_Event_Query::$_event_query_show_expired = EEH_Event_Query::_show_expired( $show_expired );
139
-		EEH_Event_Query::$_event_query_orderby = EEH_Event_Query::_orderby( $orderby );
140
-		EEH_Event_Query::$_event_query_sort = EEH_Event_Query::_sort( $sort );
136
+		EEH_Event_Query::$_event_query_month = EEH_Event_Query::_display_month($month);
137
+		EEH_Event_Query::$_event_query_category = EEH_Event_Query::_event_category_slug($category);
138
+		EEH_Event_Query::$_event_query_show_expired = EEH_Event_Query::_show_expired($show_expired);
139
+		EEH_Event_Query::$_event_query_orderby = EEH_Event_Query::_orderby($orderby);
140
+		EEH_Event_Query::$_event_query_sort = EEH_Event_Query::_sort($sort);
141 141
 	}
142 142
 
143 143
 
@@ -149,8 +149,8 @@  discard block
 block discarded – undo
149 149
 	 * @param string $month
150 150
 	 * @return    string
151 151
 	 */
152
-	private static function _display_month( $month = '' ) {
153
-		return EE_Registry::instance()->REQ->is_set( 'event_query_month' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_month' ) ) : $month;
152
+	private static function _display_month($month = '') {
153
+		return EE_Registry::instance()->REQ->is_set('event_query_month') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_month')) : $month;
154 154
 	}
155 155
 
156 156
 
@@ -162,8 +162,8 @@  discard block
 block discarded – undo
162 162
 	 * @param string $category
163 163
 	 * @return    string
164 164
 	 */
165
-	private static function _event_category_slug( $category = '' ) {
166
-		return EE_Registry::instance()->REQ->is_set( 'event_query_category' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_category' ) ) : $category;
165
+	private static function _event_category_slug($category = '') {
166
+		return EE_Registry::instance()->REQ->is_set('event_query_category') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_category')) : $category;
167 167
 	}
168 168
 
169 169
 
@@ -175,10 +175,10 @@  discard block
 block discarded – undo
175 175
 	 * @param bool $show_expired
176 176
 	 * @return    boolean
177 177
 	 */
178
-	private static function _show_expired( $show_expired = FALSE ) {
178
+	private static function _show_expired($show_expired = FALSE) {
179 179
 		// override default expired option if set via filter
180
-		$_event_query_show_expired =EE_Registry::instance()->REQ->is_set( 'event_query_show_expired' ) ? EE_Registry::instance()->REQ->get( 'event_query_show_expired' ) : $show_expired;
181
-		return filter_var( $_event_query_show_expired, FILTER_VALIDATE_BOOLEAN );
180
+		$_event_query_show_expired = EE_Registry::instance()->REQ->is_set('event_query_show_expired') ? EE_Registry::instance()->REQ->get('event_query_show_expired') : $show_expired;
181
+		return filter_var($_event_query_show_expired, FILTER_VALIDATE_BOOLEAN);
182 182
 	}
183 183
 
184 184
 
@@ -190,10 +190,10 @@  discard block
 block discarded – undo
190 190
 	 * @param    string $orderby
191 191
 	 * @return    array
192 192
 	 */
193
-	private static function _orderby( $orderby = 'start_date' ) {
194
-		$event_query_orderby = EE_Registry::instance()->REQ->is_set( 'event_query_orderby' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_orderby' ) ) : $orderby;
195
-		$event_query_orderby = is_array( $event_query_orderby ) ? $event_query_orderby : explode( ',', $event_query_orderby );
196
-		$event_query_orderby = array_map( 'trim', $event_query_orderby );
193
+	private static function _orderby($orderby = 'start_date') {
194
+		$event_query_orderby = EE_Registry::instance()->REQ->is_set('event_query_orderby') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_orderby')) : $orderby;
195
+		$event_query_orderby = is_array($event_query_orderby) ? $event_query_orderby : explode(',', $event_query_orderby);
196
+		$event_query_orderby = array_map('trim', $event_query_orderby);
197 197
 		return $event_query_orderby;
198 198
 	}
199 199
 
@@ -206,9 +206,9 @@  discard block
 block discarded – undo
206 206
 	 * @param string $sort
207 207
 	 * @return    array
208 208
 	 */
209
-	private static function _sort( $sort = 'ASC' ) {
210
-		$sort = EE_Registry::instance()->REQ->is_set( 'event_query_sort' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_sort' ) ) : $sort;
211
-		return in_array( $sort, array( 'ASC', 'asc', 'DESC', 'desc' )) ? strtoupper( $sort ) : 'ASC';
209
+	private static function _sort($sort = 'ASC') {
210
+		$sort = EE_Registry::instance()->REQ->is_set('event_query_sort') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_sort')) : $sort;
211
+		return in_array($sort, array('ASC', 'asc', 'DESC', 'desc')) ? strtoupper($sort) : 'ASC';
212 212
 	}
213 213
 
214 214
 
@@ -221,10 +221,10 @@  discard block
 block discarded – undo
221 221
 	 *
222 222
 	 * @return array   array of clauses
223 223
 	 */
224
-	public static function posts_clauses( $clauses, WP_Query $wp_query ) {
225
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
224
+	public static function posts_clauses($clauses, WP_Query $wp_query) {
225
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
226 226
 			global $wpdb;
227
-			$clauses['groupby'] = $wpdb->posts . '.ID ';
227
+			$clauses['groupby'] = $wpdb->posts.'.ID ';
228 228
 		}
229 229
 		return $clauses;
230 230
 	}
@@ -239,10 +239,10 @@  discard block
 block discarded – undo
239 239
 	 * @param WP_Query $wp_query
240 240
 	 * @return    string
241 241
 	 */
242
-	public static function posts_fields( $SQL, WP_Query $wp_query ) {
243
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
242
+	public static function posts_fields($SQL, WP_Query $wp_query) {
243
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
244 244
 			// adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
245
-			$SQL .= EEH_Event_Query::posts_fields_sql_for_orderby( EEH_Event_Query::$_event_query_orderby );
245
+			$SQL .= EEH_Event_Query::posts_fields_sql_for_orderby(EEH_Event_Query::$_event_query_orderby);
246 246
 		}
247 247
 		return $SQL;
248 248
 	}
@@ -257,29 +257,29 @@  discard block
 block discarded – undo
257 257
 	 * @internal  param bool|string $mixed $join_terms pass TRUE or term string, doesn't really matter since this value doesn't really get used for anything yet
258 258
 	 * @return    string
259 259
 	 */
260
-	public static function posts_fields_sql_for_orderby( $orderby_params = array() ) {
261
-		$SQL = ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ' ;
262
-		foreach( (array)$orderby_params as $orderby ) {
263
-			switch ( $orderby ) {
260
+	public static function posts_fields_sql_for_orderby($orderby_params = array()) {
261
+		$SQL = ', MIN( '.EEM_Datetime::instance()->table().'.DTT_EVT_start ) as event_start_date ';
262
+		foreach ((array) $orderby_params as $orderby) {
263
+			switch ($orderby) {
264 264
 
265 265
 				case 'ticket_start' :
266
-					$SQL .= ', ' . EEM_Ticket::instance()->table() . '.TKT_start_date' ;
266
+					$SQL .= ', '.EEM_Ticket::instance()->table().'.TKT_start_date';
267 267
 					break;
268 268
 
269 269
 				case 'ticket_end' :
270
-					$SQL .= ', ' . EEM_Ticket::instance()->table() . '.TKT_end_date' ;
270
+					$SQL .= ', '.EEM_Ticket::instance()->table().'.TKT_end_date';
271 271
 					break;
272 272
 
273 273
 				case 'venue_title' :
274
-					$SQL .= ', Venue.post_title AS venue_title' ;
274
+					$SQL .= ', Venue.post_title AS venue_title';
275 275
 					break;
276 276
 
277 277
 				case 'city' :
278
-					$SQL .= ', ' . EEM_Venue::instance()->second_table() . '.VNU_city' ;
278
+					$SQL .= ', '.EEM_Venue::instance()->second_table().'.VNU_city';
279 279
 					break;
280 280
 
281 281
 				case 'state' :
282
-					$SQL .= ', ' . EEM_State::instance()->table() . '.STA_name' ;
282
+					$SQL .= ', '.EEM_State::instance()->table().'.STA_name';
283 283
 					break;
284 284
 
285 285
 			}
@@ -297,12 +297,12 @@  discard block
 block discarded – undo
297 297
 	 * @param WP_Query $wp_query
298 298
 	 * @return    string
299 299
 	 */
300
-	public static function posts_join( $SQL = '', WP_Query $wp_query ) {
301
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
300
+	public static function posts_join($SQL = '', WP_Query $wp_query) {
301
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
302 302
 			// Category
303
-			$SQL = EEH_Event_Query::posts_join_sql_for_show_expired( $SQL, EEH_Event_Query::$_event_query_show_expired );
304
-			$SQL = EEH_Event_Query::posts_join_sql_for_terms( $SQL, EEH_Event_Query::$_event_query_category );
305
-			$SQL = EEH_Event_Query::posts_join_for_orderby( $SQL, EEH_Event_Query::$_event_query_orderby );
303
+			$SQL = EEH_Event_Query::posts_join_sql_for_show_expired($SQL, EEH_Event_Query::$_event_query_show_expired);
304
+			$SQL = EEH_Event_Query::posts_join_sql_for_terms($SQL, EEH_Event_Query::$_event_query_category);
305
+			$SQL = EEH_Event_Query::posts_join_for_orderby($SQL, EEH_Event_Query::$_event_query_orderby);
306 306
 		}
307 307
 		return $SQL;
308 308
 	}
@@ -317,11 +317,11 @@  discard block
 block discarded – undo
317 317
 	 * @param    boolean $show_expired if TRUE, then displayed past events
318 318
 	 * @return string
319 319
 	 */
320
-	public static function posts_join_sql_for_show_expired( $SQL = '', $show_expired = FALSE ) {
321
-		if ( ! $show_expired ) {
322
-			$join = EEM_Event::instance()->table() . '.ID = ' . EEM_Datetime::instance()->table() . '.' . EEM_Event::instance()->primary_key_name();
323
-			if ( strpos( $SQL, $join ) === FALSE ) {
324
-				$SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . $join . ' ) ';
320
+	public static function posts_join_sql_for_show_expired($SQL = '', $show_expired = FALSE) {
321
+		if ( ! $show_expired) {
322
+			$join = EEM_Event::instance()->table().'.ID = '.EEM_Datetime::instance()->table().'.'.EEM_Event::instance()->primary_key_name();
323
+			if (strpos($SQL, $join) === FALSE) {
324
+				$SQL .= ' INNER JOIN '.EEM_Datetime::instance()->table().' ON ( '.$join.' ) ';
325 325
 			}
326 326
 		}
327 327
 		return $SQL;
@@ -337,8 +337,8 @@  discard block
 block discarded – undo
337 337
 	 * @param 	string $join_terms pass TRUE or term string, doesn't really matter since this value doesn't really get used for anything yet
338 338
 	 * @return 	string
339 339
 	 */
340
-	public static function posts_join_sql_for_terms( $SQL = '', $join_terms = '' ) {
341
-		if ( ! empty( $join_terms ) ) {
340
+	public static function posts_join_sql_for_terms($SQL = '', $join_terms = '') {
341
+		if ( ! empty($join_terms)) {
342 342
 			global $wpdb;
343 343
 			$SQL .= " LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)";
344 344
 			$SQL .= " LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
@@ -358,25 +358,25 @@  discard block
 block discarded – undo
358 358
 	 * @param 	array $orderby_params
359 359
 	 * @return 	string
360 360
 	 */
361
-	public static function posts_join_for_orderby( $SQL = '', $orderby_params = array() ) {
362
-		foreach ( (array)$orderby_params as $orderby ) {
363
-			switch ( $orderby ) {
361
+	public static function posts_join_for_orderby($SQL = '', $orderby_params = array()) {
362
+		foreach ((array) $orderby_params as $orderby) {
363
+			switch ($orderby) {
364 364
 				case 'ticket_start' :
365 365
 				case 'ticket_end' :
366
-					$SQL .= EEH_Event_Query::_posts_join_for_datetime( $SQL, EEM_Datetime_Ticket::instance()->table() . '.' . EEM_Datetime::instance()->primary_key_name() );
367
-					$SQL .= ' LEFT JOIN ' . EEM_Ticket::instance()->table() . ' ON (' . EEM_Datetime_Ticket::instance()->table() . '.' . EEM_Ticket::instance()->primary_key_name() . ' = ' . EEM_Ticket::instance()->table() . '.' . EEM_Ticket::instance()->primary_key_name() . ' )';
366
+					$SQL .= EEH_Event_Query::_posts_join_for_datetime($SQL, EEM_Datetime_Ticket::instance()->table().'.'.EEM_Datetime::instance()->primary_key_name());
367
+					$SQL .= ' LEFT JOIN '.EEM_Ticket::instance()->table().' ON ('.EEM_Datetime_Ticket::instance()->table().'.'.EEM_Ticket::instance()->primary_key_name().' = '.EEM_Ticket::instance()->table().'.'.EEM_Ticket::instance()->primary_key_name().' )';
368 368
 					break;
369 369
 				case 'venue_title' :
370 370
 				case 'city' :
371
-					$SQL .= EEH_Event_Query::_posts_join_for_event_venue( $SQL );
371
+					$SQL .= EEH_Event_Query::_posts_join_for_event_venue($SQL);
372 372
 					break;
373 373
 				case 'state' :
374
-					$SQL .= EEH_Event_Query::_posts_join_for_event_venue( $SQL );
375
-					$SQL .= EEH_Event_Query::_posts_join_for_venue_state( $SQL );
374
+					$SQL .= EEH_Event_Query::_posts_join_for_event_venue($SQL);
375
+					$SQL .= EEH_Event_Query::_posts_join_for_venue_state($SQL);
376 376
 					break;
377 377
 				case 'start_date' :
378 378
 				default :
379
-					$SQL .= EEH_Event_Query::_posts_join_for_datetime( $SQL, EEM_Event::instance()->table() . '.ID' );
379
+					$SQL .= EEH_Event_Query::_posts_join_for_datetime($SQL, EEM_Event::instance()->table().'.ID');
380 380
 					break;
381 381
 
382 382
 			}
@@ -394,11 +394,11 @@  discard block
 block discarded – undo
394 394
 	 * @param string $join
395 395
 	 * @return string
396 396
 	 */
397
-	protected static function _posts_join_for_datetime( $SQL = '', $join = '' ) {
398
-		if ( ! empty( $join )) {
399
-			$join .= ' = ' . EEM_Datetime::instance()->table() . '.' . EEM_Event::instance()->primary_key_name();
400
-			if ( strpos( $SQL, $join ) === FALSE ) {
401
-				return ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . $join . ' )';
397
+	protected static function _posts_join_for_datetime($SQL = '', $join = '') {
398
+		if ( ! empty($join)) {
399
+			$join .= ' = '.EEM_Datetime::instance()->table().'.'.EEM_Event::instance()->primary_key_name();
400
+			if (strpos($SQL, $join) === FALSE) {
401
+				return ' INNER JOIN '.EEM_Datetime::instance()->table().' ON ( '.$join.' )';
402 402
 			}
403 403
 		}
404 404
 		return '';
@@ -413,13 +413,13 @@  discard block
 block discarded – undo
413 413
 	 * @param string $SQL
414 414
 	 * @return string
415 415
 	 */
416
-	protected static function _posts_join_for_event_venue( $SQL = '' ) {
416
+	protected static function _posts_join_for_event_venue($SQL = '') {
417 417
 		// Event Venue table name
418 418
 		$event_venue_table = EEM_Event_Venue::instance()->table();
419 419
 		// generate conditions for:  Event <=> Event Venue  JOIN clause
420
-		$event_to_event_venue_join = EEM_Event::instance()->table() . '.ID = ' . $event_venue_table . '.' . EEM_Event::instance()->primary_key_name();
420
+		$event_to_event_venue_join = EEM_Event::instance()->table().'.ID = '.$event_venue_table.'.'.EEM_Event::instance()->primary_key_name();
421 421
 		// don't add joins if they have already been added
422
-		if ( strpos( $SQL, $event_to_event_venue_join ) === FALSE ) {
422
+		if (strpos($SQL, $event_to_event_venue_join) === FALSE) {
423 423
 			// Venue table name
424 424
 			$venue_table = EEM_Venue::instance()->table();
425 425
 			// Venue table pk
@@ -432,10 +432,10 @@  discard block
 block discarded – undo
432 432
 			$venue_SQL .= " LEFT JOIN $venue_table as Venue ON ( $event_venue_table.$venue_table_pk = Venue.ID )";
433 433
 			// generate JOIN clause for: Venue <=> Venue Meta
434 434
 			$venue_SQL .= " LEFT JOIN $venue_meta_table ON ( Venue.ID = $venue_meta_table.$venue_table_pk )";
435
-			unset( $event_venue_table, $event_to_event_venue_join, $venue_table, $venue_table_pk, $venue_meta_table );
435
+			unset($event_venue_table, $event_to_event_venue_join, $venue_table, $venue_table_pk, $venue_meta_table);
436 436
 			return $venue_SQL;
437 437
 		}
438
-		unset( $event_venue_table, $event_to_event_venue_join );
438
+		unset($event_venue_table, $event_to_event_venue_join);
439 439
 		return '';
440 440
 	}
441 441
 
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
 	 * @param string $SQL
449 449
 	 * @return string
450 450
 	 */
451
-	protected static function _posts_join_for_venue_state( $SQL = '' ) {
451
+	protected static function _posts_join_for_venue_state($SQL = '') {
452 452
 		// Venue Meta table name
453 453
 		$venue_meta_table = EEM_Venue::instance()->second_table();
454 454
 		// State table name
@@ -456,16 +456,16 @@  discard block
 block discarded – undo
456 456
 		// State table pk
457 457
 		$state_table_pk = EEM_State::instance()->primary_key_name();
458 458
 		// verify vars
459
-		if ( $venue_meta_table && $state_table && $state_table_pk ) {
459
+		if ($venue_meta_table && $state_table && $state_table_pk) {
460 460
 			// like: wp_esp_venue_meta.STA_ID = wp_esp_state.STA_ID
461 461
 			$join = "$venue_meta_table.$state_table_pk = $state_table.$state_table_pk";
462 462
 			// don't add join if it has already been added
463
-			if ( strpos( $SQL, $join ) === FALSE ) {
464
-				unset( $state_table_pk, $venue_meta_table, $venue_table_pk );
463
+			if (strpos($SQL, $join) === FALSE) {
464
+				unset($state_table_pk, $venue_meta_table, $venue_table_pk);
465 465
 				return " LEFT JOIN $state_table ON ( $join )";
466 466
 			}
467 467
 		}
468
-		unset( $join, $state_table, $state_table_pk, $venue_meta_table, $venue_table_pk );
468
+		unset($join, $state_table, $state_table_pk, $venue_meta_table, $venue_table_pk);
469 469
 		return '';
470 470
 	}
471 471
 
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
 	 * @param WP_Query $wp_query
480 480
 	 * @return    string
481 481
 	 */
482
-	public static function posts_where( $SQL = '', WP_Query $wp_query ) {
483
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
482
+	public static function posts_where($SQL = '', WP_Query $wp_query) {
483
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
484 484
 			// Show Expired ?
485
-			$SQL .= EEH_Event_Query::posts_where_sql_for_show_expired( EEH_Event_Query::$_event_query_show_expired  );
485
+			$SQL .= EEH_Event_Query::posts_where_sql_for_show_expired(EEH_Event_Query::$_event_query_show_expired);
486 486
 			// Category
487
-			$SQL .= EEH_Event_Query::posts_where_sql_for_event_category_slug( EEH_Event_Query::$_event_query_category  );
487
+			$SQL .= EEH_Event_Query::posts_where_sql_for_event_category_slug(EEH_Event_Query::$_event_query_category);
488 488
 			// Start Date
489
-			$SQL .= EEH_Event_Query::posts_where_sql_for_event_list_month( EEH_Event_Query::$_event_query_month );
489
+			$SQL .= EEH_Event_Query::posts_where_sql_for_event_list_month(EEH_Event_Query::$_event_query_month);
490 490
 		}
491 491
 		return $SQL;
492 492
 	}
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 	 * @param    boolean $show_expired if TRUE, then displayed past events
501 501
 	 * @return    string
502 502
 	 */
503
-	public static function posts_where_sql_for_show_expired( $show_expired = FALSE ) {
504
-		return ! $show_expired ? ' AND ' . EEM_Datetime::instance()->table() . '.DTT_EVT_end > \'' . current_time( 'mysql', TRUE ) . '\' ' : '';
503
+	public static function posts_where_sql_for_show_expired($show_expired = FALSE) {
504
+		return ! $show_expired ? ' AND '.EEM_Datetime::instance()->table().'.DTT_EVT_end > \''.current_time('mysql', TRUE).'\' ' : '';
505 505
 	}
506 506
 
507 507
 
@@ -513,9 +513,9 @@  discard block
 block discarded – undo
513 513
 	 * @param    boolean $event_category_slug
514 514
 	 * @return    string
515 515
 	 */
516
-	public static function posts_where_sql_for_event_category_slug( $event_category_slug = NULL ) {
516
+	public static function posts_where_sql_for_event_category_slug($event_category_slug = NULL) {
517 517
 		global $wpdb;
518
-		return ! empty( $event_category_slug ) ? " AND {$wpdb->terms}.slug = '{$event_category_slug}' " : '';
518
+		return ! empty($event_category_slug) ? " AND {$wpdb->terms}.slug = '{$event_category_slug}' " : '';
519 519
 	}
520 520
 
521 521
 
@@ -527,14 +527,14 @@  discard block
 block discarded – undo
527 527
 	 * @param    boolean $month
528 528
 	 * @return    string
529 529
 	 */
530
-	public static function posts_where_sql_for_event_list_month( $month = NULL ) {
530
+	public static function posts_where_sql_for_event_list_month($month = NULL) {
531 531
 		$SQL = '';
532
-		if ( ! empty( $month ) ) {
532
+		if ( ! empty($month)) {
533 533
 			$datetime_table = EEM_Datetime::instance()->table();
534 534
 			// event start date is LESS than the end of the month ( so nothing that doesn't start until next month )
535
-			$SQL = " AND {$datetime_table}.DTT_EVT_start <= '" . date( 'Y-m-t 23:59:59', strtotime( $month ) ) . "'";
535
+			$SQL = " AND {$datetime_table}.DTT_EVT_start <= '".date('Y-m-t 23:59:59', strtotime($month))."'";
536 536
 			// event end date is GREATER than the start of the month ( so nothing that ended before this month )
537
-			$SQL .= " AND {$datetime_table}.DTT_EVT_end >= '" . date( 'Y-m-01 0:0:00', strtotime( $month ) ) . "' ";
537
+			$SQL .= " AND {$datetime_table}.DTT_EVT_end >= '".date('Y-m-01 0:0:00', strtotime($month))."' ";
538 538
 		}
539 539
 		return $SQL;
540 540
 	}
@@ -549,9 +549,9 @@  discard block
 block discarded – undo
549 549
 	 * @param WP_Query $wp_query
550 550
 	 * @return    string
551 551
 	 */
552
-	public static function posts_orderby( $SQL = '', WP_Query $wp_query ) {
553
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
554
-			$SQL = EEH_Event_Query::posts_orderby_sql( EEH_Event_Query::$_event_query_orderby, EEH_Event_Query::$_event_query_sort );
552
+	public static function posts_orderby($SQL = '', WP_Query $wp_query) {
553
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
554
+			$SQL = EEH_Event_Query::posts_orderby_sql(EEH_Event_Query::$_event_query_orderby, EEH_Event_Query::$_event_query_sort);
555 555
 		}
556 556
 		return $SQL;
557 557
 	}
@@ -582,63 +582,63 @@  discard block
 block discarded – undo
582 582
 	 * @param string     $sort
583 583
 	 * @return string
584 584
 	 */
585
-	public static function posts_orderby_sql( $orderby_params = array(), $sort = 'ASC' ) {
585
+	public static function posts_orderby_sql($orderby_params = array(), $sort = 'ASC') {
586 586
 		global $wpdb;
587 587
 		$SQL = '';
588 588
 		$counter = 0;
589 589
 		//make sure 'orderby' is set in query params
590
-		if ( ! isset( self::$_query_params['orderby'] )) {
590
+		if ( ! isset(self::$_query_params['orderby'])) {
591 591
 			self::$_query_params['orderby'] = array();
592 592
 		}
593 593
 		// loop thru $orderby_params (type cast as array)
594
-		foreach ( (array)$orderby_params as $orderby ) {
594
+		foreach ((array) $orderby_params as $orderby) {
595 595
 			// check if we have already added this param
596
-			if ( isset( self::$_query_params['orderby'][ $orderby ] )) {
596
+			if (isset(self::$_query_params['orderby'][$orderby])) {
597 597
 				// if so then remove from the $orderby_params so that the count() method below is accurate
598
-				unset( $orderby_params[ $orderby ] );
598
+				unset($orderby_params[$orderby]);
599 599
 				// then bump ahead to the next param
600 600
 				continue;
601 601
 			}
602 602
 			// this will ad a comma depending on whether this is the first or last param
603
-			$glue = $counter == 0 || $counter == count( $orderby_params ) ? ' ' : ', ';
603
+			$glue = $counter == 0 || $counter == count($orderby_params) ? ' ' : ', ';
604 604
 			// ok what's we dealing with?
605
-			switch ( $orderby ) {
605
+			switch ($orderby) {
606 606
 				case 'id' :
607 607
 				case 'ID' :
608
-					$SQL .= $glue . $wpdb->posts . '.ID ' . $sort;
608
+					$SQL .= $glue.$wpdb->posts.'.ID '.$sort;
609 609
 					break;
610 610
 				case 'end_date' :
611
-					$SQL .= $glue . EEM_Datetime::instance()->table() . '.DTT_EVT_end ' . $sort;
611
+					$SQL .= $glue.EEM_Datetime::instance()->table().'.DTT_EVT_end '.$sort;
612 612
 					break;
613 613
 				case 'event_name' :
614
-					$SQL .= $glue . $wpdb->posts . '.post_title ' . $sort;
614
+					$SQL .= $glue.$wpdb->posts.'.post_title '.$sort;
615 615
 					break;
616 616
 				case 'category_slug' :
617
-					$SQL .= $glue . $wpdb->terms . '.slug ' . $sort;
617
+					$SQL .= $glue.$wpdb->terms.'.slug '.$sort;
618 618
 					break;
619 619
 				case 'ticket_start' :
620
-					$SQL .= $glue . EEM_Ticket::instance()->table() . '.TKT_start_date ' . $sort;
620
+					$SQL .= $glue.EEM_Ticket::instance()->table().'.TKT_start_date '.$sort;
621 621
 					break;
622 622
 				case 'ticket_end' :
623
-					$SQL .= $glue . EEM_Ticket::instance()->table() . '.TKT_end_date ' . $sort;
623
+					$SQL .= $glue.EEM_Ticket::instance()->table().'.TKT_end_date '.$sort;
624 624
 					break;
625 625
 				case 'venue_title' :
626
-					$SQL .= $glue . 'venue_title ' . $sort;
626
+					$SQL .= $glue.'venue_title '.$sort;
627 627
 					break;
628 628
 				case 'city' :
629
-					$SQL .= $glue . EEM_Venue::instance()->second_table() . '.VNU_city ' . $sort;
629
+					$SQL .= $glue.EEM_Venue::instance()->second_table().'.VNU_city '.$sort;
630 630
 					break;
631 631
 				case 'state' :
632
-					$SQL .= $glue . EEM_State::instance()->table() . '.STA_name ' . $sort;
632
+					$SQL .= $glue.EEM_State::instance()->table().'.STA_name '.$sort;
633 633
 					break;
634 634
 				case 'start_date' :
635 635
 				default :
636
-					$SQL .= $glue . ' event_start_date ' . $sort;
636
+					$SQL .= $glue.' event_start_date '.$sort;
637 637
 					break;
638 638
 			}
639 639
 			// add to array of orderby params that have been added
640
-			self::$_query_params['orderby'][ $orderby ] = TRUE;
641
-			$counter ++;
640
+			self::$_query_params['orderby'][$orderby] = TRUE;
641
+			$counter++;
642 642
 		}
643 643
 		return $SQL;
644 644
 	}
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
     {
176 176
         // set autoloaders for all of the classes implementing EEI_Plugin_API
177 177
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
178
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
178
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
179 179
         //load and setup EE_Capabilities
180 180
         $this->registry->load_core('Capabilities');
181 181
         //caps need to be initialized on every request so that capability maps are set.
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
                 && $_GET['activate'] === 'true'
199 199
             )
200 200
         ) {
201
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
201
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
202 202
         }
203 203
     }
204 204
 
@@ -621,7 +621,7 @@  discard block
 block discarded – undo
621 621
     private function _parse_model_names()
622 622
     {
623 623
         //get all the files in the EE_MODELS folder that end in .model.php
624
-        $models = glob(EE_MODELS . '*.model.php');
624
+        $models = glob(EE_MODELS.'*.model.php');
625 625
         $model_names = array();
626 626
         $non_abstract_db_models = array();
627 627
         foreach ($models as $model) {
@@ -649,8 +649,8 @@  discard block
 block discarded – undo
649 649
      */
650 650
     private function _maybe_brew_regular()
651 651
     {
652
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
653
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
652
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
653
+            require_once EE_CAFF_PATH.'brewing_regular.php';
654 654
         }
655 655
     }
656 656
 
@@ -691,8 +691,8 @@  discard block
 block discarded – undo
691 691
                 'event_espresso');
692 692
             $msg .= '<ul>';
693 693
             foreach ($class_names as $class_name) {
694
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
695
-                        $class_name) . '</b></li>';
694
+                $msg .= '<li><b>Event Espresso - '.str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
695
+                        $class_name).'</b></li>';
696 696
             }
697 697
             $msg .= '</ul>';
698 698
             $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
             'href'  => $events_admin_url,
988 988
             'meta'  => array(
989 989
                 'title' => __('Event Espresso', 'event_espresso'),
990
-                'class' => $menu_class . 'first',
990
+                'class' => $menu_class.'first',
991 991
             ),
992 992
         ));
993 993
         //Events
@@ -1364,10 +1364,10 @@  discard block
 block discarded – undo
1364 1364
             // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1365 1365
             if (apply_filters('FHEE_load_jquery_validate', false)) {
1366 1366
                 // register jQuery Validate and additional methods
1367
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1367
+                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
1368 1368
                     array('jquery'), '1.15.0', true);
1369 1369
                 wp_register_script('jquery-validate-extra-methods',
1370
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1370
+                    EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
1371 1371
                     array('jquery', 'jquery-validate'), '1.15.0', true);
1372 1372
             }
1373 1373
         }
Please login to merge, or discard this patch.
Indentation   +1423 added lines, -1423 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -16,1428 +16,1428 @@  discard block
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
21
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
22
-     */
23
-    const req_type_normal = 0;
24
-
25
-    /**
26
-     * Indicates this is a brand new installation of EE so we should install
27
-     * tables and default data etc
28
-     */
29
-    const req_type_new_activation = 1;
30
-
31
-    /**
32
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
33
-     * and we just exited maintenance mode). We MUST check the database is setup properly
34
-     * and that default data is setup too
35
-     */
36
-    const req_type_reactivation = 2;
37
-
38
-    /**
39
-     * indicates that EE has been upgraded since its previous request.
40
-     * We may have data migration scripts to call and will want to trigger maintenance mode
41
-     */
42
-    const req_type_upgrade = 3;
43
-
44
-    /**
45
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
46
-     */
47
-    const req_type_downgrade = 4;
48
-
49
-    /**
50
-     * @deprecated since version 4.6.0.dev.006
51
-     * Now whenever a new_activation is detected the request type is still just
52
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
53
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
54
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
55
-     * (Specifically, when the migration manager indicates migrations are finished
56
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
57
-     */
58
-    const req_type_activation_but_not_installed = 5;
59
-
60
-    /**
61
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
62
-     */
63
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
64
-
65
-
66
-    /**
67
-     *    instance of the EE_System object
68
-     *
69
-     * @var    $_instance
70
-     * @access    private
71
-     */
72
-    private static $_instance = null;
73
-
74
-    /**
75
-     * @type  EE_Registry $Registry
76
-     * @access    protected
77
-     */
78
-    protected $registry;
79
-
80
-    /**
81
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
82
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
83
-     *
84
-     * @var int
85
-     */
86
-    private $_req_type;
87
-
88
-    /**
89
-     * Whether or not there was a non-micro version change in EE core version during this request
90
-     *
91
-     * @var boolean
92
-     */
93
-    private $_major_version_change = false;
94
-
95
-
96
-
97
-    /**
98
-     * @singleton method used to instantiate class object
99
-     * @access    public
100
-     * @param  \EE_Registry $Registry
101
-     * @return \EE_System
102
-     */
103
-    public static function instance(EE_Registry $Registry = null)
104
-    {
105
-        // check if class object is instantiated
106
-        if ( ! self::$_instance instanceof EE_System) {
107
-            self::$_instance = new self($Registry);
108
-        }
109
-        return self::$_instance;
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * resets the instance and returns it
116
-     *
117
-     * @return EE_System
118
-     */
119
-    public static function reset()
120
-    {
121
-        self::$_instance->_req_type = null;
122
-        //make sure none of the old hooks are left hanging around
123
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
124
-        //we need to reset the migration manager in order for it to detect DMSs properly
125
-        EE_Data_Migration_Manager::reset();
126
-        self::instance()->detect_activations_or_upgrades();
127
-        self::instance()->perform_activations_upgrades_and_migrations();
128
-        return self::instance();
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     *    sets hooks for running rest of system
135
-     *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
136
-     *    starting EE Addons from any other point may lead to problems
137
-     *
138
-     * @access private
139
-     * @param  \EE_Registry $Registry
140
-     */
141
-    private function __construct(EE_Registry $Registry)
142
-    {
143
-        $this->registry = $Registry;
144
-        do_action('AHEE__EE_System__construct__begin', $this);
145
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
146
-        add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
147
-        // when an ee addon is activated, we want to call the core hook(s) again
148
-        // because the newly-activated addon didn't get a chance to run at all
149
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
150
-        // detect whether install or upgrade
151
-        add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
152
-            3);
153
-        // load EE_Config, EE_Textdomain, etc
154
-        add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
155
-        // load EE_Config, EE_Textdomain, etc
156
-        add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
157
-            array($this, 'register_shortcodes_modules_and_widgets'), 7);
158
-        // you wanna get going? I wanna get going... let's get going!
159
-        add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
160
-        //other housekeeping
161
-        //exclude EE critical pages from wp_list_pages
162
-        add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
163
-        // ALL EE Addons should use the following hook point to attach their initial setup too
164
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
165
-        do_action('AHEE__EE_System__construct__complete', $this);
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     * load_espresso_addons
172
-     * allow addons to load first so that they can set hooks for running DMS's, etc
173
-     * this is hooked into both:
174
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
175
-     *        which runs during the WP 'plugins_loaded' action at priority 5
176
-     *    and the WP 'activate_plugin' hookpoint
177
-     *
178
-     * @access public
179
-     * @return void
180
-     */
181
-    public function load_espresso_addons()
182
-    {
183
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
184
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
185
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
186
-        //load and setup EE_Capabilities
187
-        $this->registry->load_core('Capabilities');
188
-        //caps need to be initialized on every request so that capability maps are set.
189
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
190
-        $this->registry->CAP->init_caps();
191
-        do_action('AHEE__EE_System__load_espresso_addons');
192
-        //if the WP API basic auth plugin isn't already loaded, load it now.
193
-        //We want it for mobile apps. Just include the entire plugin
194
-        //also, don't load the basic auth when a plugin is getting activated, because
195
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
-        //and causes a fatal error
197
-        if ( ! function_exists('json_basic_auth_handler')
198
-             && ! function_exists('json_basic_auth_error')
199
-             && ! (
200
-                isset($_GET['action'])
201
-                && in_array($_GET['action'], array('activate', 'activate-selected'))
202
-            )
203
-             && ! (
204
-                isset($_GET['activate'])
205
-                && $_GET['activate'] === 'true'
206
-            )
207
-        ) {
208
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
-        }
210
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * detect_activations_or_upgrades
217
-     * Checks for activation or upgrade of core first;
218
-     * then also checks if any registered addons have been activated or upgraded
219
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
220
-     * which runs during the WP 'plugins_loaded' action at priority 3
221
-     *
222
-     * @access public
223
-     * @return void
224
-     */
225
-    public function detect_activations_or_upgrades()
226
-    {
227
-        //first off: let's make sure to handle core
228
-        $this->detect_if_activation_or_upgrade();
229
-        foreach ($this->registry->addons as $addon) {
230
-            //detect teh request type for that addon
231
-            $addon->detect_activation_or_upgrade();
232
-        }
233
-    }
234
-
235
-
236
-
237
-    /**
238
-     * detect_if_activation_or_upgrade
239
-     * Takes care of detecting whether this is a brand new install or code upgrade,
240
-     * and either setting up the DB or setting up maintenance mode etc.
241
-     *
242
-     * @access public
243
-     * @return void
244
-     */
245
-    public function detect_if_activation_or_upgrade()
246
-    {
247
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
248
-        // load M-Mode class
249
-        $this->registry->load_core('Maintenance_Mode');
250
-        // check if db has been updated, or if its a brand-new installation
251
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
252
-        $request_type = $this->detect_req_type($espresso_db_update);
253
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
254
-        switch ($request_type) {
255
-            case EE_System::req_type_new_activation:
256
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
257
-                $this->_handle_core_version_change($espresso_db_update);
258
-                break;
259
-            case EE_System::req_type_reactivation:
260
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
261
-                $this->_handle_core_version_change($espresso_db_update);
262
-                break;
263
-            case EE_System::req_type_upgrade:
264
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
265
-                //migrations may be required now that we've upgraded
266
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
267
-                $this->_handle_core_version_change($espresso_db_update);
268
-                //				echo "done upgrade";die;
269
-                break;
270
-            case EE_System::req_type_downgrade:
271
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
272
-                //its possible migrations are no longer required
273
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
274
-                $this->_handle_core_version_change($espresso_db_update);
275
-                break;
276
-            case EE_System::req_type_normal:
277
-            default:
278
-                //				$this->_maybe_redirect_to_ee_about();
279
-                break;
280
-        }
281
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
282
-    }
283
-
284
-
285
-
286
-    /**
287
-     * Updates the list of installed versions and sets hooks for
288
-     * initializing the database later during the request
289
-     *
290
-     * @param array $espresso_db_update
291
-     */
292
-    protected function _handle_core_version_change($espresso_db_update)
293
-    {
294
-        $this->update_list_of_installed_versions($espresso_db_update);
295
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
296
-        add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
297
-            array($this, 'initialize_db_if_no_migrations_required'));
298
-    }
299
-
300
-
301
-
302
-    /**
303
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
304
-     * information about what versions of EE have been installed and activated,
305
-     * NOT necessarily the state of the database
306
-     *
307
-     * @param null $espresso_db_update
308
-     * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
309
-     *           from the options table
310
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
311
-     */
312
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
313
-    {
314
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
315
-        if ( ! $espresso_db_update) {
316
-            $espresso_db_update = get_option('espresso_db_update');
317
-        }
318
-        // check that option is an array
319
-        if ( ! is_array($espresso_db_update)) {
320
-            // if option is FALSE, then it never existed
321
-            if ($espresso_db_update === false) {
322
-                // make $espresso_db_update an array and save option with autoload OFF
323
-                $espresso_db_update = array();
324
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
325
-            } else {
326
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
327
-                $espresso_db_update = array($espresso_db_update => array());
328
-                update_option('espresso_db_update', $espresso_db_update);
329
-            }
330
-        } else {
331
-            $corrected_db_update = array();
332
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
333
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
334
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
335
-                    //the key is an int, and the value IS NOT an array
336
-                    //so it must be numerically-indexed, where values are versions installed...
337
-                    //fix it!
338
-                    $version_string = $should_be_array;
339
-                    $corrected_db_update[$version_string] = array('unknown-date');
340
-                } else {
341
-                    //ok it checks out
342
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
343
-                }
344
-            }
345
-            $espresso_db_update = $corrected_db_update;
346
-            update_option('espresso_db_update', $espresso_db_update);
347
-        }
348
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
349
-        return $espresso_db_update;
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * Does the traditional work of setting up the plugin's database and adding default data.
356
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
357
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
358
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
359
-     * so that it will be done when migrations are finished
360
-     *
361
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
362
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
363
-     *                                       This is a resource-intensive job
364
-     *                                       so we prefer to only do it when necessary
365
-     * @return void
366
-     */
367
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
368
-    {
369
-        $request_type = $this->detect_req_type();
370
-        //only initialize system if we're not in maintenance mode.
371
-        if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
372
-            update_option('ee_flush_rewrite_rules', true);
373
-            if ($verify_schema) {
374
-                EEH_Activation::initialize_db_and_folders();
375
-            }
376
-            EEH_Activation::initialize_db_content();
377
-            EEH_Activation::system_initialization();
378
-            if ($initialize_addons_too) {
379
-                $this->initialize_addons();
380
-            }
381
-        } else {
382
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
383
-        }
384
-        if ($request_type === EE_System::req_type_new_activation
385
-            || $request_type === EE_System::req_type_reactivation
386
-            || (
387
-                $request_type === EE_System::req_type_upgrade
388
-                && $this->is_major_version_change()
389
-            )
390
-        ) {
391
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
392
-        }
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * Initializes the db for all registered addons
399
-     */
400
-    public function initialize_addons()
401
-    {
402
-        //foreach registered addon, make sure its db is up-to-date too
403
-        foreach ($this->registry->addons as $addon) {
404
-            $addon->initialize_db_if_no_migrations_required();
405
-        }
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
412
-     *
413
-     * @param    array  $version_history
414
-     * @param    string $current_version_to_add version to be added to the version history
415
-     * @return    boolean success as to whether or not this option was changed
416
-     */
417
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
418
-    {
419
-        if ( ! $version_history) {
420
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
421
-        }
422
-        if ($current_version_to_add == null) {
423
-            $current_version_to_add = espresso_version();
424
-        }
425
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
426
-        // re-save
427
-        return update_option('espresso_db_update', $version_history);
428
-    }
429
-
430
-
431
-
432
-    /**
433
-     * Detects if the current version indicated in the has existed in the list of
434
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
435
-     *
436
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
437
-     *                                  If not supplied, fetches it from the options table.
438
-     *                                  Also, caches its result so later parts of the code can also know whether
439
-     *                                  there's been an update or not. This way we can add the current version to
440
-     *                                  espresso_db_update, but still know if this is a new install or not
441
-     * @return int one of the constants on EE_System::req_type_
442
-     */
443
-    public function detect_req_type($espresso_db_update = null)
444
-    {
445
-        if ($this->_req_type === null) {
446
-            $espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
447
-                : $this->fix_espresso_db_upgrade_option();
448
-            $this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
449
-                'ee_espresso_activation', espresso_version());
450
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
451
-        }
452
-        return $this->_req_type;
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     * Returns whether or not there was a non-micro version change (ie, change in either
459
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
460
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
461
-     *
462
-     * @param $activation_history
463
-     * @return bool
464
-     */
465
-    protected function _detect_major_version_change($activation_history)
466
-    {
467
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
468
-        $previous_version_parts = explode('.', $previous_version);
469
-        $current_version_parts = explode('.', espresso_version());
470
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
471
-               && ($previous_version_parts[0] !== $current_version_parts[0]
472
-                   || $previous_version_parts[1] !== $current_version_parts[1]
473
-               );
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * Returns true if either the major or minor version of EE changed during this request.
480
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
481
-     *
482
-     * @return bool
483
-     */
484
-    public function is_major_version_change()
485
-    {
486
-        return $this->_major_version_change;
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
493
-     * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
494
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
495
-     * just activated to (for core that will always be espresso_version())
496
-     *
497
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
498
-     *                                                 ee plugin. for core that's 'espresso_db_update'
499
-     * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
500
-     *                                                 indicate that this plugin was just activated
501
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
502
-     *                                                 espresso_version())
503
-     * @return int one of the constants on EE_System::req_type_*
504
-     */
505
-    public static function detect_req_type_given_activation_history(
506
-        $activation_history_for_addon,
507
-        $activation_indicator_option_name,
508
-        $version_to_upgrade_to
509
-    ) {
510
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
511
-        if ($activation_history_for_addon) {
512
-            //it exists, so this isn't a completely new install
513
-            //check if this version already in that list of previously installed versions
514
-            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
515
-                //it a version we haven't seen before
516
-                if ($version_is_higher === 1) {
517
-                    $req_type = EE_System::req_type_upgrade;
518
-                } else {
519
-                    $req_type = EE_System::req_type_downgrade;
520
-                }
521
-                delete_option($activation_indicator_option_name);
522
-            } else {
523
-                // its not an update. maybe a reactivation?
524
-                if (get_option($activation_indicator_option_name, false)) {
525
-                    if ($version_is_higher === -1) {
526
-                        $req_type = EE_System::req_type_downgrade;
527
-                    } elseif ($version_is_higher === 0) {
528
-                        //we've seen this version before, but it's an activation. must be a reactivation
529
-                        $req_type = EE_System::req_type_reactivation;
530
-                    } else {//$version_is_higher === 1
531
-                        $req_type = EE_System::req_type_upgrade;
532
-                    }
533
-                    delete_option($activation_indicator_option_name);
534
-                } else {
535
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
536
-                    if ($version_is_higher === -1) {
537
-                        $req_type = EE_System::req_type_downgrade;
538
-                    } elseif ($version_is_higher === 0) {
539
-                        //we've seen this version before and it's not an activation. its normal request
540
-                        $req_type = EE_System::req_type_normal;
541
-                    } else {//$version_is_higher === 1
542
-                        $req_type = EE_System::req_type_upgrade;
543
-                    }
544
-                }
545
-            }
546
-        } else {
547
-            //brand new install
548
-            $req_type = EE_System::req_type_new_activation;
549
-            delete_option($activation_indicator_option_name);
550
-        }
551
-        return $req_type;
552
-    }
553
-
554
-
555
-
556
-    /**
557
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
558
-     * the $activation_history_for_addon
559
-     *
560
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
561
-     *                                             sometimes containing 'unknown-date'
562
-     * @param string $version_to_upgrade_to        (current version)
563
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
564
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
565
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
566
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
567
-     */
568
-    protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
569
-    {
570
-        //find the most recently-activated version
571
-        $most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
572
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * Gets the most recently active version listed in the activation history,
579
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
580
-     *
581
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
582
-     *                                   sometimes containing 'unknown-date'
583
-     * @return string
584
-     */
585
-    protected static function _get_most_recently_active_version_from_activation_history($activation_history)
586
-    {
587
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
588
-        $most_recently_active_version = '0.0.0.dev.000';
589
-        if (is_array($activation_history)) {
590
-            foreach ($activation_history as $version => $times_activated) {
591
-                //check there is a record of when this version was activated. Otherwise,
592
-                //mark it as unknown
593
-                if ( ! $times_activated) {
594
-                    $times_activated = array('unknown-date');
595
-                }
596
-                if (is_string($times_activated)) {
597
-                    $times_activated = array($times_activated);
598
-                }
599
-                foreach ($times_activated as $an_activation) {
600
-                    if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
601
-                        $most_recently_active_version = $version;
602
-                        $most_recently_active_version_activation = $an_activation == 'unknown-date'
603
-                            ? '1970-01-01 00:00:00' : $an_activation;
604
-                    }
605
-                }
606
-            }
607
-        }
608
-        return $most_recently_active_version;
609
-    }
610
-
611
-
612
-
613
-    /**
614
-     * This redirects to the about EE page after activation
615
-     *
616
-     * @return void
617
-     */
618
-    public function redirect_to_about_ee()
619
-    {
620
-        $notices = EE_Error::get_notices(false);
621
-        //if current user is an admin and it's not an ajax or rest request
622
-        if (
623
-            ! (defined('DOING_AJAX') && DOING_AJAX)
624
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
625
-            && ! isset($notices['errors'])
626
-            && apply_filters(
627
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
628
-                $this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
629
-            )
630
-        ) {
631
-            $query_params = array('page' => 'espresso_about');
632
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
633
-                $query_params['new_activation'] = true;
634
-            }
635
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
636
-                $query_params['reactivation'] = true;
637
-            }
638
-            $url = add_query_arg($query_params, admin_url('admin.php'));
639
-            wp_safe_redirect($url);
640
-            exit();
641
-        }
642
-    }
643
-
644
-
645
-
646
-    /**
647
-     * load_core_configuration
648
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
649
-     * which runs during the WP 'plugins_loaded' action at priority 5
650
-     *
651
-     * @return void
652
-     */
653
-    public function load_core_configuration()
654
-    {
655
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
656
-        $this->registry->load_core('EE_Load_Textdomain');
657
-        //load textdomain
658
-        EE_Load_Textdomain::load_textdomain();
659
-        // load and setup EE_Config and EE_Network_Config
660
-        $this->registry->load_core('Config');
661
-        $this->registry->load_core('Network_Config');
662
-        // setup autoloaders
663
-        // enable logging?
664
-        if ($this->registry->CFG->admin->use_full_logging) {
665
-            $this->registry->load_core('Log');
666
-        }
667
-        // check for activation errors
668
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
669
-        if ($activation_errors) {
670
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
671
-            update_option('ee_plugin_activation_errors', false);
672
-        }
673
-        // get model names
674
-        $this->_parse_model_names();
675
-        //load caf stuff a chance to play during the activation process too.
676
-        $this->_maybe_brew_regular();
677
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
684
-     *
685
-     * @return void
686
-     */
687
-    private function _parse_model_names()
688
-    {
689
-        //get all the files in the EE_MODELS folder that end in .model.php
690
-        $models = glob(EE_MODELS . '*.model.php');
691
-        $model_names = array();
692
-        $non_abstract_db_models = array();
693
-        foreach ($models as $model) {
694
-            // get model classname
695
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
696
-            $short_name = str_replace('EEM_', '', $classname);
697
-            $reflectionClass = new ReflectionClass($classname);
698
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
699
-                $non_abstract_db_models[$short_name] = $classname;
700
-            }
701
-            $model_names[$short_name] = $classname;
702
-        }
703
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
704
-        $this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
705
-            $non_abstract_db_models);
706
-    }
707
-
708
-
709
-
710
-    /**
711
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
712
-     * that need to be setup before our EE_System launches.
713
-     *
714
-     * @return void
715
-     */
716
-    private function _maybe_brew_regular()
717
-    {
718
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
720
-        }
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * register_shortcodes_modules_and_widgets
727
-     * generate lists of shortcodes and modules, then verify paths and classes
728
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
729
-     * which runs during the WP 'plugins_loaded' action at priority 7
730
-     *
731
-     * @access public
732
-     * @return void
733
-     */
734
-    public function register_shortcodes_modules_and_widgets()
735
-    {
736
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
737
-        // check for addons using old hookpoint
738
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
739
-            $this->_incompatible_addon_error();
740
-        }
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     * _incompatible_addon_error
747
-     *
748
-     * @access public
749
-     * @return void
750
-     */
751
-    private function _incompatible_addon_error()
752
-    {
753
-        // get array of classes hooking into here
754
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
755
-        if ( ! empty($class_names)) {
756
-            $msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
757
-                'event_espresso');
758
-            $msg .= '<ul>';
759
-            foreach ($class_names as $class_name) {
760
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
-                        $class_name) . '</b></li>';
762
-            }
763
-            $msg .= '</ul>';
764
-            $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
765
-                'event_espresso');
766
-            // save list of incompatible addons to wp-options for later use
767
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
768
-            if (is_admin()) {
769
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
770
-            }
771
-        }
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * brew_espresso
778
-     * begins the process of setting hooks for initializing EE in the correct order
779
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
780
-     * which runs during the WP 'plugins_loaded' action at priority 9
781
-     *
782
-     * @return void
783
-     */
784
-    public function brew_espresso()
785
-    {
786
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
787
-        // load some final core systems
788
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
789
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
790
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
791
-        add_action('init', array($this, 'load_controllers'), 7);
792
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
793
-        add_action('init', array($this, 'initialize'), 10);
794
-        add_action('init', array($this, 'initialize_last'), 100);
795
-        add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
796
-        add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
797
-        add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
798
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
799
-            // pew pew pew
800
-            $this->registry->load_core('PUE');
801
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
802
-        }
803
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
804
-    }
805
-
806
-
807
-
808
-    /**
809
-     *    set_hooks_for_core
810
-     *
811
-     * @access public
812
-     * @return    void
813
-     */
814
-    public function set_hooks_for_core()
815
-    {
816
-        $this->_deactivate_incompatible_addons();
817
-        do_action('AHEE__EE_System__set_hooks_for_core');
818
-    }
819
-
820
-
821
-
822
-    /**
823
-     * Using the information gathered in EE_System::_incompatible_addon_error,
824
-     * deactivates any addons considered incompatible with the current version of EE
825
-     */
826
-    private function _deactivate_incompatible_addons()
827
-    {
828
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
829
-        if ( ! empty($incompatible_addons)) {
830
-            $active_plugins = get_option('active_plugins', array());
831
-            foreach ($active_plugins as $active_plugin) {
832
-                foreach ($incompatible_addons as $incompatible_addon) {
833
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
834
-                        unset($_GET['activate']);
835
-                        espresso_deactivate_plugin($active_plugin);
836
-                    }
837
-                }
838
-            }
839
-        }
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     *    perform_activations_upgrades_and_migrations
846
-     *
847
-     * @access public
848
-     * @return    void
849
-     */
850
-    public function perform_activations_upgrades_and_migrations()
851
-    {
852
-        //first check if we had previously attempted to setup EE's directories but failed
853
-        if (EEH_Activation::upload_directories_incomplete()) {
854
-            EEH_Activation::create_upload_directories();
855
-        }
856
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
857
-    }
858
-
859
-
860
-
861
-    /**
862
-     *    load_CPTs_and_session
863
-     *
864
-     * @access public
865
-     * @return    void
866
-     */
867
-    public function load_CPTs_and_session()
868
-    {
869
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
870
-        // register Custom Post Types
871
-        $this->registry->load_core('Register_CPTs');
872
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
873
-    }
874
-
875
-
876
-
877
-    /**
878
-     * load_controllers
879
-     * this is the best place to load any additional controllers that needs access to EE core.
880
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
881
-     * time
882
-     *
883
-     * @access public
884
-     * @return void
885
-     */
886
-    public function load_controllers()
887
-    {
888
-        do_action('AHEE__EE_System__load_controllers__start');
889
-        // let's get it started
890
-        if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
891
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
892
-            $this->registry->load_core('Front_Controller', array(), false, true);
893
-        } else if ( ! EE_FRONT_AJAX) {
894
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
895
-            EE_Registry::instance()->load_core('Admin');
896
-        }
897
-        do_action('AHEE__EE_System__load_controllers__complete');
898
-    }
899
-
900
-
901
-
902
-    /**
903
-     * core_loaded_and_ready
904
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
905
-     *
906
-     * @access public
907
-     * @return void
908
-     */
909
-    public function core_loaded_and_ready()
910
-    {
911
-        do_action('AHEE__EE_System__core_loaded_and_ready');
912
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
913
-        $this->registry->load_core('Session');
914
-        //		add_action( 'wp_loaded', array( $this, 'set_hooks_for_shortcodes_modules_and_addons' ), 1 );
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * initialize
921
-     * this is the best place to begin initializing client code
922
-     *
923
-     * @access public
924
-     * @return void
925
-     */
926
-    public function initialize()
927
-    {
928
-        do_action('AHEE__EE_System__initialize');
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * initialize_last
935
-     * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
936
-     * initialize has done so
937
-     *
938
-     * @access public
939
-     * @return void
940
-     */
941
-    public function initialize_last()
942
-    {
943
-        do_action('AHEE__EE_System__initialize_last');
944
-    }
945
-
946
-
947
-
948
-    /**
949
-     * set_hooks_for_shortcodes_modules_and_addons
950
-     * this is the best place for other systems to set callbacks for hooking into other parts of EE
951
-     * this happens at the very beginning of the wp_loaded hookpoint
952
-     *
953
-     * @access public
954
-     * @return void
955
-     */
956
-    public function set_hooks_for_shortcodes_modules_and_addons()
957
-    {
958
-        //		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
959
-    }
960
-
961
-
962
-
963
-    /**
964
-     * do_not_cache
965
-     * sets no cache headers and defines no cache constants for WP plugins
966
-     *
967
-     * @access public
968
-     * @return void
969
-     */
970
-    public static function do_not_cache()
971
-    {
972
-        // set no cache constants
973
-        if ( ! defined('DONOTCACHEPAGE')) {
974
-            define('DONOTCACHEPAGE', true);
975
-        }
976
-        if ( ! defined('DONOTCACHCEOBJECT')) {
977
-            define('DONOTCACHCEOBJECT', true);
978
-        }
979
-        if ( ! defined('DONOTCACHEDB')) {
980
-            define('DONOTCACHEDB', true);
981
-        }
982
-        // add no cache headers
983
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
984
-        // plus a little extra for nginx and Google Chrome
985
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
986
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
987
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
988
-    }
989
-
990
-
991
-
992
-    /**
993
-     *    extra_nocache_headers
994
-     *
995
-     * @access    public
996
-     * @param $headers
997
-     * @return    array
998
-     */
999
-    public static function extra_nocache_headers($headers)
1000
-    {
1001
-        // for NGINX
1002
-        $headers['X-Accel-Expires'] = 0;
1003
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1004
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1005
-        return $headers;
1006
-    }
1007
-
1008
-
1009
-
1010
-    /**
1011
-     *    nocache_headers
1012
-     *
1013
-     * @access    public
1014
-     * @return    void
1015
-     */
1016
-    public static function nocache_headers()
1017
-    {
1018
-        nocache_headers();
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     *    espresso_toolbar_items
1025
-     *
1026
-     * @access public
1027
-     * @param  WP_Admin_Bar $admin_bar
1028
-     * @return void
1029
-     */
1030
-    public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1031
-    {
1032
-        // if in full M-Mode, or its an AJAX request, or user is NOT an admin
1033
-        if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1034
-            || defined('DOING_AJAX')
1035
-            || ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1036
-        ) {
1037
-            return;
1038
-        }
1039
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1040
-        $menu_class = 'espresso_menu_item_class';
1041
-        //we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1042
-        //because they're only defined in each of their respective constructors
1043
-        //and this might be a frontend request, in which case they aren't available
1044
-        $events_admin_url = admin_url("admin.php?page=espresso_events");
1045
-        $reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1046
-        $extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1047
-        //Top Level
1048
-        $admin_bar->add_menu(array(
1049
-            'id'    => 'espresso-toolbar',
1050
-            'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1051
-                       . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1052
-                       . '</span>',
1053
-            'href'  => $events_admin_url,
1054
-            'meta'  => array(
1055
-                'title' => __('Event Espresso', 'event_espresso'),
1056
-                'class' => $menu_class . 'first',
1057
-            ),
1058
-        ));
1059
-        //Events
1060
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1061
-            $admin_bar->add_menu(array(
1062
-                'id'     => 'espresso-toolbar-events',
1063
-                'parent' => 'espresso-toolbar',
1064
-                'title'  => __('Events', 'event_espresso'),
1065
-                'href'   => $events_admin_url,
1066
-                'meta'   => array(
1067
-                    'title'  => __('Events', 'event_espresso'),
1068
-                    'target' => '',
1069
-                    'class'  => $menu_class,
1070
-                ),
1071
-            ));
1072
-        }
1073
-        if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1074
-            //Events Add New
1075
-            $admin_bar->add_menu(array(
1076
-                'id'     => 'espresso-toolbar-events-new',
1077
-                'parent' => 'espresso-toolbar-events',
1078
-                'title'  => __('Add New', 'event_espresso'),
1079
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1080
-                'meta'   => array(
1081
-                    'title'  => __('Add New', 'event_espresso'),
1082
-                    'target' => '',
1083
-                    'class'  => $menu_class,
1084
-                ),
1085
-            ));
1086
-        }
1087
-        if (is_single() && (get_post_type() == 'espresso_events')) {
1088
-            //Current post
1089
-            global $post;
1090
-            if ($this->registry->CAP->current_user_can('ee_edit_event',
1091
-                'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1092
-            ) {
1093
-                //Events Edit Current Event
1094
-                $admin_bar->add_menu(array(
1095
-                    'id'     => 'espresso-toolbar-events-edit',
1096
-                    'parent' => 'espresso-toolbar-events',
1097
-                    'title'  => __('Edit Event', 'event_espresso'),
1098
-                    'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1099
-                        $events_admin_url),
1100
-                    'meta'   => array(
1101
-                        'title'  => __('Edit Event', 'event_espresso'),
1102
-                        'target' => '',
1103
-                        'class'  => $menu_class,
1104
-                    ),
1105
-                ));
1106
-            }
1107
-        }
1108
-        //Events View
1109
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1110
-            'ee_admin_bar_menu_espresso-toolbar-events-view')
1111
-        ) {
1112
-            $admin_bar->add_menu(array(
1113
-                'id'     => 'espresso-toolbar-events-view',
1114
-                'parent' => 'espresso-toolbar-events',
1115
-                'title'  => __('View', 'event_espresso'),
1116
-                'href'   => $events_admin_url,
1117
-                'meta'   => array(
1118
-                    'title'  => __('View', 'event_espresso'),
1119
-                    'target' => '',
1120
-                    'class'  => $menu_class,
1121
-                ),
1122
-            ));
1123
-        }
1124
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1125
-            //Events View All
1126
-            $admin_bar->add_menu(array(
1127
-                'id'     => 'espresso-toolbar-events-all',
1128
-                'parent' => 'espresso-toolbar-events-view',
1129
-                'title'  => __('All', 'event_espresso'),
1130
-                'href'   => $events_admin_url,
1131
-                'meta'   => array(
1132
-                    'title'  => __('All', 'event_espresso'),
1133
-                    'target' => '',
1134
-                    'class'  => $menu_class,
1135
-                ),
1136
-            ));
1137
-        }
1138
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1139
-            'ee_admin_bar_menu_espresso-toolbar-events-today')
1140
-        ) {
1141
-            //Events View Today
1142
-            $admin_bar->add_menu(array(
1143
-                'id'     => 'espresso-toolbar-events-today',
1144
-                'parent' => 'espresso-toolbar-events-view',
1145
-                'title'  => __('Today', 'event_espresso'),
1146
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1147
-                    $events_admin_url),
1148
-                'meta'   => array(
1149
-                    'title'  => __('Today', 'event_espresso'),
1150
-                    'target' => '',
1151
-                    'class'  => $menu_class,
1152
-                ),
1153
-            ));
1154
-        }
1155
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1156
-            'ee_admin_bar_menu_espresso-toolbar-events-month')
1157
-        ) {
1158
-            //Events View This Month
1159
-            $admin_bar->add_menu(array(
1160
-                'id'     => 'espresso-toolbar-events-month',
1161
-                'parent' => 'espresso-toolbar-events-view',
1162
-                'title'  => __('This Month', 'event_espresso'),
1163
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1164
-                    $events_admin_url),
1165
-                'meta'   => array(
1166
-                    'title'  => __('This Month', 'event_espresso'),
1167
-                    'target' => '',
1168
-                    'class'  => $menu_class,
1169
-                ),
1170
-            ));
1171
-        }
1172
-        //Registration Overview
1173
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1174
-            'ee_admin_bar_menu_espresso-toolbar-registrations')
1175
-        ) {
1176
-            $admin_bar->add_menu(array(
1177
-                'id'     => 'espresso-toolbar-registrations',
1178
-                'parent' => 'espresso-toolbar',
1179
-                'title'  => __('Registrations', 'event_espresso'),
1180
-                'href'   => $reg_admin_url,
1181
-                'meta'   => array(
1182
-                    'title'  => __('Registrations', 'event_espresso'),
1183
-                    'target' => '',
1184
-                    'class'  => $menu_class,
1185
-                ),
1186
-            ));
1187
-        }
1188
-        //Registration Overview Today
1189
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1190
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1191
-        ) {
1192
-            $admin_bar->add_menu(array(
1193
-                'id'     => 'espresso-toolbar-registrations-today',
1194
-                'parent' => 'espresso-toolbar-registrations',
1195
-                'title'  => __('Today', 'event_espresso'),
1196
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1197
-                    $reg_admin_url),
1198
-                'meta'   => array(
1199
-                    'title'  => __('Today', 'event_espresso'),
1200
-                    'target' => '',
1201
-                    'class'  => $menu_class,
1202
-                ),
1203
-            ));
1204
-        }
1205
-        //Registration Overview Today Completed
1206
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1207
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1208
-        ) {
1209
-            $admin_bar->add_menu(array(
1210
-                'id'     => 'espresso-toolbar-registrations-today-approved',
1211
-                'parent' => 'espresso-toolbar-registrations-today',
1212
-                'title'  => __('Approved', 'event_espresso'),
1213
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1214
-                    'action'      => 'default',
1215
-                    'status'      => 'today',
1216
-                    '_reg_status' => EEM_Registration::status_id_approved,
1217
-                ), $reg_admin_url),
1218
-                'meta'   => array(
1219
-                    'title'  => __('Approved', 'event_espresso'),
1220
-                    'target' => '',
1221
-                    'class'  => $menu_class,
1222
-                ),
1223
-            ));
1224
-        }
1225
-        //Registration Overview Today Pending\
1226
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1227
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1228
-        ) {
1229
-            $admin_bar->add_menu(array(
1230
-                'id'     => 'espresso-toolbar-registrations-today-pending',
1231
-                'parent' => 'espresso-toolbar-registrations-today',
1232
-                'title'  => __('Pending', 'event_espresso'),
1233
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1234
-                    'action'     => 'default',
1235
-                    'status'     => 'today',
1236
-                    'reg_status' => EEM_Registration::status_id_pending_payment,
1237
-                ), $reg_admin_url),
1238
-                'meta'   => array(
1239
-                    'title'  => __('Pending Payment', 'event_espresso'),
1240
-                    'target' => '',
1241
-                    'class'  => $menu_class,
1242
-                ),
1243
-            ));
1244
-        }
1245
-        //Registration Overview Today Incomplete
1246
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1247
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1248
-        ) {
1249
-            $admin_bar->add_menu(array(
1250
-                'id'     => 'espresso-toolbar-registrations-today-not-approved',
1251
-                'parent' => 'espresso-toolbar-registrations-today',
1252
-                'title'  => __('Not Approved', 'event_espresso'),
1253
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1254
-                    'action'      => 'default',
1255
-                    'status'      => 'today',
1256
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1257
-                ), $reg_admin_url),
1258
-                'meta'   => array(
1259
-                    'title'  => __('Not Approved', 'event_espresso'),
1260
-                    'target' => '',
1261
-                    'class'  => $menu_class,
1262
-                ),
1263
-            ));
1264
-        }
1265
-        //Registration Overview Today Incomplete
1266
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1267
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1268
-        ) {
1269
-            $admin_bar->add_menu(array(
1270
-                'id'     => 'espresso-toolbar-registrations-today-cancelled',
1271
-                'parent' => 'espresso-toolbar-registrations-today',
1272
-                'title'  => __('Cancelled', 'event_espresso'),
1273
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1274
-                    'action'      => 'default',
1275
-                    'status'      => 'today',
1276
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1277
-                ), $reg_admin_url),
1278
-                'meta'   => array(
1279
-                    'title'  => __('Cancelled', 'event_espresso'),
1280
-                    'target' => '',
1281
-                    'class'  => $menu_class,
1282
-                ),
1283
-            ));
1284
-        }
1285
-        //Registration Overview This Month
1286
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1287
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1288
-        ) {
1289
-            $admin_bar->add_menu(array(
1290
-                'id'     => 'espresso-toolbar-registrations-month',
1291
-                'parent' => 'espresso-toolbar-registrations',
1292
-                'title'  => __('This Month', 'event_espresso'),
1293
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1294
-                    $reg_admin_url),
1295
-                'meta'   => array(
1296
-                    'title'  => __('This Month', 'event_espresso'),
1297
-                    'target' => '',
1298
-                    'class'  => $menu_class,
1299
-                ),
1300
-            ));
1301
-        }
1302
-        //Registration Overview This Month Approved
1303
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1305
-        ) {
1306
-            $admin_bar->add_menu(array(
1307
-                'id'     => 'espresso-toolbar-registrations-month-approved',
1308
-                'parent' => 'espresso-toolbar-registrations-month',
1309
-                'title'  => __('Approved', 'event_espresso'),
1310
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1311
-                    'action'      => 'default',
1312
-                    'status'      => 'month',
1313
-                    '_reg_status' => EEM_Registration::status_id_approved,
1314
-                ), $reg_admin_url),
1315
-                'meta'   => array(
1316
-                    'title'  => __('Approved', 'event_espresso'),
1317
-                    'target' => '',
1318
-                    'class'  => $menu_class,
1319
-                ),
1320
-            ));
1321
-        }
1322
-        //Registration Overview This Month Pending
1323
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1324
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1325
-        ) {
1326
-            $admin_bar->add_menu(array(
1327
-                'id'     => 'espresso-toolbar-registrations-month-pending',
1328
-                'parent' => 'espresso-toolbar-registrations-month',
1329
-                'title'  => __('Pending', 'event_espresso'),
1330
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1331
-                    'action'      => 'default',
1332
-                    'status'      => 'month',
1333
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1334
-                ), $reg_admin_url),
1335
-                'meta'   => array(
1336
-                    'title'  => __('Pending', 'event_espresso'),
1337
-                    'target' => '',
1338
-                    'class'  => $menu_class,
1339
-                ),
1340
-            ));
1341
-        }
1342
-        //Registration Overview This Month Not Approved
1343
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1344
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1345
-        ) {
1346
-            $admin_bar->add_menu(array(
1347
-                'id'     => 'espresso-toolbar-registrations-month-not-approved',
1348
-                'parent' => 'espresso-toolbar-registrations-month',
1349
-                'title'  => __('Not Approved', 'event_espresso'),
1350
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1351
-                    'action'      => 'default',
1352
-                    'status'      => 'month',
1353
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1354
-                ), $reg_admin_url),
1355
-                'meta'   => array(
1356
-                    'title'  => __('Not Approved', 'event_espresso'),
1357
-                    'target' => '',
1358
-                    'class'  => $menu_class,
1359
-                ),
1360
-            ));
1361
-        }
1362
-        //Registration Overview This Month Cancelled
1363
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1364
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1365
-        ) {
1366
-            $admin_bar->add_menu(array(
1367
-                'id'     => 'espresso-toolbar-registrations-month-cancelled',
1368
-                'parent' => 'espresso-toolbar-registrations-month',
1369
-                'title'  => __('Cancelled', 'event_espresso'),
1370
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1371
-                    'action'      => 'default',
1372
-                    'status'      => 'month',
1373
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1374
-                ), $reg_admin_url),
1375
-                'meta'   => array(
1376
-                    'title'  => __('Cancelled', 'event_espresso'),
1377
-                    'target' => '',
1378
-                    'class'  => $menu_class,
1379
-                ),
1380
-            ));
1381
-        }
1382
-        //Extensions & Services
1383
-        if ($this->registry->CAP->current_user_can('ee_read_ee',
1384
-            'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1385
-        ) {
1386
-            $admin_bar->add_menu(array(
1387
-                'id'     => 'espresso-toolbar-extensions-and-services',
1388
-                'parent' => 'espresso-toolbar',
1389
-                'title'  => __('Extensions & Services', 'event_espresso'),
1390
-                'href'   => $extensions_admin_url,
1391
-                'meta'   => array(
1392
-                    'title'  => __('Extensions & Services', 'event_espresso'),
1393
-                    'target' => '',
1394
-                    'class'  => $menu_class,
1395
-                ),
1396
-            ));
1397
-        }
1398
-    }
1399
-
1400
-
1401
-
1402
-    /**
1403
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1404
-     * never returned with the function.
1405
-     *
1406
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1407
-     * @return array
1408
-     */
1409
-    public function remove_pages_from_wp_list_pages($exclude_array)
1410
-    {
1411
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1412
-    }
1413
-
1414
-
1415
-
1416
-
1417
-
1418
-
1419
-    /***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1420
-    /**
1421
-     *    wp_enqueue_scripts
1422
-     *
1423
-     * @access    public
1424
-     * @return    void
1425
-     */
1426
-    public function wp_enqueue_scripts()
1427
-    {
1428
-        // unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1429
-        if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1430
-            // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431
-            if (apply_filters('FHEE_load_jquery_validate', false)) {
1432
-                // register jQuery Validate and additional methods
1433
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1434
-                    array('jquery'), '1.15.0', true);
1435
-                wp_register_script('jquery-validate-extra-methods',
1436
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1437
-                    array('jquery', 'jquery-validate'), '1.15.0', true);
1438
-            }
1439
-        }
1440
-    }
19
+	/**
20
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
21
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
22
+	 */
23
+	const req_type_normal = 0;
24
+
25
+	/**
26
+	 * Indicates this is a brand new installation of EE so we should install
27
+	 * tables and default data etc
28
+	 */
29
+	const req_type_new_activation = 1;
30
+
31
+	/**
32
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
33
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
34
+	 * and that default data is setup too
35
+	 */
36
+	const req_type_reactivation = 2;
37
+
38
+	/**
39
+	 * indicates that EE has been upgraded since its previous request.
40
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
41
+	 */
42
+	const req_type_upgrade = 3;
43
+
44
+	/**
45
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
46
+	 */
47
+	const req_type_downgrade = 4;
48
+
49
+	/**
50
+	 * @deprecated since version 4.6.0.dev.006
51
+	 * Now whenever a new_activation is detected the request type is still just
52
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
53
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
54
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
55
+	 * (Specifically, when the migration manager indicates migrations are finished
56
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
57
+	 */
58
+	const req_type_activation_but_not_installed = 5;
59
+
60
+	/**
61
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
62
+	 */
63
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
64
+
65
+
66
+	/**
67
+	 *    instance of the EE_System object
68
+	 *
69
+	 * @var    $_instance
70
+	 * @access    private
71
+	 */
72
+	private static $_instance = null;
73
+
74
+	/**
75
+	 * @type  EE_Registry $Registry
76
+	 * @access    protected
77
+	 */
78
+	protected $registry;
79
+
80
+	/**
81
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
82
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
83
+	 *
84
+	 * @var int
85
+	 */
86
+	private $_req_type;
87
+
88
+	/**
89
+	 * Whether or not there was a non-micro version change in EE core version during this request
90
+	 *
91
+	 * @var boolean
92
+	 */
93
+	private $_major_version_change = false;
94
+
95
+
96
+
97
+	/**
98
+	 * @singleton method used to instantiate class object
99
+	 * @access    public
100
+	 * @param  \EE_Registry $Registry
101
+	 * @return \EE_System
102
+	 */
103
+	public static function instance(EE_Registry $Registry = null)
104
+	{
105
+		// check if class object is instantiated
106
+		if ( ! self::$_instance instanceof EE_System) {
107
+			self::$_instance = new self($Registry);
108
+		}
109
+		return self::$_instance;
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * resets the instance and returns it
116
+	 *
117
+	 * @return EE_System
118
+	 */
119
+	public static function reset()
120
+	{
121
+		self::$_instance->_req_type = null;
122
+		//make sure none of the old hooks are left hanging around
123
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
124
+		//we need to reset the migration manager in order for it to detect DMSs properly
125
+		EE_Data_Migration_Manager::reset();
126
+		self::instance()->detect_activations_or_upgrades();
127
+		self::instance()->perform_activations_upgrades_and_migrations();
128
+		return self::instance();
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 *    sets hooks for running rest of system
135
+	 *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
136
+	 *    starting EE Addons from any other point may lead to problems
137
+	 *
138
+	 * @access private
139
+	 * @param  \EE_Registry $Registry
140
+	 */
141
+	private function __construct(EE_Registry $Registry)
142
+	{
143
+		$this->registry = $Registry;
144
+		do_action('AHEE__EE_System__construct__begin', $this);
145
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
146
+		add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
147
+		// when an ee addon is activated, we want to call the core hook(s) again
148
+		// because the newly-activated addon didn't get a chance to run at all
149
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
150
+		// detect whether install or upgrade
151
+		add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
152
+			3);
153
+		// load EE_Config, EE_Textdomain, etc
154
+		add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
155
+		// load EE_Config, EE_Textdomain, etc
156
+		add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
157
+			array($this, 'register_shortcodes_modules_and_widgets'), 7);
158
+		// you wanna get going? I wanna get going... let's get going!
159
+		add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
160
+		//other housekeeping
161
+		//exclude EE critical pages from wp_list_pages
162
+		add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
163
+		// ALL EE Addons should use the following hook point to attach their initial setup too
164
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
165
+		do_action('AHEE__EE_System__construct__complete', $this);
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 * load_espresso_addons
172
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
173
+	 * this is hooked into both:
174
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
175
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
176
+	 *    and the WP 'activate_plugin' hookpoint
177
+	 *
178
+	 * @access public
179
+	 * @return void
180
+	 */
181
+	public function load_espresso_addons()
182
+	{
183
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
184
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
185
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
186
+		//load and setup EE_Capabilities
187
+		$this->registry->load_core('Capabilities');
188
+		//caps need to be initialized on every request so that capability maps are set.
189
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
190
+		$this->registry->CAP->init_caps();
191
+		do_action('AHEE__EE_System__load_espresso_addons');
192
+		//if the WP API basic auth plugin isn't already loaded, load it now.
193
+		//We want it for mobile apps. Just include the entire plugin
194
+		//also, don't load the basic auth when a plugin is getting activated, because
195
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
+		//and causes a fatal error
197
+		if ( ! function_exists('json_basic_auth_handler')
198
+			 && ! function_exists('json_basic_auth_error')
199
+			 && ! (
200
+				isset($_GET['action'])
201
+				&& in_array($_GET['action'], array('activate', 'activate-selected'))
202
+			)
203
+			 && ! (
204
+				isset($_GET['activate'])
205
+				&& $_GET['activate'] === 'true'
206
+			)
207
+		) {
208
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
+		}
210
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * detect_activations_or_upgrades
217
+	 * Checks for activation or upgrade of core first;
218
+	 * then also checks if any registered addons have been activated or upgraded
219
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
220
+	 * which runs during the WP 'plugins_loaded' action at priority 3
221
+	 *
222
+	 * @access public
223
+	 * @return void
224
+	 */
225
+	public function detect_activations_or_upgrades()
226
+	{
227
+		//first off: let's make sure to handle core
228
+		$this->detect_if_activation_or_upgrade();
229
+		foreach ($this->registry->addons as $addon) {
230
+			//detect teh request type for that addon
231
+			$addon->detect_activation_or_upgrade();
232
+		}
233
+	}
234
+
235
+
236
+
237
+	/**
238
+	 * detect_if_activation_or_upgrade
239
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
240
+	 * and either setting up the DB or setting up maintenance mode etc.
241
+	 *
242
+	 * @access public
243
+	 * @return void
244
+	 */
245
+	public function detect_if_activation_or_upgrade()
246
+	{
247
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
248
+		// load M-Mode class
249
+		$this->registry->load_core('Maintenance_Mode');
250
+		// check if db has been updated, or if its a brand-new installation
251
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
252
+		$request_type = $this->detect_req_type($espresso_db_update);
253
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
254
+		switch ($request_type) {
255
+			case EE_System::req_type_new_activation:
256
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
257
+				$this->_handle_core_version_change($espresso_db_update);
258
+				break;
259
+			case EE_System::req_type_reactivation:
260
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
261
+				$this->_handle_core_version_change($espresso_db_update);
262
+				break;
263
+			case EE_System::req_type_upgrade:
264
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
265
+				//migrations may be required now that we've upgraded
266
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
267
+				$this->_handle_core_version_change($espresso_db_update);
268
+				//				echo "done upgrade";die;
269
+				break;
270
+			case EE_System::req_type_downgrade:
271
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
272
+				//its possible migrations are no longer required
273
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
274
+				$this->_handle_core_version_change($espresso_db_update);
275
+				break;
276
+			case EE_System::req_type_normal:
277
+			default:
278
+				//				$this->_maybe_redirect_to_ee_about();
279
+				break;
280
+		}
281
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
282
+	}
283
+
284
+
285
+
286
+	/**
287
+	 * Updates the list of installed versions and sets hooks for
288
+	 * initializing the database later during the request
289
+	 *
290
+	 * @param array $espresso_db_update
291
+	 */
292
+	protected function _handle_core_version_change($espresso_db_update)
293
+	{
294
+		$this->update_list_of_installed_versions($espresso_db_update);
295
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
296
+		add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
297
+			array($this, 'initialize_db_if_no_migrations_required'));
298
+	}
299
+
300
+
301
+
302
+	/**
303
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
304
+	 * information about what versions of EE have been installed and activated,
305
+	 * NOT necessarily the state of the database
306
+	 *
307
+	 * @param null $espresso_db_update
308
+	 * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
309
+	 *           from the options table
310
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
311
+	 */
312
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
313
+	{
314
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
315
+		if ( ! $espresso_db_update) {
316
+			$espresso_db_update = get_option('espresso_db_update');
317
+		}
318
+		// check that option is an array
319
+		if ( ! is_array($espresso_db_update)) {
320
+			// if option is FALSE, then it never existed
321
+			if ($espresso_db_update === false) {
322
+				// make $espresso_db_update an array and save option with autoload OFF
323
+				$espresso_db_update = array();
324
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
325
+			} else {
326
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
327
+				$espresso_db_update = array($espresso_db_update => array());
328
+				update_option('espresso_db_update', $espresso_db_update);
329
+			}
330
+		} else {
331
+			$corrected_db_update = array();
332
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
333
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
334
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
335
+					//the key is an int, and the value IS NOT an array
336
+					//so it must be numerically-indexed, where values are versions installed...
337
+					//fix it!
338
+					$version_string = $should_be_array;
339
+					$corrected_db_update[$version_string] = array('unknown-date');
340
+				} else {
341
+					//ok it checks out
342
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
343
+				}
344
+			}
345
+			$espresso_db_update = $corrected_db_update;
346
+			update_option('espresso_db_update', $espresso_db_update);
347
+		}
348
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
349
+		return $espresso_db_update;
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * Does the traditional work of setting up the plugin's database and adding default data.
356
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
357
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
358
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
359
+	 * so that it will be done when migrations are finished
360
+	 *
361
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
362
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
363
+	 *                                       This is a resource-intensive job
364
+	 *                                       so we prefer to only do it when necessary
365
+	 * @return void
366
+	 */
367
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
368
+	{
369
+		$request_type = $this->detect_req_type();
370
+		//only initialize system if we're not in maintenance mode.
371
+		if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
372
+			update_option('ee_flush_rewrite_rules', true);
373
+			if ($verify_schema) {
374
+				EEH_Activation::initialize_db_and_folders();
375
+			}
376
+			EEH_Activation::initialize_db_content();
377
+			EEH_Activation::system_initialization();
378
+			if ($initialize_addons_too) {
379
+				$this->initialize_addons();
380
+			}
381
+		} else {
382
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
383
+		}
384
+		if ($request_type === EE_System::req_type_new_activation
385
+			|| $request_type === EE_System::req_type_reactivation
386
+			|| (
387
+				$request_type === EE_System::req_type_upgrade
388
+				&& $this->is_major_version_change()
389
+			)
390
+		) {
391
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
392
+		}
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * Initializes the db for all registered addons
399
+	 */
400
+	public function initialize_addons()
401
+	{
402
+		//foreach registered addon, make sure its db is up-to-date too
403
+		foreach ($this->registry->addons as $addon) {
404
+			$addon->initialize_db_if_no_migrations_required();
405
+		}
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
412
+	 *
413
+	 * @param    array  $version_history
414
+	 * @param    string $current_version_to_add version to be added to the version history
415
+	 * @return    boolean success as to whether or not this option was changed
416
+	 */
417
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
418
+	{
419
+		if ( ! $version_history) {
420
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
421
+		}
422
+		if ($current_version_to_add == null) {
423
+			$current_version_to_add = espresso_version();
424
+		}
425
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
426
+		// re-save
427
+		return update_option('espresso_db_update', $version_history);
428
+	}
429
+
430
+
431
+
432
+	/**
433
+	 * Detects if the current version indicated in the has existed in the list of
434
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
435
+	 *
436
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
437
+	 *                                  If not supplied, fetches it from the options table.
438
+	 *                                  Also, caches its result so later parts of the code can also know whether
439
+	 *                                  there's been an update or not. This way we can add the current version to
440
+	 *                                  espresso_db_update, but still know if this is a new install or not
441
+	 * @return int one of the constants on EE_System::req_type_
442
+	 */
443
+	public function detect_req_type($espresso_db_update = null)
444
+	{
445
+		if ($this->_req_type === null) {
446
+			$espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
447
+				: $this->fix_espresso_db_upgrade_option();
448
+			$this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
449
+				'ee_espresso_activation', espresso_version());
450
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
451
+		}
452
+		return $this->_req_type;
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 * Returns whether or not there was a non-micro version change (ie, change in either
459
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
460
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
461
+	 *
462
+	 * @param $activation_history
463
+	 * @return bool
464
+	 */
465
+	protected function _detect_major_version_change($activation_history)
466
+	{
467
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
468
+		$previous_version_parts = explode('.', $previous_version);
469
+		$current_version_parts = explode('.', espresso_version());
470
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
471
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
472
+				   || $previous_version_parts[1] !== $current_version_parts[1]
473
+			   );
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * Returns true if either the major or minor version of EE changed during this request.
480
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
481
+	 *
482
+	 * @return bool
483
+	 */
484
+	public function is_major_version_change()
485
+	{
486
+		return $this->_major_version_change;
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
493
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
494
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
495
+	 * just activated to (for core that will always be espresso_version())
496
+	 *
497
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
498
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
499
+	 * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
500
+	 *                                                 indicate that this plugin was just activated
501
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
502
+	 *                                                 espresso_version())
503
+	 * @return int one of the constants on EE_System::req_type_*
504
+	 */
505
+	public static function detect_req_type_given_activation_history(
506
+		$activation_history_for_addon,
507
+		$activation_indicator_option_name,
508
+		$version_to_upgrade_to
509
+	) {
510
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
511
+		if ($activation_history_for_addon) {
512
+			//it exists, so this isn't a completely new install
513
+			//check if this version already in that list of previously installed versions
514
+			if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
515
+				//it a version we haven't seen before
516
+				if ($version_is_higher === 1) {
517
+					$req_type = EE_System::req_type_upgrade;
518
+				} else {
519
+					$req_type = EE_System::req_type_downgrade;
520
+				}
521
+				delete_option($activation_indicator_option_name);
522
+			} else {
523
+				// its not an update. maybe a reactivation?
524
+				if (get_option($activation_indicator_option_name, false)) {
525
+					if ($version_is_higher === -1) {
526
+						$req_type = EE_System::req_type_downgrade;
527
+					} elseif ($version_is_higher === 0) {
528
+						//we've seen this version before, but it's an activation. must be a reactivation
529
+						$req_type = EE_System::req_type_reactivation;
530
+					} else {//$version_is_higher === 1
531
+						$req_type = EE_System::req_type_upgrade;
532
+					}
533
+					delete_option($activation_indicator_option_name);
534
+				} else {
535
+					//we've seen this version before and the activation indicate doesn't show it was just activated
536
+					if ($version_is_higher === -1) {
537
+						$req_type = EE_System::req_type_downgrade;
538
+					} elseif ($version_is_higher === 0) {
539
+						//we've seen this version before and it's not an activation. its normal request
540
+						$req_type = EE_System::req_type_normal;
541
+					} else {//$version_is_higher === 1
542
+						$req_type = EE_System::req_type_upgrade;
543
+					}
544
+				}
545
+			}
546
+		} else {
547
+			//brand new install
548
+			$req_type = EE_System::req_type_new_activation;
549
+			delete_option($activation_indicator_option_name);
550
+		}
551
+		return $req_type;
552
+	}
553
+
554
+
555
+
556
+	/**
557
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
558
+	 * the $activation_history_for_addon
559
+	 *
560
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
561
+	 *                                             sometimes containing 'unknown-date'
562
+	 * @param string $version_to_upgrade_to        (current version)
563
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
564
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
565
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
566
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
567
+	 */
568
+	protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
569
+	{
570
+		//find the most recently-activated version
571
+		$most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
572
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * Gets the most recently active version listed in the activation history,
579
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
580
+	 *
581
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
582
+	 *                                   sometimes containing 'unknown-date'
583
+	 * @return string
584
+	 */
585
+	protected static function _get_most_recently_active_version_from_activation_history($activation_history)
586
+	{
587
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
588
+		$most_recently_active_version = '0.0.0.dev.000';
589
+		if (is_array($activation_history)) {
590
+			foreach ($activation_history as $version => $times_activated) {
591
+				//check there is a record of when this version was activated. Otherwise,
592
+				//mark it as unknown
593
+				if ( ! $times_activated) {
594
+					$times_activated = array('unknown-date');
595
+				}
596
+				if (is_string($times_activated)) {
597
+					$times_activated = array($times_activated);
598
+				}
599
+				foreach ($times_activated as $an_activation) {
600
+					if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
601
+						$most_recently_active_version = $version;
602
+						$most_recently_active_version_activation = $an_activation == 'unknown-date'
603
+							? '1970-01-01 00:00:00' : $an_activation;
604
+					}
605
+				}
606
+			}
607
+		}
608
+		return $most_recently_active_version;
609
+	}
610
+
611
+
612
+
613
+	/**
614
+	 * This redirects to the about EE page after activation
615
+	 *
616
+	 * @return void
617
+	 */
618
+	public function redirect_to_about_ee()
619
+	{
620
+		$notices = EE_Error::get_notices(false);
621
+		//if current user is an admin and it's not an ajax or rest request
622
+		if (
623
+			! (defined('DOING_AJAX') && DOING_AJAX)
624
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
625
+			&& ! isset($notices['errors'])
626
+			&& apply_filters(
627
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
628
+				$this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
629
+			)
630
+		) {
631
+			$query_params = array('page' => 'espresso_about');
632
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
633
+				$query_params['new_activation'] = true;
634
+			}
635
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
636
+				$query_params['reactivation'] = true;
637
+			}
638
+			$url = add_query_arg($query_params, admin_url('admin.php'));
639
+			wp_safe_redirect($url);
640
+			exit();
641
+		}
642
+	}
643
+
644
+
645
+
646
+	/**
647
+	 * load_core_configuration
648
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
649
+	 * which runs during the WP 'plugins_loaded' action at priority 5
650
+	 *
651
+	 * @return void
652
+	 */
653
+	public function load_core_configuration()
654
+	{
655
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
656
+		$this->registry->load_core('EE_Load_Textdomain');
657
+		//load textdomain
658
+		EE_Load_Textdomain::load_textdomain();
659
+		// load and setup EE_Config and EE_Network_Config
660
+		$this->registry->load_core('Config');
661
+		$this->registry->load_core('Network_Config');
662
+		// setup autoloaders
663
+		// enable logging?
664
+		if ($this->registry->CFG->admin->use_full_logging) {
665
+			$this->registry->load_core('Log');
666
+		}
667
+		// check for activation errors
668
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
669
+		if ($activation_errors) {
670
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
671
+			update_option('ee_plugin_activation_errors', false);
672
+		}
673
+		// get model names
674
+		$this->_parse_model_names();
675
+		//load caf stuff a chance to play during the activation process too.
676
+		$this->_maybe_brew_regular();
677
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
684
+	 *
685
+	 * @return void
686
+	 */
687
+	private function _parse_model_names()
688
+	{
689
+		//get all the files in the EE_MODELS folder that end in .model.php
690
+		$models = glob(EE_MODELS . '*.model.php');
691
+		$model_names = array();
692
+		$non_abstract_db_models = array();
693
+		foreach ($models as $model) {
694
+			// get model classname
695
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
696
+			$short_name = str_replace('EEM_', '', $classname);
697
+			$reflectionClass = new ReflectionClass($classname);
698
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
699
+				$non_abstract_db_models[$short_name] = $classname;
700
+			}
701
+			$model_names[$short_name] = $classname;
702
+		}
703
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
704
+		$this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
705
+			$non_abstract_db_models);
706
+	}
707
+
708
+
709
+
710
+	/**
711
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
712
+	 * that need to be setup before our EE_System launches.
713
+	 *
714
+	 * @return void
715
+	 */
716
+	private function _maybe_brew_regular()
717
+	{
718
+		if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
720
+		}
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * register_shortcodes_modules_and_widgets
727
+	 * generate lists of shortcodes and modules, then verify paths and classes
728
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
729
+	 * which runs during the WP 'plugins_loaded' action at priority 7
730
+	 *
731
+	 * @access public
732
+	 * @return void
733
+	 */
734
+	public function register_shortcodes_modules_and_widgets()
735
+	{
736
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
737
+		// check for addons using old hookpoint
738
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
739
+			$this->_incompatible_addon_error();
740
+		}
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 * _incompatible_addon_error
747
+	 *
748
+	 * @access public
749
+	 * @return void
750
+	 */
751
+	private function _incompatible_addon_error()
752
+	{
753
+		// get array of classes hooking into here
754
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
755
+		if ( ! empty($class_names)) {
756
+			$msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
757
+				'event_espresso');
758
+			$msg .= '<ul>';
759
+			foreach ($class_names as $class_name) {
760
+				$msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
+						$class_name) . '</b></li>';
762
+			}
763
+			$msg .= '</ul>';
764
+			$msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
765
+				'event_espresso');
766
+			// save list of incompatible addons to wp-options for later use
767
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
768
+			if (is_admin()) {
769
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
770
+			}
771
+		}
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * brew_espresso
778
+	 * begins the process of setting hooks for initializing EE in the correct order
779
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
780
+	 * which runs during the WP 'plugins_loaded' action at priority 9
781
+	 *
782
+	 * @return void
783
+	 */
784
+	public function brew_espresso()
785
+	{
786
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
787
+		// load some final core systems
788
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
789
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
790
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
791
+		add_action('init', array($this, 'load_controllers'), 7);
792
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
793
+		add_action('init', array($this, 'initialize'), 10);
794
+		add_action('init', array($this, 'initialize_last'), 100);
795
+		add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
796
+		add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
797
+		add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
798
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
799
+			// pew pew pew
800
+			$this->registry->load_core('PUE');
801
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
802
+		}
803
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
804
+	}
805
+
806
+
807
+
808
+	/**
809
+	 *    set_hooks_for_core
810
+	 *
811
+	 * @access public
812
+	 * @return    void
813
+	 */
814
+	public function set_hooks_for_core()
815
+	{
816
+		$this->_deactivate_incompatible_addons();
817
+		do_action('AHEE__EE_System__set_hooks_for_core');
818
+	}
819
+
820
+
821
+
822
+	/**
823
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
824
+	 * deactivates any addons considered incompatible with the current version of EE
825
+	 */
826
+	private function _deactivate_incompatible_addons()
827
+	{
828
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
829
+		if ( ! empty($incompatible_addons)) {
830
+			$active_plugins = get_option('active_plugins', array());
831
+			foreach ($active_plugins as $active_plugin) {
832
+				foreach ($incompatible_addons as $incompatible_addon) {
833
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
834
+						unset($_GET['activate']);
835
+						espresso_deactivate_plugin($active_plugin);
836
+					}
837
+				}
838
+			}
839
+		}
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 *    perform_activations_upgrades_and_migrations
846
+	 *
847
+	 * @access public
848
+	 * @return    void
849
+	 */
850
+	public function perform_activations_upgrades_and_migrations()
851
+	{
852
+		//first check if we had previously attempted to setup EE's directories but failed
853
+		if (EEH_Activation::upload_directories_incomplete()) {
854
+			EEH_Activation::create_upload_directories();
855
+		}
856
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
857
+	}
858
+
859
+
860
+
861
+	/**
862
+	 *    load_CPTs_and_session
863
+	 *
864
+	 * @access public
865
+	 * @return    void
866
+	 */
867
+	public function load_CPTs_and_session()
868
+	{
869
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
870
+		// register Custom Post Types
871
+		$this->registry->load_core('Register_CPTs');
872
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
873
+	}
874
+
875
+
876
+
877
+	/**
878
+	 * load_controllers
879
+	 * this is the best place to load any additional controllers that needs access to EE core.
880
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
881
+	 * time
882
+	 *
883
+	 * @access public
884
+	 * @return void
885
+	 */
886
+	public function load_controllers()
887
+	{
888
+		do_action('AHEE__EE_System__load_controllers__start');
889
+		// let's get it started
890
+		if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
891
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
892
+			$this->registry->load_core('Front_Controller', array(), false, true);
893
+		} else if ( ! EE_FRONT_AJAX) {
894
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
895
+			EE_Registry::instance()->load_core('Admin');
896
+		}
897
+		do_action('AHEE__EE_System__load_controllers__complete');
898
+	}
899
+
900
+
901
+
902
+	/**
903
+	 * core_loaded_and_ready
904
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
905
+	 *
906
+	 * @access public
907
+	 * @return void
908
+	 */
909
+	public function core_loaded_and_ready()
910
+	{
911
+		do_action('AHEE__EE_System__core_loaded_and_ready');
912
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
913
+		$this->registry->load_core('Session');
914
+		//		add_action( 'wp_loaded', array( $this, 'set_hooks_for_shortcodes_modules_and_addons' ), 1 );
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * initialize
921
+	 * this is the best place to begin initializing client code
922
+	 *
923
+	 * @access public
924
+	 * @return void
925
+	 */
926
+	public function initialize()
927
+	{
928
+		do_action('AHEE__EE_System__initialize');
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * initialize_last
935
+	 * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
936
+	 * initialize has done so
937
+	 *
938
+	 * @access public
939
+	 * @return void
940
+	 */
941
+	public function initialize_last()
942
+	{
943
+		do_action('AHEE__EE_System__initialize_last');
944
+	}
945
+
946
+
947
+
948
+	/**
949
+	 * set_hooks_for_shortcodes_modules_and_addons
950
+	 * this is the best place for other systems to set callbacks for hooking into other parts of EE
951
+	 * this happens at the very beginning of the wp_loaded hookpoint
952
+	 *
953
+	 * @access public
954
+	 * @return void
955
+	 */
956
+	public function set_hooks_for_shortcodes_modules_and_addons()
957
+	{
958
+		//		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
959
+	}
960
+
961
+
962
+
963
+	/**
964
+	 * do_not_cache
965
+	 * sets no cache headers and defines no cache constants for WP plugins
966
+	 *
967
+	 * @access public
968
+	 * @return void
969
+	 */
970
+	public static function do_not_cache()
971
+	{
972
+		// set no cache constants
973
+		if ( ! defined('DONOTCACHEPAGE')) {
974
+			define('DONOTCACHEPAGE', true);
975
+		}
976
+		if ( ! defined('DONOTCACHCEOBJECT')) {
977
+			define('DONOTCACHCEOBJECT', true);
978
+		}
979
+		if ( ! defined('DONOTCACHEDB')) {
980
+			define('DONOTCACHEDB', true);
981
+		}
982
+		// add no cache headers
983
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
984
+		// plus a little extra for nginx and Google Chrome
985
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
986
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
987
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
988
+	}
989
+
990
+
991
+
992
+	/**
993
+	 *    extra_nocache_headers
994
+	 *
995
+	 * @access    public
996
+	 * @param $headers
997
+	 * @return    array
998
+	 */
999
+	public static function extra_nocache_headers($headers)
1000
+	{
1001
+		// for NGINX
1002
+		$headers['X-Accel-Expires'] = 0;
1003
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1004
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1005
+		return $headers;
1006
+	}
1007
+
1008
+
1009
+
1010
+	/**
1011
+	 *    nocache_headers
1012
+	 *
1013
+	 * @access    public
1014
+	 * @return    void
1015
+	 */
1016
+	public static function nocache_headers()
1017
+	{
1018
+		nocache_headers();
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 *    espresso_toolbar_items
1025
+	 *
1026
+	 * @access public
1027
+	 * @param  WP_Admin_Bar $admin_bar
1028
+	 * @return void
1029
+	 */
1030
+	public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1031
+	{
1032
+		// if in full M-Mode, or its an AJAX request, or user is NOT an admin
1033
+		if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1034
+			|| defined('DOING_AJAX')
1035
+			|| ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1036
+		) {
1037
+			return;
1038
+		}
1039
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1040
+		$menu_class = 'espresso_menu_item_class';
1041
+		//we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1042
+		//because they're only defined in each of their respective constructors
1043
+		//and this might be a frontend request, in which case they aren't available
1044
+		$events_admin_url = admin_url("admin.php?page=espresso_events");
1045
+		$reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1046
+		$extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1047
+		//Top Level
1048
+		$admin_bar->add_menu(array(
1049
+			'id'    => 'espresso-toolbar',
1050
+			'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1051
+					   . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1052
+					   . '</span>',
1053
+			'href'  => $events_admin_url,
1054
+			'meta'  => array(
1055
+				'title' => __('Event Espresso', 'event_espresso'),
1056
+				'class' => $menu_class . 'first',
1057
+			),
1058
+		));
1059
+		//Events
1060
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1061
+			$admin_bar->add_menu(array(
1062
+				'id'     => 'espresso-toolbar-events',
1063
+				'parent' => 'espresso-toolbar',
1064
+				'title'  => __('Events', 'event_espresso'),
1065
+				'href'   => $events_admin_url,
1066
+				'meta'   => array(
1067
+					'title'  => __('Events', 'event_espresso'),
1068
+					'target' => '',
1069
+					'class'  => $menu_class,
1070
+				),
1071
+			));
1072
+		}
1073
+		if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1074
+			//Events Add New
1075
+			$admin_bar->add_menu(array(
1076
+				'id'     => 'espresso-toolbar-events-new',
1077
+				'parent' => 'espresso-toolbar-events',
1078
+				'title'  => __('Add New', 'event_espresso'),
1079
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1080
+				'meta'   => array(
1081
+					'title'  => __('Add New', 'event_espresso'),
1082
+					'target' => '',
1083
+					'class'  => $menu_class,
1084
+				),
1085
+			));
1086
+		}
1087
+		if (is_single() && (get_post_type() == 'espresso_events')) {
1088
+			//Current post
1089
+			global $post;
1090
+			if ($this->registry->CAP->current_user_can('ee_edit_event',
1091
+				'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1092
+			) {
1093
+				//Events Edit Current Event
1094
+				$admin_bar->add_menu(array(
1095
+					'id'     => 'espresso-toolbar-events-edit',
1096
+					'parent' => 'espresso-toolbar-events',
1097
+					'title'  => __('Edit Event', 'event_espresso'),
1098
+					'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1099
+						$events_admin_url),
1100
+					'meta'   => array(
1101
+						'title'  => __('Edit Event', 'event_espresso'),
1102
+						'target' => '',
1103
+						'class'  => $menu_class,
1104
+					),
1105
+				));
1106
+			}
1107
+		}
1108
+		//Events View
1109
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1110
+			'ee_admin_bar_menu_espresso-toolbar-events-view')
1111
+		) {
1112
+			$admin_bar->add_menu(array(
1113
+				'id'     => 'espresso-toolbar-events-view',
1114
+				'parent' => 'espresso-toolbar-events',
1115
+				'title'  => __('View', 'event_espresso'),
1116
+				'href'   => $events_admin_url,
1117
+				'meta'   => array(
1118
+					'title'  => __('View', 'event_espresso'),
1119
+					'target' => '',
1120
+					'class'  => $menu_class,
1121
+				),
1122
+			));
1123
+		}
1124
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1125
+			//Events View All
1126
+			$admin_bar->add_menu(array(
1127
+				'id'     => 'espresso-toolbar-events-all',
1128
+				'parent' => 'espresso-toolbar-events-view',
1129
+				'title'  => __('All', 'event_espresso'),
1130
+				'href'   => $events_admin_url,
1131
+				'meta'   => array(
1132
+					'title'  => __('All', 'event_espresso'),
1133
+					'target' => '',
1134
+					'class'  => $menu_class,
1135
+				),
1136
+			));
1137
+		}
1138
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1139
+			'ee_admin_bar_menu_espresso-toolbar-events-today')
1140
+		) {
1141
+			//Events View Today
1142
+			$admin_bar->add_menu(array(
1143
+				'id'     => 'espresso-toolbar-events-today',
1144
+				'parent' => 'espresso-toolbar-events-view',
1145
+				'title'  => __('Today', 'event_espresso'),
1146
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1147
+					$events_admin_url),
1148
+				'meta'   => array(
1149
+					'title'  => __('Today', 'event_espresso'),
1150
+					'target' => '',
1151
+					'class'  => $menu_class,
1152
+				),
1153
+			));
1154
+		}
1155
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1156
+			'ee_admin_bar_menu_espresso-toolbar-events-month')
1157
+		) {
1158
+			//Events View This Month
1159
+			$admin_bar->add_menu(array(
1160
+				'id'     => 'espresso-toolbar-events-month',
1161
+				'parent' => 'espresso-toolbar-events-view',
1162
+				'title'  => __('This Month', 'event_espresso'),
1163
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1164
+					$events_admin_url),
1165
+				'meta'   => array(
1166
+					'title'  => __('This Month', 'event_espresso'),
1167
+					'target' => '',
1168
+					'class'  => $menu_class,
1169
+				),
1170
+			));
1171
+		}
1172
+		//Registration Overview
1173
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1174
+			'ee_admin_bar_menu_espresso-toolbar-registrations')
1175
+		) {
1176
+			$admin_bar->add_menu(array(
1177
+				'id'     => 'espresso-toolbar-registrations',
1178
+				'parent' => 'espresso-toolbar',
1179
+				'title'  => __('Registrations', 'event_espresso'),
1180
+				'href'   => $reg_admin_url,
1181
+				'meta'   => array(
1182
+					'title'  => __('Registrations', 'event_espresso'),
1183
+					'target' => '',
1184
+					'class'  => $menu_class,
1185
+				),
1186
+			));
1187
+		}
1188
+		//Registration Overview Today
1189
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1190
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1191
+		) {
1192
+			$admin_bar->add_menu(array(
1193
+				'id'     => 'espresso-toolbar-registrations-today',
1194
+				'parent' => 'espresso-toolbar-registrations',
1195
+				'title'  => __('Today', 'event_espresso'),
1196
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1197
+					$reg_admin_url),
1198
+				'meta'   => array(
1199
+					'title'  => __('Today', 'event_espresso'),
1200
+					'target' => '',
1201
+					'class'  => $menu_class,
1202
+				),
1203
+			));
1204
+		}
1205
+		//Registration Overview Today Completed
1206
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1207
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1208
+		) {
1209
+			$admin_bar->add_menu(array(
1210
+				'id'     => 'espresso-toolbar-registrations-today-approved',
1211
+				'parent' => 'espresso-toolbar-registrations-today',
1212
+				'title'  => __('Approved', 'event_espresso'),
1213
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1214
+					'action'      => 'default',
1215
+					'status'      => 'today',
1216
+					'_reg_status' => EEM_Registration::status_id_approved,
1217
+				), $reg_admin_url),
1218
+				'meta'   => array(
1219
+					'title'  => __('Approved', 'event_espresso'),
1220
+					'target' => '',
1221
+					'class'  => $menu_class,
1222
+				),
1223
+			));
1224
+		}
1225
+		//Registration Overview Today Pending\
1226
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1227
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1228
+		) {
1229
+			$admin_bar->add_menu(array(
1230
+				'id'     => 'espresso-toolbar-registrations-today-pending',
1231
+				'parent' => 'espresso-toolbar-registrations-today',
1232
+				'title'  => __('Pending', 'event_espresso'),
1233
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1234
+					'action'     => 'default',
1235
+					'status'     => 'today',
1236
+					'reg_status' => EEM_Registration::status_id_pending_payment,
1237
+				), $reg_admin_url),
1238
+				'meta'   => array(
1239
+					'title'  => __('Pending Payment', 'event_espresso'),
1240
+					'target' => '',
1241
+					'class'  => $menu_class,
1242
+				),
1243
+			));
1244
+		}
1245
+		//Registration Overview Today Incomplete
1246
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1247
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1248
+		) {
1249
+			$admin_bar->add_menu(array(
1250
+				'id'     => 'espresso-toolbar-registrations-today-not-approved',
1251
+				'parent' => 'espresso-toolbar-registrations-today',
1252
+				'title'  => __('Not Approved', 'event_espresso'),
1253
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1254
+					'action'      => 'default',
1255
+					'status'      => 'today',
1256
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1257
+				), $reg_admin_url),
1258
+				'meta'   => array(
1259
+					'title'  => __('Not Approved', 'event_espresso'),
1260
+					'target' => '',
1261
+					'class'  => $menu_class,
1262
+				),
1263
+			));
1264
+		}
1265
+		//Registration Overview Today Incomplete
1266
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1267
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1268
+		) {
1269
+			$admin_bar->add_menu(array(
1270
+				'id'     => 'espresso-toolbar-registrations-today-cancelled',
1271
+				'parent' => 'espresso-toolbar-registrations-today',
1272
+				'title'  => __('Cancelled', 'event_espresso'),
1273
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1274
+					'action'      => 'default',
1275
+					'status'      => 'today',
1276
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1277
+				), $reg_admin_url),
1278
+				'meta'   => array(
1279
+					'title'  => __('Cancelled', 'event_espresso'),
1280
+					'target' => '',
1281
+					'class'  => $menu_class,
1282
+				),
1283
+			));
1284
+		}
1285
+		//Registration Overview This Month
1286
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1287
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1288
+		) {
1289
+			$admin_bar->add_menu(array(
1290
+				'id'     => 'espresso-toolbar-registrations-month',
1291
+				'parent' => 'espresso-toolbar-registrations',
1292
+				'title'  => __('This Month', 'event_espresso'),
1293
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1294
+					$reg_admin_url),
1295
+				'meta'   => array(
1296
+					'title'  => __('This Month', 'event_espresso'),
1297
+					'target' => '',
1298
+					'class'  => $menu_class,
1299
+				),
1300
+			));
1301
+		}
1302
+		//Registration Overview This Month Approved
1303
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1305
+		) {
1306
+			$admin_bar->add_menu(array(
1307
+				'id'     => 'espresso-toolbar-registrations-month-approved',
1308
+				'parent' => 'espresso-toolbar-registrations-month',
1309
+				'title'  => __('Approved', 'event_espresso'),
1310
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1311
+					'action'      => 'default',
1312
+					'status'      => 'month',
1313
+					'_reg_status' => EEM_Registration::status_id_approved,
1314
+				), $reg_admin_url),
1315
+				'meta'   => array(
1316
+					'title'  => __('Approved', 'event_espresso'),
1317
+					'target' => '',
1318
+					'class'  => $menu_class,
1319
+				),
1320
+			));
1321
+		}
1322
+		//Registration Overview This Month Pending
1323
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1324
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1325
+		) {
1326
+			$admin_bar->add_menu(array(
1327
+				'id'     => 'espresso-toolbar-registrations-month-pending',
1328
+				'parent' => 'espresso-toolbar-registrations-month',
1329
+				'title'  => __('Pending', 'event_espresso'),
1330
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1331
+					'action'      => 'default',
1332
+					'status'      => 'month',
1333
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1334
+				), $reg_admin_url),
1335
+				'meta'   => array(
1336
+					'title'  => __('Pending', 'event_espresso'),
1337
+					'target' => '',
1338
+					'class'  => $menu_class,
1339
+				),
1340
+			));
1341
+		}
1342
+		//Registration Overview This Month Not Approved
1343
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1344
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1345
+		) {
1346
+			$admin_bar->add_menu(array(
1347
+				'id'     => 'espresso-toolbar-registrations-month-not-approved',
1348
+				'parent' => 'espresso-toolbar-registrations-month',
1349
+				'title'  => __('Not Approved', 'event_espresso'),
1350
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1351
+					'action'      => 'default',
1352
+					'status'      => 'month',
1353
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1354
+				), $reg_admin_url),
1355
+				'meta'   => array(
1356
+					'title'  => __('Not Approved', 'event_espresso'),
1357
+					'target' => '',
1358
+					'class'  => $menu_class,
1359
+				),
1360
+			));
1361
+		}
1362
+		//Registration Overview This Month Cancelled
1363
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1364
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1365
+		) {
1366
+			$admin_bar->add_menu(array(
1367
+				'id'     => 'espresso-toolbar-registrations-month-cancelled',
1368
+				'parent' => 'espresso-toolbar-registrations-month',
1369
+				'title'  => __('Cancelled', 'event_espresso'),
1370
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1371
+					'action'      => 'default',
1372
+					'status'      => 'month',
1373
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1374
+				), $reg_admin_url),
1375
+				'meta'   => array(
1376
+					'title'  => __('Cancelled', 'event_espresso'),
1377
+					'target' => '',
1378
+					'class'  => $menu_class,
1379
+				),
1380
+			));
1381
+		}
1382
+		//Extensions & Services
1383
+		if ($this->registry->CAP->current_user_can('ee_read_ee',
1384
+			'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1385
+		) {
1386
+			$admin_bar->add_menu(array(
1387
+				'id'     => 'espresso-toolbar-extensions-and-services',
1388
+				'parent' => 'espresso-toolbar',
1389
+				'title'  => __('Extensions & Services', 'event_espresso'),
1390
+				'href'   => $extensions_admin_url,
1391
+				'meta'   => array(
1392
+					'title'  => __('Extensions & Services', 'event_espresso'),
1393
+					'target' => '',
1394
+					'class'  => $menu_class,
1395
+				),
1396
+			));
1397
+		}
1398
+	}
1399
+
1400
+
1401
+
1402
+	/**
1403
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1404
+	 * never returned with the function.
1405
+	 *
1406
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1407
+	 * @return array
1408
+	 */
1409
+	public function remove_pages_from_wp_list_pages($exclude_array)
1410
+	{
1411
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1412
+	}
1413
+
1414
+
1415
+
1416
+
1417
+
1418
+
1419
+	/***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1420
+	/**
1421
+	 *    wp_enqueue_scripts
1422
+	 *
1423
+	 * @access    public
1424
+	 * @return    void
1425
+	 */
1426
+	public function wp_enqueue_scripts()
1427
+	{
1428
+		// unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1429
+		if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1430
+			// jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431
+			if (apply_filters('FHEE_load_jquery_validate', false)) {
1432
+				// register jQuery Validate and additional methods
1433
+				wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1434
+					array('jquery'), '1.15.0', true);
1435
+				wp_register_script('jquery-validate-extra-methods',
1436
+					EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1437
+					array('jquery', 'jquery-validate'), '1.15.0', true);
1438
+			}
1439
+		}
1440
+	}
1441 1441
 
1442 1442
 
1443 1443
 
Please login to merge, or discard this patch.
core/EE_Encryption.core.php 2 patches
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('No direct script access allowed');
3
+	exit('No direct script access allowed');
4 4
 }
5 5
 
6 6
 
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 
29 29
 	/**
30 30
 	 * 	private constructor to prevent direct creation
31
-     *
31
+	 *
32 32
 	 */
33 33
   private function __construct() {
34 34
 		define( 'ESPRESSO_ENCRYPT', true );
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 
125 125
 	/**
126 126
 	 * encodes string with PHP's base64 encoding
127
-     *
127
+	 *
128 128
 	 * @source  http://php.net/manual/en/function.base64-encode.php
129 129
 	 * @param string $text_string
130 130
 	 * @internal param $string - the text to be encoded
@@ -136,14 +136,14 @@  discard block
 block discarded – undo
136 136
 			return $text_string;
137 137
 		}
138 138
 		// encode
139
-        return base64_encode ( $text_string );
139
+		return base64_encode ( $text_string );
140 140
 	}
141 141
 
142 142
 
143 143
 
144 144
 	/**
145 145
 	 * decodes string that has been encoded with PHP's base64 encoding
146
-     *
146
+	 *
147 147
 	 * @source  http://php.net/manual/en/function.base64-encode.php
148 148
 	 * @param string $encoded_string
149 149
 	 * @internal param $string - the text to be decoded
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 			return $encoded_string;
156 156
 		}
157 157
 		// decode
158
-        return base64_decode ( $encoded_string );
158
+		return base64_decode ( $encoded_string );
159 159
 	}
160 160
 
161 161
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		// encode
177 177
 		$encoded_string = base64_encode ( $text_string );
178 178
 		// remove chars to make encoding more URL friendly
179
-        return strtr ( $encoded_string, '+/=', '-_,' );
179
+		return strtr ( $encoded_string, '+/=', '-_,' );
180 180
 	}
181 181
 
182 182
 
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 		// replace previously removed characters
198 198
 		$encoded_string = strtr ( $encoded_string, '-_,', '+/=' );
199 199
 		// decode
200
-        return base64_decode ( $encoded_string );
200
+		return base64_decode ( $encoded_string );
201 201
 	}
202 202
 
203 203
 
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
 	 */
212 212
 	private function m_encrypt  ( $text_string = '' ) {
213 213
 		// you give me nothing??? GET OUT !
214
-        if (empty($text_string)) {
215
-            return $text_string;
214
+		if (empty($text_string)) {
215
+			return $text_string;
216 216
 		}
217 217
 		// get the initialization vector size
218 218
 		$iv_size = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 		$iv = mcrypt_create_iv ( $iv_size, MCRYPT_RAND );
221 221
 		// encrypt it
222 222
 		$encrypted_text = mcrypt_encrypt ( MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $text_string, MCRYPT_MODE_ECB, $iv );
223
-        // trim and maybe encode
223
+		// trim and maybe encode
224 224
 		return function_exists('base64_encode') ? trim(base64_encode($encrypted_text)) : trim($encrypted_text);
225 225
 	}
226 226
 
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 	 */
236 236
 	private function m_decrypt  ( $encrypted_text = '' )  {
237 237
 		// you give me nothing??? GET OUT !
238
-        if (empty($encrypted_text)) {
239
-            return $encrypted_text;
238
+		if (empty($encrypted_text)) {
239
+			return $encrypted_text;
240 240
 		}
241 241
 		// decode
242
-        $encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
243
-        // get the initialization vector size
242
+		$encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
243
+		// get the initialization vector size
244 244
 		$iv_size = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
245 245
 		$iv = mcrypt_create_iv ( $iv_size, MCRYPT_RAND );
246 246
 		// decrypt it
@@ -261,8 +261,8 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	private function acme_encrypt ( $text_string = '' ) {
263 263
 		// you give me nothing??? GET OUT !
264
-        if (empty($text_string)) {
265
-            return $text_string;
264
+		if (empty($text_string)) {
265
+			return $text_string;
266 266
 		}
267 267
 		$key_bits = str_split ( str_pad ( '', strlen( $text_string ), $this->get_encryption_key(), STR_PAD_RIGHT ));
268 268
 		$string_bits = str_split( $text_string );
@@ -270,15 +270,15 @@  discard block
 block discarded – undo
270 270
 			$temp = ord( $v ) + ord ( $key_bits[$k] );
271 271
 			$string_bits[$k] = chr ( $temp > 255 ? ( $temp - 256 ) : $temp );
272 272
 		}
273
-        return function_exists('base64_encode') ? base64_encode( implode( '', $string_bits ) ) : implode('', $string_bits);
273
+		return function_exists('base64_encode') ? base64_encode( implode( '', $string_bits ) ) : implode('', $string_bits);
274 274
 	}
275 275
 
276 276
 
277 277
 
278 278
 	/**
279
-     * decrypts data for acme servers that didn't bother to install PHP mcrypt
280
-     *
281
-     * @source   : http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
279
+	 * decrypts data for acme servers that didn't bother to install PHP mcrypt
280
+	 *
281
+	 * @source   : http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
282 282
 	 * @param string $encrypted_text the text to be decrypted
283 283
 	 * @return string
284 284
 	 */
@@ -287,46 +287,46 @@  discard block
 block discarded – undo
287 287
 		if  ( empty($encrypted_text))  {
288 288
 			return $encrypted_text;
289 289
 		}
290
-        // decode the data ?
291
-        $encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
290
+		// decode the data ?
291
+		$encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
292 292
 		$key_bits = str_split ( str_pad ( '', strlen ( $encrypted_text ), $this->get_encryption_key(), STR_PAD_RIGHT ));
293 293
 		$string_bits = str_split ( $encrypted_text );
294 294
 		foreach ( $string_bits as $k => $v ) {
295 295
 			$temp = ord ( $v ) - ord ( $key_bits[$k] );
296 296
 			$string_bits[$k] = chr ( $temp < 0 ? ( $temp + 256 ) : $temp );
297 297
 		}
298
-        return implode( '', $string_bits );
298
+		return implode( '', $string_bits );
299 299
 	}
300 300
 
301 301
 
302 302
 
303
-    /**
304
-     * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
305
-     * @param $string
306
-     * @return bool
307
-     */
308
-    private function valid_base_64($string)
309
-    {
310
-        // ensure data is a string
311
-        if ( ! is_string($string) || ! function_exists('base64_decode')) {
312
-            return false;
313
-        }
314
-        $decoded = base64_decode($string, true);
315
-        // Check if there is no invalid character in string
316
-        if ( ! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
317
-            return false;
318
-        }
319
-        // Decode the string in strict mode and send the response
320
-        if ( ! base64_decode($string, true)) {
321
-            return false;
322
-        }
323
-        // Encode and compare it to original one
324
-        return base64_encode($decoded) === $string;
325
-    }
326
-
327
-
328
-
329
-    /**
303
+	/**
304
+	 * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
305
+	 * @param $string
306
+	 * @return bool
307
+	 */
308
+	private function valid_base_64($string)
309
+	{
310
+		// ensure data is a string
311
+		if ( ! is_string($string) || ! function_exists('base64_decode')) {
312
+			return false;
313
+		}
314
+		$decoded = base64_decode($string, true);
315
+		// Check if there is no invalid character in string
316
+		if ( ! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
317
+			return false;
318
+		}
319
+		// Decode the string in strict mode and send the response
320
+		if ( ! base64_decode($string, true)) {
321
+			return false;
322
+		}
323
+		// Encode and compare it to original one
324
+		return base64_encode($decoded) === $string;
325
+	}
326
+
327
+
328
+
329
+	/**
330 330
 	 * generate random string
331 331
 	 * @source   : http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
332 332
 	 * @access   public
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -31,8 +31,8 @@  discard block
 block discarded – undo
31 31
      *
32 32
 	 */
33 33
   private function __construct() {
34
-		define( 'ESPRESSO_ENCRYPT', true );
35
-		if ( ! function_exists( 'mcrypt_encrypt' ) ) {
34
+		define('ESPRESSO_ENCRYPT', true);
35
+		if ( ! function_exists('mcrypt_encrypt')) {
36 36
 			$this->_use_mcrypt = false;
37 37
 		}
38 38
 	}
@@ -44,9 +44,9 @@  discard block
 block discarded – undo
44 44
 	 *	@access public
45 45
 	 * @return \EE_Encryption
46 46
 	 */
47
-	public static function instance ( ) {
47
+	public static function instance( ) {
48 48
 		// check if class object is instantiated
49
-		if ( ! self::$_instance instanceof EE_Encryption ) {
49
+		if ( ! self::$_instance instanceof EE_Encryption) {
50 50
 			self::$_instance = new self();
51 51
 		}
52 52
 		return self::$_instance;
@@ -61,15 +61,15 @@  discard block
 block discarded – undo
61 61
 	 */
62 62
 	public  function get_encryption_key() {
63 63
 		// if encryption key has not been set
64
-		if ( empty( $this->_encryption_key )) {
64
+		if (empty($this->_encryption_key)) {
65 65
 			// retrieve encryption_key from db
66
-			$this->_encryption_key = get_option( 'ee_encryption_key', '' );
66
+			$this->_encryption_key = get_option('ee_encryption_key', '');
67 67
 			// WHAT?? No encryption_key in the db ??
68
-			if ( $this->_encryption_key === '' ) {
68
+			if ($this->_encryption_key === '') {
69 69
 				// let's make one. And md5 it to make it just the right size for a key
70
-				$new_key =  md5($this->generate_random_string());
70
+				$new_key = md5($this->generate_random_string());
71 71
 				// now save it to the db for later
72
-				add_option( 'ee_encryption_key', $new_key );
72
+				add_option('ee_encryption_key', $new_key);
73 73
 				// here's the key - FINALLY !
74 74
 				$this->_encryption_key = $new_key;
75 75
 			}
@@ -85,15 +85,15 @@  discard block
 block discarded – undo
85 85
 	 * @param string $text_string  - the text to be encrypted
86 86
 	 * @return string
87 87
 	 */
88
-	public function encrypt ( $text_string = '' ) {
88
+	public function encrypt($text_string = '') {
89 89
 		// you give me nothing??? GET OUT !
90
-		if  ( empty( $text_string ))  {
90
+		if (empty($text_string)) {
91 91
 			return $text_string;
92 92
 		}
93
-		if ( $this->_use_mcrypt ) {
94
-			$encrypted_text = $this->m_encrypt( $text_string );
93
+		if ($this->_use_mcrypt) {
94
+			$encrypted_text = $this->m_encrypt($text_string);
95 95
 		} else {
96
-			$encrypted_text = $this->acme_encrypt( $text_string );
96
+			$encrypted_text = $this->acme_encrypt($text_string);
97 97
 		}
98 98
 		return $encrypted_text;
99 99
 	}
@@ -106,16 +106,16 @@  discard block
 block discarded – undo
106 106
 	 * @param string $encrypted_text - the text to be decrypted
107 107
 	 * @return string
108 108
 	 */
109
-	public function decrypt  ( $encrypted_text = '' )  {
109
+	public function decrypt($encrypted_text = '') {
110 110
 		// you give me nothing??? GET OUT !
111
-		if  ( empty( $encrypted_text ))  {
111
+		if (empty($encrypted_text)) {
112 112
 			return $encrypted_text;
113 113
 		}
114 114
 		// if PHP's mcrypt functions are installed then we'll use them
115
-		if ( $this->_use_mcrypt ) {
116
-			$decrypted_text = $this->m_decrypt( $encrypted_text );
115
+		if ($this->_use_mcrypt) {
116
+			$decrypted_text = $this->m_decrypt($encrypted_text);
117 117
 		} else {
118
-			$decrypted_text = $this->acme_decrypt( $encrypted_text );
118
+			$decrypted_text = $this->acme_decrypt($encrypted_text);
119 119
 		}
120 120
 		return $decrypted_text;
121 121
  	}
@@ -130,13 +130,13 @@  discard block
 block discarded – undo
130 130
 	 * @internal param $string - the text to be encoded
131 131
 	 * @return string
132 132
 	 */
133
-	public function base64_string_encode ( $text_string = '' ) {
133
+	public function base64_string_encode($text_string = '') {
134 134
 		// you give me nothing??? GET OUT !
135
-		if  (empty($text_string) || ! function_exists('base64_encode'))  {
135
+		if (empty($text_string) || ! function_exists('base64_encode')) {
136 136
 			return $text_string;
137 137
 		}
138 138
 		// encode
139
-        return base64_encode ( $text_string );
139
+        return base64_encode($text_string);
140 140
 	}
141 141
 
142 142
 
@@ -149,13 +149,13 @@  discard block
 block discarded – undo
149 149
 	 * @internal param $string - the text to be decoded
150 150
 	 * @return string
151 151
 	 */
152
-	public function base64_string_decode ( $encoded_string = '' ) {
152
+	public function base64_string_decode($encoded_string = '') {
153 153
 		// you give me nothing??? GET OUT !
154
-		if  (empty($encoded_string) || ! $this->valid_base_64($encoded_string))  {
154
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
155 155
 			return $encoded_string;
156 156
 		}
157 157
 		// decode
158
-        return base64_decode ( $encoded_string );
158
+        return base64_decode($encoded_string);
159 159
 	}
160 160
 
161 161
 
@@ -168,15 +168,15 @@  discard block
 block discarded – undo
168 168
 	 * @internal param $string - the text to be encoded
169 169
 	 * @return string
170 170
 	 */
171
-	public function base64_url_encode ( $text_string = '' ) {
171
+	public function base64_url_encode($text_string = '') {
172 172
 		// you give me nothing??? GET OUT !
173
-		if  (empty($text_string) || ! function_exists('base64_encode'))  {
173
+		if (empty($text_string) || ! function_exists('base64_encode')) {
174 174
 			return $text_string;
175 175
 		}
176 176
 		// encode
177
-		$encoded_string = base64_encode ( $text_string );
177
+		$encoded_string = base64_encode($text_string);
178 178
 		// remove chars to make encoding more URL friendly
179
-        return strtr ( $encoded_string, '+/=', '-_,' );
179
+        return strtr($encoded_string, '+/=', '-_,');
180 180
 	}
181 181
 
182 182
 
@@ -189,15 +189,15 @@  discard block
 block discarded – undo
189 189
 	 * @internal param $string - the text to be decoded
190 190
 	 * @return string
191 191
 	 */
192
-	public function base64_url_decode ( $encoded_string = '' ) {
192
+	public function base64_url_decode($encoded_string = '') {
193 193
 		// you give me nothing??? GET OUT !
194
-		if  (empty($encoded_string) || ! $this->valid_base_64($encoded_string))  {
194
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
195 195
 			return $encoded_string;
196 196
 		}
197 197
 		// replace previously removed characters
198
-		$encoded_string = strtr ( $encoded_string, '-_,', '+/=' );
198
+		$encoded_string = strtr($encoded_string, '-_,', '+/=');
199 199
 		// decode
200
-        return base64_decode ( $encoded_string );
200
+        return base64_decode($encoded_string);
201 201
 	}
202 202
 
203 203
 
@@ -209,17 +209,17 @@  discard block
 block discarded – undo
209 209
 	 * @internal param $string - the text to be encrypted
210 210
 	 * @return string
211 211
 	 */
212
-	private function m_encrypt  ( $text_string = '' ) {
212
+	private function m_encrypt($text_string = '') {
213 213
 		// you give me nothing??? GET OUT !
214 214
         if (empty($text_string)) {
215 215
             return $text_string;
216 216
 		}
217 217
 		// get the initialization vector size
218
-		$iv_size = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
218
+		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
219 219
 		// initialization vector
220
-		$iv = mcrypt_create_iv ( $iv_size, MCRYPT_RAND );
220
+		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
221 221
 		// encrypt it
222
-		$encrypted_text = mcrypt_encrypt ( MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $text_string, MCRYPT_MODE_ECB, $iv );
222
+		$encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $text_string, MCRYPT_MODE_ECB, $iv);
223 223
         // trim and maybe encode
224 224
 		return function_exists('base64_encode') ? trim(base64_encode($encrypted_text)) : trim($encrypted_text);
225 225
 	}
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 	 * @internal param $string - the text to be decrypted
234 234
 	 * @return string
235 235
 	 */
236
-	private function m_decrypt  ( $encrypted_text = '' )  {
236
+	private function m_decrypt($encrypted_text = '') {
237 237
 		// you give me nothing??? GET OUT !
238 238
         if (empty($encrypted_text)) {
239 239
             return $encrypted_text;
@@ -241,11 +241,11 @@  discard block
 block discarded – undo
241 241
 		// decode
242 242
         $encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
243 243
         // get the initialization vector size
244
-		$iv_size = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
245
-		$iv = mcrypt_create_iv ( $iv_size, MCRYPT_RAND );
244
+		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
245
+		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
246 246
 		// decrypt it
247
-		$decrypted_text = mcrypt_decrypt ( MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $encrypted_text, MCRYPT_MODE_ECB, $iv );
248
-		$decrypted_text = trim ( $decrypted_text );
247
+		$decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $encrypted_text, MCRYPT_MODE_ECB, $iv);
248
+		$decrypted_text = trim($decrypted_text);
249 249
 		return $decrypted_text;
250 250
 	}
251 251
 
@@ -259,18 +259,18 @@  discard block
 block discarded – undo
259 259
 	 * @internal param $string - the text to be decrypted
260 260
 	 * @return string
261 261
 	 */
262
-	private function acme_encrypt ( $text_string = '' ) {
262
+	private function acme_encrypt($text_string = '') {
263 263
 		// you give me nothing??? GET OUT !
264 264
         if (empty($text_string)) {
265 265
             return $text_string;
266 266
 		}
267
-		$key_bits = str_split ( str_pad ( '', strlen( $text_string ), $this->get_encryption_key(), STR_PAD_RIGHT ));
268
-		$string_bits = str_split( $text_string );
269
-		foreach ( $string_bits as $k =>$v ) {
270
-			$temp = ord( $v ) + ord ( $key_bits[$k] );
271
-			$string_bits[$k] = chr ( $temp > 255 ? ( $temp - 256 ) : $temp );
267
+		$key_bits = str_split(str_pad('', strlen($text_string), $this->get_encryption_key(), STR_PAD_RIGHT));
268
+		$string_bits = str_split($text_string);
269
+		foreach ($string_bits as $k =>$v) {
270
+			$temp = ord($v) + ord($key_bits[$k]);
271
+			$string_bits[$k] = chr($temp > 255 ? ($temp - 256) : $temp);
272 272
 		}
273
-        return function_exists('base64_encode') ? base64_encode( implode( '', $string_bits ) ) : implode('', $string_bits);
273
+        return function_exists('base64_encode') ? base64_encode(implode('', $string_bits)) : implode('', $string_bits);
274 274
 	}
275 275
 
276 276
 
@@ -282,20 +282,20 @@  discard block
 block discarded – undo
282 282
 	 * @param string $encrypted_text the text to be decrypted
283 283
 	 * @return string
284 284
 	 */
285
-	private function acme_decrypt ( $encrypted_text = '' ) {
285
+	private function acme_decrypt($encrypted_text = '') {
286 286
 		// you give me nothing??? GET OUT !
287
-		if  ( empty($encrypted_text))  {
287
+		if (empty($encrypted_text)) {
288 288
 			return $encrypted_text;
289 289
 		}
290 290
         // decode the data ?
291 291
         $encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
292
-		$key_bits = str_split ( str_pad ( '', strlen ( $encrypted_text ), $this->get_encryption_key(), STR_PAD_RIGHT ));
293
-		$string_bits = str_split ( $encrypted_text );
294
-		foreach ( $string_bits as $k => $v ) {
295
-			$temp = ord ( $v ) - ord ( $key_bits[$k] );
296
-			$string_bits[$k] = chr ( $temp < 0 ? ( $temp + 256 ) : $temp );
292
+		$key_bits = str_split(str_pad('', strlen($encrypted_text), $this->get_encryption_key(), STR_PAD_RIGHT));
293
+		$string_bits = str_split($encrypted_text);
294
+		foreach ($string_bits as $k => $v) {
295
+			$temp = ord($v) - ord($key_bits[$k]);
296
+			$string_bits[$k] = chr($temp < 0 ? ($temp + 256) : $temp);
297 297
 		}
298
-        return implode( '', $string_bits );
298
+        return implode('', $string_bits);
299 299
 	}
300 300
 
301 301
 
@@ -334,13 +334,13 @@  discard block
 block discarded – undo
334 334
 	 * @internal param $string - number of characters for random string
335 335
 	 * @return string
336 336
 	 */
337
-	public function generate_random_string ( $length = 40 ) {
338
-		$iterations = ceil ( $length / 40 );
337
+	public function generate_random_string($length = 40) {
338
+		$iterations = ceil($length / 40);
339 339
 		$random_string = '';
340
-		for ($i = 0; $i < $iterations; $i ++) {
341
-			$random_string .= sha1( microtime(TRUE) . mt_rand( 10000, 90000 ));
340
+		for ($i = 0; $i < $iterations; $i++) {
341
+			$random_string .= sha1(microtime(TRUE).mt_rand(10000, 90000));
342 342
 		}
343
-		$random_string =  substr( $random_string, 0, $length );
343
+		$random_string = substr($random_string, 0, $length);
344 344
 		return $random_string;
345 345
 	}
346 346
 
Please login to merge, or discard this patch.
admin_pages/maintenance/Maintenance_Admin_Page.core.php 2 patches
Indentation   +542 added lines, -542 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 
@@ -28,562 +28,562 @@  discard block
 block discarded – undo
28 28
 {
29 29
 
30 30
 
31
-    public function __construct($routing = true)
32
-    {
33
-        parent::__construct($routing);
34
-    }
35
-
36
-
37
-
38
-    protected function _init_page_props()
39
-    {
40
-        $this->page_slug = EE_MAINTENANCE_PG_SLUG;
41
-        $this->page_label = EE_MAINTENANCE_LABEL;
42
-        $this->_admin_base_url = EE_MAINTENANCE_ADMIN_URL;
43
-        $this->_admin_base_path = EE_MAINTENANCE_ADMIN;
44
-    }
45
-
46
-
47
-
48
-    protected function _ajax_hooks()
49
-    {
50
-        add_action('wp_ajax_migration_step', array($this, 'migration_step'));
51
-        add_action('wp_ajax_add_error_to_migrations_ran', array($this, 'add_error_to_migrations_ran'));
52
-    }
53
-
54
-
55
-
56
-    protected function _define_page_props()
57
-    {
58
-        $this->_admin_page_title = EE_MAINTENANCE_LABEL;
59
-        $this->_labels = array(
60
-            'buttons' => array(
61
-                'reset_capabilities' => __('Reset Event Espresso Capabilities', 'event_espresso'),
62
-            ),
63
-        );
64
-    }
65
-
66
-
67
-
68
-    protected function _set_page_routes()
69
-    {
70
-        $this->_page_routes = array(
71
-            'default'                             => array(
72
-                'func'       => '_maintenance',
73
-                'capability' => 'manage_options',
74
-            ),
75
-            'change_maintenance_level'            => array(
76
-                'func'       => '_change_maintenance_level',
77
-                'capability' => 'manage_options',
78
-                'noheader'   => true,
79
-            ),
80
-            'system_status'                       => array(
81
-                'func'       => '_system_status',
82
-                'capability' => 'manage_options',
83
-            ),
84
-            'send_migration_crash_report'         => array(
85
-                'func'       => '_send_migration_crash_report',
86
-                'capability' => 'manage_options',
87
-                'noheader'   => true,
88
-            ),
89
-            'confirm_migration_crash_report_sent' => array(
90
-                'func'       => '_confirm_migration_crash_report_sent',
91
-                'capability' => 'manage_options',
92
-            ),
93
-            'data_reset'                          => array(
94
-                'func'       => '_data_reset_and_delete',
95
-                'capability' => 'manage_options',
96
-            ),
97
-            'reset_db'                            => array(
98
-                'func'       => '_reset_db',
99
-                'capability' => 'manage_options',
100
-                'noheader'   => true,
101
-                'args'       => array('nuke_old_ee4_data' => true),
102
-            ),
103
-            'start_with_fresh_ee4_db'             => array(
104
-                'func'       => '_reset_db',
105
-                'capability' => 'manage_options',
106
-                'noheader'   => true,
107
-                'args'       => array('nuke_old_ee4_data' => false),
108
-            ),
109
-            'delete_db'                           => array(
110
-                'func'       => '_delete_db',
111
-                'capability' => 'manage_options',
112
-                'noheader'   => true,
113
-            ),
114
-            'rerun_migration_from_ee3'            => array(
115
-                'func'       => '_rerun_migration_from_ee3',
116
-                'capability' => 'manage_options',
117
-                'noheader'   => true,
118
-            ),
119
-            'reset_capabilities'                  => array(
120
-                'func'       => '_reset_capabilities',
121
-                'capability' => 'manage_options',
122
-                'noheader'   => true,
123
-            ),
124
-            'reattempt_migration'                 => array(
125
-                'func'       => '_reattempt_migration',
126
-                'capability' => 'manage_options',
127
-                'noheader'   => true,
128
-            ),
129
-        );
130
-    }
131
-
132
-
133
-
134
-    protected function _set_page_config()
135
-    {
136
-        $this->_page_config = array(
137
-            'default'       => array(
138
-                'nav'           => array(
139
-                    'label' => __('Maintenance', 'event_espresso'),
140
-                    'order' => 10,
141
-                ),
142
-                'require_nonce' => false,
143
-            ),
144
-            'data_reset'    => array(
145
-                'nav'           => array(
146
-                    'label' => __('Reset/Delete Data', 'event_espresso'),
147
-                    'order' => 20,
148
-                ),
149
-                'require_nonce' => false,
150
-            ),
151
-            'system_status' => array(
152
-                'nav'           => array(
153
-                    'label' => __("System Information", "event_espresso"),
154
-                    'order' => 30,
155
-                ),
156
-                'require_nonce' => false,
157
-            ),
158
-        );
159
-    }
160
-
161
-
162
-
163
-    /**
164
-     * default maintenance page. If we're in maintenance mode level 2, then we need to show
165
-     * the migration scripts and all that UI.
166
-     */
167
-    public function _maintenance()
168
-    {
169
-        //it all depends if we're in maintenance model level 1 (frontend-only) or
170
-        //level 2 (everything except maintenance page)
171
-        try {
172
-            //get the current maintenance level and check if
173
-            //we are removed
174
-            $mm = EE_Maintenance_Mode::instance()->level();
175
-            $placed_in_mm = EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
176
-            if ($mm == EE_Maintenance_Mode::level_2_complete_maintenance && ! $placed_in_mm) {
177
-                //we just took the site out of maintenance mode, so notify the user.
178
-                //unfortunately this message appears to be echoed on the NEXT page load...
179
-                //oh well, we should really be checking for this on addon deactivation anyways
180
-                EE_Error::add_attention(__('Site taken out of maintenance mode because no data migration scripts are required',
181
-                    'event_espresso'));
182
-                $this->_process_notices(array('page' => 'espresso_maintenance_settings'), false);
183
-            }
184
-            //in case an exception is thrown while trying to handle migrations
185
-            switch (EE_Maintenance_Mode::instance()->level()) {
186
-                case EE_Maintenance_Mode::level_0_not_in_maintenance:
187
-                case EE_Maintenance_Mode::level_1_frontend_only_maintenance:
188
-                    $show_maintenance_switch = true;
189
-                    $show_backup_db_text = false;
190
-                    $show_migration_progress = false;
191
-                    $script_names = array();
192
-                    $addons_should_be_upgraded_first = false;
193
-                    break;
194
-                case EE_Maintenance_Mode::level_2_complete_maintenance:
195
-                    $show_maintenance_switch = false;
196
-                    $show_migration_progress = true;
197
-                    if (isset($this->_req_data['continue_migration'])) {
198
-                        $show_backup_db_text = false;
199
-                    } else {
200
-                        $show_backup_db_text = true;
201
-                    }
202
-                    $scripts_needing_to_run = EE_Data_Migration_Manager::instance()
203
-                                                                       ->check_for_applicable_data_migration_scripts();
204
-                    $addons_should_be_upgraded_first = EE_Data_Migration_Manager::instance()->addons_need_updating();
205
-                    $script_names = array();
206
-                    $current_script = null;
207
-                    foreach ($scripts_needing_to_run as $script) {
208
-                        if ($script instanceof EE_Data_Migration_Script_Base) {
209
-                            if ( ! $current_script) {
210
-                                $current_script = $script;
211
-                                $current_script->migration_page_hooks();
212
-                            }
213
-                            $script_names[] = $script->pretty_name();
214
-                        }
215
-                    }
216
-                    break;
217
-            }
218
-            $most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
219
-            $exception_thrown = false;
220
-        } catch (EE_Error $e) {
221
-            EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
222
-            //now, just so we can display the page correctly, make a error migration script stage object
223
-            //and also put the error on it. It only persists for the duration of this request
224
-            $most_recent_migration = new EE_DMS_Unknown_1_0_0();
225
-            $most_recent_migration->add_error($e->getMessage());
226
-            $exception_thrown = true;
227
-        }
228
-        $current_db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set();
229
-        $current_db_state = str_replace('.decaf', '', $current_db_state);
230
-        if ($exception_thrown
231
-            || ($most_recent_migration
232
-                && $most_recent_migration instanceof EE_Data_Migration_Script_Base
233
-                && $most_recent_migration->is_broken()
234
-            )
235
-        ) {
236
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
237
-            $this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
238
-            $this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(array('action'  => 'confirm_migration_crash_report_sent',
239
-                                                                                        'success' => '0',
240
-            ), EE_MAINTENANCE_ADMIN_URL);
241
-        } elseif ($addons_should_be_upgraded_first) {
242
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
243
-        } else {
244
-            if ($most_recent_migration
245
-                && $most_recent_migration instanceof EE_Data_Migration_Script_Base
246
-                && $most_recent_migration->can_continue()
247
-            ) {
248
-                $show_backup_db_text = false;
249
-                $show_continue_current_migration_script = true;
250
-                $show_most_recent_migration = true;
251
-            } elseif (isset($this->_req_data['continue_migration'])) {
252
-                $show_most_recent_migration = true;
253
-                $show_continue_current_migration_script = false;
254
-            } else {
255
-                $show_most_recent_migration = false;
256
-                $show_continue_current_migration_script = false;
257
-            }
258
-            if (isset($current_script)) {
259
-                $migrates_to = $current_script->migrates_to_version();
260
-                $plugin_slug = $migrates_to['slug'];
261
-                $new_version = $migrates_to['version'];
262
-                $this->_template_args = array_merge($this->_template_args, array(
263
-                    'current_db_state' => sprintf(__("EE%s (%s)", "event_espresso"),
264
-                        isset($current_db_state[$plugin_slug]) ? $current_db_state[$plugin_slug] : 3, $plugin_slug),
265
-                    'next_db_state'    => isset($current_script) ? sprintf(__("EE%s (%s)", 'event_espresso'),
266
-                        $new_version, $plugin_slug) : null,
267
-                ));
268
-            }
269
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
270
-            $this->_template_args = array_merge(
271
-                $this->_template_args,
272
-                array(
273
-                    'show_most_recent_migration'             => $show_most_recent_migration,
274
-                    //flag for showing the most recent migration's status and/or errors
275
-                    'show_migration_progress'                => $show_migration_progress,
276
-                    //flag for showing the option to run migrations and see their progress
277
-                    'show_backup_db_text'                    => $show_backup_db_text,
278
-                    //flag for showing text telling the user to backup their DB
279
-                    'show_maintenance_switch'                => $show_maintenance_switch,
280
-                    //flag for showing the option to change maintenance mode between levels 0 and 1
281
-                    'script_names'                           => $script_names,
282
-                    //array of names of scripts that have run
283
-                    'show_continue_current_migration_script' => $show_continue_current_migration_script,
284
-                    //flag to change wording to indicating that we're only CONTINUING a migration script (somehow it got interrupted0
285
-                    'reset_db_page_link'                     => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
286
-                        EE_MAINTENANCE_ADMIN_URL),
287
-                    'update_migration_script_page_link'      => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'change_maintenance_level'),
288
-                        EE_MAINTENANCE_ADMIN_URL),
289
-                    'ultimate_db_state'                      => sprintf(__("EE%s", 'event_espresso'),
290
-                        espresso_version()),
291
-                )
292
-            );
293
-            //make sure we have the form fields helper available. It usually is, but sometimes it isn't
294
-            //localize script stuff
295
-            wp_localize_script('ee-maintenance', 'ee_maintenance', array(
296
-                'migrating'                        => __("Migrating...", "event_espresso"),
297
-                'next'                             => __("Next", "event_espresso"),
298
-                'fatal_error'                      => __("A Fatal Error Has Occurred", "event_espresso"),
299
-                'click_next_when_ready'            => __("The current Migration has ended. Click 'next' when ready to proceed",
300
-                    "event_espresso"),
301
-                'status_no_more_migration_scripts' => EE_Data_Migration_Manager::status_no_more_migration_scripts,
302
-                'status_fatal_error'               => EE_Data_Migration_Manager::status_fatal_error,
303
-                'status_completed'                 => EE_Data_Migration_Manager::status_completed,
304
-            ));
305
-        }
306
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;//the actual most recently ran migration
307
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
308
-            $this->_template_args, true);
309
-        $this->display_admin_page_with_sidebar();
310
-    }
311
-
312
-
313
-
314
-    /**
315
-     * returns JSON and executes another step of the currently-executing data migration (called via ajax)
316
-     */
317
-    public function migration_step()
318
-    {
319
-        $this->_template_args['data'] = EE_Data_Migration_Manager::instance()->response_to_migration_ajax_request();
320
-        $this->_return_json();
321
-    }
322
-
323
-
324
-
325
-    /**
326
-     * Can be used by js when it notices a response with HTML in it in order
327
-     * to log the malformed response
328
-     */
329
-    public function add_error_to_migrations_ran()
330
-    {
331
-        EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($this->_req_data['message']);
332
-        $this->_template_args['data'] = array('ok' => true);
333
-        $this->_return_json();
334
-    }
335
-
336
-
337
-
338
-    /**
339
-     * changes the maintenance level, provided there are still no migration scripts that shoudl run
340
-     */
341
-    public function _change_maintenance_level()
342
-    {
343
-        $new_level = intval($this->_req_data['maintenance_mode_level']);
344
-        if ( ! EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
345
-            EE_Maintenance_Mode::instance()->set_maintenance_level($new_level);
346
-            $success = true;
347
-        } else {
348
-            EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
349
-            $success = false;
350
-        }
351
-        $this->_redirect_after_action($success, 'Maintenance Mode', __("Updated", "event_espresso"));
352
-    }
353
-
354
-
355
-
356
-    /**
357
-     * a tab with options for resetting and/or deleting EE data
358
-     *
359
-     * @throws \EE_Error
360
-     */
361
-    public function _data_reset_and_delete()
362
-    {
363
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
364
-        $this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
365
-            'reset_capabilities',
366
-            'reset_capabilities',
367
-            array(),
368
-            'button button-primary',
369
-            '',
370
-            false
371
-        );
372
-        $this->_template_args['delete_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
373
-            array('action' => 'delete_db'),
374
-            EE_MAINTENANCE_ADMIN_URL
375
-        );
376
-        $this->_template_args['reset_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
377
-            array('action' => 'reset_db'),
378
-            EE_MAINTENANCE_ADMIN_URL
379
-        );
380
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
381
-            $this->_template_path,
382
-            $this->_template_args,
383
-            true
384
-        );
385
-        $this->display_admin_page_with_sidebar();
386
-    }
387
-
388
-
389
-
390
-    protected function _reset_capabilities()
391
-    {
392
-        EE_Registry::instance()->CAP->init_caps(true);
393
-        EE_Error::add_success(__('Default Event Espresso capabilities have been restored for all current roles.',
394
-            'event_espresso'));
395
-        $this->_redirect_after_action(false, '', '', array('action' => 'data_reset'), true);
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * resets the DMSs so we can attempt to continue migrating after a fatal error
402
-     * (only a good idea when someone has somehow tried ot fix whatever caused
403
-     * the fatal error in teh first place)
404
-     */
405
-    protected function _reattempt_migration()
406
-    {
407
-        EE_Data_Migration_Manager::instance()->reattempt();
408
-        $this->_redirect_after_action(false, '', '', array('action' => 'default'), true);
409
-    }
410
-
411
-
412
-
413
-    /**
414
-     * shows the big ol' System Information page
415
-     */
416
-    public function _system_status()
417
-    {
418
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
419
-        $this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
420
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
421
-            $this->_template_args, true);
422
-        $this->display_admin_page_with_sidebar();
423
-    }
424
-
425
-
426
-
427
-    public function _send_migration_crash_report()
428
-    {
429
-        $from = $this->_req_data['from'];
430
-        $from_name = $this->_req_data['from_name'];
431
-        $body = $this->_req_data['body'];
432
-        try {
433
-            $success = wp_mail(EE_SUPPORT_EMAIL,
434
-                'Migration Crash Report',
435
-                $body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
436
-                array(
437
-                    "from:$from_name<$from>",
438
-                    //					'content-type:text/html charset=UTF-8'
439
-                ));
440
-        } catch (Exception $e) {
441
-            $success = false;
442
-        }
443
-        $this->_redirect_after_action($success, __("Migration Crash Report", "event_espresso"),
444
-            __("sent", "event_espresso"),
445
-            array('success' => $success, 'action' => 'confirm_migration_crash_report_sent'));
446
-    }
447
-
448
-
449
-
450
-    public function _confirm_migration_crash_report_sent()
451
-    {
452
-        try {
453
-            $most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
454
-        } catch (EE_Error $e) {
455
-            EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
456
-            //now, just so we can display the page correctly, make a error migration script stage object
457
-            //and also put the error on it. It only persists for the duration of this request
458
-            $most_recent_migration = new EE_DMS_Unknown_1_0_0();
459
-            $most_recent_migration->add_error($e->getMessage());
460
-        }
461
-        $success = $this->_req_data['success'] == '1' ? true : false;
462
-        $this->_template_args['success'] = $success;
463
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;
464
-        $this->_template_args['reset_db_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
465
-            EE_MAINTENANCE_ADMIN_URL);
466
-        $this->_template_args['reset_db_page_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'data_reset'),
467
-            EE_MAINTENANCE_ADMIN_URL);
468
-        $this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reattempt_migration'),
469
-            EE_MAINTENANCE_ADMIN_URL);
470
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
471
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
472
-            $this->_template_args, true);
473
-        $this->display_admin_page_with_sidebar();
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * Resets the entire EE4 database.
480
-     * Currently basically only sets up ee4 database for a fresh install- doesn't
481
-     * actually clean out the old wp options, or cpts (although does erase old ee table data)
482
-     *
483
-     * @param boolean $nuke_old_ee4_data controls whether or not we
484
-     *                                   destroy the old ee4 data, or just try initializing ee4 default data
485
-     */
486
-    public function _reset_db($nuke_old_ee4_data = true)
487
-    {
488
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
489
-        if ($nuke_old_ee4_data) {
490
-            EEH_Activation::delete_all_espresso_cpt_data();
491
-            EEH_Activation::delete_all_espresso_tables_and_data(false);
492
-            EEH_Activation::remove_cron_tasks();
493
-        }
494
-        //make sure when we reset the registry's config that it
495
-        //switches to using the new singleton
496
-        EE_Registry::instance()->CFG = EE_Registry::instance()->CFG->reset(true);
497
-        EE_System::instance()->initialize_db_if_no_migrations_required(true);
498
-        EE_System::instance()->redirect_to_about_ee();
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * Deletes ALL EE tables, Records, and Options from the database.
505
-     */
506
-    public function _delete_db()
507
-    {
508
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
509
-        EEH_Activation::delete_all_espresso_cpt_data();
510
-        EEH_Activation::delete_all_espresso_tables_and_data();
511
-        EEH_Activation::remove_cron_tasks();
512
-        EEH_Activation::deactivate_event_espresso();
513
-        wp_safe_redirect(admin_url('plugins.php'));
514
-        exit;
515
-    }
516
-
517
-
518
-
519
-    /**
520
-     * sets up EE4 to rerun the migrations from ee3 to ee4
521
-     */
522
-    public function _rerun_migration_from_ee3()
523
-    {
524
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
525
-        EEH_Activation::delete_all_espresso_cpt_data();
526
-        EEH_Activation::delete_all_espresso_tables_and_data(false);
527
-        //set the db state to something that will require migrations
528
-        update_option(EE_Data_Migration_Manager::current_database_state, '3.1.36.0');
529
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_2_complete_maintenance);
530
-        $this->_redirect_after_action(true, __("Database", 'event_espresso'), __("reset", 'event_espresso'));
531
-    }
532
-
533
-
534
-
535
-    //none of the below group are currently used for Gateway Settings
536
-    protected function _add_screen_options()
537
-    {
538
-    }
539
-
540
-
541
-
542
-    protected function _add_feature_pointers()
543
-    {
544
-    }
545
-
31
+	public function __construct($routing = true)
32
+	{
33
+		parent::__construct($routing);
34
+	}
35
+
36
+
37
+
38
+	protected function _init_page_props()
39
+	{
40
+		$this->page_slug = EE_MAINTENANCE_PG_SLUG;
41
+		$this->page_label = EE_MAINTENANCE_LABEL;
42
+		$this->_admin_base_url = EE_MAINTENANCE_ADMIN_URL;
43
+		$this->_admin_base_path = EE_MAINTENANCE_ADMIN;
44
+	}
45
+
46
+
47
+
48
+	protected function _ajax_hooks()
49
+	{
50
+		add_action('wp_ajax_migration_step', array($this, 'migration_step'));
51
+		add_action('wp_ajax_add_error_to_migrations_ran', array($this, 'add_error_to_migrations_ran'));
52
+	}
53
+
54
+
55
+
56
+	protected function _define_page_props()
57
+	{
58
+		$this->_admin_page_title = EE_MAINTENANCE_LABEL;
59
+		$this->_labels = array(
60
+			'buttons' => array(
61
+				'reset_capabilities' => __('Reset Event Espresso Capabilities', 'event_espresso'),
62
+			),
63
+		);
64
+	}
65
+
66
+
67
+
68
+	protected function _set_page_routes()
69
+	{
70
+		$this->_page_routes = array(
71
+			'default'                             => array(
72
+				'func'       => '_maintenance',
73
+				'capability' => 'manage_options',
74
+			),
75
+			'change_maintenance_level'            => array(
76
+				'func'       => '_change_maintenance_level',
77
+				'capability' => 'manage_options',
78
+				'noheader'   => true,
79
+			),
80
+			'system_status'                       => array(
81
+				'func'       => '_system_status',
82
+				'capability' => 'manage_options',
83
+			),
84
+			'send_migration_crash_report'         => array(
85
+				'func'       => '_send_migration_crash_report',
86
+				'capability' => 'manage_options',
87
+				'noheader'   => true,
88
+			),
89
+			'confirm_migration_crash_report_sent' => array(
90
+				'func'       => '_confirm_migration_crash_report_sent',
91
+				'capability' => 'manage_options',
92
+			),
93
+			'data_reset'                          => array(
94
+				'func'       => '_data_reset_and_delete',
95
+				'capability' => 'manage_options',
96
+			),
97
+			'reset_db'                            => array(
98
+				'func'       => '_reset_db',
99
+				'capability' => 'manage_options',
100
+				'noheader'   => true,
101
+				'args'       => array('nuke_old_ee4_data' => true),
102
+			),
103
+			'start_with_fresh_ee4_db'             => array(
104
+				'func'       => '_reset_db',
105
+				'capability' => 'manage_options',
106
+				'noheader'   => true,
107
+				'args'       => array('nuke_old_ee4_data' => false),
108
+			),
109
+			'delete_db'                           => array(
110
+				'func'       => '_delete_db',
111
+				'capability' => 'manage_options',
112
+				'noheader'   => true,
113
+			),
114
+			'rerun_migration_from_ee3'            => array(
115
+				'func'       => '_rerun_migration_from_ee3',
116
+				'capability' => 'manage_options',
117
+				'noheader'   => true,
118
+			),
119
+			'reset_capabilities'                  => array(
120
+				'func'       => '_reset_capabilities',
121
+				'capability' => 'manage_options',
122
+				'noheader'   => true,
123
+			),
124
+			'reattempt_migration'                 => array(
125
+				'func'       => '_reattempt_migration',
126
+				'capability' => 'manage_options',
127
+				'noheader'   => true,
128
+			),
129
+		);
130
+	}
131
+
132
+
133
+
134
+	protected function _set_page_config()
135
+	{
136
+		$this->_page_config = array(
137
+			'default'       => array(
138
+				'nav'           => array(
139
+					'label' => __('Maintenance', 'event_espresso'),
140
+					'order' => 10,
141
+				),
142
+				'require_nonce' => false,
143
+			),
144
+			'data_reset'    => array(
145
+				'nav'           => array(
146
+					'label' => __('Reset/Delete Data', 'event_espresso'),
147
+					'order' => 20,
148
+				),
149
+				'require_nonce' => false,
150
+			),
151
+			'system_status' => array(
152
+				'nav'           => array(
153
+					'label' => __("System Information", "event_espresso"),
154
+					'order' => 30,
155
+				),
156
+				'require_nonce' => false,
157
+			),
158
+		);
159
+	}
160
+
161
+
162
+
163
+	/**
164
+	 * default maintenance page. If we're in maintenance mode level 2, then we need to show
165
+	 * the migration scripts and all that UI.
166
+	 */
167
+	public function _maintenance()
168
+	{
169
+		//it all depends if we're in maintenance model level 1 (frontend-only) or
170
+		//level 2 (everything except maintenance page)
171
+		try {
172
+			//get the current maintenance level and check if
173
+			//we are removed
174
+			$mm = EE_Maintenance_Mode::instance()->level();
175
+			$placed_in_mm = EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
176
+			if ($mm == EE_Maintenance_Mode::level_2_complete_maintenance && ! $placed_in_mm) {
177
+				//we just took the site out of maintenance mode, so notify the user.
178
+				//unfortunately this message appears to be echoed on the NEXT page load...
179
+				//oh well, we should really be checking for this on addon deactivation anyways
180
+				EE_Error::add_attention(__('Site taken out of maintenance mode because no data migration scripts are required',
181
+					'event_espresso'));
182
+				$this->_process_notices(array('page' => 'espresso_maintenance_settings'), false);
183
+			}
184
+			//in case an exception is thrown while trying to handle migrations
185
+			switch (EE_Maintenance_Mode::instance()->level()) {
186
+				case EE_Maintenance_Mode::level_0_not_in_maintenance:
187
+				case EE_Maintenance_Mode::level_1_frontend_only_maintenance:
188
+					$show_maintenance_switch = true;
189
+					$show_backup_db_text = false;
190
+					$show_migration_progress = false;
191
+					$script_names = array();
192
+					$addons_should_be_upgraded_first = false;
193
+					break;
194
+				case EE_Maintenance_Mode::level_2_complete_maintenance:
195
+					$show_maintenance_switch = false;
196
+					$show_migration_progress = true;
197
+					if (isset($this->_req_data['continue_migration'])) {
198
+						$show_backup_db_text = false;
199
+					} else {
200
+						$show_backup_db_text = true;
201
+					}
202
+					$scripts_needing_to_run = EE_Data_Migration_Manager::instance()
203
+																	   ->check_for_applicable_data_migration_scripts();
204
+					$addons_should_be_upgraded_first = EE_Data_Migration_Manager::instance()->addons_need_updating();
205
+					$script_names = array();
206
+					$current_script = null;
207
+					foreach ($scripts_needing_to_run as $script) {
208
+						if ($script instanceof EE_Data_Migration_Script_Base) {
209
+							if ( ! $current_script) {
210
+								$current_script = $script;
211
+								$current_script->migration_page_hooks();
212
+							}
213
+							$script_names[] = $script->pretty_name();
214
+						}
215
+					}
216
+					break;
217
+			}
218
+			$most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
219
+			$exception_thrown = false;
220
+		} catch (EE_Error $e) {
221
+			EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
222
+			//now, just so we can display the page correctly, make a error migration script stage object
223
+			//and also put the error on it. It only persists for the duration of this request
224
+			$most_recent_migration = new EE_DMS_Unknown_1_0_0();
225
+			$most_recent_migration->add_error($e->getMessage());
226
+			$exception_thrown = true;
227
+		}
228
+		$current_db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set();
229
+		$current_db_state = str_replace('.decaf', '', $current_db_state);
230
+		if ($exception_thrown
231
+			|| ($most_recent_migration
232
+				&& $most_recent_migration instanceof EE_Data_Migration_Script_Base
233
+				&& $most_recent_migration->is_broken()
234
+			)
235
+		) {
236
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
237
+			$this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
238
+			$this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(array('action'  => 'confirm_migration_crash_report_sent',
239
+																						'success' => '0',
240
+			), EE_MAINTENANCE_ADMIN_URL);
241
+		} elseif ($addons_should_be_upgraded_first) {
242
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
243
+		} else {
244
+			if ($most_recent_migration
245
+				&& $most_recent_migration instanceof EE_Data_Migration_Script_Base
246
+				&& $most_recent_migration->can_continue()
247
+			) {
248
+				$show_backup_db_text = false;
249
+				$show_continue_current_migration_script = true;
250
+				$show_most_recent_migration = true;
251
+			} elseif (isset($this->_req_data['continue_migration'])) {
252
+				$show_most_recent_migration = true;
253
+				$show_continue_current_migration_script = false;
254
+			} else {
255
+				$show_most_recent_migration = false;
256
+				$show_continue_current_migration_script = false;
257
+			}
258
+			if (isset($current_script)) {
259
+				$migrates_to = $current_script->migrates_to_version();
260
+				$plugin_slug = $migrates_to['slug'];
261
+				$new_version = $migrates_to['version'];
262
+				$this->_template_args = array_merge($this->_template_args, array(
263
+					'current_db_state' => sprintf(__("EE%s (%s)", "event_espresso"),
264
+						isset($current_db_state[$plugin_slug]) ? $current_db_state[$plugin_slug] : 3, $plugin_slug),
265
+					'next_db_state'    => isset($current_script) ? sprintf(__("EE%s (%s)", 'event_espresso'),
266
+						$new_version, $plugin_slug) : null,
267
+				));
268
+			}
269
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
270
+			$this->_template_args = array_merge(
271
+				$this->_template_args,
272
+				array(
273
+					'show_most_recent_migration'             => $show_most_recent_migration,
274
+					//flag for showing the most recent migration's status and/or errors
275
+					'show_migration_progress'                => $show_migration_progress,
276
+					//flag for showing the option to run migrations and see their progress
277
+					'show_backup_db_text'                    => $show_backup_db_text,
278
+					//flag for showing text telling the user to backup their DB
279
+					'show_maintenance_switch'                => $show_maintenance_switch,
280
+					//flag for showing the option to change maintenance mode between levels 0 and 1
281
+					'script_names'                           => $script_names,
282
+					//array of names of scripts that have run
283
+					'show_continue_current_migration_script' => $show_continue_current_migration_script,
284
+					//flag to change wording to indicating that we're only CONTINUING a migration script (somehow it got interrupted0
285
+					'reset_db_page_link'                     => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
286
+						EE_MAINTENANCE_ADMIN_URL),
287
+					'update_migration_script_page_link'      => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'change_maintenance_level'),
288
+						EE_MAINTENANCE_ADMIN_URL),
289
+					'ultimate_db_state'                      => sprintf(__("EE%s", 'event_espresso'),
290
+						espresso_version()),
291
+				)
292
+			);
293
+			//make sure we have the form fields helper available. It usually is, but sometimes it isn't
294
+			//localize script stuff
295
+			wp_localize_script('ee-maintenance', 'ee_maintenance', array(
296
+				'migrating'                        => __("Migrating...", "event_espresso"),
297
+				'next'                             => __("Next", "event_espresso"),
298
+				'fatal_error'                      => __("A Fatal Error Has Occurred", "event_espresso"),
299
+				'click_next_when_ready'            => __("The current Migration has ended. Click 'next' when ready to proceed",
300
+					"event_espresso"),
301
+				'status_no_more_migration_scripts' => EE_Data_Migration_Manager::status_no_more_migration_scripts,
302
+				'status_fatal_error'               => EE_Data_Migration_Manager::status_fatal_error,
303
+				'status_completed'                 => EE_Data_Migration_Manager::status_completed,
304
+			));
305
+		}
306
+		$this->_template_args['most_recent_migration'] = $most_recent_migration;//the actual most recently ran migration
307
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
308
+			$this->_template_args, true);
309
+		$this->display_admin_page_with_sidebar();
310
+	}
311
+
312
+
313
+
314
+	/**
315
+	 * returns JSON and executes another step of the currently-executing data migration (called via ajax)
316
+	 */
317
+	public function migration_step()
318
+	{
319
+		$this->_template_args['data'] = EE_Data_Migration_Manager::instance()->response_to_migration_ajax_request();
320
+		$this->_return_json();
321
+	}
322
+
323
+
324
+
325
+	/**
326
+	 * Can be used by js when it notices a response with HTML in it in order
327
+	 * to log the malformed response
328
+	 */
329
+	public function add_error_to_migrations_ran()
330
+	{
331
+		EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($this->_req_data['message']);
332
+		$this->_template_args['data'] = array('ok' => true);
333
+		$this->_return_json();
334
+	}
335
+
336
+
337
+
338
+	/**
339
+	 * changes the maintenance level, provided there are still no migration scripts that shoudl run
340
+	 */
341
+	public function _change_maintenance_level()
342
+	{
343
+		$new_level = intval($this->_req_data['maintenance_mode_level']);
344
+		if ( ! EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
345
+			EE_Maintenance_Mode::instance()->set_maintenance_level($new_level);
346
+			$success = true;
347
+		} else {
348
+			EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
349
+			$success = false;
350
+		}
351
+		$this->_redirect_after_action($success, 'Maintenance Mode', __("Updated", "event_espresso"));
352
+	}
353
+
354
+
355
+
356
+	/**
357
+	 * a tab with options for resetting and/or deleting EE data
358
+	 *
359
+	 * @throws \EE_Error
360
+	 */
361
+	public function _data_reset_and_delete()
362
+	{
363
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
364
+		$this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
365
+			'reset_capabilities',
366
+			'reset_capabilities',
367
+			array(),
368
+			'button button-primary',
369
+			'',
370
+			false
371
+		);
372
+		$this->_template_args['delete_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
373
+			array('action' => 'delete_db'),
374
+			EE_MAINTENANCE_ADMIN_URL
375
+		);
376
+		$this->_template_args['reset_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
377
+			array('action' => 'reset_db'),
378
+			EE_MAINTENANCE_ADMIN_URL
379
+		);
380
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
381
+			$this->_template_path,
382
+			$this->_template_args,
383
+			true
384
+		);
385
+		$this->display_admin_page_with_sidebar();
386
+	}
387
+
388
+
389
+
390
+	protected function _reset_capabilities()
391
+	{
392
+		EE_Registry::instance()->CAP->init_caps(true);
393
+		EE_Error::add_success(__('Default Event Espresso capabilities have been restored for all current roles.',
394
+			'event_espresso'));
395
+		$this->_redirect_after_action(false, '', '', array('action' => 'data_reset'), true);
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * resets the DMSs so we can attempt to continue migrating after a fatal error
402
+	 * (only a good idea when someone has somehow tried ot fix whatever caused
403
+	 * the fatal error in teh first place)
404
+	 */
405
+	protected function _reattempt_migration()
406
+	{
407
+		EE_Data_Migration_Manager::instance()->reattempt();
408
+		$this->_redirect_after_action(false, '', '', array('action' => 'default'), true);
409
+	}
410
+
411
+
412
+
413
+	/**
414
+	 * shows the big ol' System Information page
415
+	 */
416
+	public function _system_status()
417
+	{
418
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
419
+		$this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
420
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
421
+			$this->_template_args, true);
422
+		$this->display_admin_page_with_sidebar();
423
+	}
424
+
425
+
426
+
427
+	public function _send_migration_crash_report()
428
+	{
429
+		$from = $this->_req_data['from'];
430
+		$from_name = $this->_req_data['from_name'];
431
+		$body = $this->_req_data['body'];
432
+		try {
433
+			$success = wp_mail(EE_SUPPORT_EMAIL,
434
+				'Migration Crash Report',
435
+				$body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
436
+				array(
437
+					"from:$from_name<$from>",
438
+					//					'content-type:text/html charset=UTF-8'
439
+				));
440
+		} catch (Exception $e) {
441
+			$success = false;
442
+		}
443
+		$this->_redirect_after_action($success, __("Migration Crash Report", "event_espresso"),
444
+			__("sent", "event_espresso"),
445
+			array('success' => $success, 'action' => 'confirm_migration_crash_report_sent'));
446
+	}
447
+
448
+
449
+
450
+	public function _confirm_migration_crash_report_sent()
451
+	{
452
+		try {
453
+			$most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
454
+		} catch (EE_Error $e) {
455
+			EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
456
+			//now, just so we can display the page correctly, make a error migration script stage object
457
+			//and also put the error on it. It only persists for the duration of this request
458
+			$most_recent_migration = new EE_DMS_Unknown_1_0_0();
459
+			$most_recent_migration->add_error($e->getMessage());
460
+		}
461
+		$success = $this->_req_data['success'] == '1' ? true : false;
462
+		$this->_template_args['success'] = $success;
463
+		$this->_template_args['most_recent_migration'] = $most_recent_migration;
464
+		$this->_template_args['reset_db_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
465
+			EE_MAINTENANCE_ADMIN_URL);
466
+		$this->_template_args['reset_db_page_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'data_reset'),
467
+			EE_MAINTENANCE_ADMIN_URL);
468
+		$this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reattempt_migration'),
469
+			EE_MAINTENANCE_ADMIN_URL);
470
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
471
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
472
+			$this->_template_args, true);
473
+		$this->display_admin_page_with_sidebar();
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * Resets the entire EE4 database.
480
+	 * Currently basically only sets up ee4 database for a fresh install- doesn't
481
+	 * actually clean out the old wp options, or cpts (although does erase old ee table data)
482
+	 *
483
+	 * @param boolean $nuke_old_ee4_data controls whether or not we
484
+	 *                                   destroy the old ee4 data, or just try initializing ee4 default data
485
+	 */
486
+	public function _reset_db($nuke_old_ee4_data = true)
487
+	{
488
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
489
+		if ($nuke_old_ee4_data) {
490
+			EEH_Activation::delete_all_espresso_cpt_data();
491
+			EEH_Activation::delete_all_espresso_tables_and_data(false);
492
+			EEH_Activation::remove_cron_tasks();
493
+		}
494
+		//make sure when we reset the registry's config that it
495
+		//switches to using the new singleton
496
+		EE_Registry::instance()->CFG = EE_Registry::instance()->CFG->reset(true);
497
+		EE_System::instance()->initialize_db_if_no_migrations_required(true);
498
+		EE_System::instance()->redirect_to_about_ee();
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * Deletes ALL EE tables, Records, and Options from the database.
505
+	 */
506
+	public function _delete_db()
507
+	{
508
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
509
+		EEH_Activation::delete_all_espresso_cpt_data();
510
+		EEH_Activation::delete_all_espresso_tables_and_data();
511
+		EEH_Activation::remove_cron_tasks();
512
+		EEH_Activation::deactivate_event_espresso();
513
+		wp_safe_redirect(admin_url('plugins.php'));
514
+		exit;
515
+	}
516
+
517
+
518
+
519
+	/**
520
+	 * sets up EE4 to rerun the migrations from ee3 to ee4
521
+	 */
522
+	public function _rerun_migration_from_ee3()
523
+	{
524
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
525
+		EEH_Activation::delete_all_espresso_cpt_data();
526
+		EEH_Activation::delete_all_espresso_tables_and_data(false);
527
+		//set the db state to something that will require migrations
528
+		update_option(EE_Data_Migration_Manager::current_database_state, '3.1.36.0');
529
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_2_complete_maintenance);
530
+		$this->_redirect_after_action(true, __("Database", 'event_espresso'), __("reset", 'event_espresso'));
531
+	}
532
+
533
+
534
+
535
+	//none of the below group are currently used for Gateway Settings
536
+	protected function _add_screen_options()
537
+	{
538
+	}
539
+
540
+
541
+
542
+	protected function _add_feature_pointers()
543
+	{
544
+	}
545
+
546 546
 
547 547
 
548
-    public function admin_init()
549
-    {
550
-    }
551
-
552
-
553
-
554
-    public function admin_notices()
555
-    {
556
-    }
557
-
548
+	public function admin_init()
549
+	{
550
+	}
551
+
552
+
553
+
554
+	public function admin_notices()
555
+	{
556
+	}
557
+
558 558
 
559 559
 
560
-    public function admin_footer_scripts()
561
-    {
562
-    }
560
+	public function admin_footer_scripts()
561
+	{
562
+	}
563 563
 
564 564
 
565 565
 
566
-    public function load_scripts_styles()
567
-    {
568
-        wp_enqueue_script('ee_admin_js');
566
+	public function load_scripts_styles()
567
+	{
568
+		wp_enqueue_script('ee_admin_js');
569 569
 //		wp_enqueue_media();
570 570
 //		wp_enqueue_script('media-upload');
571
-        wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL . '/ee-maintenance.js', array('jquery'),
572
-            EVENT_ESPRESSO_VERSION, true);
573
-        wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css', array(),
574
-            EVENT_ESPRESSO_VERSION);
575
-        wp_enqueue_style('espresso_maintenance');
576
-    }
571
+		wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL . '/ee-maintenance.js', array('jquery'),
572
+			EVENT_ESPRESSO_VERSION, true);
573
+		wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css', array(),
574
+			EVENT_ESPRESSO_VERSION);
575
+		wp_enqueue_style('espresso_maintenance');
576
+	}
577 577
 
578 578
 
579 579
 
580
-    public function load_scripts_styles_default()
581
-    {
582
-        //styles
580
+	public function load_scripts_styles_default()
581
+	{
582
+		//styles
583 583
 //		wp_enqueue_style('ee-text-links');
584 584
 //		//scripts
585 585
 //		wp_enqueue_script('ee-text-links');
586
-    }
586
+	}
587 587
 
588 588
 
589 589
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -233,13 +233,13 @@  discard block
 block discarded – undo
233 233
                 && $most_recent_migration->is_broken()
234 234
             )
235 235
         ) {
236
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
236
+            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_migration_was_borked_page.template.php';
237 237
             $this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
238 238
             $this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(array('action'  => 'confirm_migration_crash_report_sent',
239 239
                                                                                         'success' => '0',
240 240
             ), EE_MAINTENANCE_ADMIN_URL);
241 241
         } elseif ($addons_should_be_upgraded_first) {
242
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
242
+            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_upgrade_addons_before_migrating.template.php';
243 243
         } else {
244 244
             if ($most_recent_migration
245 245
                 && $most_recent_migration instanceof EE_Data_Migration_Script_Base
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
                         $new_version, $plugin_slug) : null,
267 267
                 ));
268 268
             }
269
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
269
+            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_migration_page.template.php';
270 270
             $this->_template_args = array_merge(
271 271
                 $this->_template_args,
272 272
                 array(
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
                 'status_completed'                 => EE_Data_Migration_Manager::status_completed,
304 304
             ));
305 305
         }
306
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;//the actual most recently ran migration
306
+        $this->_template_args['most_recent_migration'] = $most_recent_migration; //the actual most recently ran migration
307 307
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
308 308
             $this->_template_args, true);
309 309
         $this->display_admin_page_with_sidebar();
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
      */
361 361
     public function _data_reset_and_delete()
362 362
     {
363
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
363
+        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_data_reset_and_delete.template.php';
364 364
         $this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
365 365
             'reset_capabilities',
366 366
             'reset_capabilities',
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
      */
416 416
     public function _system_status()
417 417
     {
418
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
418
+        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_system_stati_page.template.php';
419 419
         $this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
420 420
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
421 421
             $this->_template_args, true);
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
         try {
433 433
             $success = wp_mail(EE_SUPPORT_EMAIL,
434 434
                 'Migration Crash Report',
435
-                $body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
435
+                $body."/r/n<br>".print_r(EEM_System_Status::instance()->get_system_stati(), true),
436 436
                 array(
437 437
                     "from:$from_name<$from>",
438 438
                     //					'content-type:text/html charset=UTF-8'
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
             EE_MAINTENANCE_ADMIN_URL);
468 468
         $this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reattempt_migration'),
469 469
             EE_MAINTENANCE_ADMIN_URL);
470
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
470
+        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_confirm_migration_crash_report_sent.template.php';
471 471
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
472 472
             $this->_template_args, true);
473 473
         $this->display_admin_page_with_sidebar();
@@ -568,9 +568,9 @@  discard block
 block discarded – undo
568 568
         wp_enqueue_script('ee_admin_js');
569 569
 //		wp_enqueue_media();
570 570
 //		wp_enqueue_script('media-upload');
571
-        wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL . '/ee-maintenance.js', array('jquery'),
571
+        wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL.'/ee-maintenance.js', array('jquery'),
572 572
             EVENT_ESPRESSO_VERSION, true);
573
-        wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css', array(),
573
+        wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL.'ee-maintenance.css', array(),
574 574
             EVENT_ESPRESSO_VERSION);
575 575
         wp_enqueue_style('espresso_maintenance');
576 576
     }
Please login to merge, or discard this patch.