Completed
Branch feature/checkins-to-csv (0f20a6)
by
unknown
26:05 queued 23:46
created
core/libraries/batch/JobHandlers/RegistrationsReport.php 2 patches
Indentation   +467 added lines, -467 removed lines patch added patch discarded remove patch
@@ -41,486 +41,486 @@
 block discarded – undo
41 41
  */
42 42
 class RegistrationsReport extends JobHandlerFile
43 43
 {
44
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
45
-    // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
46
-    /**
47
-     * Performs any necessary setup for starting the job. This is also a good
48
-     * place to setup the $job_arguments which will be used for subsequent HTTP requests
49
-     * when continue_job will be called
50
-     *
51
-     * @param JobParameters $job_parameters
52
-     * @return JobStepResponse
53
-     * @throws BatchRequestException
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public function create_job(JobParameters $job_parameters)
58
-    {
59
-        $event_id = (int) $job_parameters->request_datum('EVT_ID', '0');
60
-        $DTT_ID = (int) $job_parameters->request_datum('DTT_ID', '0');
61
-        if (! EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
62
-            throw new BatchRequestException(esc_html__('You do not have permission to view registrations', 'event_espresso'));
63
-        }
64
-        $filepath = $this->create_file_from_job_with_name(
65
-            $job_parameters->job_id(),
66
-            $this->get_filename()
67
-        );
68
-        $job_parameters->add_extra_data('filepath', $filepath);
69
-        $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
70
-            array(
71
-                'OR'                 => array(
72
-                    // don't include registrations from failed or abandoned transactions...
73
-                    'Transaction.STS_ID' => array(
74
-                        'NOT IN',
75
-                        array(
76
-                            EEM_Transaction::failed_status_code,
77
-                            EEM_Transaction::abandoned_status_code,
78
-                        ),
79
-                    ),
80
-                    // unless the registration is approved, in which case include it regardless of transaction status
81
-                    'STS_ID'             => EEM_Registration::status_id_approved,
82
-                ),
83
-                'Ticket.TKT_deleted' => array('IN', array(true, false)),
84
-            ),
85
-            'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
86
-            'force_join' => array('Transaction', 'Ticket', 'Attendee'),
87
-            'caps'       => EEM_Base::caps_read_admin,
88
-        ), $event_id);
89
-        if ($event_id) {
90
-            $query_params[0]['EVT_ID'] = $event_id;
91
-        } else {
92
-            $query_params['force_join'][] = 'Event';
93
-        }
94
-        if (! isset($query_params['force_join'])) {
95
-            $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
96
-        }
97
-        $job_parameters->add_extra_data('query_params', $query_params);
98
-        $question_labels = $this->_get_question_labels($query_params);
99
-        $job_parameters->add_extra_data('question_labels', $question_labels);
100
-        $job_parameters->set_job_size($this->count_units_to_process($query_params));
101
-        // we should also set the header columns
102
-        $csv_data_for_row = $this->get_csv_data_for(
103
-            $event_id,
104
-            0,
105
-            1,
106
-            $job_parameters->extra_datum('question_labels'),
107
-            $job_parameters->extra_datum('query_params'),
108
-            $DTT_ID
109
-        );
110
-        EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
111
-        // if we actually processed a row there, record it
112
-        if ($job_parameters->job_size()) {
113
-            $job_parameters->mark_processed(1);
114
-        }
115
-        return new JobStepResponse(
116
-            $job_parameters,
117
-            esc_html__('Registrations report started successfully...', 'event_espresso')
118
-        );
119
-    }
44
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
45
+	// phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
46
+	/**
47
+	 * Performs any necessary setup for starting the job. This is also a good
48
+	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
49
+	 * when continue_job will be called
50
+	 *
51
+	 * @param JobParameters $job_parameters
52
+	 * @return JobStepResponse
53
+	 * @throws BatchRequestException
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public function create_job(JobParameters $job_parameters)
58
+	{
59
+		$event_id = (int) $job_parameters->request_datum('EVT_ID', '0');
60
+		$DTT_ID = (int) $job_parameters->request_datum('DTT_ID', '0');
61
+		if (! EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
62
+			throw new BatchRequestException(esc_html__('You do not have permission to view registrations', 'event_espresso'));
63
+		}
64
+		$filepath = $this->create_file_from_job_with_name(
65
+			$job_parameters->job_id(),
66
+			$this->get_filename()
67
+		);
68
+		$job_parameters->add_extra_data('filepath', $filepath);
69
+		$query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
70
+			array(
71
+				'OR'                 => array(
72
+					// don't include registrations from failed or abandoned transactions...
73
+					'Transaction.STS_ID' => array(
74
+						'NOT IN',
75
+						array(
76
+							EEM_Transaction::failed_status_code,
77
+							EEM_Transaction::abandoned_status_code,
78
+						),
79
+					),
80
+					// unless the registration is approved, in which case include it regardless of transaction status
81
+					'STS_ID'             => EEM_Registration::status_id_approved,
82
+				),
83
+				'Ticket.TKT_deleted' => array('IN', array(true, false)),
84
+			),
85
+			'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
86
+			'force_join' => array('Transaction', 'Ticket', 'Attendee'),
87
+			'caps'       => EEM_Base::caps_read_admin,
88
+		), $event_id);
89
+		if ($event_id) {
90
+			$query_params[0]['EVT_ID'] = $event_id;
91
+		} else {
92
+			$query_params['force_join'][] = 'Event';
93
+		}
94
+		if (! isset($query_params['force_join'])) {
95
+			$query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
96
+		}
97
+		$job_parameters->add_extra_data('query_params', $query_params);
98
+		$question_labels = $this->_get_question_labels($query_params);
99
+		$job_parameters->add_extra_data('question_labels', $question_labels);
100
+		$job_parameters->set_job_size($this->count_units_to_process($query_params));
101
+		// we should also set the header columns
102
+		$csv_data_for_row = $this->get_csv_data_for(
103
+			$event_id,
104
+			0,
105
+			1,
106
+			$job_parameters->extra_datum('question_labels'),
107
+			$job_parameters->extra_datum('query_params'),
108
+			$DTT_ID
109
+		);
110
+		EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
111
+		// if we actually processed a row there, record it
112
+		if ($job_parameters->job_size()) {
113
+			$job_parameters->mark_processed(1);
114
+		}
115
+		return new JobStepResponse(
116
+			$job_parameters,
117
+			esc_html__('Registrations report started successfully...', 'event_espresso')
118
+		);
119
+	}
120 120
 
121 121
 
122
-    /**
123
-     * Gets the filename
124
-     *
125
-     * @return string
126
-     */
127
-    protected function get_filename()
128
-    {
129
-        return apply_filters(
130
-            'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__get_filename',
131
-            sprintf(
132
-                "event-espresso-registrations-%s.csv",
133
-                str_replace(array(':', ' '), '-', current_time('mysql'))
134
-            )
135
-        );
136
-    }
122
+	/**
123
+	 * Gets the filename
124
+	 *
125
+	 * @return string
126
+	 */
127
+	protected function get_filename()
128
+	{
129
+		return apply_filters(
130
+			'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__get_filename',
131
+			sprintf(
132
+				"event-espresso-registrations-%s.csv",
133
+				str_replace(array(':', ' '), '-', current_time('mysql'))
134
+			)
135
+		);
136
+	}
137 137
 
138 138
 
139
-    /**
140
-     * Gets the questions which are to be used for this report, so they
141
-     * can be remembered for later
142
-     *
143
-     * @param array $registration_query_params
144
-     * @return array question admin labels to be used for this report
145
-     * @throws EE_Error
146
-     */
147
-    protected function _get_question_labels($registration_query_params)
148
-    {
149
-        $where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
150
-        $question_query_params = array();
151
-        if ($where !== null) {
152
-            $question_query_params = array(
153
-                $this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
154
-            );
155
-        }
156
-        // Make sure it's not a system question
157
-        $question_query_params[0]['OR*not-system-questions'] = [
158
-            'QST_system' => '',
159
-            'QST_system*null' => ['IS_NULL']
160
-        ];
161
-        if (
162
-            apply_filters(
163
-                'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
164
-                false,
165
-                $registration_query_params
166
-            )
167
-        ) {
168
-            $question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
169
-        }
170
-        $question_query_params['group_by'] = array('QST_ID');
171
-        return array_unique(EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
172
-    }
139
+	/**
140
+	 * Gets the questions which are to be used for this report, so they
141
+	 * can be remembered for later
142
+	 *
143
+	 * @param array $registration_query_params
144
+	 * @return array question admin labels to be used for this report
145
+	 * @throws EE_Error
146
+	 */
147
+	protected function _get_question_labels($registration_query_params)
148
+	{
149
+		$where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
150
+		$question_query_params = array();
151
+		if ($where !== null) {
152
+			$question_query_params = array(
153
+				$this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
154
+			);
155
+		}
156
+		// Make sure it's not a system question
157
+		$question_query_params[0]['OR*not-system-questions'] = [
158
+			'QST_system' => '',
159
+			'QST_system*null' => ['IS_NULL']
160
+		];
161
+		if (
162
+			apply_filters(
163
+				'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
164
+				false,
165
+				$registration_query_params
166
+			)
167
+		) {
168
+			$question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
169
+		}
170
+		$question_query_params['group_by'] = array('QST_ID');
171
+		return array_unique(EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
172
+	}
173 173
 
174 174
 
175
-    /**
176
-     * Takes where params meant for registrations and changes them to work for questions
177
-     *
178
-     * @param array $reg_where_params
179
-     * @return array
180
-     * @throws EE_Error
181
-     */
182
-    protected function _change_registration_where_params_to_question_where_params($reg_where_params)
183
-    {
184
-        $question_where_params = array();
185
-        foreach ($reg_where_params as $key => $val) {
186
-            if (EEM_Registration::instance()->is_logic_query_param_key($key)) {
187
-                $question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
188
-            } else {
189
-                // it's a normal where condition
190
-                $question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
191
-            }
192
-        }
193
-        return $question_where_params;
194
-    }
175
+	/**
176
+	 * Takes where params meant for registrations and changes them to work for questions
177
+	 *
178
+	 * @param array $reg_where_params
179
+	 * @return array
180
+	 * @throws EE_Error
181
+	 */
182
+	protected function _change_registration_where_params_to_question_where_params($reg_where_params)
183
+	{
184
+		$question_where_params = array();
185
+		foreach ($reg_where_params as $key => $val) {
186
+			if (EEM_Registration::instance()->is_logic_query_param_key($key)) {
187
+				$question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
188
+			} else {
189
+				// it's a normal where condition
190
+				$question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
191
+			}
192
+		}
193
+		return $question_where_params;
194
+	}
195 195
 
196 196
 
197
-    /**
198
-     * Performs another step of the job
199
-     *
200
-     * @param JobParameters $job_parameters
201
-     * @param int $batch_size
202
-     * @return JobStepResponse
203
-     * @throws EE_Error
204
-     * @throws ReflectionException
205
-     */
206
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
207
-    {
208
-        if ($job_parameters->units_processed() < $job_parameters->job_size()) {
209
-            $csv_data = $this->get_csv_data_for(
210
-                (int) $job_parameters->request_datum('EVT_ID', '0'),
211
-                $job_parameters->units_processed(),
212
-                $batch_size,
213
-                $job_parameters->extra_datum('question_labels'),
214
-                $job_parameters->extra_datum('query_params'),
215
-                (int) $job_parameters->request_datum('DTT_ID', '0')
216
-            );
217
-            EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
218
-            $units_processed = count($csv_data);
219
-        } else {
220
-            $csv_data = array();
221
-            $units_processed = 0;
222
-        }
223
-        $job_parameters->mark_processed($units_processed);
224
-        $extra_response_data = array(
225
-            'file_url' => '',
226
-        );
227
-        if ($units_processed < $batch_size) {
228
-            $job_parameters->set_status(JobParameters::status_complete);
229
-            $extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
230
-        }
197
+	/**
198
+	 * Performs another step of the job
199
+	 *
200
+	 * @param JobParameters $job_parameters
201
+	 * @param int $batch_size
202
+	 * @return JobStepResponse
203
+	 * @throws EE_Error
204
+	 * @throws ReflectionException
205
+	 */
206
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
207
+	{
208
+		if ($job_parameters->units_processed() < $job_parameters->job_size()) {
209
+			$csv_data = $this->get_csv_data_for(
210
+				(int) $job_parameters->request_datum('EVT_ID', '0'),
211
+				$job_parameters->units_processed(),
212
+				$batch_size,
213
+				$job_parameters->extra_datum('question_labels'),
214
+				$job_parameters->extra_datum('query_params'),
215
+				(int) $job_parameters->request_datum('DTT_ID', '0')
216
+			);
217
+			EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
218
+			$units_processed = count($csv_data);
219
+		} else {
220
+			$csv_data = array();
221
+			$units_processed = 0;
222
+		}
223
+		$job_parameters->mark_processed($units_processed);
224
+		$extra_response_data = array(
225
+			'file_url' => '',
226
+		);
227
+		if ($units_processed < $batch_size) {
228
+			$job_parameters->set_status(JobParameters::status_complete);
229
+			$extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
230
+		}
231 231
 
232
-        return new JobStepResponse(
233
-            $job_parameters,
234
-            sprintf(esc_html__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count((array) $csv_data)),
235
-            $extra_response_data
236
-        );
237
-    }
232
+		return new JobStepResponse(
233
+			$job_parameters,
234
+			sprintf(esc_html__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count((array) $csv_data)),
235
+			$extra_response_data
236
+		);
237
+	}
238 238
 
239 239
 
240
-    /**
241
-     * Gets the csv data for a batch of registrations
242
-     *
243
-     * @param int|null $event_id
244
-     * @param int $offset
245
-     * @param int $limit
246
-     * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
247
-     * @param array $query_params for using where querying the model
248
-     * @param int $DTT_ID
249
-     * @return array top-level keys are numeric, next-level keys are column headers
250
-     * @throws EE_Error
251
-     * @throws ReflectionException
252
-     */
253
-    public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params, $DTT_ID = 0)
254
-    {
255
-        $reg_fields_to_include = [
256
-            'TXN_ID',
257
-            'ATT_ID',
258
-            'REG_date',
259
-            'REG_code',
260
-            'REG_count',
261
-            'REG_final_price',
262
-        ];
263
-        $att_fields_to_include = [
264
-            'ATT_fname',
265
-            'ATT_lname',
266
-            'ATT_email',
267
-            'ATT_address',
268
-            'ATT_address2',
269
-            'ATT_city',
270
-            'STA_ID',
271
-            'CNT_ISO',
272
-            'ATT_zip',
273
-            'ATT_phone',
274
-        ];
275
-        $registrations_csv_ready_array = [];
276
-        $reg_model = EE_Registry::instance()->load_model('Registration');
277
-        $query_params['limit'] = [$offset, $limit];
278
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
279
-        foreach ($registration_rows as $reg_row) {
280
-            if (!is_array($reg_row)) {
281
-                continue;
282
-            }
283
-            $reg_csv_array = [];
284
-            // registration Id
285
-            $reg_id_field = $reg_model->field_settings_for('REG_ID');
286
-            $reg_csv_array[ EEH_Export::get_column_name_for_field($reg_id_field) ] = EEH_Export::prepare_value_from_db_for_display(
287
-                $reg_model,
288
-                'REG_ID',
289
-                $reg_row[ $reg_id_field->get_qualified_column() ]
290
-            );
291
-            if (! $event_id) {
292
-                // get the event's name and Id
293
-                $reg_csv_array[ (string) esc_html__('Event', 'event_espresso') ] = sprintf(
294
-                    /* translators: 1: event name, 2: event ID */
295
-                    esc_html__('%1$s (%2$s)', 'event_espresso'),
296
-                    EEH_Export::prepare_value_from_db_for_display(
297
-                        EEM_Event::instance(),
298
-                        'EVT_name',
299
-                        $reg_row['Event_CPT.post_title']
300
-                    ),
301
-                    $reg_row['Event_CPT.ID']
302
-                );
303
-            }
304
-            // add attendee columns
305
-            $reg_csv_array = AttendeeCSV::addAttendeeColumns($att_fields_to_include, $reg_row, $reg_csv_array);
306
-            // add registration columns
307
-            $reg_csv_array = RegistrationCSV::addRegistrationColumns($reg_fields_to_include, $reg_row, $reg_model, $reg_csv_array);
308
-            // get pretty status
309
-            $stati = EEM_Status::instance()->localized_status(
310
-                [
311
-                    $reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
312
-                    $reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
313
-                ],
314
-                false,
315
-                'sentence'
316
-            );
317
-            $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
318
-            $reg_csv_array[ (string) esc_html__("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
319
-            // get pretty transaction status
320
-            $reg_csv_array[ (string) esc_html__("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
321
-            $reg_csv_array[ (string) esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
322
-                ? EEH_Export::prepare_value_from_db_for_display(
323
-                    EEM_Transaction::instance(),
324
-                    'TXN_total',
325
-                    $reg_row['TransactionTable.TXN_total'],
326
-                    'localized_float'
327
-                ) : '0.00';
328
-            $reg_csv_array[ (string) esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
329
-                ? EEH_Export::prepare_value_from_db_for_display(
330
-                    EEM_Transaction::instance(),
331
-                    'TXN_paid',
332
-                    $reg_row['TransactionTable.TXN_paid'],
333
-                    'localized_float'
334
-                ) : '0.00';
335
-            $payment_methods = [];
336
-            $gateway_txn_ids_etc = [];
337
-            $payment_times = [];
338
-            if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
339
-                $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
340
-                    [
341
-                        [
342
-                            'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
343
-                            'STS_ID' => EEM_Payment::status_id_approved,
344
-                        ],
345
-                        'force_join' => ['Payment_Method'],
346
-                    ],
347
-                    ARRAY_A,
348
-                    'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
349
-                );
350
-                list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
351
-            }
352
-            $reg_csv_array[ (string) esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
353
-            $reg_csv_array[ (string) esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
354
-            $reg_csv_array[ (string) esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
355
-                ',',
356
-                $gateway_txn_ids_etc
357
-            );
358
-            // get ticket of registration and its price
359
-            $ticket_model = EE_Registry::instance()->load_model('Ticket');
360
-            if ($reg_row['Ticket.TKT_ID']) {
361
-                $ticket_name = EEH_Export::prepare_value_from_db_for_display(
362
-                    $ticket_model,
363
-                    'TKT_name',
364
-                    $reg_row['Ticket.TKT_name']
365
-                );
366
-                $datetimes_strings = [];
367
-                foreach (
368
-                    EEM_Datetime::instance()->get_all_wpdb_results(
369
-                        [
370
-                            ['Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']],
371
-                            'order_by' => ['DTT_EVT_start' => 'ASC'],
372
-                            'default_where_conditions' => 'none',
373
-                        ]
374
-                    ) as $datetime
375
-                ) {
376
-                    $datetimes_strings[] = EEH_Export::prepare_value_from_db_for_display(
377
-                        EEM_Datetime::instance(),
378
-                        'DTT_EVT_start',
379
-                        $datetime['Datetime.DTT_EVT_start']
380
-                    );
381
-                }
382
-            } else {
383
-                $ticket_name = esc_html__('Unknown', 'event_espresso');
384
-                $datetimes_strings = [esc_html__('Unknown', 'event_espresso')];
385
-            }
386
-            $reg_csv_array[ (string) $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
387
-            $reg_csv_array[ (string) esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
388
-            // add answer columns
389
-            $reg_csv_array = AnswersCSV::addAnswerColumns($reg_row, $reg_csv_array, $question_labels);
390
-            // Include check-in data
391
-            if ($event_id && $DTT_ID) {
392
-                // get whether or not the user has checked in
393
-                $reg_csv_array[ (string) esc_html__('Datetime Check-ins #', 'event_espresso') ] = $reg_model->count_related(
394
-                    $reg_row['Registration.REG_ID'],
395
-                    'Checkin',
396
-                    [
397
-                        [
398
-                            'DTT_ID' => $DTT_ID
399
-                        ]
400
-                    ]
401
-                );
402
-                /** @var EE_Datetime $datetime */
403
-                $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
404
-                $checkin_rows = EEM_Checkin::instance()->get_all(
405
-                    [
406
-                        [
407
-                            'REG_ID' => $reg_row['Registration.REG_ID'],
408
-                            'DTT_ID' => $datetime->get('DTT_ID'),
409
-                        ],
410
-                    ]
411
-                );
412
-                $checkins = [];
413
-                foreach ($checkin_rows as $checkin_row) {
414
-                    /** @var EE_Checkin $checkin_row */
415
-                    $checkin_value = CheckinsCSV::getCheckinValue($checkin_row);
416
-                    if ($checkin_value) {
417
-                        $checkins[] = $checkin_value;
418
-                    }
419
-                }
420
-                $datetime_name = CheckinsCSV::getDatetineLabel($datetime);
421
-                $reg_csv_array[ (string) $datetime_name ] = implode(' --- ', $checkins);
422
-            } elseif ($event_id) {
423
-                // get whether or not the user has checked in
424
-                $reg_csv_array[ (string) esc_html__('Event Check-ins #', 'event_espresso') ] = $reg_model->count_related(
425
-                    $reg_row['Registration.REG_ID'],
426
-                    'Checkin'
427
-                );
428
-                $datetimes = EEM_Datetime::instance()->get_all(
429
-                    [
430
-                        [
431
-                            'Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID'],
432
-                        ],
433
-                        'order_by' => ['DTT_EVT_start' => 'ASC'],
434
-                        'default_where_conditions' => 'none',
435
-                    ]
436
-                );
437
-                foreach ($datetimes as $datetime) {
438
-                    /** @var EE_Checkin $checkin_row */
439
-                    $checkin_row = EEM_Checkin::instance()->get_one(
440
-                        [
441
-                            [
442
-                                'REG_ID' => $reg_row['Registration.REG_ID'],
443
-                                'DTT_ID' => $datetime->get('DTT_ID'),
444
-                            ],
445
-                            'limit' => 1,
446
-                            'order_by' => [
447
-                                'CHK_ID' => 'DESC'
448
-                            ]
449
-                        ]
450
-                    );
451
-                    $checkin_value = CheckinsCSV::getCheckinValue($checkin_row);
452
-                    $datetime_name = CheckinsCSV::getDatetineLabel($datetime);
453
-                    $reg_csv_array[ (string) $datetime_name ] = $checkin_value;
454
-                }
455
-            }
456
-            /**
457
-             * Filter to change the contents of each row of the registrations report CSV file.
458
-             * This can be used to add or remote columns from the CSV file, or change their values.
459
-             * Note when using: all rows in the CSV should have the same columns.
460
-             * @param array $reg_csv_array keys are the column names, values are their cell values
461
-             * @param array $reg_row one entry from EEM_Registration::get_all_wpdb_results()
462
-             */
463
-            $registrations_csv_ready_array[] = apply_filters(
464
-                'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__reg_csv_array',
465
-                $reg_csv_array,
466
-                $reg_row
467
-            );
468
-        }
469
-        // if we couldn't export anything, we want to at least show the column headers
470
-        if (empty($registrations_csv_ready_array)) {
471
-            $reg_csv_array = [];
472
-            $model_and_fields_to_include = [
473
-                'Registration' => $reg_fields_to_include,
474
-                'Attendee'     => $att_fields_to_include,
475
-            ];
476
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
477
-                $model = EE_Registry::instance()->load_model($model_name);
478
-                foreach ($field_list as $field_name) {
479
-                    $field = $model->field_settings_for($field_name);
480
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = null;
481
-                }
482
-            }
483
-            $registrations_csv_ready_array[] = $reg_csv_array;
484
-        }
485
-        return $registrations_csv_ready_array;
486
-    }
240
+	/**
241
+	 * Gets the csv data for a batch of registrations
242
+	 *
243
+	 * @param int|null $event_id
244
+	 * @param int $offset
245
+	 * @param int $limit
246
+	 * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
247
+	 * @param array $query_params for using where querying the model
248
+	 * @param int $DTT_ID
249
+	 * @return array top-level keys are numeric, next-level keys are column headers
250
+	 * @throws EE_Error
251
+	 * @throws ReflectionException
252
+	 */
253
+	public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params, $DTT_ID = 0)
254
+	{
255
+		$reg_fields_to_include = [
256
+			'TXN_ID',
257
+			'ATT_ID',
258
+			'REG_date',
259
+			'REG_code',
260
+			'REG_count',
261
+			'REG_final_price',
262
+		];
263
+		$att_fields_to_include = [
264
+			'ATT_fname',
265
+			'ATT_lname',
266
+			'ATT_email',
267
+			'ATT_address',
268
+			'ATT_address2',
269
+			'ATT_city',
270
+			'STA_ID',
271
+			'CNT_ISO',
272
+			'ATT_zip',
273
+			'ATT_phone',
274
+		];
275
+		$registrations_csv_ready_array = [];
276
+		$reg_model = EE_Registry::instance()->load_model('Registration');
277
+		$query_params['limit'] = [$offset, $limit];
278
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
279
+		foreach ($registration_rows as $reg_row) {
280
+			if (!is_array($reg_row)) {
281
+				continue;
282
+			}
283
+			$reg_csv_array = [];
284
+			// registration Id
285
+			$reg_id_field = $reg_model->field_settings_for('REG_ID');
286
+			$reg_csv_array[ EEH_Export::get_column_name_for_field($reg_id_field) ] = EEH_Export::prepare_value_from_db_for_display(
287
+				$reg_model,
288
+				'REG_ID',
289
+				$reg_row[ $reg_id_field->get_qualified_column() ]
290
+			);
291
+			if (! $event_id) {
292
+				// get the event's name and Id
293
+				$reg_csv_array[ (string) esc_html__('Event', 'event_espresso') ] = sprintf(
294
+					/* translators: 1: event name, 2: event ID */
295
+					esc_html__('%1$s (%2$s)', 'event_espresso'),
296
+					EEH_Export::prepare_value_from_db_for_display(
297
+						EEM_Event::instance(),
298
+						'EVT_name',
299
+						$reg_row['Event_CPT.post_title']
300
+					),
301
+					$reg_row['Event_CPT.ID']
302
+				);
303
+			}
304
+			// add attendee columns
305
+			$reg_csv_array = AttendeeCSV::addAttendeeColumns($att_fields_to_include, $reg_row, $reg_csv_array);
306
+			// add registration columns
307
+			$reg_csv_array = RegistrationCSV::addRegistrationColumns($reg_fields_to_include, $reg_row, $reg_model, $reg_csv_array);
308
+			// get pretty status
309
+			$stati = EEM_Status::instance()->localized_status(
310
+				[
311
+					$reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
312
+					$reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
313
+				],
314
+				false,
315
+				'sentence'
316
+			);
317
+			$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
318
+			$reg_csv_array[ (string) esc_html__("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
319
+			// get pretty transaction status
320
+			$reg_csv_array[ (string) esc_html__("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
321
+			$reg_csv_array[ (string) esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
322
+				? EEH_Export::prepare_value_from_db_for_display(
323
+					EEM_Transaction::instance(),
324
+					'TXN_total',
325
+					$reg_row['TransactionTable.TXN_total'],
326
+					'localized_float'
327
+				) : '0.00';
328
+			$reg_csv_array[ (string) esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
329
+				? EEH_Export::prepare_value_from_db_for_display(
330
+					EEM_Transaction::instance(),
331
+					'TXN_paid',
332
+					$reg_row['TransactionTable.TXN_paid'],
333
+					'localized_float'
334
+				) : '0.00';
335
+			$payment_methods = [];
336
+			$gateway_txn_ids_etc = [];
337
+			$payment_times = [];
338
+			if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
339
+				$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
340
+					[
341
+						[
342
+							'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
343
+							'STS_ID' => EEM_Payment::status_id_approved,
344
+						],
345
+						'force_join' => ['Payment_Method'],
346
+					],
347
+					ARRAY_A,
348
+					'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
349
+				);
350
+				list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
351
+			}
352
+			$reg_csv_array[ (string) esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
353
+			$reg_csv_array[ (string) esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
354
+			$reg_csv_array[ (string) esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
355
+				',',
356
+				$gateway_txn_ids_etc
357
+			);
358
+			// get ticket of registration and its price
359
+			$ticket_model = EE_Registry::instance()->load_model('Ticket');
360
+			if ($reg_row['Ticket.TKT_ID']) {
361
+				$ticket_name = EEH_Export::prepare_value_from_db_for_display(
362
+					$ticket_model,
363
+					'TKT_name',
364
+					$reg_row['Ticket.TKT_name']
365
+				);
366
+				$datetimes_strings = [];
367
+				foreach (
368
+					EEM_Datetime::instance()->get_all_wpdb_results(
369
+						[
370
+							['Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']],
371
+							'order_by' => ['DTT_EVT_start' => 'ASC'],
372
+							'default_where_conditions' => 'none',
373
+						]
374
+					) as $datetime
375
+				) {
376
+					$datetimes_strings[] = EEH_Export::prepare_value_from_db_for_display(
377
+						EEM_Datetime::instance(),
378
+						'DTT_EVT_start',
379
+						$datetime['Datetime.DTT_EVT_start']
380
+					);
381
+				}
382
+			} else {
383
+				$ticket_name = esc_html__('Unknown', 'event_espresso');
384
+				$datetimes_strings = [esc_html__('Unknown', 'event_espresso')];
385
+			}
386
+			$reg_csv_array[ (string) $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
387
+			$reg_csv_array[ (string) esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
388
+			// add answer columns
389
+			$reg_csv_array = AnswersCSV::addAnswerColumns($reg_row, $reg_csv_array, $question_labels);
390
+			// Include check-in data
391
+			if ($event_id && $DTT_ID) {
392
+				// get whether or not the user has checked in
393
+				$reg_csv_array[ (string) esc_html__('Datetime Check-ins #', 'event_espresso') ] = $reg_model->count_related(
394
+					$reg_row['Registration.REG_ID'],
395
+					'Checkin',
396
+					[
397
+						[
398
+							'DTT_ID' => $DTT_ID
399
+						]
400
+					]
401
+				);
402
+				/** @var EE_Datetime $datetime */
403
+				$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
404
+				$checkin_rows = EEM_Checkin::instance()->get_all(
405
+					[
406
+						[
407
+							'REG_ID' => $reg_row['Registration.REG_ID'],
408
+							'DTT_ID' => $datetime->get('DTT_ID'),
409
+						],
410
+					]
411
+				);
412
+				$checkins = [];
413
+				foreach ($checkin_rows as $checkin_row) {
414
+					/** @var EE_Checkin $checkin_row */
415
+					$checkin_value = CheckinsCSV::getCheckinValue($checkin_row);
416
+					if ($checkin_value) {
417
+						$checkins[] = $checkin_value;
418
+					}
419
+				}
420
+				$datetime_name = CheckinsCSV::getDatetineLabel($datetime);
421
+				$reg_csv_array[ (string) $datetime_name ] = implode(' --- ', $checkins);
422
+			} elseif ($event_id) {
423
+				// get whether or not the user has checked in
424
+				$reg_csv_array[ (string) esc_html__('Event Check-ins #', 'event_espresso') ] = $reg_model->count_related(
425
+					$reg_row['Registration.REG_ID'],
426
+					'Checkin'
427
+				);
428
+				$datetimes = EEM_Datetime::instance()->get_all(
429
+					[
430
+						[
431
+							'Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID'],
432
+						],
433
+						'order_by' => ['DTT_EVT_start' => 'ASC'],
434
+						'default_where_conditions' => 'none',
435
+					]
436
+				);
437
+				foreach ($datetimes as $datetime) {
438
+					/** @var EE_Checkin $checkin_row */
439
+					$checkin_row = EEM_Checkin::instance()->get_one(
440
+						[
441
+							[
442
+								'REG_ID' => $reg_row['Registration.REG_ID'],
443
+								'DTT_ID' => $datetime->get('DTT_ID'),
444
+							],
445
+							'limit' => 1,
446
+							'order_by' => [
447
+								'CHK_ID' => 'DESC'
448
+							]
449
+						]
450
+					);
451
+					$checkin_value = CheckinsCSV::getCheckinValue($checkin_row);
452
+					$datetime_name = CheckinsCSV::getDatetineLabel($datetime);
453
+					$reg_csv_array[ (string) $datetime_name ] = $checkin_value;
454
+				}
455
+			}
456
+			/**
457
+			 * Filter to change the contents of each row of the registrations report CSV file.
458
+			 * This can be used to add or remote columns from the CSV file, or change their values.
459
+			 * Note when using: all rows in the CSV should have the same columns.
460
+			 * @param array $reg_csv_array keys are the column names, values are their cell values
461
+			 * @param array $reg_row one entry from EEM_Registration::get_all_wpdb_results()
462
+			 */
463
+			$registrations_csv_ready_array[] = apply_filters(
464
+				'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__reg_csv_array',
465
+				$reg_csv_array,
466
+				$reg_row
467
+			);
468
+		}
469
+		// if we couldn't export anything, we want to at least show the column headers
470
+		if (empty($registrations_csv_ready_array)) {
471
+			$reg_csv_array = [];
472
+			$model_and_fields_to_include = [
473
+				'Registration' => $reg_fields_to_include,
474
+				'Attendee'     => $att_fields_to_include,
475
+			];
476
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
477
+				$model = EE_Registry::instance()->load_model($model_name);
478
+				foreach ($field_list as $field_name) {
479
+					$field = $model->field_settings_for($field_name);
480
+					$reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = null;
481
+				}
482
+			}
483
+			$registrations_csv_ready_array[] = $reg_csv_array;
484
+		}
485
+		return $registrations_csv_ready_array;
486
+	}
487 487
 
488 488
 
489
-    /**
490
-     * Counts total unit to process
491
-     *
492
-     * @param array $query_params
493
-     * @return int
494
-     * @throws EE_Error
495
-     */
496
-    public function count_units_to_process($query_params)
497
-    {
498
-        return EEM_Registration::instance()->count(
499
-            array_diff_key(
500
-                $query_params,
501
-                array_flip(
502
-                    ['limit']
503
-                )
504
-            )
505
-        );
506
-    }
489
+	/**
490
+	 * Counts total unit to process
491
+	 *
492
+	 * @param array $query_params
493
+	 * @return int
494
+	 * @throws EE_Error
495
+	 */
496
+	public function count_units_to_process($query_params)
497
+	{
498
+		return EEM_Registration::instance()->count(
499
+			array_diff_key(
500
+				$query_params,
501
+				array_flip(
502
+					['limit']
503
+				)
504
+			)
505
+		);
506
+	}
507 507
 
508 508
 
509
-    /**
510
-     * Performs any clean-up logic when we know the job is completed.
511
-     * In this case, we delete the temporary file
512
-     *
513
-     * @param JobParameters $job_parameters
514
-     * @return JobStepResponse
515
-     * @throws EE_Error
516
-     */
517
-    public function cleanup_job(JobParameters $job_parameters)
518
-    {
519
-        $this->_file_helper->delete(
520
-            EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
521
-            true,
522
-            'd'
523
-        );
524
-        return new JobStepResponse($job_parameters, esc_html__('Cleaned up temporary file', 'event_espresso'));
525
-    }
509
+	/**
510
+	 * Performs any clean-up logic when we know the job is completed.
511
+	 * In this case, we delete the temporary file
512
+	 *
513
+	 * @param JobParameters $job_parameters
514
+	 * @return JobStepResponse
515
+	 * @throws EE_Error
516
+	 */
517
+	public function cleanup_job(JobParameters $job_parameters)
518
+	{
519
+		$this->_file_helper->delete(
520
+			EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
521
+			true,
522
+			'd'
523
+		);
524
+		return new JobStepResponse($job_parameters, esc_html__('Cleaned up temporary file', 'event_espresso'));
525
+	}
526 526
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
     {
59 59
         $event_id = (int) $job_parameters->request_datum('EVT_ID', '0');
60 60
         $DTT_ID = (int) $job_parameters->request_datum('DTT_ID', '0');
61
-        if (! EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
61
+        if ( ! EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
62 62
             throw new BatchRequestException(esc_html__('You do not have permission to view registrations', 'event_espresso'));
63 63
         }
64 64
         $filepath = $this->create_file_from_job_with_name(
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
         } else {
92 92
             $query_params['force_join'][] = 'Event';
93 93
         }
94
-        if (! isset($query_params['force_join'])) {
94
+        if ( ! isset($query_params['force_join'])) {
95 95
             $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
96 96
         }
97 97
         $job_parameters->add_extra_data('query_params', $query_params);
@@ -184,10 +184,10 @@  discard block
 block discarded – undo
184 184
         $question_where_params = array();
185 185
         foreach ($reg_where_params as $key => $val) {
186 186
             if (EEM_Registration::instance()->is_logic_query_param_key($key)) {
187
-                $question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
187
+                $question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
188 188
             } else {
189 189
                 // it's a normal where condition
190
-                $question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
190
+                $question_where_params['Question_Group.Event.Registration.'.$key] = $val;
191 191
             }
192 192
         }
193 193
         return $question_where_params;
@@ -277,20 +277,20 @@  discard block
 block discarded – undo
277 277
         $query_params['limit'] = [$offset, $limit];
278 278
         $registration_rows = $reg_model->get_all_wpdb_results($query_params);
279 279
         foreach ($registration_rows as $reg_row) {
280
-            if (!is_array($reg_row)) {
280
+            if ( ! is_array($reg_row)) {
281 281
                 continue;
282 282
             }
283 283
             $reg_csv_array = [];
284 284
             // registration Id
285 285
             $reg_id_field = $reg_model->field_settings_for('REG_ID');
286
-            $reg_csv_array[ EEH_Export::get_column_name_for_field($reg_id_field) ] = EEH_Export::prepare_value_from_db_for_display(
286
+            $reg_csv_array[EEH_Export::get_column_name_for_field($reg_id_field)] = EEH_Export::prepare_value_from_db_for_display(
287 287
                 $reg_model,
288 288
                 'REG_ID',
289
-                $reg_row[ $reg_id_field->get_qualified_column() ]
289
+                $reg_row[$reg_id_field->get_qualified_column()]
290 290
             );
291
-            if (! $event_id) {
291
+            if ( ! $event_id) {
292 292
                 // get the event's name and Id
293
-                $reg_csv_array[ (string) esc_html__('Event', 'event_espresso') ] = sprintf(
293
+                $reg_csv_array[(string) esc_html__('Event', 'event_espresso')] = sprintf(
294 294
                     /* translators: 1: event name, 2: event ID */
295 295
                     esc_html__('%1$s (%2$s)', 'event_espresso'),
296 296
                     EEH_Export::prepare_value_from_db_for_display(
@@ -315,17 +315,17 @@  discard block
 block discarded – undo
315 315
                 'sentence'
316 316
             );
317 317
             $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
318
-            $reg_csv_array[ (string) esc_html__("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
318
+            $reg_csv_array[(string) esc_html__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
319 319
             // get pretty transaction status
320
-            $reg_csv_array[ (string) esc_html__("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
321
-            $reg_csv_array[ (string) esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
320
+            $reg_csv_array[(string) esc_html__("Transaction Status", 'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
321
+            $reg_csv_array[(string) esc_html__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
322 322
                 ? EEH_Export::prepare_value_from_db_for_display(
323 323
                     EEM_Transaction::instance(),
324 324
                     'TXN_total',
325 325
                     $reg_row['TransactionTable.TXN_total'],
326 326
                     'localized_float'
327 327
                 ) : '0.00';
328
-            $reg_csv_array[ (string) esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
328
+            $reg_csv_array[(string) esc_html__('Amount Paid', 'event_espresso')] = $is_primary_reg
329 329
                 ? EEH_Export::prepare_value_from_db_for_display(
330 330
                     EEM_Transaction::instance(),
331 331
                     'TXN_paid',
@@ -349,9 +349,9 @@  discard block
 block discarded – undo
349 349
                 );
350 350
                 list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
351 351
             }
352
-            $reg_csv_array[ (string) esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
353
-            $reg_csv_array[ (string) esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
354
-            $reg_csv_array[ (string) esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
352
+            $reg_csv_array[(string) esc_html__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
353
+            $reg_csv_array[(string) esc_html__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
354
+            $reg_csv_array[(string) esc_html__('Gateway Transaction ID(s)', 'event_espresso')] = implode(
355 355
                 ',',
356 356
                 $gateway_txn_ids_etc
357 357
             );
@@ -383,14 +383,14 @@  discard block
 block discarded – undo
383 383
                 $ticket_name = esc_html__('Unknown', 'event_espresso');
384 384
                 $datetimes_strings = [esc_html__('Unknown', 'event_espresso')];
385 385
             }
386
-            $reg_csv_array[ (string) $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
387
-            $reg_csv_array[ (string) esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
386
+            $reg_csv_array[(string) $ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
387
+            $reg_csv_array[(string) esc_html__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
388 388
             // add answer columns
389 389
             $reg_csv_array = AnswersCSV::addAnswerColumns($reg_row, $reg_csv_array, $question_labels);
390 390
             // Include check-in data
391 391
             if ($event_id && $DTT_ID) {
392 392
                 // get whether or not the user has checked in
393
-                $reg_csv_array[ (string) esc_html__('Datetime Check-ins #', 'event_espresso') ] = $reg_model->count_related(
393
+                $reg_csv_array[(string) esc_html__('Datetime Check-ins #', 'event_espresso')] = $reg_model->count_related(
394 394
                     $reg_row['Registration.REG_ID'],
395 395
                     'Checkin',
396 396
                     [
@@ -418,10 +418,10 @@  discard block
 block discarded – undo
418 418
                     }
419 419
                 }
420 420
                 $datetime_name = CheckinsCSV::getDatetineLabel($datetime);
421
-                $reg_csv_array[ (string) $datetime_name ] = implode(' --- ', $checkins);
421
+                $reg_csv_array[(string) $datetime_name] = implode(' --- ', $checkins);
422 422
             } elseif ($event_id) {
423 423
                 // get whether or not the user has checked in
424
-                $reg_csv_array[ (string) esc_html__('Event Check-ins #', 'event_espresso') ] = $reg_model->count_related(
424
+                $reg_csv_array[(string) esc_html__('Event Check-ins #', 'event_espresso')] = $reg_model->count_related(
425 425
                     $reg_row['Registration.REG_ID'],
426 426
                     'Checkin'
427 427
                 );
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
                     );
451 451
                     $checkin_value = CheckinsCSV::getCheckinValue($checkin_row);
452 452
                     $datetime_name = CheckinsCSV::getDatetineLabel($datetime);
453
-                    $reg_csv_array[ (string) $datetime_name ] = $checkin_value;
453
+                    $reg_csv_array[(string) $datetime_name] = $checkin_value;
454 454
                 }
455 455
             }
456 456
             /**
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
                 $model = EE_Registry::instance()->load_model($model_name);
478 478
                 foreach ($field_list as $field_name) {
479 479
                     $field = $model->field_settings_for($field_name);
480
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = null;
480
+                    $reg_csv_array[EEH_Export::get_column_name_for_field($field)] = null;
481 481
                 }
482 482
             }
483 483
             $registrations_csv_ready_array[] = $reg_csv_array;
Please login to merge, or discard this patch.
services/admin/registrations/list_table/csv_reports/RegistrationCSV.php 2 patches
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -19,66 +19,66 @@
 block discarded – undo
19 19
 class RegistrationCSV
20 20
 {
21 21
 
22
-    /**
23
-     * Adds registration columns to the CSV row
24
-     *
25
-     * @param array $fields
26
-     * @param array $reg_row
27
-     * @param EEM_Registration $reg_model
28
-     * @param array $data
29
-     * @return mixed
30
-     * @throws EE_Error
31
-     */
32
-    public static function addRegistrationColumns(array $fields, array $reg_row, EEM_Registration $reg_model, array $data)
33
-    {
34
-        foreach ($fields as $field_name) {
35
-            $field = $reg_model->field_settings_for($field_name);
36
-            switch ($field_name) {
37
-                case 'REG_final_price':
38
-                    $value = EEH_Export::prepare_value_from_db_for_display(
39
-                        $reg_model,
40
-                        $field_name,
41
-                        $reg_row['Registration.REG_final_price'],
42
-                        'localized_float'
43
-                    );
44
-                    break;
45
-                case 'REG_count':
46
-                    $value = sprintf(
47
-                        /* translators: 1: number of registration in group (REG_count), 2: registration group size (REG_group_size) */
48
-                        esc_html__('%1$s of %2$s', 'event_espresso'),
49
-                        EEH_Export::prepare_value_from_db_for_display(
50
-                            $reg_model,
51
-                            'REG_count',
52
-                            $reg_row['Registration.REG_count']
53
-                        ),
54
-                        EEH_Export::prepare_value_from_db_for_display(
55
-                            $reg_model,
56
-                            'REG_group_size',
57
-                            $reg_row['Registration.REG_group_size']
58
-                        )
59
-                    );
60
-                    break;
61
-                case 'REG_date':
62
-                    $value = EEH_Export::prepare_value_from_db_for_display(
63
-                        $reg_model,
64
-                        $field_name,
65
-                        $reg_row['Registration.REG_date'],
66
-                        'no_html'
67
-                    );
68
-                    break;
69
-                default:
70
-                    $value = EEH_Export::prepare_value_from_db_for_display(
71
-                        $reg_model,
72
-                        $field_name,
73
-                        $reg_row[ $field->get_qualified_column() ]
74
-                    );
75
-            }
76
-            $data[ EEH_Export::get_column_name_for_field($field) ] = $value;
77
-            if ($field_name == 'REG_final_price') {
78
-                // add a column named Currency after the final price
79
-                $data[ (string) esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
80
-            }
81
-        }
82
-        return $data;
83
-    }
22
+	/**
23
+	 * Adds registration columns to the CSV row
24
+	 *
25
+	 * @param array $fields
26
+	 * @param array $reg_row
27
+	 * @param EEM_Registration $reg_model
28
+	 * @param array $data
29
+	 * @return mixed
30
+	 * @throws EE_Error
31
+	 */
32
+	public static function addRegistrationColumns(array $fields, array $reg_row, EEM_Registration $reg_model, array $data)
33
+	{
34
+		foreach ($fields as $field_name) {
35
+			$field = $reg_model->field_settings_for($field_name);
36
+			switch ($field_name) {
37
+				case 'REG_final_price':
38
+					$value = EEH_Export::prepare_value_from_db_for_display(
39
+						$reg_model,
40
+						$field_name,
41
+						$reg_row['Registration.REG_final_price'],
42
+						'localized_float'
43
+					);
44
+					break;
45
+				case 'REG_count':
46
+					$value = sprintf(
47
+						/* translators: 1: number of registration in group (REG_count), 2: registration group size (REG_group_size) */
48
+						esc_html__('%1$s of %2$s', 'event_espresso'),
49
+						EEH_Export::prepare_value_from_db_for_display(
50
+							$reg_model,
51
+							'REG_count',
52
+							$reg_row['Registration.REG_count']
53
+						),
54
+						EEH_Export::prepare_value_from_db_for_display(
55
+							$reg_model,
56
+							'REG_group_size',
57
+							$reg_row['Registration.REG_group_size']
58
+						)
59
+					);
60
+					break;
61
+				case 'REG_date':
62
+					$value = EEH_Export::prepare_value_from_db_for_display(
63
+						$reg_model,
64
+						$field_name,
65
+						$reg_row['Registration.REG_date'],
66
+						'no_html'
67
+					);
68
+					break;
69
+				default:
70
+					$value = EEH_Export::prepare_value_from_db_for_display(
71
+						$reg_model,
72
+						$field_name,
73
+						$reg_row[ $field->get_qualified_column() ]
74
+					);
75
+			}
76
+			$data[ EEH_Export::get_column_name_for_field($field) ] = $value;
77
+			if ($field_name == 'REG_final_price') {
78
+				// add a column named Currency after the final price
79
+				$data[ (string) esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
80
+			}
81
+		}
82
+		return $data;
83
+	}
84 84
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -70,13 +70,13 @@
 block discarded – undo
70 70
                     $value = EEH_Export::prepare_value_from_db_for_display(
71 71
                         $reg_model,
72 72
                         $field_name,
73
-                        $reg_row[ $field->get_qualified_column() ]
73
+                        $reg_row[$field->get_qualified_column()]
74 74
                     );
75 75
             }
76
-            $data[ EEH_Export::get_column_name_for_field($field) ] = $value;
76
+            $data[EEH_Export::get_column_name_for_field($field)] = $value;
77 77
             if ($field_name == 'REG_final_price') {
78 78
                 // add a column named Currency after the final price
79
-                $data[ (string) esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
79
+                $data[(string) esc_html__("Currency", "event_espresso")] = EE_Config::instance()->currency->code;
80 80
             }
81 81
         }
82 82
         return $data;
Please login to merge, or discard this patch.
domain/services/admin/registrations/list_table/csv_reports/AttendeeCSV.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -18,49 +18,49 @@
 block discarded – undo
18 18
 class AttendeeCSV
19 19
 {
20 20
 
21
-    /**
22
-     * Adds attendee columns to the CSV row
23
-     *
24
-     * @param array $fields
25
-     * @param array $reg_row
26
-     * @param array $data
27
-     * @return array
28
-     * @throws EE_Error
29
-     */
30
-    public static function addAttendeeColumns(array $fields, array $reg_row, array $data)
31
-    {
32
-        foreach ($fields as $field_name) {
33
-            $field_obj = EEM_Attendee::instance()->field_settings_for($field_name);
34
-            if ($reg_row['Attendee_CPT.ID']) {
35
-                switch ($field_name) {
36
-                    case 'STA_ID':
37
-                        $value = EEM_State::instance()->get_var(
38
-                            [
39
-                                ['STA_ID' => $reg_row['Attendee_Meta.STA_ID']]
40
-                            ],
41
-                            'STA_name'
42
-                        );
43
-                        break;
44
-                    case 'CNT_ISO':
45
-                        $value = EEM_Country::instance()->get_var(
46
-                            [
47
-                                ['CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO']]
48
-                            ],
49
-                            'CNT_name'
50
-                        );
51
-                        break;
52
-                    default:
53
-                        $value = EEH_Export::prepare_value_from_db_for_display(
54
-                            EEM_Attendee::instance(),
55
-                            $field_name,
56
-                            $reg_row[ $field_obj->get_qualified_column() ]
57
-                        );
58
-                }
59
-            } else {
60
-                $value = '';
61
-            }
62
-            $data[ EEH_Export::get_column_name_for_field($field_obj) ] = $value;
63
-        }
64
-        return $data;
65
-    }
21
+	/**
22
+	 * Adds attendee columns to the CSV row
23
+	 *
24
+	 * @param array $fields
25
+	 * @param array $reg_row
26
+	 * @param array $data
27
+	 * @return array
28
+	 * @throws EE_Error
29
+	 */
30
+	public static function addAttendeeColumns(array $fields, array $reg_row, array $data)
31
+	{
32
+		foreach ($fields as $field_name) {
33
+			$field_obj = EEM_Attendee::instance()->field_settings_for($field_name);
34
+			if ($reg_row['Attendee_CPT.ID']) {
35
+				switch ($field_name) {
36
+					case 'STA_ID':
37
+						$value = EEM_State::instance()->get_var(
38
+							[
39
+								['STA_ID' => $reg_row['Attendee_Meta.STA_ID']]
40
+							],
41
+							'STA_name'
42
+						);
43
+						break;
44
+					case 'CNT_ISO':
45
+						$value = EEM_Country::instance()->get_var(
46
+							[
47
+								['CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO']]
48
+							],
49
+							'CNT_name'
50
+						);
51
+						break;
52
+					default:
53
+						$value = EEH_Export::prepare_value_from_db_for_display(
54
+							EEM_Attendee::instance(),
55
+							$field_name,
56
+							$reg_row[ $field_obj->get_qualified_column() ]
57
+						);
58
+				}
59
+			} else {
60
+				$value = '';
61
+			}
62
+			$data[ EEH_Export::get_column_name_for_field($field_obj) ] = $value;
63
+		}
64
+		return $data;
65
+	}
66 66
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -53,13 +53,13 @@
 block discarded – undo
53 53
                         $value = EEH_Export::prepare_value_from_db_for_display(
54 54
                             EEM_Attendee::instance(),
55 55
                             $field_name,
56
-                            $reg_row[ $field_obj->get_qualified_column() ]
56
+                            $reg_row[$field_obj->get_qualified_column()]
57 57
                         );
58 58
                 }
59 59
             } else {
60 60
                 $value = '';
61 61
             }
62
-            $data[ EEH_Export::get_column_name_for_field($field_obj) ] = $value;
62
+            $data[EEH_Export::get_column_name_for_field($field_obj)] = $value;
63 63
         }
64 64
         return $data;
65 65
     }
Please login to merge, or discard this patch.
core/db_classes/EE_Export.class.php 2 patches
Indentation   +780 added lines, -780 removed lines patch added patch discarded remove patch
@@ -18,784 +18,784 @@
 block discarded – undo
18 18
 class EE_Export
19 19
 {
20 20
 
21
-    const option_prefix = 'ee_report_job_';
22
-
23
-
24
-    // instance of the EE_Export object
25
-    private static $_instance = null;
26
-
27
-    // instance of the EE_CSV object
28
-    /**
29
-     *
30
-     * @var EE_CSV
31
-     */
32
-    public $EE_CSV = null;
33
-
34
-
35
-    private $_req_data = array();
36
-
37
-
38
-    /**
39
-     *        private constructor to prevent direct creation
40
-     *
41
-     * @Constructor
42
-     * @access private
43
-     * @param array $request_data
44
-     */
45
-    private function __construct($request_data = array())
46
-    {
47
-        $this->_req_data = $request_data;
48
-        $this->today = date("Y-m-d", time());
49
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
50
-        $this->EE_CSV = EE_CSV::instance();
51
-    }
52
-
53
-
54
-    /**
55
-     *        @ singleton method used to instantiate class object
56
-     *        @ access public
57
-     *
58
-     * @param array $request_data
59
-     * @return \EE_Export
60
-     */
61
-    public static function instance($request_data = array())
62
-    {
63
-        // check if class object is instantiated
64
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
65
-            self::$_instance = new self($request_data);
66
-        }
67
-        return self::$_instance;
68
-    }
69
-
70
-
71
-    /**
72
-     * @Export Event Espresso data - routes export requests
73
-     * @access public
74
-     * @return void | bool
75
-     */
76
-    public function export()
77
-    {
78
-        // in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
79
-        if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
80
-            // check if action2 has export action
81
-            if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
82
-                // whoop! there it is!
83
-                $this->_req_data['action'] = $this->_req_data['action2'];
84
-            }
85
-        }
86
-
87
-        $this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
88
-
89
-        switch ($this->_req_data['export']) {
90
-            case 'report':
91
-                switch ($this->_req_data['action']) {
92
-                    case "event":
93
-                    case "export_events":
94
-                    case 'all_event_data':
95
-                        $this->export_all_event_data();
96
-                        break;
97
-
98
-                    case 'registrations_report_for_event':
99
-                        $this->report_registrations_for_event($this->_req_data['EVT_ID']);
100
-                        break;
101
-
102
-                    case 'attendees':
103
-                        $this->export_attendees();
104
-                        break;
105
-
106
-                    case 'categories':
107
-                        $this->export_categories();
108
-                        break;
109
-
110
-                    default:
111
-                        EE_Error::add_error(
112
-                            esc_html__('An error occurred! The requested export report could not be found.', 'event_espresso'),
113
-                            __FILE__,
114
-                            __FUNCTION__,
115
-                            __LINE__
116
-                        );
117
-                        return false;
118
-                        break;
119
-                }
120
-                break; // end of switch export : report
121
-            default:
122
-                break;
123
-        } // end of switch export
124
-
125
-        exit;
126
-    }
127
-
128
-    /**
129
-     * Downloads a CSV file with all the columns, but no data. This should be used for importing
130
-     *
131
-     * @return void kills execution
132
-     * @throws EE_Error
133
-     * @throws ReflectionException
134
-     */
135
-    public function export_sample()
136
-    {
137
-        $event = EEM_Event::instance()->get_one();
138
-        $this->_req_data['EVT_ID'] = $event->ID();
139
-        $this->export_all_event_data();
140
-    }
141
-
142
-
143
-    /**
144
-     * @Export data for ALL events
145
-     * @access public
146
-     * @return void
147
-     * @throws EE_Error
148
-     * @throws ReflectionException
149
-     */
150
-    public function export_all_event_data()
151
-    {
152
-        // are any Event IDs set?
153
-        $event_query_params = array();
154
-        $related_models_query_params = array();
155
-        $related_through_reg_query_params = array();
156
-        $datetime_ticket_query_params = array();
157
-        $price_query_params = array();
158
-        $price_type_query_params = array();
159
-        $term_query_params = array();
160
-        $state_country_query_params = array();
161
-        $question_group_query_params = array();
162
-        $question_query_params = array();
163
-        if (isset($this->_req_data['EVT_ID'])) {
164
-            // do we have an array of IDs ?
165
-
166
-            if (is_array($this->_req_data['EVT_ID'])) {
167
-                $EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
168
-                $value_to_equal = array('IN', $EVT_IDs);
169
-                $filename = 'events';
170
-            } else {
171
-                // generate regular where = clause
172
-                $EVT_ID = absint($this->_req_data['EVT_ID']);
173
-                $value_to_equal = $EVT_ID;
174
-                $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
175
-
176
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
177
-            }
178
-            $event_query_params[0]['EVT_ID'] = $value_to_equal;
179
-            $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
180
-            $related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
181
-            $datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
182
-            $price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
183
-            $price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
184
-            $term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
185
-            $state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
186
-            $question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
187
-            $question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
188
-        } else {
189
-            $filename = 'all-events';
190
-        }
191
-
192
-
193
-        // array in the format:  table name =>  query where clause
194
-        $models_to_export = array(
195
-            'Event'                   => $event_query_params,
196
-            'Datetime'                => $related_models_query_params,
197
-            'Ticket_Template'         => $price_query_params,
198
-            'Ticket'                  => $datetime_ticket_query_params,
199
-            'Datetime_Ticket'         => $datetime_ticket_query_params,
200
-            'Price_Type'              => $price_type_query_params,
201
-            'Price'                   => $price_query_params,
202
-            'Ticket_Price'            => $price_query_params,
203
-            'Term'                    => $term_query_params,
204
-            'Term_Taxonomy'           => $related_models_query_params,
205
-            'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
206
-            'Country'                 => $state_country_query_params,
207
-            'State'                   => $state_country_query_params,
208
-            'Venue'                   => $related_models_query_params,
209
-            'Event_Venue'             => $related_models_query_params,
210
-            'Question_Group'          => $question_group_query_params,
211
-            'Event_Question_Group'    => $question_group_query_params,
212
-            'Question'                => $question_query_params,
213
-            'Question_Group_Question' => $question_query_params,
214
-            // 'Transaction'=>$related_through_reg_query_params,
215
-            // 'Registration'=>$related_models_query_params,
216
-            // 'Attendee'=>$related_through_reg_query_params,
217
-            // 'Line_Item'=>
218
-
219
-        );
220
-
221
-        $model_data = $this->_get_export_data_for_models($models_to_export);
222
-
223
-        $filename = $this->generate_filename($filename);
224
-
225
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
226
-            EE_Error::add_error(
227
-                esc_html__(
228
-                    "'An error occurred and the Event details could not be exported from the database.'",
229
-                    "event_espresso"
230
-                ),
231
-                __FILE__,
232
-                __FUNCTION__,
233
-                __LINE__
234
-            );
235
-        }
236
-    }
237
-
238
-    public function report_attendees()
239
-    {
240
-        $attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
241
-            array(
242
-                'force_join' => array('State', 'Country'),
243
-                'caps'       => EEM_Base::caps_read_admin,
244
-            )
245
-        );
246
-        $csv_data = array();
247
-        foreach ($attendee_rows as $attendee_row) {
248
-            $csv_row = array();
249
-            foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
250
-                if ($field_name == 'STA_ID') {
251
-                    $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
252
-                    $csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
253
-                    ) ];
254
-                } elseif ($field_name == 'CNT_ISO') {
255
-                    $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
256
-                    $csv_row[ esc_html__(
257
-                        'Country',
258
-                        'event_espresso'
259
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
260
-                } else {
261
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
262
-                }
263
-            }
264
-            $csv_data[] = $csv_row;
265
-        }
266
-
267
-        $filename = $this->generate_filename('contact-list-report');
268
-
269
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
270
-        $this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
271
-        $this->EE_CSV->end_sending_csv($handle);
272
-    }
273
-
274
-
275
-    /**
276
-     * @Export data for ALL attendees
277
-     * @access public
278
-     * @return void
279
-     * @throws EE_Error
280
-     */
281
-    public function export_attendees()
282
-    {
283
-
284
-        $states_that_have_an_attendee = EEM_State::instance()->get_all(
285
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
286
-        );
287
-        $countries_that_have_an_attendee = EEM_Country::instance()->get_all(
288
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
289
-        );
290
-        // $states_to_export_query_params
291
-        $models_to_export = array(
292
-            'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
293
-            'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
294
-            'Attendee' => array(),
295
-        );
296
-
297
-
298
-        $model_data = $this->_get_export_data_for_models($models_to_export);
299
-        $filename = $this->generate_filename('all-attendees');
300
-
301
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
302
-            EE_Error::add_error(
303
-                esc_html__(
304
-                    'An error occurred and the Attendee data could not be exported from the database.',
305
-                    'event_espresso'
306
-                ),
307
-                __FILE__,
308
-                __FUNCTION__,
309
-                __LINE__
310
-            );
311
-        }
312
-    }
313
-
314
-    /**
315
-     * Shortcut for preparing a database result for display
316
-     *
317
-     * @param EEM_Base $model
318
-     * @param string $field_name
319
-     * @param string $raw_db_value
320
-     * @param bool|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
321
-     *                                      NOT display pretty
322
-     * @return string
323
-     * @throws EE_Error
324
-     */
325
-    protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
326
-    {
327
-        $field_obj = $model->field_settings_for($field_name);
328
-        $value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
329
-        if ($field_obj instanceof EE_Datetime_Field) {
330
-            $field_obj->set_date_format(
331
-                EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
332
-                $pretty_schema
333
-            );
334
-            $field_obj->set_time_format(
335
-                EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
336
-                $pretty_schema
337
-            );
338
-        }
339
-        if ($pretty_schema === true) {
340
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
341
-        } elseif (is_string($pretty_schema)) {
342
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
343
-        } else {
344
-            return $field_obj->prepare_for_get($value_on_model_obj);
345
-        }
346
-    }
347
-
348
-    /**
349
-     * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
350
-     * name, and the questions associated with the registrations
351
-     *
352
-     * @param int $event_id
353
-     * @throws EE_Error
354
-     * @throws ReflectionException
355
-     */
356
-    public function report_registrations_for_event($event_id = null)
357
-    {
358
-        $reg_fields_to_include = array(
359
-            'TXN_ID',
360
-            'ATT_ID',
361
-            'REG_ID',
362
-            'REG_date',
363
-            'REG_code',
364
-            'REG_count',
365
-            'REG_final_price',
366
-
367
-        );
368
-        $att_fields_to_include = array(
369
-            'ATT_fname',
370
-            'ATT_lname',
371
-            'ATT_email',
372
-            'ATT_address',
373
-            'ATT_address2',
374
-            'ATT_city',
375
-            'STA_ID',
376
-            'CNT_ISO',
377
-            'ATT_zip',
378
-            'ATT_phone',
379
-        );
380
-
381
-        $registrations_csv_ready_array = array();
382
-        $reg_model = EE_Registry::instance()->load_model('Registration');
383
-        $query_params = apply_filters(
384
-            'FHEE__EE_Export__report_registration_for_event',
385
-            array(
386
-                array(
387
-                    'OR'                 => array(
388
-                        // don't include registrations from failed or abandoned transactions...
389
-                        'Transaction.STS_ID' => array(
390
-                            'NOT IN',
391
-                            array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
392
-                        ),
393
-                        // unless the registration is approved, in which case include it regardless of transaction status
394
-                        'STS_ID'             => EEM_Registration::status_id_approved,
395
-                    ),
396
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
397
-                ),
398
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
399
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
400
-                'caps'       => EEM_Base::caps_read_admin,
401
-            ),
402
-            $event_id
403
-        );
404
-        if ($event_id) {
405
-            $query_params[0]['EVT_ID'] = $event_id;
406
-        } else {
407
-            $query_params['force_join'][] = 'Event';
408
-        }
409
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
410
-        // get all questions which relate to someone in this group
411
-        $registration_ids = array();
412
-        foreach ($registration_rows as $reg_row) {
413
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
414
-        }
415
-        // EEM_Question::instance()->show_next_x_db_queries();
416
-        $questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
417
-            array(array('Answer.REG_ID' => array('IN', $registration_ids)))
418
-        );
419
-        foreach ($registration_rows as $reg_row) {
420
-            if (is_array($reg_row)) {
421
-                $reg_csv_array = array();
422
-                if (! $event_id) {
423
-                    // get the event's name and Id
424
-                    $reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
425
-                        esc_html__('%1$s (%2$s)', 'event_espresso'),
426
-                        $this->_prepare_value_from_db_for_display(
427
-                            EEM_Event::instance(),
428
-                            'EVT_name',
429
-                            $reg_row['Event_CPT.post_title']
430
-                        ),
431
-                        $reg_row['Event_CPT.ID']
432
-                    );
433
-                }
434
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
435
-                /*@var $reg_row EE_Registration */
436
-                foreach ($reg_fields_to_include as $field_name) {
437
-                    $field = $reg_model->field_settings_for($field_name);
438
-                    if ($field_name == 'REG_final_price') {
439
-                        $value = $this->_prepare_value_from_db_for_display(
440
-                            $reg_model,
441
-                            $field_name,
442
-                            $reg_row['Registration.REG_final_price'],
443
-                            'localized_float'
444
-                        );
445
-                    } elseif ($field_name == 'REG_count') {
446
-                        $value = sprintf(
447
-                            esc_html__('%s of %s', 'event_espresso'),
448
-                            $this->_prepare_value_from_db_for_display(
449
-                                $reg_model,
450
-                                'REG_count',
451
-                                $reg_row['Registration.REG_count']
452
-                            ),
453
-                            $this->_prepare_value_from_db_for_display(
454
-                                $reg_model,
455
-                                'REG_group_size',
456
-                                $reg_row['Registration.REG_group_size']
457
-                            )
458
-                        );
459
-                    } elseif ($field_name == 'REG_date') {
460
-                        $value = $this->_prepare_value_from_db_for_display(
461
-                            $reg_model,
462
-                            $field_name,
463
-                            $reg_row['Registration.REG_date'],
464
-                            'no_html'
465
-                        );
466
-                    } else {
467
-                        $value = $this->_prepare_value_from_db_for_display(
468
-                            $reg_model,
469
-                            $field_name,
470
-                            $reg_row[ $field->get_qualified_column() ]
471
-                        );
472
-                    }
473
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
474
-                    if ($field_name == 'REG_final_price') {
475
-                        // add a column named Currency after the final price
476
-                        $reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
477
-                    }
478
-                }
479
-                // get pretty status
480
-                $stati = EEM_Status::instance()->localized_status(
481
-                    array(
482
-                        $reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
483
-                        $reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
484
-                    ),
485
-                    false,
486
-                    'sentence'
487
-                );
488
-                $reg_csv_array[ esc_html__(
489
-                    "Registration Status",
490
-                    'event_espresso'
491
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
492
-                // get pretty trnasaction status
493
-                $reg_csv_array[ esc_html__(
494
-                    "Transaction Status",
495
-                    'event_espresso'
496
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
497
-                $reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
498
-                    ? $this->_prepare_value_from_db_for_display(
499
-                        EEM_Transaction::instance(),
500
-                        'TXN_total',
501
-                        $reg_row['TransactionTable.TXN_total'],
502
-                        'localized_float'
503
-                    ) : '0.00';
504
-                $reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
505
-                    ? $this->_prepare_value_from_db_for_display(
506
-                        EEM_Transaction::instance(),
507
-                        'TXN_paid',
508
-                        $reg_row['TransactionTable.TXN_paid'],
509
-                        'localized_float'
510
-                    ) : '0.00';
511
-                $payment_methods = array();
512
-                $gateway_txn_ids_etc = array();
513
-                $payment_times = array();
514
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
515
-                    $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
516
-                        array(
517
-                            array(
518
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
519
-                                'STS_ID' => EEM_Payment::status_id_approved,
520
-                            ),
521
-                            'force_join' => array('Payment_Method'),
522
-                        ),
523
-                        ARRAY_A,
524
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
525
-                    );
526
-                    list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
527
-                }
528
-                $reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
529
-                $reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
530
-                $reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
531
-                    ',',
532
-                    $gateway_txn_ids_etc
533
-                );
534
-
535
-                // get whether or not the user has checked in
536
-                $reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
537
-                    $reg_row['Registration.REG_ID'],
538
-                    'Checkin'
539
-                );
540
-                // get ticket of registration and its price
541
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
542
-                if ($reg_row['Ticket.TKT_ID']) {
543
-                    $ticket_name = $this->_prepare_value_from_db_for_display(
544
-                        $ticket_model,
545
-                        'TKT_name',
546
-                        $reg_row['Ticket.TKT_name']
547
-                    );
548
-                    $datetimes_strings = array();
549
-                    foreach (
550
-                        EEM_Datetime::instance()->get_all_wpdb_results(
551
-                            array(
552
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
553
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
554
-                            'default_where_conditions' => 'none',
555
-                            )
556
-                        ) as $datetime
557
-                    ) {
558
-                        $datetimes_strings[] = $this->_prepare_value_from_db_for_display(
559
-                            EEM_Datetime::instance(),
560
-                            'DTT_EVT_start',
561
-                            $datetime['Datetime.DTT_EVT_start']
562
-                        );
563
-                    }
564
-                } else {
565
-                    $ticket_name = esc_html__('Unknown', 'event_espresso');
566
-                    $datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
567
-                }
568
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
569
-                $reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
570
-                // get datetime(s) of registration
571
-
572
-                // add attendee columns
573
-                foreach ($att_fields_to_include as $att_field_name) {
574
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
575
-                    if ($reg_row['Attendee_CPT.ID']) {
576
-                        if ($att_field_name == 'STA_ID') {
577
-                            $value = EEM_State::instance()->get_var(
578
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
579
-                                'STA_name'
580
-                            );
581
-                        } elseif ($att_field_name == 'CNT_ISO') {
582
-                            $value = EEM_Country::instance()->get_var(
583
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
584
-                                'CNT_name'
585
-                            );
586
-                        } else {
587
-                            $value = $this->_prepare_value_from_db_for_display(
588
-                                EEM_Attendee::instance(),
589
-                                $att_field_name,
590
-                                $reg_row[ $field_obj->get_qualified_column() ]
591
-                            );
592
-                        }
593
-                    } else {
594
-                        $value = '';
595
-                    }
596
-
597
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
598
-                }
599
-
600
-                // make sure each registration has the same questions in the same order
601
-                foreach ($questions_for_these_regs_rows as $question_row) {
602
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
603
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
604
-                    }
605
-                }
606
-                // now fill out the questions THEY answered
607
-                foreach (
608
-                    EEM_Answer::instance()->get_all_wpdb_results(
609
-                        array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
610
-                    ) as $answer_row
611
-                ) {
612
-                    /* @var $answer EE_Answer */
613
-                    if ($answer_row['Question.QST_ID']) {
614
-                        $question_label = $this->_prepare_value_from_db_for_display(
615
-                            EEM_Question::instance(),
616
-                            'QST_admin_label',
617
-                            $answer_row['Question.QST_admin_label']
618
-                        );
619
-                    } else {
620
-                        $question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
621
-                    }
622
-                    if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
623
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
624
-                            $answer_row['Answer.ANS_value']
625
-                        );
626
-                    } else {
627
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
628
-                            EEM_Answer::instance(),
629
-                            'ANS_value',
630
-                            $answer_row['Answer.ANS_value']
631
-                        );
632
-                    }
633
-                }
634
-                $registrations_csv_ready_array[] = apply_filters(
635
-                    'FHEE__EE_Export__report_registrations__reg_csv_array',
636
-                    $reg_csv_array,
637
-                    $reg_row
638
-                );
639
-            }
640
-        }
641
-
642
-        // if we couldn't export anything, we want to at least show the column headers
643
-        if (empty($registrations_csv_ready_array)) {
644
-            $reg_csv_array = array();
645
-            $model_and_fields_to_include = array(
646
-                'Registration' => $reg_fields_to_include,
647
-                'Attendee'     => $att_fields_to_include,
648
-            );
649
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
650
-                $model = EE_Registry::instance()->load_model($model_name);
651
-                foreach ($field_list as $field_name) {
652
-                    $field = $model->field_settings_for($field_name);
653
-                    $reg_csv_array[ $this->_get_column_name_for_field(
654
-                        $field
655
-                    ) ] = null;// $registration->get($field->get_name());
656
-                }
657
-            }
658
-            $registrations_csv_ready_array [] = $reg_csv_array;
659
-        }
660
-        if ($event_id) {
661
-            $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
662
-            if (! $event_slug) {
663
-                $event_slug = esc_html__('unknown', 'event_espresso');
664
-            }
665
-        } else {
666
-            $event_slug = esc_html__('all', 'event_espresso');
667
-        }
668
-        $filename = sprintf("registrations-for-%s", $event_slug);
669
-
670
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
671
-        $this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
672
-        $this->EE_CSV->end_sending_csv($handle);
673
-    }
674
-
675
-    /**
676
-     * Gets the 'normal' column named for fields
677
-     *
678
-     * @param EE_Model_Field_Base $field
679
-     * @return string
680
-     * @throws EE_Error
681
-     */
682
-    protected function _get_column_name_for_field(EE_Model_Field_Base $field)
683
-    {
684
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
685
-    }
686
-
687
-
688
-    /**
689
-     * @Export data for ALL events
690
-     * @access public
691
-     * @return void
692
-     */
693
-    public function export_categories()
694
-    {
695
-        // are any Event IDs set?
696
-        $query_params = array();
697
-        if (isset($this->_req_data['EVT_CAT_ID'])) {
698
-            // do we have an array of IDs ?
699
-            if (is_array($this->_req_data['EVT_CAT_ID'])) {
700
-                // generate an "IN (CSV)" where clause
701
-                $EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
702
-                $filename = 'event-categories';
703
-                $query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
704
-            } else {
705
-                // generate regular where = clause
706
-                $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
707
-                $filename = 'event-category#' . $EVT_CAT_ID;
708
-                $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
709
-            }
710
-        } else {
711
-            // no IDs means we will d/l the entire table
712
-            $filename = 'all-categories';
713
-        }
714
-
715
-        $tables_to_export = array(
716
-            'Term_Taxonomy' => $query_params,
717
-        );
718
-
719
-        $table_data = $this->_get_export_data_for_models($tables_to_export);
720
-        $filename = $this->generate_filename($filename);
721
-
722
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
723
-            EE_Error::add_error(
724
-                esc_html__(
725
-                    'An error occurred and the Category details could not be exported from the database.',
726
-                    'event_espresso'
727
-                ),
728
-                __FILE__,
729
-                __FUNCTION__,
730
-                __LINE__
731
-            );
732
-        }
733
-    }
734
-
735
-
736
-    /**
737
-     * @process export name to create a suitable filename
738
-     * @access  private
739
-     * @param string - export_name
740
-     * @return string on success, FALSE on fail
741
-     */
742
-    private function generate_filename($export_name = '')
743
-    {
744
-        if ($export_name != '') {
745
-            $filename = get_bloginfo('name') . '-' . $export_name;
746
-            $filename = sanitize_key($filename) . '-' . $this->today;
747
-            return $filename;
748
-        } else {
749
-            EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
750
-        }
751
-        return false;
752
-    }
753
-
754
-
755
-    /**
756
-     * @recursive function for exporting table data and merging the results with the next results
757
-     * @access    private
758
-     * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
759
-     *                                query params @return bool on success, FALSE on fail
760
-     * @throws EE_Error
761
-     * @throws ReflectionException
762
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
763
-     */
764
-    private function _get_export_data_for_models($models_to_export = array())
765
-    {
766
-        $table_data = false;
767
-        if (is_array($models_to_export)) {
768
-            foreach ($models_to_export as $model_name => $query_params) {
769
-                // check for a numerically-indexed array. in that case, $model_name is the value!!
770
-                if (is_int($model_name)) {
771
-                    $model_name = $query_params;
772
-                    $query_params = array();
773
-                }
774
-                $model = EE_Registry::instance()->load_model($model_name);
775
-                $model_objects = $model->get_all($query_params);
776
-
777
-                $table_data[ $model_name ] = array();
778
-                foreach ($model_objects as $model_object) {
779
-                    $model_data_array = array();
780
-                    $fields = $model->field_settings();
781
-                    foreach ($fields as $field) {
782
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
783
-                        if ($field instanceof EE_Datetime_Field) {
784
-                            // $field->set_date_format('Y-m-d');
785
-                            // $field->set_time_format('H:i:s');
786
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
787
-                                $field->get_name(),
788
-                                'Y-m-d',
789
-                                'H:i:s'
790
-                            );
791
-                        } else {
792
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
793
-                        }
794
-                    }
795
-                    $table_data[ $model_name ][] = $model_data_array;
796
-                }
797
-            }
798
-        }
799
-        return $table_data;
800
-    }
21
+	const option_prefix = 'ee_report_job_';
22
+
23
+
24
+	// instance of the EE_Export object
25
+	private static $_instance = null;
26
+
27
+	// instance of the EE_CSV object
28
+	/**
29
+	 *
30
+	 * @var EE_CSV
31
+	 */
32
+	public $EE_CSV = null;
33
+
34
+
35
+	private $_req_data = array();
36
+
37
+
38
+	/**
39
+	 *        private constructor to prevent direct creation
40
+	 *
41
+	 * @Constructor
42
+	 * @access private
43
+	 * @param array $request_data
44
+	 */
45
+	private function __construct($request_data = array())
46
+	{
47
+		$this->_req_data = $request_data;
48
+		$this->today = date("Y-m-d", time());
49
+		require_once(EE_CLASSES . 'EE_CSV.class.php');
50
+		$this->EE_CSV = EE_CSV::instance();
51
+	}
52
+
53
+
54
+	/**
55
+	 *        @ singleton method used to instantiate class object
56
+	 *        @ access public
57
+	 *
58
+	 * @param array $request_data
59
+	 * @return \EE_Export
60
+	 */
61
+	public static function instance($request_data = array())
62
+	{
63
+		// check if class object is instantiated
64
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
65
+			self::$_instance = new self($request_data);
66
+		}
67
+		return self::$_instance;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @Export Event Espresso data - routes export requests
73
+	 * @access public
74
+	 * @return void | bool
75
+	 */
76
+	public function export()
77
+	{
78
+		// in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
79
+		if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
80
+			// check if action2 has export action
81
+			if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
82
+				// whoop! there it is!
83
+				$this->_req_data['action'] = $this->_req_data['action2'];
84
+			}
85
+		}
86
+
87
+		$this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
88
+
89
+		switch ($this->_req_data['export']) {
90
+			case 'report':
91
+				switch ($this->_req_data['action']) {
92
+					case "event":
93
+					case "export_events":
94
+					case 'all_event_data':
95
+						$this->export_all_event_data();
96
+						break;
97
+
98
+					case 'registrations_report_for_event':
99
+						$this->report_registrations_for_event($this->_req_data['EVT_ID']);
100
+						break;
101
+
102
+					case 'attendees':
103
+						$this->export_attendees();
104
+						break;
105
+
106
+					case 'categories':
107
+						$this->export_categories();
108
+						break;
109
+
110
+					default:
111
+						EE_Error::add_error(
112
+							esc_html__('An error occurred! The requested export report could not be found.', 'event_espresso'),
113
+							__FILE__,
114
+							__FUNCTION__,
115
+							__LINE__
116
+						);
117
+						return false;
118
+						break;
119
+				}
120
+				break; // end of switch export : report
121
+			default:
122
+				break;
123
+		} // end of switch export
124
+
125
+		exit;
126
+	}
127
+
128
+	/**
129
+	 * Downloads a CSV file with all the columns, but no data. This should be used for importing
130
+	 *
131
+	 * @return void kills execution
132
+	 * @throws EE_Error
133
+	 * @throws ReflectionException
134
+	 */
135
+	public function export_sample()
136
+	{
137
+		$event = EEM_Event::instance()->get_one();
138
+		$this->_req_data['EVT_ID'] = $event->ID();
139
+		$this->export_all_event_data();
140
+	}
141
+
142
+
143
+	/**
144
+	 * @Export data for ALL events
145
+	 * @access public
146
+	 * @return void
147
+	 * @throws EE_Error
148
+	 * @throws ReflectionException
149
+	 */
150
+	public function export_all_event_data()
151
+	{
152
+		// are any Event IDs set?
153
+		$event_query_params = array();
154
+		$related_models_query_params = array();
155
+		$related_through_reg_query_params = array();
156
+		$datetime_ticket_query_params = array();
157
+		$price_query_params = array();
158
+		$price_type_query_params = array();
159
+		$term_query_params = array();
160
+		$state_country_query_params = array();
161
+		$question_group_query_params = array();
162
+		$question_query_params = array();
163
+		if (isset($this->_req_data['EVT_ID'])) {
164
+			// do we have an array of IDs ?
165
+
166
+			if (is_array($this->_req_data['EVT_ID'])) {
167
+				$EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
168
+				$value_to_equal = array('IN', $EVT_IDs);
169
+				$filename = 'events';
170
+			} else {
171
+				// generate regular where = clause
172
+				$EVT_ID = absint($this->_req_data['EVT_ID']);
173
+				$value_to_equal = $EVT_ID;
174
+				$event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
175
+
176
+				$filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
177
+			}
178
+			$event_query_params[0]['EVT_ID'] = $value_to_equal;
179
+			$related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
180
+			$related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
181
+			$datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
182
+			$price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
183
+			$price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
184
+			$term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
185
+			$state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
186
+			$question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
187
+			$question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
188
+		} else {
189
+			$filename = 'all-events';
190
+		}
191
+
192
+
193
+		// array in the format:  table name =>  query where clause
194
+		$models_to_export = array(
195
+			'Event'                   => $event_query_params,
196
+			'Datetime'                => $related_models_query_params,
197
+			'Ticket_Template'         => $price_query_params,
198
+			'Ticket'                  => $datetime_ticket_query_params,
199
+			'Datetime_Ticket'         => $datetime_ticket_query_params,
200
+			'Price_Type'              => $price_type_query_params,
201
+			'Price'                   => $price_query_params,
202
+			'Ticket_Price'            => $price_query_params,
203
+			'Term'                    => $term_query_params,
204
+			'Term_Taxonomy'           => $related_models_query_params,
205
+			'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
206
+			'Country'                 => $state_country_query_params,
207
+			'State'                   => $state_country_query_params,
208
+			'Venue'                   => $related_models_query_params,
209
+			'Event_Venue'             => $related_models_query_params,
210
+			'Question_Group'          => $question_group_query_params,
211
+			'Event_Question_Group'    => $question_group_query_params,
212
+			'Question'                => $question_query_params,
213
+			'Question_Group_Question' => $question_query_params,
214
+			// 'Transaction'=>$related_through_reg_query_params,
215
+			// 'Registration'=>$related_models_query_params,
216
+			// 'Attendee'=>$related_through_reg_query_params,
217
+			// 'Line_Item'=>
218
+
219
+		);
220
+
221
+		$model_data = $this->_get_export_data_for_models($models_to_export);
222
+
223
+		$filename = $this->generate_filename($filename);
224
+
225
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
226
+			EE_Error::add_error(
227
+				esc_html__(
228
+					"'An error occurred and the Event details could not be exported from the database.'",
229
+					"event_espresso"
230
+				),
231
+				__FILE__,
232
+				__FUNCTION__,
233
+				__LINE__
234
+			);
235
+		}
236
+	}
237
+
238
+	public function report_attendees()
239
+	{
240
+		$attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
241
+			array(
242
+				'force_join' => array('State', 'Country'),
243
+				'caps'       => EEM_Base::caps_read_admin,
244
+			)
245
+		);
246
+		$csv_data = array();
247
+		foreach ($attendee_rows as $attendee_row) {
248
+			$csv_row = array();
249
+			foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
250
+				if ($field_name == 'STA_ID') {
251
+					$state_name_field = EEM_State::instance()->field_settings_for('STA_name');
252
+					$csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
253
+					) ];
254
+				} elseif ($field_name == 'CNT_ISO') {
255
+					$country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
256
+					$csv_row[ esc_html__(
257
+						'Country',
258
+						'event_espresso'
259
+					) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
260
+				} else {
261
+					$csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
262
+				}
263
+			}
264
+			$csv_data[] = $csv_row;
265
+		}
266
+
267
+		$filename = $this->generate_filename('contact-list-report');
268
+
269
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
270
+		$this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
271
+		$this->EE_CSV->end_sending_csv($handle);
272
+	}
273
+
274
+
275
+	/**
276
+	 * @Export data for ALL attendees
277
+	 * @access public
278
+	 * @return void
279
+	 * @throws EE_Error
280
+	 */
281
+	public function export_attendees()
282
+	{
283
+
284
+		$states_that_have_an_attendee = EEM_State::instance()->get_all(
285
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
286
+		);
287
+		$countries_that_have_an_attendee = EEM_Country::instance()->get_all(
288
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
289
+		);
290
+		// $states_to_export_query_params
291
+		$models_to_export = array(
292
+			'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
293
+			'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
294
+			'Attendee' => array(),
295
+		);
296
+
297
+
298
+		$model_data = $this->_get_export_data_for_models($models_to_export);
299
+		$filename = $this->generate_filename('all-attendees');
300
+
301
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
302
+			EE_Error::add_error(
303
+				esc_html__(
304
+					'An error occurred and the Attendee data could not be exported from the database.',
305
+					'event_espresso'
306
+				),
307
+				__FILE__,
308
+				__FUNCTION__,
309
+				__LINE__
310
+			);
311
+		}
312
+	}
313
+
314
+	/**
315
+	 * Shortcut for preparing a database result for display
316
+	 *
317
+	 * @param EEM_Base $model
318
+	 * @param string $field_name
319
+	 * @param string $raw_db_value
320
+	 * @param bool|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
321
+	 *                                      NOT display pretty
322
+	 * @return string
323
+	 * @throws EE_Error
324
+	 */
325
+	protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
326
+	{
327
+		$field_obj = $model->field_settings_for($field_name);
328
+		$value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
329
+		if ($field_obj instanceof EE_Datetime_Field) {
330
+			$field_obj->set_date_format(
331
+				EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
332
+				$pretty_schema
333
+			);
334
+			$field_obj->set_time_format(
335
+				EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
336
+				$pretty_schema
337
+			);
338
+		}
339
+		if ($pretty_schema === true) {
340
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
341
+		} elseif (is_string($pretty_schema)) {
342
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
343
+		} else {
344
+			return $field_obj->prepare_for_get($value_on_model_obj);
345
+		}
346
+	}
347
+
348
+	/**
349
+	 * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
350
+	 * name, and the questions associated with the registrations
351
+	 *
352
+	 * @param int $event_id
353
+	 * @throws EE_Error
354
+	 * @throws ReflectionException
355
+	 */
356
+	public function report_registrations_for_event($event_id = null)
357
+	{
358
+		$reg_fields_to_include = array(
359
+			'TXN_ID',
360
+			'ATT_ID',
361
+			'REG_ID',
362
+			'REG_date',
363
+			'REG_code',
364
+			'REG_count',
365
+			'REG_final_price',
366
+
367
+		);
368
+		$att_fields_to_include = array(
369
+			'ATT_fname',
370
+			'ATT_lname',
371
+			'ATT_email',
372
+			'ATT_address',
373
+			'ATT_address2',
374
+			'ATT_city',
375
+			'STA_ID',
376
+			'CNT_ISO',
377
+			'ATT_zip',
378
+			'ATT_phone',
379
+		);
380
+
381
+		$registrations_csv_ready_array = array();
382
+		$reg_model = EE_Registry::instance()->load_model('Registration');
383
+		$query_params = apply_filters(
384
+			'FHEE__EE_Export__report_registration_for_event',
385
+			array(
386
+				array(
387
+					'OR'                 => array(
388
+						// don't include registrations from failed or abandoned transactions...
389
+						'Transaction.STS_ID' => array(
390
+							'NOT IN',
391
+							array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
392
+						),
393
+						// unless the registration is approved, in which case include it regardless of transaction status
394
+						'STS_ID'             => EEM_Registration::status_id_approved,
395
+					),
396
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
397
+				),
398
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
399
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
400
+				'caps'       => EEM_Base::caps_read_admin,
401
+			),
402
+			$event_id
403
+		);
404
+		if ($event_id) {
405
+			$query_params[0]['EVT_ID'] = $event_id;
406
+		} else {
407
+			$query_params['force_join'][] = 'Event';
408
+		}
409
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
410
+		// get all questions which relate to someone in this group
411
+		$registration_ids = array();
412
+		foreach ($registration_rows as $reg_row) {
413
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
414
+		}
415
+		// EEM_Question::instance()->show_next_x_db_queries();
416
+		$questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
417
+			array(array('Answer.REG_ID' => array('IN', $registration_ids)))
418
+		);
419
+		foreach ($registration_rows as $reg_row) {
420
+			if (is_array($reg_row)) {
421
+				$reg_csv_array = array();
422
+				if (! $event_id) {
423
+					// get the event's name and Id
424
+					$reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
425
+						esc_html__('%1$s (%2$s)', 'event_espresso'),
426
+						$this->_prepare_value_from_db_for_display(
427
+							EEM_Event::instance(),
428
+							'EVT_name',
429
+							$reg_row['Event_CPT.post_title']
430
+						),
431
+						$reg_row['Event_CPT.ID']
432
+					);
433
+				}
434
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
435
+				/*@var $reg_row EE_Registration */
436
+				foreach ($reg_fields_to_include as $field_name) {
437
+					$field = $reg_model->field_settings_for($field_name);
438
+					if ($field_name == 'REG_final_price') {
439
+						$value = $this->_prepare_value_from_db_for_display(
440
+							$reg_model,
441
+							$field_name,
442
+							$reg_row['Registration.REG_final_price'],
443
+							'localized_float'
444
+						);
445
+					} elseif ($field_name == 'REG_count') {
446
+						$value = sprintf(
447
+							esc_html__('%s of %s', 'event_espresso'),
448
+							$this->_prepare_value_from_db_for_display(
449
+								$reg_model,
450
+								'REG_count',
451
+								$reg_row['Registration.REG_count']
452
+							),
453
+							$this->_prepare_value_from_db_for_display(
454
+								$reg_model,
455
+								'REG_group_size',
456
+								$reg_row['Registration.REG_group_size']
457
+							)
458
+						);
459
+					} elseif ($field_name == 'REG_date') {
460
+						$value = $this->_prepare_value_from_db_for_display(
461
+							$reg_model,
462
+							$field_name,
463
+							$reg_row['Registration.REG_date'],
464
+							'no_html'
465
+						);
466
+					} else {
467
+						$value = $this->_prepare_value_from_db_for_display(
468
+							$reg_model,
469
+							$field_name,
470
+							$reg_row[ $field->get_qualified_column() ]
471
+						);
472
+					}
473
+					$reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
474
+					if ($field_name == 'REG_final_price') {
475
+						// add a column named Currency after the final price
476
+						$reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
477
+					}
478
+				}
479
+				// get pretty status
480
+				$stati = EEM_Status::instance()->localized_status(
481
+					array(
482
+						$reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
483
+						$reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
484
+					),
485
+					false,
486
+					'sentence'
487
+				);
488
+				$reg_csv_array[ esc_html__(
489
+					"Registration Status",
490
+					'event_espresso'
491
+				) ] = $stati[ $reg_row['Registration.STS_ID'] ];
492
+				// get pretty trnasaction status
493
+				$reg_csv_array[ esc_html__(
494
+					"Transaction Status",
495
+					'event_espresso'
496
+				) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
497
+				$reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
498
+					? $this->_prepare_value_from_db_for_display(
499
+						EEM_Transaction::instance(),
500
+						'TXN_total',
501
+						$reg_row['TransactionTable.TXN_total'],
502
+						'localized_float'
503
+					) : '0.00';
504
+				$reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
505
+					? $this->_prepare_value_from_db_for_display(
506
+						EEM_Transaction::instance(),
507
+						'TXN_paid',
508
+						$reg_row['TransactionTable.TXN_paid'],
509
+						'localized_float'
510
+					) : '0.00';
511
+				$payment_methods = array();
512
+				$gateway_txn_ids_etc = array();
513
+				$payment_times = array();
514
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
515
+					$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
516
+						array(
517
+							array(
518
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
519
+								'STS_ID' => EEM_Payment::status_id_approved,
520
+							),
521
+							'force_join' => array('Payment_Method'),
522
+						),
523
+						ARRAY_A,
524
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
525
+					);
526
+					list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
527
+				}
528
+				$reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
529
+				$reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
530
+				$reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
531
+					',',
532
+					$gateway_txn_ids_etc
533
+				);
534
+
535
+				// get whether or not the user has checked in
536
+				$reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
537
+					$reg_row['Registration.REG_ID'],
538
+					'Checkin'
539
+				);
540
+				// get ticket of registration and its price
541
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
542
+				if ($reg_row['Ticket.TKT_ID']) {
543
+					$ticket_name = $this->_prepare_value_from_db_for_display(
544
+						$ticket_model,
545
+						'TKT_name',
546
+						$reg_row['Ticket.TKT_name']
547
+					);
548
+					$datetimes_strings = array();
549
+					foreach (
550
+						EEM_Datetime::instance()->get_all_wpdb_results(
551
+							array(
552
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
553
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
554
+							'default_where_conditions' => 'none',
555
+							)
556
+						) as $datetime
557
+					) {
558
+						$datetimes_strings[] = $this->_prepare_value_from_db_for_display(
559
+							EEM_Datetime::instance(),
560
+							'DTT_EVT_start',
561
+							$datetime['Datetime.DTT_EVT_start']
562
+						);
563
+					}
564
+				} else {
565
+					$ticket_name = esc_html__('Unknown', 'event_espresso');
566
+					$datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
567
+				}
568
+				$reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
569
+				$reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
570
+				// get datetime(s) of registration
571
+
572
+				// add attendee columns
573
+				foreach ($att_fields_to_include as $att_field_name) {
574
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
575
+					if ($reg_row['Attendee_CPT.ID']) {
576
+						if ($att_field_name == 'STA_ID') {
577
+							$value = EEM_State::instance()->get_var(
578
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
579
+								'STA_name'
580
+							);
581
+						} elseif ($att_field_name == 'CNT_ISO') {
582
+							$value = EEM_Country::instance()->get_var(
583
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
584
+								'CNT_name'
585
+							);
586
+						} else {
587
+							$value = $this->_prepare_value_from_db_for_display(
588
+								EEM_Attendee::instance(),
589
+								$att_field_name,
590
+								$reg_row[ $field_obj->get_qualified_column() ]
591
+							);
592
+						}
593
+					} else {
594
+						$value = '';
595
+					}
596
+
597
+					$reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
598
+				}
599
+
600
+				// make sure each registration has the same questions in the same order
601
+				foreach ($questions_for_these_regs_rows as $question_row) {
602
+					if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
603
+						$reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
604
+					}
605
+				}
606
+				// now fill out the questions THEY answered
607
+				foreach (
608
+					EEM_Answer::instance()->get_all_wpdb_results(
609
+						array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
610
+					) as $answer_row
611
+				) {
612
+					/* @var $answer EE_Answer */
613
+					if ($answer_row['Question.QST_ID']) {
614
+						$question_label = $this->_prepare_value_from_db_for_display(
615
+							EEM_Question::instance(),
616
+							'QST_admin_label',
617
+							$answer_row['Question.QST_admin_label']
618
+						);
619
+					} else {
620
+						$question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
621
+					}
622
+					if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
623
+						$reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
624
+							$answer_row['Answer.ANS_value']
625
+						);
626
+					} else {
627
+						$reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
628
+							EEM_Answer::instance(),
629
+							'ANS_value',
630
+							$answer_row['Answer.ANS_value']
631
+						);
632
+					}
633
+				}
634
+				$registrations_csv_ready_array[] = apply_filters(
635
+					'FHEE__EE_Export__report_registrations__reg_csv_array',
636
+					$reg_csv_array,
637
+					$reg_row
638
+				);
639
+			}
640
+		}
641
+
642
+		// if we couldn't export anything, we want to at least show the column headers
643
+		if (empty($registrations_csv_ready_array)) {
644
+			$reg_csv_array = array();
645
+			$model_and_fields_to_include = array(
646
+				'Registration' => $reg_fields_to_include,
647
+				'Attendee'     => $att_fields_to_include,
648
+			);
649
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
650
+				$model = EE_Registry::instance()->load_model($model_name);
651
+				foreach ($field_list as $field_name) {
652
+					$field = $model->field_settings_for($field_name);
653
+					$reg_csv_array[ $this->_get_column_name_for_field(
654
+						$field
655
+					) ] = null;// $registration->get($field->get_name());
656
+				}
657
+			}
658
+			$registrations_csv_ready_array [] = $reg_csv_array;
659
+		}
660
+		if ($event_id) {
661
+			$event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
662
+			if (! $event_slug) {
663
+				$event_slug = esc_html__('unknown', 'event_espresso');
664
+			}
665
+		} else {
666
+			$event_slug = esc_html__('all', 'event_espresso');
667
+		}
668
+		$filename = sprintf("registrations-for-%s", $event_slug);
669
+
670
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
671
+		$this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
672
+		$this->EE_CSV->end_sending_csv($handle);
673
+	}
674
+
675
+	/**
676
+	 * Gets the 'normal' column named for fields
677
+	 *
678
+	 * @param EE_Model_Field_Base $field
679
+	 * @return string
680
+	 * @throws EE_Error
681
+	 */
682
+	protected function _get_column_name_for_field(EE_Model_Field_Base $field)
683
+	{
684
+		return $field->get_nicename() . "[" . $field->get_name() . "]";
685
+	}
686
+
687
+
688
+	/**
689
+	 * @Export data for ALL events
690
+	 * @access public
691
+	 * @return void
692
+	 */
693
+	public function export_categories()
694
+	{
695
+		// are any Event IDs set?
696
+		$query_params = array();
697
+		if (isset($this->_req_data['EVT_CAT_ID'])) {
698
+			// do we have an array of IDs ?
699
+			if (is_array($this->_req_data['EVT_CAT_ID'])) {
700
+				// generate an "IN (CSV)" where clause
701
+				$EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
702
+				$filename = 'event-categories';
703
+				$query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
704
+			} else {
705
+				// generate regular where = clause
706
+				$EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
707
+				$filename = 'event-category#' . $EVT_CAT_ID;
708
+				$query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
709
+			}
710
+		} else {
711
+			// no IDs means we will d/l the entire table
712
+			$filename = 'all-categories';
713
+		}
714
+
715
+		$tables_to_export = array(
716
+			'Term_Taxonomy' => $query_params,
717
+		);
718
+
719
+		$table_data = $this->_get_export_data_for_models($tables_to_export);
720
+		$filename = $this->generate_filename($filename);
721
+
722
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
723
+			EE_Error::add_error(
724
+				esc_html__(
725
+					'An error occurred and the Category details could not be exported from the database.',
726
+					'event_espresso'
727
+				),
728
+				__FILE__,
729
+				__FUNCTION__,
730
+				__LINE__
731
+			);
732
+		}
733
+	}
734
+
735
+
736
+	/**
737
+	 * @process export name to create a suitable filename
738
+	 * @access  private
739
+	 * @param string - export_name
740
+	 * @return string on success, FALSE on fail
741
+	 */
742
+	private function generate_filename($export_name = '')
743
+	{
744
+		if ($export_name != '') {
745
+			$filename = get_bloginfo('name') . '-' . $export_name;
746
+			$filename = sanitize_key($filename) . '-' . $this->today;
747
+			return $filename;
748
+		} else {
749
+			EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
750
+		}
751
+		return false;
752
+	}
753
+
754
+
755
+	/**
756
+	 * @recursive function for exporting table data and merging the results with the next results
757
+	 * @access    private
758
+	 * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
759
+	 *                                query params @return bool on success, FALSE on fail
760
+	 * @throws EE_Error
761
+	 * @throws ReflectionException
762
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
763
+	 */
764
+	private function _get_export_data_for_models($models_to_export = array())
765
+	{
766
+		$table_data = false;
767
+		if (is_array($models_to_export)) {
768
+			foreach ($models_to_export as $model_name => $query_params) {
769
+				// check for a numerically-indexed array. in that case, $model_name is the value!!
770
+				if (is_int($model_name)) {
771
+					$model_name = $query_params;
772
+					$query_params = array();
773
+				}
774
+				$model = EE_Registry::instance()->load_model($model_name);
775
+				$model_objects = $model->get_all($query_params);
776
+
777
+				$table_data[ $model_name ] = array();
778
+				foreach ($model_objects as $model_object) {
779
+					$model_data_array = array();
780
+					$fields = $model->field_settings();
781
+					foreach ($fields as $field) {
782
+						$column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
783
+						if ($field instanceof EE_Datetime_Field) {
784
+							// $field->set_date_format('Y-m-d');
785
+							// $field->set_time_format('H:i:s');
786
+							$model_data_array[ $column_name ] = $model_object->get_datetime(
787
+								$field->get_name(),
788
+								'Y-m-d',
789
+								'H:i:s'
790
+							);
791
+						} else {
792
+							$model_data_array[ $column_name ] = $model_object->get($field->get_name());
793
+						}
794
+					}
795
+					$table_data[ $model_name ][] = $model_data_array;
796
+				}
797
+			}
798
+		}
799
+		return $table_data;
800
+	}
801 801
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
     {
47 47
         $this->_req_data = $request_data;
48 48
         $this->today = date("Y-m-d", time());
49
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
49
+        require_once(EE_CLASSES.'EE_CSV.class.php');
50 50
         $this->EE_CSV = EE_CSV::instance();
51 51
     }
52 52
 
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
                 $value_to_equal = $EVT_ID;
174 174
                 $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
175 175
 
176
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
176
+                $filename = 'event-'.($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
177 177
             }
178 178
             $event_query_params[0]['EVT_ID'] = $value_to_equal;
179 179
             $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 
223 223
         $filename = $this->generate_filename($filename);
224 224
 
225
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
225
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
226 226
             EE_Error::add_error(
227 227
                 esc_html__(
228 228
                     "'An error occurred and the Event details could not be exported from the database.'",
@@ -249,16 +249,16 @@  discard block
 block discarded – undo
249 249
             foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
250 250
                 if ($field_name == 'STA_ID') {
251 251
                     $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
252
-                    $csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
253
-                    ) ];
252
+                    $csv_row[esc_html__('State', 'event_espresso')] = $attendee_row[$state_name_field->get_qualified_column(
253
+                    )];
254 254
                 } elseif ($field_name == 'CNT_ISO') {
255 255
                     $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
256
-                    $csv_row[ esc_html__(
256
+                    $csv_row[esc_html__(
257 257
                         'Country',
258 258
                         'event_espresso'
259
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
259
+                    )] = $attendee_row[$country_name_field->get_qualified_column()];
260 260
                 } else {
261
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
261
+                    $csv_row[$field_obj->get_nicename()] = $attendee_row[$field_obj->get_qualified_column()];
262 262
                 }
263 263
             }
264 264
             $csv_data[] = $csv_row;
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
         $model_data = $this->_get_export_data_for_models($models_to_export);
299 299
         $filename = $this->generate_filename('all-attendees');
300 300
 
301
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
301
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
302 302
             EE_Error::add_error(
303 303
                 esc_html__(
304 304
                     'An error occurred and the Attendee data could not be exported from the database.',
@@ -419,9 +419,9 @@  discard block
 block discarded – undo
419 419
         foreach ($registration_rows as $reg_row) {
420 420
             if (is_array($reg_row)) {
421 421
                 $reg_csv_array = array();
422
-                if (! $event_id) {
422
+                if ( ! $event_id) {
423 423
                     // get the event's name and Id
424
-                    $reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
424
+                    $reg_csv_array[esc_html__('Event', 'event_espresso')] = sprintf(
425 425
                         esc_html__('%1$s (%2$s)', 'event_espresso'),
426 426
                         $this->_prepare_value_from_db_for_display(
427 427
                             EEM_Event::instance(),
@@ -467,13 +467,13 @@  discard block
 block discarded – undo
467 467
                         $value = $this->_prepare_value_from_db_for_display(
468 468
                             $reg_model,
469 469
                             $field_name,
470
-                            $reg_row[ $field->get_qualified_column() ]
470
+                            $reg_row[$field->get_qualified_column()]
471 471
                         );
472 472
                     }
473
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
473
+                    $reg_csv_array[$this->_get_column_name_for_field($field)] = $value;
474 474
                     if ($field_name == 'REG_final_price') {
475 475
                         // add a column named Currency after the final price
476
-                        $reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
476
+                        $reg_csv_array[esc_html__("Currency", "event_espresso")] = EE_Config::instance()->currency->code;
477 477
                     }
478 478
                 }
479 479
                 // get pretty status
@@ -485,23 +485,23 @@  discard block
 block discarded – undo
485 485
                     false,
486 486
                     'sentence'
487 487
                 );
488
-                $reg_csv_array[ esc_html__(
488
+                $reg_csv_array[esc_html__(
489 489
                     "Registration Status",
490 490
                     'event_espresso'
491
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
491
+                )] = $stati[$reg_row['Registration.STS_ID']];
492 492
                 // get pretty trnasaction status
493
-                $reg_csv_array[ esc_html__(
493
+                $reg_csv_array[esc_html__(
494 494
                     "Transaction Status",
495 495
                     'event_espresso'
496
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
497
-                $reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
496
+                )] = $stati[$reg_row['TransactionTable.STS_ID']];
497
+                $reg_csv_array[esc_html__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
498 498
                     ? $this->_prepare_value_from_db_for_display(
499 499
                         EEM_Transaction::instance(),
500 500
                         'TXN_total',
501 501
                         $reg_row['TransactionTable.TXN_total'],
502 502
                         'localized_float'
503 503
                     ) : '0.00';
504
-                $reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
504
+                $reg_csv_array[esc_html__('Amount Paid', 'event_espresso')] = $is_primary_reg
505 505
                     ? $this->_prepare_value_from_db_for_display(
506 506
                         EEM_Transaction::instance(),
507 507
                         'TXN_paid',
@@ -525,15 +525,15 @@  discard block
 block discarded – undo
525 525
                     );
526 526
                     list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
527 527
                 }
528
-                $reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
529
-                $reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
530
-                $reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
528
+                $reg_csv_array[esc_html__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
529
+                $reg_csv_array[esc_html__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
530
+                $reg_csv_array[esc_html__('Gateway Transaction ID(s)', 'event_espresso')] = implode(
531 531
                     ',',
532 532
                     $gateway_txn_ids_etc
533 533
                 );
534 534
 
535 535
                 // get whether or not the user has checked in
536
-                $reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
536
+                $reg_csv_array[esc_html__("Check-Ins", "event_espresso")] = $reg_model->count_related(
537 537
                     $reg_row['Registration.REG_ID'],
538 538
                     'Checkin'
539 539
                 );
@@ -565,8 +565,8 @@  discard block
 block discarded – undo
565 565
                     $ticket_name = esc_html__('Unknown', 'event_espresso');
566 566
                     $datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
567 567
                 }
568
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
569
-                $reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
568
+                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
569
+                $reg_csv_array[esc_html__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
570 570
                 // get datetime(s) of registration
571 571
 
572 572
                 // add attendee columns
@@ -587,20 +587,20 @@  discard block
 block discarded – undo
587 587
                             $value = $this->_prepare_value_from_db_for_display(
588 588
                                 EEM_Attendee::instance(),
589 589
                                 $att_field_name,
590
-                                $reg_row[ $field_obj->get_qualified_column() ]
590
+                                $reg_row[$field_obj->get_qualified_column()]
591 591
                             );
592 592
                         }
593 593
                     } else {
594 594
                         $value = '';
595 595
                     }
596 596
 
597
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
597
+                    $reg_csv_array[$this->_get_column_name_for_field($field_obj)] = $value;
598 598
                 }
599 599
 
600 600
                 // make sure each registration has the same questions in the same order
601 601
                 foreach ($questions_for_these_regs_rows as $question_row) {
602
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
603
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
602
+                    if ( ! isset($reg_csv_array[$question_row['Question.QST_admin_label']])) {
603
+                        $reg_csv_array[$question_row['Question.QST_admin_label']] = null;
604 604
                     }
605 605
                 }
606 606
                 // now fill out the questions THEY answered
@@ -620,11 +620,11 @@  discard block
 block discarded – undo
620 620
                         $question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
621 621
                     }
622 622
                     if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
623
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
623
+                        $reg_csv_array[$question_label] = EEM_State::instance()->get_state_name_by_ID(
624 624
                             $answer_row['Answer.ANS_value']
625 625
                         );
626 626
                     } else {
627
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
627
+                        $reg_csv_array[$question_label] = $this->_prepare_value_from_db_for_display(
628 628
                             EEM_Answer::instance(),
629 629
                             'ANS_value',
630 630
                             $answer_row['Answer.ANS_value']
@@ -650,16 +650,16 @@  discard block
 block discarded – undo
650 650
                 $model = EE_Registry::instance()->load_model($model_name);
651 651
                 foreach ($field_list as $field_name) {
652 652
                     $field = $model->field_settings_for($field_name);
653
-                    $reg_csv_array[ $this->_get_column_name_for_field(
653
+                    $reg_csv_array[$this->_get_column_name_for_field(
654 654
                         $field
655
-                    ) ] = null;// $registration->get($field->get_name());
655
+                    )] = null; // $registration->get($field->get_name());
656 656
                 }
657 657
             }
658 658
             $registrations_csv_ready_array [] = $reg_csv_array;
659 659
         }
660 660
         if ($event_id) {
661 661
             $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
662
-            if (! $event_slug) {
662
+            if ( ! $event_slug) {
663 663
                 $event_slug = esc_html__('unknown', 'event_espresso');
664 664
             }
665 665
         } else {
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
      */
682 682
     protected function _get_column_name_for_field(EE_Model_Field_Base $field)
683 683
     {
684
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
684
+        return $field->get_nicename()."[".$field->get_name()."]";
685 685
     }
686 686
 
687 687
 
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
             } else {
705 705
                 // generate regular where = clause
706 706
                 $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
707
-                $filename = 'event-category#' . $EVT_CAT_ID;
707
+                $filename = 'event-category#'.$EVT_CAT_ID;
708 708
                 $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
709 709
             }
710 710
         } else {
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
         $table_data = $this->_get_export_data_for_models($tables_to_export);
720 720
         $filename = $this->generate_filename($filename);
721 721
 
722
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
722
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
723 723
             EE_Error::add_error(
724 724
                 esc_html__(
725 725
                     'An error occurred and the Category details could not be exported from the database.',
@@ -742,8 +742,8 @@  discard block
 block discarded – undo
742 742
     private function generate_filename($export_name = '')
743 743
     {
744 744
         if ($export_name != '') {
745
-            $filename = get_bloginfo('name') . '-' . $export_name;
746
-            $filename = sanitize_key($filename) . '-' . $this->today;
745
+            $filename = get_bloginfo('name').'-'.$export_name;
746
+            $filename = sanitize_key($filename).'-'.$this->today;
747 747
             return $filename;
748 748
         } else {
749 749
             EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
@@ -774,25 +774,25 @@  discard block
 block discarded – undo
774 774
                 $model = EE_Registry::instance()->load_model($model_name);
775 775
                 $model_objects = $model->get_all($query_params);
776 776
 
777
-                $table_data[ $model_name ] = array();
777
+                $table_data[$model_name] = array();
778 778
                 foreach ($model_objects as $model_object) {
779 779
                     $model_data_array = array();
780 780
                     $fields = $model->field_settings();
781 781
                     foreach ($fields as $field) {
782
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
782
+                        $column_name = $field->get_nicename()."[".$field->get_name()."]";
783 783
                         if ($field instanceof EE_Datetime_Field) {
784 784
                             // $field->set_date_format('Y-m-d');
785 785
                             // $field->set_time_format('H:i:s');
786
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
786
+                            $model_data_array[$column_name] = $model_object->get_datetime(
787 787
                                 $field->get_name(),
788 788
                                 'Y-m-d',
789 789
                                 'H:i:s'
790 790
                             );
791 791
                         } else {
792
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
792
+                            $model_data_array[$column_name] = $model_object->get($field->get_name());
793 793
                         }
794 794
                     }
795
-                    $table_data[ $model_name ][] = $model_data_array;
795
+                    $table_data[$model_name][] = $model_data_array;
796 796
                 }
797 797
             }
798 798
         }
Please login to merge, or discard this patch.