Completed
Branch dev (64e3a7)
by
unknown
13:10 queued 05:44
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.
services/admin/registrations/list_table/csv_reports/PaymentsInfoCSV.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -12,28 +12,28 @@
 block discarded – undo
12 12
 class PaymentsInfoCSV
13 13
 {
14 14
 
15
-    /**
16
-     * Extracts payment information using the payment records
17
-     *
18
-     * @param array $payments_info
19
-     * @return array
20
-     */
21
-    public static function extractPaymentInfo(array $payments_info)
22
-    {
23
-        $payment_methods = [];
24
-        $gateway_txn_ids_etc = [];
25
-        $payment_times = [];
26
-        foreach ($payments_info as $payment_method_and_gateway_txn_id) {
27
-            $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
28
-                ? $payment_method_and_gateway_txn_id['name']
29
-                : esc_html__('Unknown', 'event_espresso');
30
-            $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
31
-                ? $payment_method_and_gateway_txn_id['gateway_txn_id']
32
-                : '';
33
-            $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
34
-                ? $payment_method_and_gateway_txn_id['payment_time']
35
-                : '';
36
-        }
37
-        return [$payment_methods, $gateway_txn_ids_etc, $payment_times];
38
-    }
15
+	/**
16
+	 * Extracts payment information using the payment records
17
+	 *
18
+	 * @param array $payments_info
19
+	 * @return array
20
+	 */
21
+	public static function extractPaymentInfo(array $payments_info)
22
+	{
23
+		$payment_methods = [];
24
+		$gateway_txn_ids_etc = [];
25
+		$payment_times = [];
26
+		foreach ($payments_info as $payment_method_and_gateway_txn_id) {
27
+			$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
28
+				? $payment_method_and_gateway_txn_id['name']
29
+				: esc_html__('Unknown', 'event_espresso');
30
+			$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
31
+				? $payment_method_and_gateway_txn_id['gateway_txn_id']
32
+				: '';
33
+			$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
34
+				? $payment_method_and_gateway_txn_id['payment_time']
35
+				: '';
36
+		}
37
+		return [$payment_methods, $gateway_txn_ids_etc, $payment_times];
38
+	}
39 39
 }
Please login to merge, or discard this patch.
domain/services/admin/registrations/list_table/csv_reports/AnswersCSV.php 2 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -18,61 +18,61 @@
 block discarded – undo
18 18
 class AnswersCSV
19 19
 {
20 20
 
21
-    /**
22
-     * Add question / answer columns to the CSV row
23
-     *
24
-     * @param array $reg_row
25
-     * @param array $data
26
-     * @param array $question_labels
27
-     * @return mixed
28
-     * @throws EE_Error
29
-     */
30
-    public static function addAnswerColumns(array $reg_row, $data, $question_labels)
31
-    {
32
-        // make sure each registration has the same questions in the same order
33
-        foreach ($question_labels as $question_label) {
34
-            if (! isset($data[ $question_label ])) {
35
-                $data[ $question_label ] = null;
36
-            }
37
-        }
38
-        $answers = EEM_Answer::instance()->get_all_wpdb_results([
39
-            ['REG_ID' => $reg_row['Registration.REG_ID']],
40
-            'force_join' => ['Question'],
41
-        ]);
42
-        // now fill out the questions THEY answered
43
-        foreach ($answers as $answer_row) {
44
-            if ($answer_row['Question.QST_system']) {
45
-                // it's an answer to a system question. That was already displayed as part of the attendee
46
-                // fields, so don't write it out again thanks.
47
-                continue;
48
-            }
49
-            if ($answer_row['Question.QST_ID']) {
50
-                $question_label = EEH_Export::prepare_value_from_db_for_display(
51
-                    EEM_Question::instance(),
52
-                    'QST_admin_label',
53
-                    $answer_row['Question.QST_admin_label']
54
-                );
55
-            } else {
56
-                $question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
57
-            }
58
-            if (
59
-                isset($answer_row['Question.QST_type'])
60
-                && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state
61
-            ) {
62
-                $data[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
63
-                    $answer_row['Answer.ANS_value']
64
-                );
65
-            } else {
66
-                // this isn't for html, so don't show html entities
67
-                $data[ $question_label ] = html_entity_decode(
68
-                    EEH_Export::prepare_value_from_db_for_display(
69
-                        EEM_Answer::instance(),
70
-                        'ANS_value',
71
-                        $answer_row['Answer.ANS_value']
72
-                    )
73
-                );
74
-            }
75
-        }
76
-        return $data;
77
-    }
21
+	/**
22
+	 * Add question / answer columns to the CSV row
23
+	 *
24
+	 * @param array $reg_row
25
+	 * @param array $data
26
+	 * @param array $question_labels
27
+	 * @return mixed
28
+	 * @throws EE_Error
29
+	 */
30
+	public static function addAnswerColumns(array $reg_row, $data, $question_labels)
31
+	{
32
+		// make sure each registration has the same questions in the same order
33
+		foreach ($question_labels as $question_label) {
34
+			if (! isset($data[ $question_label ])) {
35
+				$data[ $question_label ] = null;
36
+			}
37
+		}
38
+		$answers = EEM_Answer::instance()->get_all_wpdb_results([
39
+			['REG_ID' => $reg_row['Registration.REG_ID']],
40
+			'force_join' => ['Question'],
41
+		]);
42
+		// now fill out the questions THEY answered
43
+		foreach ($answers as $answer_row) {
44
+			if ($answer_row['Question.QST_system']) {
45
+				// it's an answer to a system question. That was already displayed as part of the attendee
46
+				// fields, so don't write it out again thanks.
47
+				continue;
48
+			}
49
+			if ($answer_row['Question.QST_ID']) {
50
+				$question_label = EEH_Export::prepare_value_from_db_for_display(
51
+					EEM_Question::instance(),
52
+					'QST_admin_label',
53
+					$answer_row['Question.QST_admin_label']
54
+				);
55
+			} else {
56
+				$question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
57
+			}
58
+			if (
59
+				isset($answer_row['Question.QST_type'])
60
+				&& $answer_row['Question.QST_type'] == EEM_Question::QST_type_state
61
+			) {
62
+				$data[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
63
+					$answer_row['Answer.ANS_value']
64
+				);
65
+			} else {
66
+				// this isn't for html, so don't show html entities
67
+				$data[ $question_label ] = html_entity_decode(
68
+					EEH_Export::prepare_value_from_db_for_display(
69
+						EEM_Answer::instance(),
70
+						'ANS_value',
71
+						$answer_row['Answer.ANS_value']
72
+					)
73
+				);
74
+			}
75
+		}
76
+		return $data;
77
+	}
78 78
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -46,8 +46,8 @@  discard block
 block discarded – undo
46 46
     {
47 47
         // make sure each registration has the same questions in the same order
48 48
         foreach ($question_labels as $question_label) {
49
-            if (! isset($data[ $question_label ])) {
50
-                $data[ $question_label ] = null;
49
+            if ( ! isset($data[$question_label])) {
50
+                $data[$question_label] = null;
51 51
             }
52 52
         }
53 53
         $answers = EEM_Answer::instance()->get_all_wpdb_results([
@@ -74,12 +74,12 @@  discard block
 block discarded – undo
74 74
                 isset($answer_row['Question.QST_type'])
75 75
                 && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state
76 76
             ) {
77
-                $data[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
77
+                $data[$question_label] = EEM_State::instance()->get_state_name_by_ID(
78 78
                     $answer_row['Answer.ANS_value']
79 79
                 );
80 80
             } else {
81 81
                 // this isn't for html, so don't show html entities
82
-                $data[ $question_label ] = html_entity_decode(
82
+                $data[$question_label] = html_entity_decode(
83 83
                     EEH_Export::prepare_value_from_db_for_display(
84 84
                         EEM_Answer::instance(),
85 85
                         'ANS_value',
Please login to merge, or discard this patch.
core/db_classes/EE_Export.class.php 2 patches
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -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.
Indentation   +780 added lines, -780 removed lines patch added patch discarded remove patch
@@ -17,784 +17,784 @@
 block discarded – undo
17 17
  */
18 18
 class EE_Export
19 19
 {
20
-    const option_prefix = 'ee_report_job_';
21
-
22
-
23
-    // instance of the EE_Export object
24
-    private static $_instance = null;
25
-
26
-    // instance of the EE_CSV object
27
-    /**
28
-     *
29
-     * @var EE_CSV
30
-     */
31
-    public $EE_CSV = null;
32
-
33
-
34
-    private $_req_data = array();
35
-
36
-
37
-    /**
38
-     *        private constructor to prevent direct creation
39
-     *
40
-     * @Constructor
41
-     * @access private
42
-     * @param array $request_data
43
-     */
44
-    private function __construct($request_data = array())
45
-    {
46
-        $this->_req_data = $request_data;
47
-        $this->today = date("Y-m-d", time());
48
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
49
-        $this->EE_CSV = EE_CSV::instance();
50
-    }
51
-
52
-
53
-    /**
54
-     *        @ singleton method used to instantiate class object
55
-     *        @ access public
56
-     *
57
-     * @param array $request_data
58
-     * @return \EE_Export
59
-     */
60
-    public static function instance($request_data = array())
61
-    {
62
-        // check if class object is instantiated
63
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
64
-            self::$_instance = new self($request_data);
65
-        }
66
-        return self::$_instance;
67
-    }
68
-
69
-
70
-    /**
71
-     * @Export Event Espresso data - routes export requests
72
-     * @access public
73
-     * @return void | bool
74
-     */
75
-    public function export()
76
-    {
77
-        // in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
78
-        if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
79
-            // check if action2 has export action
80
-            if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
81
-                // whoop! there it is!
82
-                $this->_req_data['action'] = $this->_req_data['action2'];
83
-            }
84
-        }
85
-
86
-        $this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
87
-
88
-        switch ($this->_req_data['export']) {
89
-            case 'report':
90
-                switch ($this->_req_data['action']) {
91
-                    case "event":
92
-                    case "export_events":
93
-                    case 'all_event_data':
94
-                        $this->export_all_event_data();
95
-                        break;
96
-
97
-                    case 'registrations_report_for_event':
98
-                        $this->report_registrations_for_event($this->_req_data['EVT_ID']);
99
-                        break;
100
-
101
-                    case 'attendees':
102
-                        $this->export_attendees();
103
-                        break;
104
-
105
-                    case 'categories':
106
-                        $this->export_categories();
107
-                        break;
108
-
109
-                    default:
110
-                        EE_Error::add_error(
111
-                            esc_html__('An error occurred! The requested export report could not be found.', 'event_espresso'),
112
-                            __FILE__,
113
-                            __FUNCTION__,
114
-                            __LINE__
115
-                        );
116
-                        return false;
117
-                        break;
118
-                }
119
-                break; // end of switch export : report
120
-            default:
121
-                break;
122
-        } // end of switch export
123
-
124
-        exit;
125
-    }
126
-
127
-    /**
128
-     * Downloads a CSV file with all the columns, but no data. This should be used for importing
129
-     *
130
-     * @return void kills execution
131
-     * @throws EE_Error
132
-     * @throws ReflectionException
133
-     */
134
-    public function export_sample()
135
-    {
136
-        $event = EEM_Event::instance()->get_one();
137
-        $this->_req_data['EVT_ID'] = $event->ID();
138
-        $this->export_all_event_data();
139
-    }
140
-
141
-
142
-    /**
143
-     * @Export data for ALL events
144
-     * @access public
145
-     * @return void
146
-     * @throws EE_Error
147
-     * @throws ReflectionException
148
-     */
149
-    public function export_all_event_data()
150
-    {
151
-        // are any Event IDs set?
152
-        $event_query_params = array();
153
-        $related_models_query_params = array();
154
-        $related_through_reg_query_params = array();
155
-        $datetime_ticket_query_params = array();
156
-        $price_query_params = array();
157
-        $price_type_query_params = array();
158
-        $term_query_params = array();
159
-        $state_country_query_params = array();
160
-        $question_group_query_params = array();
161
-        $question_query_params = array();
162
-        if (isset($this->_req_data['EVT_ID'])) {
163
-            // do we have an array of IDs ?
164
-
165
-            if (is_array($this->_req_data['EVT_ID'])) {
166
-                $EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
167
-                $value_to_equal = array('IN', $EVT_IDs);
168
-                $filename = 'events';
169
-            } else {
170
-                // generate regular where = clause
171
-                $EVT_ID = absint($this->_req_data['EVT_ID']);
172
-                $value_to_equal = $EVT_ID;
173
-                $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
174
-
175
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
176
-            }
177
-            $event_query_params[0]['EVT_ID'] = $value_to_equal;
178
-            $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
179
-            $related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
180
-            $datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
181
-            $price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
182
-            $price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
183
-            $term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
184
-            $state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
185
-            $question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
186
-            $question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
187
-        } else {
188
-            $filename = 'all-events';
189
-        }
190
-
191
-
192
-        // array in the format:  table name =>  query where clause
193
-        $models_to_export = array(
194
-            'Event'                   => $event_query_params,
195
-            'Datetime'                => $related_models_query_params,
196
-            'Ticket_Template'         => $price_query_params,
197
-            'Ticket'                  => $datetime_ticket_query_params,
198
-            'Datetime_Ticket'         => $datetime_ticket_query_params,
199
-            'Price_Type'              => $price_type_query_params,
200
-            'Price'                   => $price_query_params,
201
-            'Ticket_Price'            => $price_query_params,
202
-            'Term'                    => $term_query_params,
203
-            'Term_Taxonomy'           => $related_models_query_params,
204
-            'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
205
-            'Country'                 => $state_country_query_params,
206
-            'State'                   => $state_country_query_params,
207
-            'Venue'                   => $related_models_query_params,
208
-            'Event_Venue'             => $related_models_query_params,
209
-            'Question_Group'          => $question_group_query_params,
210
-            'Event_Question_Group'    => $question_group_query_params,
211
-            'Question'                => $question_query_params,
212
-            'Question_Group_Question' => $question_query_params,
213
-            // 'Transaction'=>$related_through_reg_query_params,
214
-            // 'Registration'=>$related_models_query_params,
215
-            // 'Attendee'=>$related_through_reg_query_params,
216
-            // 'Line_Item'=>
217
-
218
-        );
219
-
220
-        $model_data = $this->_get_export_data_for_models($models_to_export);
221
-
222
-        $filename = $this->generate_filename($filename);
223
-
224
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
225
-            EE_Error::add_error(
226
-                esc_html__(
227
-                    "'An error occurred and the Event details could not be exported from the database.'",
228
-                    "event_espresso"
229
-                ),
230
-                __FILE__,
231
-                __FUNCTION__,
232
-                __LINE__
233
-            );
234
-        }
235
-    }
236
-
237
-    public function report_attendees()
238
-    {
239
-        $attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
240
-            array(
241
-                'force_join' => array('State', 'Country'),
242
-                'caps'       => EEM_Base::caps_read_admin,
243
-            )
244
-        );
245
-        $csv_data = array();
246
-        foreach ($attendee_rows as $attendee_row) {
247
-            $csv_row = array();
248
-            foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
249
-                if ($field_name == 'STA_ID') {
250
-                    $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
251
-                    $csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
252
-                    ) ];
253
-                } elseif ($field_name == 'CNT_ISO') {
254
-                    $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
255
-                    $csv_row[ esc_html__(
256
-                        'Country',
257
-                        'event_espresso'
258
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
259
-                } else {
260
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
261
-                }
262
-            }
263
-            $csv_data[] = $csv_row;
264
-        }
265
-
266
-        $filename = $this->generate_filename('contact-list-report');
267
-
268
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
269
-        $this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
270
-        $this->EE_CSV->end_sending_csv($handle);
271
-    }
272
-
273
-
274
-    /**
275
-     * @Export data for ALL attendees
276
-     * @access public
277
-     * @return void
278
-     * @throws EE_Error
279
-     */
280
-    public function export_attendees()
281
-    {
282
-
283
-        $states_that_have_an_attendee = EEM_State::instance()->get_all(
284
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
285
-        );
286
-        $countries_that_have_an_attendee = EEM_Country::instance()->get_all(
287
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
288
-        );
289
-        // $states_to_export_query_params
290
-        $models_to_export = array(
291
-            'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
292
-            'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
293
-            'Attendee' => array(),
294
-        );
295
-
296
-
297
-        $model_data = $this->_get_export_data_for_models($models_to_export);
298
-        $filename = $this->generate_filename('all-attendees');
299
-
300
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
301
-            EE_Error::add_error(
302
-                esc_html__(
303
-                    'An error occurred and the Attendee data could not be exported from the database.',
304
-                    'event_espresso'
305
-                ),
306
-                __FILE__,
307
-                __FUNCTION__,
308
-                __LINE__
309
-            );
310
-        }
311
-    }
312
-
313
-    /**
314
-     * Shortcut for preparing a database result for display
315
-     *
316
-     * @param EEM_Base $model
317
-     * @param string $field_name
318
-     * @param string $raw_db_value
319
-     * @param bool|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
320
-     *                                      NOT display pretty
321
-     * @return string
322
-     * @throws EE_Error
323
-     */
324
-    protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
325
-    {
326
-        $field_obj = $model->field_settings_for($field_name);
327
-        $value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
328
-        if ($field_obj instanceof EE_Datetime_Field) {
329
-            $field_obj->set_date_format(
330
-                EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
331
-                $pretty_schema
332
-            );
333
-            $field_obj->set_time_format(
334
-                EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
335
-                $pretty_schema
336
-            );
337
-        }
338
-        if ($pretty_schema === true) {
339
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
340
-        } elseif (is_string($pretty_schema)) {
341
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
342
-        } else {
343
-            return $field_obj->prepare_for_get($value_on_model_obj);
344
-        }
345
-    }
346
-
347
-    /**
348
-     * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
349
-     * name, and the questions associated with the registrations
350
-     *
351
-     * @param int $event_id
352
-     * @throws EE_Error
353
-     * @throws ReflectionException
354
-     */
355
-    public function report_registrations_for_event($event_id = null)
356
-    {
357
-        $reg_fields_to_include = array(
358
-            'TXN_ID',
359
-            'ATT_ID',
360
-            'REG_ID',
361
-            'REG_date',
362
-            'REG_code',
363
-            'REG_count',
364
-            'REG_final_price',
365
-
366
-        );
367
-        $att_fields_to_include = array(
368
-            'ATT_fname',
369
-            'ATT_lname',
370
-            'ATT_email',
371
-            'ATT_address',
372
-            'ATT_address2',
373
-            'ATT_city',
374
-            'STA_ID',
375
-            'CNT_ISO',
376
-            'ATT_zip',
377
-            'ATT_phone',
378
-        );
379
-
380
-        $registrations_csv_ready_array = array();
381
-        $reg_model = EE_Registry::instance()->load_model('Registration');
382
-        $query_params = apply_filters(
383
-            'FHEE__EE_Export__report_registration_for_event',
384
-            array(
385
-                array(
386
-                    'OR'                 => array(
387
-                        // don't include registrations from failed or abandoned transactions...
388
-                        'Transaction.STS_ID' => array(
389
-                            'NOT IN',
390
-                            array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
391
-                        ),
392
-                        // unless the registration is approved, in which case include it regardless of transaction status
393
-                        'STS_ID'             => EEM_Registration::status_id_approved,
394
-                    ),
395
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
396
-                ),
397
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
398
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
399
-                'caps'       => EEM_Base::caps_read_admin,
400
-            ),
401
-            $event_id
402
-        );
403
-        if ($event_id) {
404
-            $query_params[0]['EVT_ID'] = $event_id;
405
-        } else {
406
-            $query_params['force_join'][] = 'Event';
407
-        }
408
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
409
-        // get all questions which relate to someone in this group
410
-        $registration_ids = array();
411
-        foreach ($registration_rows as $reg_row) {
412
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
413
-        }
414
-        // EEM_Question::instance()->show_next_x_db_queries();
415
-        $questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
416
-            array(array('Answer.REG_ID' => array('IN', $registration_ids)))
417
-        );
418
-        foreach ($registration_rows as $reg_row) {
419
-            if (is_array($reg_row)) {
420
-                $reg_csv_array = array();
421
-                if (! $event_id) {
422
-                    // get the event's name and Id
423
-                    $reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
424
-                        esc_html__('%1$s (%2$s)', 'event_espresso'),
425
-                        $this->_prepare_value_from_db_for_display(
426
-                            EEM_Event::instance(),
427
-                            'EVT_name',
428
-                            $reg_row['Event_CPT.post_title']
429
-                        ),
430
-                        $reg_row['Event_CPT.ID']
431
-                    );
432
-                }
433
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
434
-                /*@var $reg_row EE_Registration */
435
-                foreach ($reg_fields_to_include as $field_name) {
436
-                    $field = $reg_model->field_settings_for($field_name);
437
-                    if ($field_name == 'REG_final_price') {
438
-                        $value = $this->_prepare_value_from_db_for_display(
439
-                            $reg_model,
440
-                            $field_name,
441
-                            $reg_row['Registration.REG_final_price'],
442
-                            'localized_float'
443
-                        );
444
-                    } elseif ($field_name == 'REG_count') {
445
-                        $value = sprintf(
446
-                            esc_html__('%s of %s', 'event_espresso'),
447
-                            $this->_prepare_value_from_db_for_display(
448
-                                $reg_model,
449
-                                'REG_count',
450
-                                $reg_row['Registration.REG_count']
451
-                            ),
452
-                            $this->_prepare_value_from_db_for_display(
453
-                                $reg_model,
454
-                                'REG_group_size',
455
-                                $reg_row['Registration.REG_group_size']
456
-                            )
457
-                        );
458
-                    } elseif ($field_name == 'REG_date') {
459
-                        $value = $this->_prepare_value_from_db_for_display(
460
-                            $reg_model,
461
-                            $field_name,
462
-                            $reg_row['Registration.REG_date'],
463
-                            'no_html'
464
-                        );
465
-                    } else {
466
-                        $value = $this->_prepare_value_from_db_for_display(
467
-                            $reg_model,
468
-                            $field_name,
469
-                            $reg_row[ $field->get_qualified_column() ]
470
-                        );
471
-                    }
472
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
473
-                    if ($field_name == 'REG_final_price') {
474
-                        // add a column named Currency after the final price
475
-                        $reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
476
-                    }
477
-                }
478
-                // get pretty status
479
-                $stati = EEM_Status::instance()->localized_status(
480
-                    array(
481
-                        $reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
482
-                        $reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
483
-                    ),
484
-                    false,
485
-                    'sentence'
486
-                );
487
-                $reg_csv_array[ esc_html__(
488
-                    "Registration Status",
489
-                    'event_espresso'
490
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
491
-                // get pretty trnasaction status
492
-                $reg_csv_array[ esc_html__(
493
-                    "Transaction Status",
494
-                    'event_espresso'
495
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
496
-                $reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
497
-                    ? $this->_prepare_value_from_db_for_display(
498
-                        EEM_Transaction::instance(),
499
-                        'TXN_total',
500
-                        $reg_row['TransactionTable.TXN_total'],
501
-                        'localized_float'
502
-                    ) : '0.00';
503
-                $reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
504
-                    ? $this->_prepare_value_from_db_for_display(
505
-                        EEM_Transaction::instance(),
506
-                        'TXN_paid',
507
-                        $reg_row['TransactionTable.TXN_paid'],
508
-                        'localized_float'
509
-                    ) : '0.00';
510
-                $payment_methods = array();
511
-                $gateway_txn_ids_etc = array();
512
-                $payment_times = array();
513
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
514
-                    $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
515
-                        array(
516
-                            array(
517
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
518
-                                'STS_ID' => EEM_Payment::status_id_approved,
519
-                            ),
520
-                            'force_join' => array('Payment_Method'),
521
-                        ),
522
-                        ARRAY_A,
523
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
524
-                    );
525
-                    list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
526
-                }
527
-                $reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
528
-                $reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
529
-                $reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
530
-                    ',',
531
-                    $gateway_txn_ids_etc
532
-                );
533
-
534
-                // get whether or not the user has checked in
535
-                $reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
536
-                    $reg_row['Registration.REG_ID'],
537
-                    'Checkin'
538
-                );
539
-                // get ticket of registration and its price
540
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
541
-                if ($reg_row['Ticket.TKT_ID']) {
542
-                    $ticket_name = $this->_prepare_value_from_db_for_display(
543
-                        $ticket_model,
544
-                        'TKT_name',
545
-                        $reg_row['Ticket.TKT_name']
546
-                    );
547
-                    $datetimes_strings = array();
548
-                    foreach (
549
-                        EEM_Datetime::instance()->get_all_wpdb_results(
550
-                            array(
551
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
552
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
553
-                            'default_where_conditions' => 'none',
554
-                            )
555
-                        ) as $datetime
556
-                    ) {
557
-                        $datetimes_strings[] = $this->_prepare_value_from_db_for_display(
558
-                            EEM_Datetime::instance(),
559
-                            'DTT_EVT_start',
560
-                            $datetime['Datetime.DTT_EVT_start']
561
-                        );
562
-                    }
563
-                } else {
564
-                    $ticket_name = esc_html__('Unknown', 'event_espresso');
565
-                    $datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
566
-                }
567
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
568
-                $reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
569
-                // get datetime(s) of registration
570
-
571
-                // add attendee columns
572
-                foreach ($att_fields_to_include as $att_field_name) {
573
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
574
-                    if ($reg_row['Attendee_CPT.ID']) {
575
-                        if ($att_field_name == 'STA_ID') {
576
-                            $value = EEM_State::instance()->get_var(
577
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
578
-                                'STA_name'
579
-                            );
580
-                        } elseif ($att_field_name == 'CNT_ISO') {
581
-                            $value = EEM_Country::instance()->get_var(
582
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
583
-                                'CNT_name'
584
-                            );
585
-                        } else {
586
-                            $value = $this->_prepare_value_from_db_for_display(
587
-                                EEM_Attendee::instance(),
588
-                                $att_field_name,
589
-                                $reg_row[ $field_obj->get_qualified_column() ]
590
-                            );
591
-                        }
592
-                    } else {
593
-                        $value = '';
594
-                    }
595
-
596
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
597
-                }
598
-
599
-                // make sure each registration has the same questions in the same order
600
-                foreach ($questions_for_these_regs_rows as $question_row) {
601
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
602
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
603
-                    }
604
-                }
605
-                // now fill out the questions THEY answered
606
-                foreach (
607
-                    EEM_Answer::instance()->get_all_wpdb_results(
608
-                        array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
609
-                    ) as $answer_row
610
-                ) {
611
-                    /* @var $answer EE_Answer */
612
-                    if ($answer_row['Question.QST_ID']) {
613
-                        $question_label = $this->_prepare_value_from_db_for_display(
614
-                            EEM_Question::instance(),
615
-                            'QST_admin_label',
616
-                            $answer_row['Question.QST_admin_label']
617
-                        );
618
-                    } else {
619
-                        $question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
620
-                    }
621
-                    if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
622
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
623
-                            $answer_row['Answer.ANS_value']
624
-                        );
625
-                    } else {
626
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
627
-                            EEM_Answer::instance(),
628
-                            'ANS_value',
629
-                            $answer_row['Answer.ANS_value']
630
-                        );
631
-                    }
632
-                }
633
-                $registrations_csv_ready_array[] = apply_filters(
634
-                    'FHEE__EE_Export__report_registrations__reg_csv_array',
635
-                    $reg_csv_array,
636
-                    $reg_row
637
-                );
638
-            }
639
-        }
640
-
641
-        // if we couldn't export anything, we want to at least show the column headers
642
-        if (empty($registrations_csv_ready_array)) {
643
-            $reg_csv_array = array();
644
-            $model_and_fields_to_include = array(
645
-                'Registration' => $reg_fields_to_include,
646
-                'Attendee'     => $att_fields_to_include,
647
-            );
648
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
649
-                $model = EE_Registry::instance()->load_model($model_name);
650
-                foreach ($field_list as $field_name) {
651
-                    $field = $model->field_settings_for($field_name);
652
-                    $reg_csv_array[ $this->_get_column_name_for_field(
653
-                        $field
654
-                    ) ] = null;// $registration->get($field->get_name());
655
-                }
656
-            }
657
-            $registrations_csv_ready_array [] = $reg_csv_array;
658
-        }
659
-        if ($event_id) {
660
-            $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
661
-            if (! $event_slug) {
662
-                $event_slug = esc_html__('unknown', 'event_espresso');
663
-            }
664
-        } else {
665
-            $event_slug = esc_html__('all', 'event_espresso');
666
-        }
667
-        $filename = sprintf("registrations-for-%s", $event_slug);
668
-
669
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
670
-        $this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
671
-        $this->EE_CSV->end_sending_csv($handle);
672
-    }
673
-
674
-    /**
675
-     * Gets the 'normal' column named for fields
676
-     *
677
-     * @param EE_Model_Field_Base $field
678
-     * @return string
679
-     * @throws EE_Error
680
-     */
681
-    protected function _get_column_name_for_field(EE_Model_Field_Base $field)
682
-    {
683
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
684
-    }
685
-
686
-
687
-    /**
688
-     * @Export data for ALL events
689
-     * @access public
690
-     * @return void
691
-     */
692
-    public function export_categories()
693
-    {
694
-        // are any Event IDs set?
695
-        $query_params = array();
696
-        if (isset($this->_req_data['EVT_CAT_ID'])) {
697
-            // do we have an array of IDs ?
698
-            if (is_array($this->_req_data['EVT_CAT_ID'])) {
699
-                // generate an "IN (CSV)" where clause
700
-                $EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
701
-                $filename = 'event-categories';
702
-                $query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
703
-            } else {
704
-                // generate regular where = clause
705
-                $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
706
-                $filename = 'event-category#' . $EVT_CAT_ID;
707
-                $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
708
-            }
709
-        } else {
710
-            // no IDs means we will d/l the entire table
711
-            $filename = 'all-categories';
712
-        }
713
-
714
-        $tables_to_export = array(
715
-            'Term_Taxonomy' => $query_params,
716
-        );
717
-
718
-        $table_data = $this->_get_export_data_for_models($tables_to_export);
719
-        $filename = $this->generate_filename($filename);
720
-
721
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
722
-            EE_Error::add_error(
723
-                esc_html__(
724
-                    'An error occurred and the Category details could not be exported from the database.',
725
-                    'event_espresso'
726
-                ),
727
-                __FILE__,
728
-                __FUNCTION__,
729
-                __LINE__
730
-            );
731
-        }
732
-    }
733
-
734
-
735
-    /**
736
-     * @process export name to create a suitable filename
737
-     * @access  private
738
-     * @param string - export_name
739
-     * @return string on success, FALSE on fail
740
-     */
741
-    private function generate_filename($export_name = '')
742
-    {
743
-        if ($export_name != '') {
744
-            $filename = get_bloginfo('name') . '-' . $export_name;
745
-            $filename = sanitize_key($filename) . '-' . $this->today;
746
-            return $filename;
747
-        } else {
748
-            EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
749
-        }
750
-        return false;
751
-    }
752
-
753
-
754
-    /**
755
-     * @recursive function for exporting table data and merging the results with the next results
756
-     * @access    private
757
-     * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
758
-     *                                query params @return bool on success, FALSE on fail
759
-     * @throws EE_Error
760
-     * @throws ReflectionException
761
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
762
-     */
763
-    private function _get_export_data_for_models($models_to_export = array())
764
-    {
765
-        $table_data = false;
766
-        if (is_array($models_to_export)) {
767
-            foreach ($models_to_export as $model_name => $query_params) {
768
-                // check for a numerically-indexed array. in that case, $model_name is the value!!
769
-                if (is_int($model_name)) {
770
-                    $model_name = $query_params;
771
-                    $query_params = array();
772
-                }
773
-                $model = EE_Registry::instance()->load_model($model_name);
774
-                $model_objects = $model->get_all($query_params);
775
-
776
-                $table_data[ $model_name ] = array();
777
-                foreach ($model_objects as $model_object) {
778
-                    $model_data_array = array();
779
-                    $fields = $model->field_settings();
780
-                    foreach ($fields as $field) {
781
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
782
-                        if ($field instanceof EE_Datetime_Field) {
783
-                            // $field->set_date_format('Y-m-d');
784
-                            // $field->set_time_format('H:i:s');
785
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
786
-                                $field->get_name(),
787
-                                'Y-m-d',
788
-                                'H:i:s'
789
-                            );
790
-                        } else {
791
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
792
-                        }
793
-                    }
794
-                    $table_data[ $model_name ][] = $model_data_array;
795
-                }
796
-            }
797
-        }
798
-        return $table_data;
799
-    }
20
+	const option_prefix = 'ee_report_job_';
21
+
22
+
23
+	// instance of the EE_Export object
24
+	private static $_instance = null;
25
+
26
+	// instance of the EE_CSV object
27
+	/**
28
+	 *
29
+	 * @var EE_CSV
30
+	 */
31
+	public $EE_CSV = null;
32
+
33
+
34
+	private $_req_data = array();
35
+
36
+
37
+	/**
38
+	 *        private constructor to prevent direct creation
39
+	 *
40
+	 * @Constructor
41
+	 * @access private
42
+	 * @param array $request_data
43
+	 */
44
+	private function __construct($request_data = array())
45
+	{
46
+		$this->_req_data = $request_data;
47
+		$this->today = date("Y-m-d", time());
48
+		require_once(EE_CLASSES . 'EE_CSV.class.php');
49
+		$this->EE_CSV = EE_CSV::instance();
50
+	}
51
+
52
+
53
+	/**
54
+	 *        @ singleton method used to instantiate class object
55
+	 *        @ access public
56
+	 *
57
+	 * @param array $request_data
58
+	 * @return \EE_Export
59
+	 */
60
+	public static function instance($request_data = array())
61
+	{
62
+		// check if class object is instantiated
63
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
64
+			self::$_instance = new self($request_data);
65
+		}
66
+		return self::$_instance;
67
+	}
68
+
69
+
70
+	/**
71
+	 * @Export Event Espresso data - routes export requests
72
+	 * @access public
73
+	 * @return void | bool
74
+	 */
75
+	public function export()
76
+	{
77
+		// in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
78
+		if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
79
+			// check if action2 has export action
80
+			if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
81
+				// whoop! there it is!
82
+				$this->_req_data['action'] = $this->_req_data['action2'];
83
+			}
84
+		}
85
+
86
+		$this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
87
+
88
+		switch ($this->_req_data['export']) {
89
+			case 'report':
90
+				switch ($this->_req_data['action']) {
91
+					case "event":
92
+					case "export_events":
93
+					case 'all_event_data':
94
+						$this->export_all_event_data();
95
+						break;
96
+
97
+					case 'registrations_report_for_event':
98
+						$this->report_registrations_for_event($this->_req_data['EVT_ID']);
99
+						break;
100
+
101
+					case 'attendees':
102
+						$this->export_attendees();
103
+						break;
104
+
105
+					case 'categories':
106
+						$this->export_categories();
107
+						break;
108
+
109
+					default:
110
+						EE_Error::add_error(
111
+							esc_html__('An error occurred! The requested export report could not be found.', 'event_espresso'),
112
+							__FILE__,
113
+							__FUNCTION__,
114
+							__LINE__
115
+						);
116
+						return false;
117
+						break;
118
+				}
119
+				break; // end of switch export : report
120
+			default:
121
+				break;
122
+		} // end of switch export
123
+
124
+		exit;
125
+	}
126
+
127
+	/**
128
+	 * Downloads a CSV file with all the columns, but no data. This should be used for importing
129
+	 *
130
+	 * @return void kills execution
131
+	 * @throws EE_Error
132
+	 * @throws ReflectionException
133
+	 */
134
+	public function export_sample()
135
+	{
136
+		$event = EEM_Event::instance()->get_one();
137
+		$this->_req_data['EVT_ID'] = $event->ID();
138
+		$this->export_all_event_data();
139
+	}
140
+
141
+
142
+	/**
143
+	 * @Export data for ALL events
144
+	 * @access public
145
+	 * @return void
146
+	 * @throws EE_Error
147
+	 * @throws ReflectionException
148
+	 */
149
+	public function export_all_event_data()
150
+	{
151
+		// are any Event IDs set?
152
+		$event_query_params = array();
153
+		$related_models_query_params = array();
154
+		$related_through_reg_query_params = array();
155
+		$datetime_ticket_query_params = array();
156
+		$price_query_params = array();
157
+		$price_type_query_params = array();
158
+		$term_query_params = array();
159
+		$state_country_query_params = array();
160
+		$question_group_query_params = array();
161
+		$question_query_params = array();
162
+		if (isset($this->_req_data['EVT_ID'])) {
163
+			// do we have an array of IDs ?
164
+
165
+			if (is_array($this->_req_data['EVT_ID'])) {
166
+				$EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
167
+				$value_to_equal = array('IN', $EVT_IDs);
168
+				$filename = 'events';
169
+			} else {
170
+				// generate regular where = clause
171
+				$EVT_ID = absint($this->_req_data['EVT_ID']);
172
+				$value_to_equal = $EVT_ID;
173
+				$event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
174
+
175
+				$filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
176
+			}
177
+			$event_query_params[0]['EVT_ID'] = $value_to_equal;
178
+			$related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
179
+			$related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
180
+			$datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
181
+			$price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
182
+			$price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
183
+			$term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
184
+			$state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
185
+			$question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
186
+			$question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
187
+		} else {
188
+			$filename = 'all-events';
189
+		}
190
+
191
+
192
+		// array in the format:  table name =>  query where clause
193
+		$models_to_export = array(
194
+			'Event'                   => $event_query_params,
195
+			'Datetime'                => $related_models_query_params,
196
+			'Ticket_Template'         => $price_query_params,
197
+			'Ticket'                  => $datetime_ticket_query_params,
198
+			'Datetime_Ticket'         => $datetime_ticket_query_params,
199
+			'Price_Type'              => $price_type_query_params,
200
+			'Price'                   => $price_query_params,
201
+			'Ticket_Price'            => $price_query_params,
202
+			'Term'                    => $term_query_params,
203
+			'Term_Taxonomy'           => $related_models_query_params,
204
+			'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
205
+			'Country'                 => $state_country_query_params,
206
+			'State'                   => $state_country_query_params,
207
+			'Venue'                   => $related_models_query_params,
208
+			'Event_Venue'             => $related_models_query_params,
209
+			'Question_Group'          => $question_group_query_params,
210
+			'Event_Question_Group'    => $question_group_query_params,
211
+			'Question'                => $question_query_params,
212
+			'Question_Group_Question' => $question_query_params,
213
+			// 'Transaction'=>$related_through_reg_query_params,
214
+			// 'Registration'=>$related_models_query_params,
215
+			// 'Attendee'=>$related_through_reg_query_params,
216
+			// 'Line_Item'=>
217
+
218
+		);
219
+
220
+		$model_data = $this->_get_export_data_for_models($models_to_export);
221
+
222
+		$filename = $this->generate_filename($filename);
223
+
224
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
225
+			EE_Error::add_error(
226
+				esc_html__(
227
+					"'An error occurred and the Event details could not be exported from the database.'",
228
+					"event_espresso"
229
+				),
230
+				__FILE__,
231
+				__FUNCTION__,
232
+				__LINE__
233
+			);
234
+		}
235
+	}
236
+
237
+	public function report_attendees()
238
+	{
239
+		$attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
240
+			array(
241
+				'force_join' => array('State', 'Country'),
242
+				'caps'       => EEM_Base::caps_read_admin,
243
+			)
244
+		);
245
+		$csv_data = array();
246
+		foreach ($attendee_rows as $attendee_row) {
247
+			$csv_row = array();
248
+			foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
249
+				if ($field_name == 'STA_ID') {
250
+					$state_name_field = EEM_State::instance()->field_settings_for('STA_name');
251
+					$csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
252
+					) ];
253
+				} elseif ($field_name == 'CNT_ISO') {
254
+					$country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
255
+					$csv_row[ esc_html__(
256
+						'Country',
257
+						'event_espresso'
258
+					) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
259
+				} else {
260
+					$csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
261
+				}
262
+			}
263
+			$csv_data[] = $csv_row;
264
+		}
265
+
266
+		$filename = $this->generate_filename('contact-list-report');
267
+
268
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
269
+		$this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
270
+		$this->EE_CSV->end_sending_csv($handle);
271
+	}
272
+
273
+
274
+	/**
275
+	 * @Export data for ALL attendees
276
+	 * @access public
277
+	 * @return void
278
+	 * @throws EE_Error
279
+	 */
280
+	public function export_attendees()
281
+	{
282
+
283
+		$states_that_have_an_attendee = EEM_State::instance()->get_all(
284
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
285
+		);
286
+		$countries_that_have_an_attendee = EEM_Country::instance()->get_all(
287
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
288
+		);
289
+		// $states_to_export_query_params
290
+		$models_to_export = array(
291
+			'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
292
+			'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
293
+			'Attendee' => array(),
294
+		);
295
+
296
+
297
+		$model_data = $this->_get_export_data_for_models($models_to_export);
298
+		$filename = $this->generate_filename('all-attendees');
299
+
300
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
301
+			EE_Error::add_error(
302
+				esc_html__(
303
+					'An error occurred and the Attendee data could not be exported from the database.',
304
+					'event_espresso'
305
+				),
306
+				__FILE__,
307
+				__FUNCTION__,
308
+				__LINE__
309
+			);
310
+		}
311
+	}
312
+
313
+	/**
314
+	 * Shortcut for preparing a database result for display
315
+	 *
316
+	 * @param EEM_Base $model
317
+	 * @param string $field_name
318
+	 * @param string $raw_db_value
319
+	 * @param bool|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
320
+	 *                                      NOT display pretty
321
+	 * @return string
322
+	 * @throws EE_Error
323
+	 */
324
+	protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
325
+	{
326
+		$field_obj = $model->field_settings_for($field_name);
327
+		$value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
328
+		if ($field_obj instanceof EE_Datetime_Field) {
329
+			$field_obj->set_date_format(
330
+				EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
331
+				$pretty_schema
332
+			);
333
+			$field_obj->set_time_format(
334
+				EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
335
+				$pretty_schema
336
+			);
337
+		}
338
+		if ($pretty_schema === true) {
339
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
340
+		} elseif (is_string($pretty_schema)) {
341
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
342
+		} else {
343
+			return $field_obj->prepare_for_get($value_on_model_obj);
344
+		}
345
+	}
346
+
347
+	/**
348
+	 * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
349
+	 * name, and the questions associated with the registrations
350
+	 *
351
+	 * @param int $event_id
352
+	 * @throws EE_Error
353
+	 * @throws ReflectionException
354
+	 */
355
+	public function report_registrations_for_event($event_id = null)
356
+	{
357
+		$reg_fields_to_include = array(
358
+			'TXN_ID',
359
+			'ATT_ID',
360
+			'REG_ID',
361
+			'REG_date',
362
+			'REG_code',
363
+			'REG_count',
364
+			'REG_final_price',
365
+
366
+		);
367
+		$att_fields_to_include = array(
368
+			'ATT_fname',
369
+			'ATT_lname',
370
+			'ATT_email',
371
+			'ATT_address',
372
+			'ATT_address2',
373
+			'ATT_city',
374
+			'STA_ID',
375
+			'CNT_ISO',
376
+			'ATT_zip',
377
+			'ATT_phone',
378
+		);
379
+
380
+		$registrations_csv_ready_array = array();
381
+		$reg_model = EE_Registry::instance()->load_model('Registration');
382
+		$query_params = apply_filters(
383
+			'FHEE__EE_Export__report_registration_for_event',
384
+			array(
385
+				array(
386
+					'OR'                 => array(
387
+						// don't include registrations from failed or abandoned transactions...
388
+						'Transaction.STS_ID' => array(
389
+							'NOT IN',
390
+							array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
391
+						),
392
+						// unless the registration is approved, in which case include it regardless of transaction status
393
+						'STS_ID'             => EEM_Registration::status_id_approved,
394
+					),
395
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
396
+				),
397
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
398
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
399
+				'caps'       => EEM_Base::caps_read_admin,
400
+			),
401
+			$event_id
402
+		);
403
+		if ($event_id) {
404
+			$query_params[0]['EVT_ID'] = $event_id;
405
+		} else {
406
+			$query_params['force_join'][] = 'Event';
407
+		}
408
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
409
+		// get all questions which relate to someone in this group
410
+		$registration_ids = array();
411
+		foreach ($registration_rows as $reg_row) {
412
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
413
+		}
414
+		// EEM_Question::instance()->show_next_x_db_queries();
415
+		$questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
416
+			array(array('Answer.REG_ID' => array('IN', $registration_ids)))
417
+		);
418
+		foreach ($registration_rows as $reg_row) {
419
+			if (is_array($reg_row)) {
420
+				$reg_csv_array = array();
421
+				if (! $event_id) {
422
+					// get the event's name and Id
423
+					$reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
424
+						esc_html__('%1$s (%2$s)', 'event_espresso'),
425
+						$this->_prepare_value_from_db_for_display(
426
+							EEM_Event::instance(),
427
+							'EVT_name',
428
+							$reg_row['Event_CPT.post_title']
429
+						),
430
+						$reg_row['Event_CPT.ID']
431
+					);
432
+				}
433
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
434
+				/*@var $reg_row EE_Registration */
435
+				foreach ($reg_fields_to_include as $field_name) {
436
+					$field = $reg_model->field_settings_for($field_name);
437
+					if ($field_name == 'REG_final_price') {
438
+						$value = $this->_prepare_value_from_db_for_display(
439
+							$reg_model,
440
+							$field_name,
441
+							$reg_row['Registration.REG_final_price'],
442
+							'localized_float'
443
+						);
444
+					} elseif ($field_name == 'REG_count') {
445
+						$value = sprintf(
446
+							esc_html__('%s of %s', 'event_espresso'),
447
+							$this->_prepare_value_from_db_for_display(
448
+								$reg_model,
449
+								'REG_count',
450
+								$reg_row['Registration.REG_count']
451
+							),
452
+							$this->_prepare_value_from_db_for_display(
453
+								$reg_model,
454
+								'REG_group_size',
455
+								$reg_row['Registration.REG_group_size']
456
+							)
457
+						);
458
+					} elseif ($field_name == 'REG_date') {
459
+						$value = $this->_prepare_value_from_db_for_display(
460
+							$reg_model,
461
+							$field_name,
462
+							$reg_row['Registration.REG_date'],
463
+							'no_html'
464
+						);
465
+					} else {
466
+						$value = $this->_prepare_value_from_db_for_display(
467
+							$reg_model,
468
+							$field_name,
469
+							$reg_row[ $field->get_qualified_column() ]
470
+						);
471
+					}
472
+					$reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
473
+					if ($field_name == 'REG_final_price') {
474
+						// add a column named Currency after the final price
475
+						$reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
476
+					}
477
+				}
478
+				// get pretty status
479
+				$stati = EEM_Status::instance()->localized_status(
480
+					array(
481
+						$reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
482
+						$reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
483
+					),
484
+					false,
485
+					'sentence'
486
+				);
487
+				$reg_csv_array[ esc_html__(
488
+					"Registration Status",
489
+					'event_espresso'
490
+				) ] = $stati[ $reg_row['Registration.STS_ID'] ];
491
+				// get pretty trnasaction status
492
+				$reg_csv_array[ esc_html__(
493
+					"Transaction Status",
494
+					'event_espresso'
495
+				) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
496
+				$reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
497
+					? $this->_prepare_value_from_db_for_display(
498
+						EEM_Transaction::instance(),
499
+						'TXN_total',
500
+						$reg_row['TransactionTable.TXN_total'],
501
+						'localized_float'
502
+					) : '0.00';
503
+				$reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
504
+					? $this->_prepare_value_from_db_for_display(
505
+						EEM_Transaction::instance(),
506
+						'TXN_paid',
507
+						$reg_row['TransactionTable.TXN_paid'],
508
+						'localized_float'
509
+					) : '0.00';
510
+				$payment_methods = array();
511
+				$gateway_txn_ids_etc = array();
512
+				$payment_times = array();
513
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
514
+					$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
515
+						array(
516
+							array(
517
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
518
+								'STS_ID' => EEM_Payment::status_id_approved,
519
+							),
520
+							'force_join' => array('Payment_Method'),
521
+						),
522
+						ARRAY_A,
523
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
524
+					);
525
+					list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
526
+				}
527
+				$reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
528
+				$reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
529
+				$reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
530
+					',',
531
+					$gateway_txn_ids_etc
532
+				);
533
+
534
+				// get whether or not the user has checked in
535
+				$reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
536
+					$reg_row['Registration.REG_ID'],
537
+					'Checkin'
538
+				);
539
+				// get ticket of registration and its price
540
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
541
+				if ($reg_row['Ticket.TKT_ID']) {
542
+					$ticket_name = $this->_prepare_value_from_db_for_display(
543
+						$ticket_model,
544
+						'TKT_name',
545
+						$reg_row['Ticket.TKT_name']
546
+					);
547
+					$datetimes_strings = array();
548
+					foreach (
549
+						EEM_Datetime::instance()->get_all_wpdb_results(
550
+							array(
551
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
552
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
553
+							'default_where_conditions' => 'none',
554
+							)
555
+						) as $datetime
556
+					) {
557
+						$datetimes_strings[] = $this->_prepare_value_from_db_for_display(
558
+							EEM_Datetime::instance(),
559
+							'DTT_EVT_start',
560
+							$datetime['Datetime.DTT_EVT_start']
561
+						);
562
+					}
563
+				} else {
564
+					$ticket_name = esc_html__('Unknown', 'event_espresso');
565
+					$datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
566
+				}
567
+				$reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
568
+				$reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
569
+				// get datetime(s) of registration
570
+
571
+				// add attendee columns
572
+				foreach ($att_fields_to_include as $att_field_name) {
573
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
574
+					if ($reg_row['Attendee_CPT.ID']) {
575
+						if ($att_field_name == 'STA_ID') {
576
+							$value = EEM_State::instance()->get_var(
577
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
578
+								'STA_name'
579
+							);
580
+						} elseif ($att_field_name == 'CNT_ISO') {
581
+							$value = EEM_Country::instance()->get_var(
582
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
583
+								'CNT_name'
584
+							);
585
+						} else {
586
+							$value = $this->_prepare_value_from_db_for_display(
587
+								EEM_Attendee::instance(),
588
+								$att_field_name,
589
+								$reg_row[ $field_obj->get_qualified_column() ]
590
+							);
591
+						}
592
+					} else {
593
+						$value = '';
594
+					}
595
+
596
+					$reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
597
+				}
598
+
599
+				// make sure each registration has the same questions in the same order
600
+				foreach ($questions_for_these_regs_rows as $question_row) {
601
+					if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
602
+						$reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
603
+					}
604
+				}
605
+				// now fill out the questions THEY answered
606
+				foreach (
607
+					EEM_Answer::instance()->get_all_wpdb_results(
608
+						array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
609
+					) as $answer_row
610
+				) {
611
+					/* @var $answer EE_Answer */
612
+					if ($answer_row['Question.QST_ID']) {
613
+						$question_label = $this->_prepare_value_from_db_for_display(
614
+							EEM_Question::instance(),
615
+							'QST_admin_label',
616
+							$answer_row['Question.QST_admin_label']
617
+						);
618
+					} else {
619
+						$question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
620
+					}
621
+					if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
622
+						$reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
623
+							$answer_row['Answer.ANS_value']
624
+						);
625
+					} else {
626
+						$reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
627
+							EEM_Answer::instance(),
628
+							'ANS_value',
629
+							$answer_row['Answer.ANS_value']
630
+						);
631
+					}
632
+				}
633
+				$registrations_csv_ready_array[] = apply_filters(
634
+					'FHEE__EE_Export__report_registrations__reg_csv_array',
635
+					$reg_csv_array,
636
+					$reg_row
637
+				);
638
+			}
639
+		}
640
+
641
+		// if we couldn't export anything, we want to at least show the column headers
642
+		if (empty($registrations_csv_ready_array)) {
643
+			$reg_csv_array = array();
644
+			$model_and_fields_to_include = array(
645
+				'Registration' => $reg_fields_to_include,
646
+				'Attendee'     => $att_fields_to_include,
647
+			);
648
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
649
+				$model = EE_Registry::instance()->load_model($model_name);
650
+				foreach ($field_list as $field_name) {
651
+					$field = $model->field_settings_for($field_name);
652
+					$reg_csv_array[ $this->_get_column_name_for_field(
653
+						$field
654
+					) ] = null;// $registration->get($field->get_name());
655
+				}
656
+			}
657
+			$registrations_csv_ready_array [] = $reg_csv_array;
658
+		}
659
+		if ($event_id) {
660
+			$event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
661
+			if (! $event_slug) {
662
+				$event_slug = esc_html__('unknown', 'event_espresso');
663
+			}
664
+		} else {
665
+			$event_slug = esc_html__('all', 'event_espresso');
666
+		}
667
+		$filename = sprintf("registrations-for-%s", $event_slug);
668
+
669
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
670
+		$this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
671
+		$this->EE_CSV->end_sending_csv($handle);
672
+	}
673
+
674
+	/**
675
+	 * Gets the 'normal' column named for fields
676
+	 *
677
+	 * @param EE_Model_Field_Base $field
678
+	 * @return string
679
+	 * @throws EE_Error
680
+	 */
681
+	protected function _get_column_name_for_field(EE_Model_Field_Base $field)
682
+	{
683
+		return $field->get_nicename() . "[" . $field->get_name() . "]";
684
+	}
685
+
686
+
687
+	/**
688
+	 * @Export data for ALL events
689
+	 * @access public
690
+	 * @return void
691
+	 */
692
+	public function export_categories()
693
+	{
694
+		// are any Event IDs set?
695
+		$query_params = array();
696
+		if (isset($this->_req_data['EVT_CAT_ID'])) {
697
+			// do we have an array of IDs ?
698
+			if (is_array($this->_req_data['EVT_CAT_ID'])) {
699
+				// generate an "IN (CSV)" where clause
700
+				$EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
701
+				$filename = 'event-categories';
702
+				$query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
703
+			} else {
704
+				// generate regular where = clause
705
+				$EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
706
+				$filename = 'event-category#' . $EVT_CAT_ID;
707
+				$query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
708
+			}
709
+		} else {
710
+			// no IDs means we will d/l the entire table
711
+			$filename = 'all-categories';
712
+		}
713
+
714
+		$tables_to_export = array(
715
+			'Term_Taxonomy' => $query_params,
716
+		);
717
+
718
+		$table_data = $this->_get_export_data_for_models($tables_to_export);
719
+		$filename = $this->generate_filename($filename);
720
+
721
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
722
+			EE_Error::add_error(
723
+				esc_html__(
724
+					'An error occurred and the Category details could not be exported from the database.',
725
+					'event_espresso'
726
+				),
727
+				__FILE__,
728
+				__FUNCTION__,
729
+				__LINE__
730
+			);
731
+		}
732
+	}
733
+
734
+
735
+	/**
736
+	 * @process export name to create a suitable filename
737
+	 * @access  private
738
+	 * @param string - export_name
739
+	 * @return string on success, FALSE on fail
740
+	 */
741
+	private function generate_filename($export_name = '')
742
+	{
743
+		if ($export_name != '') {
744
+			$filename = get_bloginfo('name') . '-' . $export_name;
745
+			$filename = sanitize_key($filename) . '-' . $this->today;
746
+			return $filename;
747
+		} else {
748
+			EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
749
+		}
750
+		return false;
751
+	}
752
+
753
+
754
+	/**
755
+	 * @recursive function for exporting table data and merging the results with the next results
756
+	 * @access    private
757
+	 * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
758
+	 *                                query params @return bool on success, FALSE on fail
759
+	 * @throws EE_Error
760
+	 * @throws ReflectionException
761
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
762
+	 */
763
+	private function _get_export_data_for_models($models_to_export = array())
764
+	{
765
+		$table_data = false;
766
+		if (is_array($models_to_export)) {
767
+			foreach ($models_to_export as $model_name => $query_params) {
768
+				// check for a numerically-indexed array. in that case, $model_name is the value!!
769
+				if (is_int($model_name)) {
770
+					$model_name = $query_params;
771
+					$query_params = array();
772
+				}
773
+				$model = EE_Registry::instance()->load_model($model_name);
774
+				$model_objects = $model->get_all($query_params);
775
+
776
+				$table_data[ $model_name ] = array();
777
+				foreach ($model_objects as $model_object) {
778
+					$model_data_array = array();
779
+					$fields = $model->field_settings();
780
+					foreach ($fields as $field) {
781
+						$column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
782
+						if ($field instanceof EE_Datetime_Field) {
783
+							// $field->set_date_format('Y-m-d');
784
+							// $field->set_time_format('H:i:s');
785
+							$model_data_array[ $column_name ] = $model_object->get_datetime(
786
+								$field->get_name(),
787
+								'Y-m-d',
788
+								'H:i:s'
789
+							);
790
+						} else {
791
+							$model_data_array[ $column_name ] = $model_object->get($field->get_name());
792
+						}
793
+					}
794
+					$table_data[ $model_name ][] = $model_data_array;
795
+				}
796
+			}
797
+		}
798
+		return $table_data;
799
+	}
800 800
 }
Please login to merge, or discard this patch.
caffeinated/admin/extend/events/templates/import_page.template.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,9 +1,9 @@
 block discarded – undo
1 1
 <div class="import-area">
2 2
     <div class="important-notice">
3 3
         <?php esc_html_e(
4
-            'The import feature has been disabled because of bugs. It is expected to be put back in place soon.',
5
-            'event_espresso'
6
-        ); ?>
4
+			'The import feature has been disabled because of bugs. It is expected to be put back in place soon.',
5
+			'event_espresso'
6
+		); ?>
7 7
     </div>
8 8
     <?php // echo wp_kses($form, \EventEspresso\core\services\request\sanitizers\AllowedTags::getWithFormTags()); ?>
9 9
 </div>
Please login to merge, or discard this patch.
modules/ical/EED_Ical.module.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -89,24 +89,24 @@  discard block
 block discarded – undo
89 89
             switch ($iCal_type) {
90 90
                 // submit buttons appear as buttons and are very compatible with a theme's style
91 91
                 case 'submit':
92
-                    $html .= '<form id="download-iCal-frm-' . $datetime->ID();
93
-                    $html .= '" class="download-iCal-frm" action="' . $URL . '" method="post" >';
92
+                    $html .= '<form id="download-iCal-frm-'.$datetime->ID();
93
+                    $html .= '" class="download-iCal-frm" action="'.$URL.'" method="post" >';
94 94
                     $html .= '<input type="submit" class="ee-ical-sbmt" value="&#xf145;" title="';
95
-                    $html .= esc_html__('Add to iCal Calendar', 'event_espresso') . '"/>';
95
+                    $html .= esc_html__('Add to iCal Calendar', 'event_espresso').'"/>';
96 96
                     $html .= '</form>';
97 97
                     break;
98 98
                 // buttons are just links that have been styled to appear as buttons,
99 99
                 // but may not be blend with a theme as well as submit buttons
100 100
                 case 'button':
101
-                    $html .= '<a class="ee-ical-btn small ee-button ee-roundish" href="' . $URL;
102
-                    $html .= '" title="' . esc_html__('Add to iCal Calendar', 'event_espresso') . '">';
101
+                    $html .= '<a class="ee-ical-btn small ee-button ee-roundish" href="'.$URL;
102
+                    $html .= '" title="'.esc_html__('Add to iCal Calendar', 'event_espresso').'">';
103 103
                     $html .= ' <span class="dashicons dashicons-calendar"></span>';
104 104
                     $html .= '</a>';
105 105
                     break;
106 106
                 // links are just links that use the calendar dashicon
107 107
                 case 'icon':
108
-                    $html .= '<a class="ee-ical-lnk" href="' . $URL . '" title="';
109
-                    $html .= esc_html__('Add to iCal Calendar', 'event_espresso') . '">';
108
+                    $html .= '<a class="ee-ical-lnk" href="'.$URL.'" title="';
109
+                    $html .= esc_html__('Add to iCal Calendar', 'event_espresso').'">';
110 110
                     $html .= ' <span class="dashicons dashicons-calendar"></span>';
111 111
                     $html .= '</a>';
112 112
                     break;
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
                     }
148 148
 
149 149
                     // Generate filename
150
-                    $filename = $event->slug() . '-' . $datetime->start_date('Y-m-d') . '.ics';
150
+                    $filename = $event->slug().'-'.$datetime->start_date('Y-m-d').'.ics';
151 151
 
152 152
                     // Check the datetime status has not been cancelled and set the ics value accordingly
153 153
                     $status = $datetime->get_active_status();
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
                     // Create array of ics details, escape strings, convert timestamps to ics format, etc
157 157
                     $ics_data = [
158 158
                         'ORGANIZER_NAME' => EE_Registry::instance()->CFG->organization->name,
159
-                        'UID'            => md5($event->name() . $event->ID() . $datetime->ID()),
159
+                        'UID'            => md5($event->name().$event->ID().$datetime->ID()),
160 160
                         'ORGANIZER'      => EE_Registry::instance()->CFG->organization->email,
161 161
                         'DTSTAMP'        => date(EED_Ical::iCal_datetime_format),
162 162
                         'LOCATION'       => $location,
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
                     foreach ($ics_data as $key => $value) {
178 178
                         // Description is escaped differently from all all values
179 179
                         if ($key === 'DESCRIPTION') {
180
-                            $ics_data[ $key ] = EED_Ical::_escape_ICal_description(wp_strip_all_tags($value));
180
+                            $ics_data[$key] = EED_Ical::_escape_ICal_description(wp_strip_all_tags($value));
181 181
                         } else {
182
-                            $ics_data[ $key ] = EED_Ical::_escape_ICal_data($value);
182
+                            $ics_data[$key] = EED_Ical::_escape_ICal_data($value);
183 183
                         }
184 184
                     }
185 185
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 
192 192
                     // set headers
193 193
                     header('Content-type: text/calendar; charset=utf-8');
194
-                    header('Content-Disposition: attachment; filename="' . $filename . '"');
194
+                    header('Content-Disposition: attachment; filename="'.$filename.'"');
195 195
                     header('Cache-Control: private, max-age=0, must-revalidate');
196 196
                     header('Pragma: public');
197 197
                     header('Content-Type: application/octet-stream');
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 
210 210
                     // Output all remaining values from ics_data.
211 211
                     foreach ($ics_data as $key => $value) {
212
-                        echo wp_kses($key . ':' . $value, AllowedTags::getAllowedTags()) . "\r\n";
212
+                        echo wp_kses($key.':'.$value, AllowedTags::getAllowedTags())."\r\n";
213 213
                     }
214 214
 
215 215
                     echo "END:VEVENT\r\n";
Please login to merge, or discard this patch.
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -14,235 +14,235 @@
 block discarded – undo
14 14
  */
15 15
 class EED_Ical extends EED_Module
16 16
 {
17
-    const iCal_datetime_format = 'Ymd\THis\Z';
18
-
19
-
20
-    /**
21
-     * @return EED_Ical|EED_Module
22
-     * @throws EE_Error
23
-     * @throws ReflectionException
24
-     */
25
-    public static function instance()
26
-    {
27
-        return parent::get_instance(__CLASS__);
28
-    }
29
-
30
-
31
-    /**
32
-     *    set_hooks - for hooking into EE Core, other modules, etc
33
-     *
34
-     * @return    void
35
-     */
36
-    public static function set_hooks()
37
-    {
38
-        // create download buttons
39
-        add_filter(
40
-            'FHEE__espresso_list_of_event_dates__datetime_html',
41
-            ['EED_Ical', 'generate_add_to_iCal_button'],
42
-            10,
43
-            2
44
-        );
45
-        // process ics download request
46
-        EE_Config::register_route('download_ics_file', 'EED_Ical', 'download_ics_file');
47
-    }
48
-
49
-
50
-    /**
51
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
52
-     *
53
-     * @return    void
54
-     */
55
-    public static function set_hooks_admin()
56
-    {
57
-    }
58
-
59
-
60
-    /**
61
-     *    run - initial module setup
62
-     *
63
-     * @param WP $WP
64
-     * @return    void
65
-     */
66
-    public function run($WP)
67
-    {
68
-    }
69
-
70
-
71
-    /**
72
-     * @param $html
73
-     * @param $datetime
74
-     * @return string
75
-     * @throws EE_Error
76
-     * @throws ReflectionException
77
-     */
78
-    public static function generate_add_to_iCal_button($html, $datetime)
79
-    {
80
-        // first verify a proper datetime object has been received
81
-        if ($datetime instanceof EE_Datetime) {
82
-            // set whether a link or submit button is shown
83
-            $iCal_type = apply_filters('FHEE__EED_Ical__generate_add_to_iCal_button__iCal_type', 'submit');
84
-            // generate a link to the route we registered in set_hooks()
85
-            $URL = add_query_arg(['ee' => 'download_ics_file', 'ics_id' => $datetime->ID()], site_url());
86
-            $URL = esc_url_Raw($URL);
87
-            // what type ?
88
-            switch ($iCal_type) {
89
-                // submit buttons appear as buttons and are very compatible with a theme's style
90
-                case 'submit':
91
-                    $html .= '<form id="download-iCal-frm-' . $datetime->ID();
92
-                    $html .= '" class="download-iCal-frm" action="' . $URL . '" method="post" >';
93
-                    $html .= '<input type="submit" class="ee-ical-sbmt" value="&#xf145;" title="';
94
-                    $html .= esc_html__('Add to iCal Calendar', 'event_espresso') . '"/>';
95
-                    $html .= '</form>';
96
-                    break;
97
-                // buttons are just links that have been styled to appear as buttons,
98
-                // but may not be blend with a theme as well as submit buttons
99
-                case 'button':
100
-                    $html .= '<a class="ee-ical-btn small ee-button ee-roundish" href="' . $URL;
101
-                    $html .= '" title="' . esc_html__('Add to iCal Calendar', 'event_espresso') . '">';
102
-                    $html .= ' <span class="dashicons dashicons-calendar"></span>';
103
-                    $html .= '</a>';
104
-                    break;
105
-                // links are just links that use the calendar dashicon
106
-                case 'icon':
107
-                    $html .= '<a class="ee-ical-lnk" href="' . $URL . '" title="';
108
-                    $html .= esc_html__('Add to iCal Calendar', 'event_espresso') . '">';
109
-                    $html .= ' <span class="dashicons dashicons-calendar"></span>';
110
-                    $html .= '</a>';
111
-                    break;
112
-            }
113
-        }
114
-        return $html;
115
-    }
116
-
117
-
118
-    /**
119
-     * @return void
120
-     * @throws EE_Error
121
-     * @throws ReflectionException
122
-     */
123
-    public static function download_ics_file()
124
-    {
125
-        $request = self::getRequest();
126
-        if ($request->requestParamIsSet('ics_id')) {
127
-            $DTT_ID   = $request->getRequestParam('ics_id', 0, 'int');
128
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
129
-            if ($datetime instanceof EE_Datetime) {
130
-                // get related event, venues, and event categories
131
-                $event = $datetime->event();
132
-                if ($event instanceof EE_Event) {
133
-                    // get related category Term object and it's name
134
-                    $category = $event->first_event_category();
135
-                    if ($category instanceof EE_Term) {
136
-                        $category = $category->name();
137
-                    }
138
-                    $location = '';
139
-                    // get first related venue and convert to CSV string
140
-                    $venue = $event->venues(['limit' => 1]);
141
-                    if (is_array($venue) && ! empty($venue)) {
142
-                        $venue = array_shift($venue);
143
-                        if ($venue instanceof EE_Venue) {
144
-                            $location = espresso_venue_raw_address('inline', $venue->ID(), false);
145
-                        }
146
-                    }
147
-
148
-                    // Generate filename
149
-                    $filename = $event->slug() . '-' . $datetime->start_date('Y-m-d') . '.ics';
150
-
151
-                    // Check the datetime status has not been cancelled and set the ics value accordingly
152
-                    $status = $datetime->get_active_status();
153
-                    $status = $status === EE_Datetime::cancelled ? 'CANCELLED' : 'CONFIRMED';
154
-
155
-                    // Create array of ics details, escape strings, convert timestamps to ics format, etc
156
-                    $ics_data = [
157
-                        'ORGANIZER_NAME' => EE_Registry::instance()->CFG->organization->name,
158
-                        'UID'            => md5($event->name() . $event->ID() . $datetime->ID()),
159
-                        'ORGANIZER'      => EE_Registry::instance()->CFG->organization->email,
160
-                        'DTSTAMP'        => date(EED_Ical::iCal_datetime_format),
161
-                        'LOCATION'       => $location,
162
-                        'SUMMARY'        => $event->name(),
163
-                        'DESCRIPTION'    => wp_strip_all_tags($event->description()),
164
-                        'STATUS'         => $status,
165
-                        'CATEGORIES'     => $category,
166
-                        'URL;VALUE=URI'  => get_permalink($event->ID()),
167
-                        'DTSTART'        => date(EED_Ical::iCal_datetime_format, $datetime->start()),
168
-                        'DTEND'          => date(EED_Ical::iCal_datetime_format, $datetime->end()),
169
-                    ];
170
-
171
-                    // Filter the values used within the ics output.
172
-                    // NOTE - all values within ics_data will be escaped automatically.
173
-                    $ics_data = apply_filters('FHEE__EED_Ical__download_ics_file_ics_data', $ics_data, $datetime);
174
-
175
-                    // Escape all ics data
176
-                    foreach ($ics_data as $key => $value) {
177
-                        // Description is escaped differently from all all values
178
-                        if ($key === 'DESCRIPTION') {
179
-                            $ics_data[ $key ] = EED_Ical::_escape_ICal_description(wp_strip_all_tags($value));
180
-                        } else {
181
-                            $ics_data[ $key ] = EED_Ical::_escape_ICal_data($value);
182
-                        }
183
-                    }
184
-
185
-                    // Pull the organizer name from ics_data and remove it from the array.
186
-                    $organizer_name = isset($ics_data['ORGANIZER_NAME'])
187
-                        ? $ics_data['ORGANIZER_NAME']
188
-                        : '';
189
-                    unset($ics_data['ORGANIZER_NAME']);
190
-
191
-                    // set headers
192
-                    header('Content-type: text/calendar; charset=utf-8');
193
-                    header('Content-Disposition: attachment; filename="' . $filename . '"');
194
-                    header('Cache-Control: private, max-age=0, must-revalidate');
195
-                    header('Pragma: public');
196
-                    header('Content-Type: application/octet-stream');
197
-                    header('Content-Type: application/force-download');
198
-                    header('Cache-Control: no-cache, must-revalidate');
199
-                    header('Content-Transfer-Encoding: binary');
200
-                    header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // past date
201
-                    ini_set('zlib.output_compression', '0');
202
-                    // echo the output
203
-                    echo "BEGIN:VCALENDAR\r\n";
204
-                    echo "VERSION:2.0\r\n";
205
-                    echo "PRODID:-//{$organizer_name}//NONSGML PDA Calendar Version 1.0//EN\r\n";
206
-                    echo "CALSCALE:GREGORIAN\r\n";
207
-                    echo "BEGIN:VEVENT\r\n";
208
-
209
-                    // Output all remaining values from ics_data.
210
-                    foreach ($ics_data as $key => $value) {
211
-                        echo wp_kses($key . ':' . $value, AllowedTags::getAllowedTags()) . "\r\n";
212
-                    }
213
-
214
-                    echo "END:VEVENT\r\n";
215
-                    echo "END:VCALENDAR\r\n";
216
-                }
217
-            }
218
-        }
219
-        die();
220
-    }
221
-
222
-
223
-    /**
224
-     *    _escape_ICal_data
225
-     *
226
-     * @param string $string
227
-     * @return    string
228
-     */
229
-    private static function _escape_ICal_data($string = '')
230
-    {
231
-        return preg_replace('/([\,;])/', '\\\$1', $string);
232
-    }
233
-
234
-
235
-    /**
236
-     *    _escape_ICal_description
237
-     *
238
-     * @param string $description
239
-     * @return    string
240
-     */
241
-    private static function _escape_ICal_description($description = '')
242
-    {
243
-        // Escape special chars within the description
244
-        $description = EED_Ical::_escape_ICal_data($description);
245
-        // Remove line breaks and output in iCal format
246
-        return str_replace(["\r\n", "\n"], '\n', $description);
247
-    }
17
+	const iCal_datetime_format = 'Ymd\THis\Z';
18
+
19
+
20
+	/**
21
+	 * @return EED_Ical|EED_Module
22
+	 * @throws EE_Error
23
+	 * @throws ReflectionException
24
+	 */
25
+	public static function instance()
26
+	{
27
+		return parent::get_instance(__CLASS__);
28
+	}
29
+
30
+
31
+	/**
32
+	 *    set_hooks - for hooking into EE Core, other modules, etc
33
+	 *
34
+	 * @return    void
35
+	 */
36
+	public static function set_hooks()
37
+	{
38
+		// create download buttons
39
+		add_filter(
40
+			'FHEE__espresso_list_of_event_dates__datetime_html',
41
+			['EED_Ical', 'generate_add_to_iCal_button'],
42
+			10,
43
+			2
44
+		);
45
+		// process ics download request
46
+		EE_Config::register_route('download_ics_file', 'EED_Ical', 'download_ics_file');
47
+	}
48
+
49
+
50
+	/**
51
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
52
+	 *
53
+	 * @return    void
54
+	 */
55
+	public static function set_hooks_admin()
56
+	{
57
+	}
58
+
59
+
60
+	/**
61
+	 *    run - initial module setup
62
+	 *
63
+	 * @param WP $WP
64
+	 * @return    void
65
+	 */
66
+	public function run($WP)
67
+	{
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param $html
73
+	 * @param $datetime
74
+	 * @return string
75
+	 * @throws EE_Error
76
+	 * @throws ReflectionException
77
+	 */
78
+	public static function generate_add_to_iCal_button($html, $datetime)
79
+	{
80
+		// first verify a proper datetime object has been received
81
+		if ($datetime instanceof EE_Datetime) {
82
+			// set whether a link or submit button is shown
83
+			$iCal_type = apply_filters('FHEE__EED_Ical__generate_add_to_iCal_button__iCal_type', 'submit');
84
+			// generate a link to the route we registered in set_hooks()
85
+			$URL = add_query_arg(['ee' => 'download_ics_file', 'ics_id' => $datetime->ID()], site_url());
86
+			$URL = esc_url_Raw($URL);
87
+			// what type ?
88
+			switch ($iCal_type) {
89
+				// submit buttons appear as buttons and are very compatible with a theme's style
90
+				case 'submit':
91
+					$html .= '<form id="download-iCal-frm-' . $datetime->ID();
92
+					$html .= '" class="download-iCal-frm" action="' . $URL . '" method="post" >';
93
+					$html .= '<input type="submit" class="ee-ical-sbmt" value="&#xf145;" title="';
94
+					$html .= esc_html__('Add to iCal Calendar', 'event_espresso') . '"/>';
95
+					$html .= '</form>';
96
+					break;
97
+				// buttons are just links that have been styled to appear as buttons,
98
+				// but may not be blend with a theme as well as submit buttons
99
+				case 'button':
100
+					$html .= '<a class="ee-ical-btn small ee-button ee-roundish" href="' . $URL;
101
+					$html .= '" title="' . esc_html__('Add to iCal Calendar', 'event_espresso') . '">';
102
+					$html .= ' <span class="dashicons dashicons-calendar"></span>';
103
+					$html .= '</a>';
104
+					break;
105
+				// links are just links that use the calendar dashicon
106
+				case 'icon':
107
+					$html .= '<a class="ee-ical-lnk" href="' . $URL . '" title="';
108
+					$html .= esc_html__('Add to iCal Calendar', 'event_espresso') . '">';
109
+					$html .= ' <span class="dashicons dashicons-calendar"></span>';
110
+					$html .= '</a>';
111
+					break;
112
+			}
113
+		}
114
+		return $html;
115
+	}
116
+
117
+
118
+	/**
119
+	 * @return void
120
+	 * @throws EE_Error
121
+	 * @throws ReflectionException
122
+	 */
123
+	public static function download_ics_file()
124
+	{
125
+		$request = self::getRequest();
126
+		if ($request->requestParamIsSet('ics_id')) {
127
+			$DTT_ID   = $request->getRequestParam('ics_id', 0, 'int');
128
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
129
+			if ($datetime instanceof EE_Datetime) {
130
+				// get related event, venues, and event categories
131
+				$event = $datetime->event();
132
+				if ($event instanceof EE_Event) {
133
+					// get related category Term object and it's name
134
+					$category = $event->first_event_category();
135
+					if ($category instanceof EE_Term) {
136
+						$category = $category->name();
137
+					}
138
+					$location = '';
139
+					// get first related venue and convert to CSV string
140
+					$venue = $event->venues(['limit' => 1]);
141
+					if (is_array($venue) && ! empty($venue)) {
142
+						$venue = array_shift($venue);
143
+						if ($venue instanceof EE_Venue) {
144
+							$location = espresso_venue_raw_address('inline', $venue->ID(), false);
145
+						}
146
+					}
147
+
148
+					// Generate filename
149
+					$filename = $event->slug() . '-' . $datetime->start_date('Y-m-d') . '.ics';
150
+
151
+					// Check the datetime status has not been cancelled and set the ics value accordingly
152
+					$status = $datetime->get_active_status();
153
+					$status = $status === EE_Datetime::cancelled ? 'CANCELLED' : 'CONFIRMED';
154
+
155
+					// Create array of ics details, escape strings, convert timestamps to ics format, etc
156
+					$ics_data = [
157
+						'ORGANIZER_NAME' => EE_Registry::instance()->CFG->organization->name,
158
+						'UID'            => md5($event->name() . $event->ID() . $datetime->ID()),
159
+						'ORGANIZER'      => EE_Registry::instance()->CFG->organization->email,
160
+						'DTSTAMP'        => date(EED_Ical::iCal_datetime_format),
161
+						'LOCATION'       => $location,
162
+						'SUMMARY'        => $event->name(),
163
+						'DESCRIPTION'    => wp_strip_all_tags($event->description()),
164
+						'STATUS'         => $status,
165
+						'CATEGORIES'     => $category,
166
+						'URL;VALUE=URI'  => get_permalink($event->ID()),
167
+						'DTSTART'        => date(EED_Ical::iCal_datetime_format, $datetime->start()),
168
+						'DTEND'          => date(EED_Ical::iCal_datetime_format, $datetime->end()),
169
+					];
170
+
171
+					// Filter the values used within the ics output.
172
+					// NOTE - all values within ics_data will be escaped automatically.
173
+					$ics_data = apply_filters('FHEE__EED_Ical__download_ics_file_ics_data', $ics_data, $datetime);
174
+
175
+					// Escape all ics data
176
+					foreach ($ics_data as $key => $value) {
177
+						// Description is escaped differently from all all values
178
+						if ($key === 'DESCRIPTION') {
179
+							$ics_data[ $key ] = EED_Ical::_escape_ICal_description(wp_strip_all_tags($value));
180
+						} else {
181
+							$ics_data[ $key ] = EED_Ical::_escape_ICal_data($value);
182
+						}
183
+					}
184
+
185
+					// Pull the organizer name from ics_data and remove it from the array.
186
+					$organizer_name = isset($ics_data['ORGANIZER_NAME'])
187
+						? $ics_data['ORGANIZER_NAME']
188
+						: '';
189
+					unset($ics_data['ORGANIZER_NAME']);
190
+
191
+					// set headers
192
+					header('Content-type: text/calendar; charset=utf-8');
193
+					header('Content-Disposition: attachment; filename="' . $filename . '"');
194
+					header('Cache-Control: private, max-age=0, must-revalidate');
195
+					header('Pragma: public');
196
+					header('Content-Type: application/octet-stream');
197
+					header('Content-Type: application/force-download');
198
+					header('Cache-Control: no-cache, must-revalidate');
199
+					header('Content-Transfer-Encoding: binary');
200
+					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // past date
201
+					ini_set('zlib.output_compression', '0');
202
+					// echo the output
203
+					echo "BEGIN:VCALENDAR\r\n";
204
+					echo "VERSION:2.0\r\n";
205
+					echo "PRODID:-//{$organizer_name}//NONSGML PDA Calendar Version 1.0//EN\r\n";
206
+					echo "CALSCALE:GREGORIAN\r\n";
207
+					echo "BEGIN:VEVENT\r\n";
208
+
209
+					// Output all remaining values from ics_data.
210
+					foreach ($ics_data as $key => $value) {
211
+						echo wp_kses($key . ':' . $value, AllowedTags::getAllowedTags()) . "\r\n";
212
+					}
213
+
214
+					echo "END:VEVENT\r\n";
215
+					echo "END:VCALENDAR\r\n";
216
+				}
217
+			}
218
+		}
219
+		die();
220
+	}
221
+
222
+
223
+	/**
224
+	 *    _escape_ICal_data
225
+	 *
226
+	 * @param string $string
227
+	 * @return    string
228
+	 */
229
+	private static function _escape_ICal_data($string = '')
230
+	{
231
+		return preg_replace('/([\,;])/', '\\\$1', $string);
232
+	}
233
+
234
+
235
+	/**
236
+	 *    _escape_ICal_description
237
+	 *
238
+	 * @param string $description
239
+	 * @return    string
240
+	 */
241
+	private static function _escape_ICal_description($description = '')
242
+	{
243
+		// Escape special chars within the description
244
+		$description = EED_Ical::_escape_ICal_data($description);
245
+		// Remove line breaks and output in iCal format
246
+		return str_replace(["\r\n", "\n"], '\n', $description);
247
+	}
248 248
 }
Please login to merge, or discard this patch.
modules/gateways/Invoice/lib/templates/invoice_body.template.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -76,20 +76,20 @@  discard block
 block discarded – undo
76 76
         </thead>
77 77
         <tbody>
78 78
         <?php
79
-        /**
80
-         * Recursive function for traversing all the sub-items of each line item
81
-         * and displaying them in the table
82
-         *
83
-         * @param EE_Line_Item $line_item
84
-         * @param boolean      $odd for indicating whether to style this line item as an 'odd' or 'even'
85
-         */
86
-        function ee_invoice_display_line_item(EE_Line_Item $line_item, $show_line_item_description, $odd = false)
87
-        {
88
-            switch ($line_item->type()) {
89
-                case EEM_Line_Item::type_total:
90
-                    foreach ($line_item->children() as $child_line_item) {
91
-                        ee_invoice_display_line_item($child_line_item, $show_line_item_description);
92
-                    } ?>
79
+		/**
80
+		 * Recursive function for traversing all the sub-items of each line item
81
+		 * and displaying them in the table
82
+		 *
83
+		 * @param EE_Line_Item $line_item
84
+		 * @param boolean      $odd for indicating whether to style this line item as an 'odd' or 'even'
85
+		 */
86
+		function ee_invoice_display_line_item(EE_Line_Item $line_item, $show_line_item_description, $odd = false)
87
+		{
88
+			switch ($line_item->type()) {
89
+				case EEM_Line_Item::type_total:
90
+					foreach ($line_item->children() as $child_line_item) {
91
+						ee_invoice_display_line_item($child_line_item, $show_line_item_description);
92
+					} ?>
93 93
                     <tr>
94 94
                         <td colspan="<?php echo ($show_line_item_description ? 5 : 4) ?>">
95 95
                             <hr>
@@ -101,50 +101,50 @@  discard block
 block discarded – undo
101 101
                         <td class="total"><?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags()); ?></td>
102 102
                     </tr>
103 103
                     <?php
104
-                    break;
104
+					break;
105 105
 
106 106
 
107
-                case EEM_Line_Item::type_sub_total:
108
-                    foreach ($line_item->children() as $child_line_item) {
109
-                        // $odd = !$odd;
110
-                        ee_invoice_display_line_item($child_line_item, $show_line_item_description, $odd);
111
-                    } ?>
107
+				case EEM_Line_Item::type_sub_total:
108
+					foreach ($line_item->children() as $child_line_item) {
109
+						// $odd = !$odd;
110
+						ee_invoice_display_line_item($child_line_item, $show_line_item_description, $odd);
111
+					} ?>
112 112
                     <tr class="total_tr odd">
113 113
                         <td colspan="<?php echo ($show_line_item_description ? 2 : 1) ?>">&nbsp;</td>
114 114
                         <td colspan="2" class="total" id="total_currency">
115 115
                             <?php esc_html_e(
116
-                                'Sub-Total',
117
-                                'event_espresso'
118
-                            ); ?></td>
116
+								'Sub-Total',
117
+								'event_espresso'
118
+							); ?></td>
119 119
                         <td class="total"><?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags()); ?></td>
120 120
                     </tr>
121 121
                     <?php
122
-                    break;
122
+					break;
123 123
 
124 124
 
125
-                case EEM_Line_Item::type_tax_sub_total:
126
-                    foreach ($line_item->children() as $child_line_item) {
127
-                        $odd = ! $odd;
128
-                        ee_invoice_display_line_item($child_line_item, $show_line_item_description, $odd);
129
-                    } ?>
125
+				case EEM_Line_Item::type_tax_sub_total:
126
+					foreach ($line_item->children() as $child_line_item) {
127
+						$odd = ! $odd;
128
+						ee_invoice_display_line_item($child_line_item, $show_line_item_description, $odd);
129
+					} ?>
130 130
                     <tr class="total_tr odd">
131 131
                         <td colspan="<?php echo ($show_line_item_description ? 2 : 1) ?>">&nbsp;</td>
132 132
                         <td colspan="2" class="total" id="total_currency">
133 133
                             <?php esc_html_e(
134
-                                'Tax Total',
135
-                                'event_espresso'
136
-                            ); ?></td>
134
+								'Tax Total',
135
+								'event_espresso'
136
+							); ?></td>
137 137
                         <td class="total"><?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags()); ?></td>
138 138
                     </tr>
139 139
                     <?php
140
-                    break;
140
+					break;
141 141
 
142 142
 
143
-                case EEM_Line_Item::type_line_item:
144
-                    $subitems = $line_item->children();
145
-                    $has_subitems = count($subitems) > 1;
146
-                    if ($has_subitems) {
147
-                        ?>
143
+				case EEM_Line_Item::type_line_item:
144
+					$subitems = $line_item->children();
145
+					$has_subitems = count($subitems) > 1;
146
+					if ($has_subitems) {
147
+						?>
148 148
                         <tr class="item <?php echo ($odd ? 'odd' : ''); ?>">
149 149
                             <td class="item_l"><?php echo esc_html($line_item->name()) ?></td>
150 150
                             <?php if ($show_line_item_description) { ?>
@@ -155,18 +155,18 @@  discard block
 block discarded – undo
155 155
                             <td class="item_c"><?php echo esc_html($line_item->unit_price_no_code()) ?></td>
156 156
 
157 157
                             <td class="item_r"> <?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags());
158
-                                echo ($line_item->is_taxable() ? '*' : ''); ?> </td>
158
+								echo ($line_item->is_taxable() ? '*' : ''); ?> </td>
159 159
                             <?php // <td class="item_l"><?php  $datetimes_strings = array(); foreach($datetimes as $datetime){ $datetimes_strings[]= $datetime->start_date_and_time();} echo implode(", ",$datetimes_strings);
160
-                            ?>
160
+							?>
161 161
                         </tr>
162 162
                         <?php
163
-                        if ($has_subitems) {
164
-                            foreach ($line_item->children() as $child_line_item) {
165
-                                ee_invoice_display_line_item($child_line_item, $show_line_item_description, $odd);
166
-                            }
167
-                        }
168
-                    } else {// no subitems - just show this line item
169
-                        ?>
163
+						if ($has_subitems) {
164
+							foreach ($line_item->children() as $child_line_item) {
165
+								ee_invoice_display_line_item($child_line_item, $show_line_item_description, $odd);
166
+							}
167
+						}
168
+					} else {// no subitems - just show this line item
169
+						?>
170 170
                         <tr class="item <?php echo ($odd ? 'odd' : ''); ?>">
171 171
                             <td class="item_l"><?php echo esc_html($line_item->name()); ?></td>
172 172
                             <?php if ($show_line_item_description) { ?>
@@ -175,15 +175,15 @@  discard block
 block discarded – undo
175 175
                             <td class="item_l"><?php echo esc_html($line_item->quantity()); ?></td>
176 176
                             <td class="item_c"><?php echo wp_kses($line_item->unit_price_no_code(), AllowedTags::getAllowedTags()); ?></td>
177 177
                             <td class="item_r"> <?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags());
178
-                                echo ($line_item->is_taxable() ? '*' : ''); ?> </td>
178
+								echo ($line_item->is_taxable() ? '*' : ''); ?> </td>
179 179
                             <?php // <td class="item_l"><?php  $datetimes_strings = array(); foreach($datetimes as $datetime){ $datetimes_strings[]= $datetime->start_date_and_time();} echo implode(", ",$datetimes_strings);
180
-                            ?>
180
+							?>
181 181
                         </tr>
182 182
                     <?php }
183 183
 
184
-                    break;
185
-                case EEM_Line_Item::type_sub_line_item:
186
-                    ?>
184
+					break;
185
+				case EEM_Line_Item::type_sub_line_item:
186
+					?>
187 187
                     <tr class="item subitem-row">
188 188
                         <td class="item_l subitem"><?php echo esc_html($line_item->name()); ?></td>
189 189
                         <?php if ($show_line_item_description) { ?>
@@ -199,9 +199,9 @@  discard block
 block discarded – undo
199 199
                         <td class="item_r"><?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags()); ?></td>
200 200
                     </tr>
201 201
                     <?php
202
-                    break;
203
-                case EEM_Line_Item::type_tax:
204
-                    ?>
202
+					break;
203
+				case EEM_Line_Item::type_tax:
204
+					?>
205 205
                     <tr class="item sub-item tax-total">
206 206
                     <td class="item_l"><?php echo esc_html($line_item->name()); ?></td>
207 207
                     <?php if ($show_line_item_description) { ?>
@@ -211,15 +211,15 @@  discard block
 block discarded – undo
211 211
 
212 212
                     <td class="item_r"><?php echo wp_kses($line_item->total_no_code(), AllowedTags::getAllowedTags()); ?></td>
213 213
                     </tr><?php
214
-                    break;
215
-            }
216
-        }
214
+					break;
215
+			}
216
+		}
217 217
 
218
-        $c = false;
219
-        /* @var $transaction EE_Transaction */
220
-        $total_line_item = $transaction->total_line_item();
221
-        ee_invoice_display_line_item($total_line_item, $show_line_item_description);
222
-        ?>
218
+		$c = false;
219
+		/* @var $transaction EE_Transaction */
220
+		$total_line_item = $transaction->total_line_item();
221
+		ee_invoice_display_line_item($total_line_item, $show_line_item_description);
222
+		?>
223 223
         </tbody>
224 224
 
225 225
     </table>
@@ -238,11 +238,11 @@  discard block
 block discarded – undo
238 238
         </thead>
239 239
         <tbody>
240 240
         <?php
241
-        $c = false;
242
-        if (! empty($payments)) {
243
-            foreach ($payments as $payment) {
244
-                /* @var $payment EE_Payment */
245
-                ?>
241
+		$c = false;
242
+		if (! empty($payments)) {
243
+			foreach ($payments as $payment) {
244
+				/* @var $payment EE_Payment */
245
+				?>
246 246
                 <tr class='item <?php echo(($c = ! $c) ? ' odd' : '') ?>'>
247 247
                     <td><?php $payment->e('PAY_gateway') ?></td>
248 248
                     <td><?php echo esc_html($payment->timestamp('D M j, Y')); ?></td>
@@ -252,17 +252,17 @@  discard block
 block discarded – undo
252 252
                     <td class='item_r'><?php echo EEH_Template::format_currency($payment->amount()); ?></td>
253 253
                 </tr>
254 254
             <?php }
255
-        } else {
256
-            ?>
255
+		} else {
256
+			?>
257 257
             <tr class='item'>
258 258
                 <td class='aln-cntr' colspan=6>
259 259
                     <?php esc_html_e(
260
-                        "No approved payments have been received",
261
-                        'event_espresso'
262
-                    ) ?></td>
260
+						"No approved payments have been received",
261
+						'event_espresso'
262
+					) ?></td>
263 263
             </tr>
264 264
         <?php }
265
-        ?>
265
+		?>
266 266
         </tbody>
267 267
         <tfoot>
268 268
         <tr class='total_tr'>
Please login to merge, or discard this patch.