Completed
Branch BUG-10375-migrations-not-repor... (dce535)
by
unknown
12:32
created
core/libraries/batch/JobHandlers/RegistrationsReport.php 1 patch
Indentation   +395 added lines, -396 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 use EventEspressoBatchRequest\Helpers\JobStepResponse;
18 18
 
19 19
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
20
-    exit('No direct script access allowed');
20
+	exit('No direct script access allowed');
21 21
 }
22 22
 
23 23
 
@@ -25,424 +25,423 @@  discard block
 block discarded – undo
25 25
 class RegistrationsReport extends JobHandlerFile
26 26
 {
27 27
 
28
-    /**
29
-     * Performs any necessary setup for starting the job. This is also a good
30
-     * place to setup the $job_arguments which will be used for subsequent HTTP requests
31
-     * when continue_job will be called
32
-     *
33
-     * @param JobParameters $job_parameters
34
-     * @throws BatchRequestException
35
-     * @return JobStepResponse
36
-     */
37
-    public function create_job(JobParameters $job_parameters)
38
-    {
39
-        $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
40
-        if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
41
-            throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
42
-        }
43
-        $filepath = $this->create_file_from_job_with_name($job_parameters->job_id(),
44
-            $this->get_filename($event_id));
45
-        $job_parameters->add_extra_data('filepath', $filepath);
46
-        if ($job_parameters->request_datum('use_filters', false)) {
47
-            $query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
48
-        } else {
49
-            $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
50
-                array(
51
-                    'OR'                 => array(
52
-                        //don't include registrations from failed or abandoned transactions...
53
-                        'Transaction.STS_ID' => array(
54
-                            'NOT IN',
55
-                            array(
56
-                                \EEM_Transaction::failed_status_code,
57
-                                \EEM_Transaction::abandoned_status_code,
58
-                            ),
59
-                        ),
60
-                        //unless the registration is approved, in which case include it regardless of transaction status
61
-                        'STS_ID'             => \EEM_Registration::status_id_approved,
62
-                    ),
63
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
64
-                ),
65
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
66
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
67
-                'caps'       => \EEM_Base::caps_read_admin,
68
-            ), $event_id);
69
-            if ($event_id) {
70
-                $query_params[0]['EVT_ID'] = $event_id;
71
-            } else {
72
-                $query_params['force_join'][] = 'Event';
73
-            }
74
-        }
75
-        if ( ! isset($query_params['force_join'])) {
76
-            $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
77
-        }
78
-        $job_parameters->add_extra_data('query_params', $query_params);
79
-        $question_labels = $this->_get_question_labels($query_params);
80
-        $job_parameters->add_extra_data('question_labels', $question_labels);
81
-        $job_parameters->set_job_size(
82
-            \EEM_Registration::instance()->count(
83
-                array_diff_key(
84
-                    $query_params,
85
-                    array_flip(
86
-                        array( 'limit' )
87
-                    )
88
-                )
89
-            )
90
-        );
91
-        //we should also set the header columns
92
-        $csv_data_for_row = $this->get_csv_data_for($event_id, 0, 1, $job_parameters->extra_datum('question_labels'),
93
-            $job_parameters->extra_datum('query_params'));
94
-        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
95
-        //if we actually processed a row there, record it
96
-        if ($job_parameters->job_size()) {
97
-            $job_parameters->mark_processed(1);
98
-        }
99
-        return new JobStepResponse($job_parameters,
100
-            __('Registrations report started successfully...', 'event_espresso'));
101
-    }
28
+	/**
29
+	 * Performs any necessary setup for starting the job. This is also a good
30
+	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
31
+	 * when continue_job will be called
32
+	 *
33
+	 * @param JobParameters $job_parameters
34
+	 * @throws BatchRequestException
35
+	 * @return JobStepResponse
36
+	 */
37
+	public function create_job(JobParameters $job_parameters)
38
+	{
39
+		$event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
40
+		if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
41
+			throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
42
+		}
43
+		$filepath = $this->create_file_from_job_with_name($job_parameters->job_id(),
44
+			$this->get_filename($event_id));
45
+		$job_parameters->add_extra_data('filepath', $filepath);
46
+		if ($job_parameters->request_datum('use_filters', false)) {
47
+			$query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
48
+		} else {
49
+			$query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
50
+				array(
51
+					'OR'                 => array(
52
+						//don't include registrations from failed or abandoned transactions...
53
+						'Transaction.STS_ID' => array(
54
+							'NOT IN',
55
+							array(
56
+								\EEM_Transaction::failed_status_code,
57
+								\EEM_Transaction::abandoned_status_code,
58
+							),
59
+						),
60
+						//unless the registration is approved, in which case include it regardless of transaction status
61
+						'STS_ID'             => \EEM_Registration::status_id_approved,
62
+					),
63
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
64
+				),
65
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
66
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
67
+				'caps'       => \EEM_Base::caps_read_admin,
68
+			), $event_id);
69
+			if ($event_id) {
70
+				$query_params[0]['EVT_ID'] = $event_id;
71
+			} else {
72
+				$query_params['force_join'][] = 'Event';
73
+			}
74
+		}
75
+		if ( ! isset($query_params['force_join'])) {
76
+			$query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
77
+		}
78
+		$job_parameters->add_extra_data('query_params', $query_params);
79
+		$question_labels = $this->_get_question_labels($query_params);
80
+		$job_parameters->add_extra_data('question_labels', $question_labels);
81
+		$job_parameters->set_job_size(
82
+			\EEM_Registration::instance()->count(
83
+				array_diff_key(
84
+					$query_params,
85
+					array_flip(
86
+						array( 'limit' )
87
+					)
88
+				)
89
+			)
90
+		);
91
+		//we should also set the header columns
92
+		$csv_data_for_row = $this->get_csv_data_for($event_id, 0, 1, $job_parameters->extra_datum('question_labels'),
93
+			$job_parameters->extra_datum('query_params'));
94
+		\EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
95
+		//if we actually processed a row there, record it
96
+		if ($job_parameters->job_size()) {
97
+			$job_parameters->mark_processed(1);
98
+		}
99
+		return new JobStepResponse($job_parameters,
100
+			__('Registrations report started successfully...', 'event_espresso'));
101
+	}
102 102
 
103 103
 
104 104
 
105
-    /**
106
-     * Gets the filename
107
-     * @return string
108
-     */
109
-    protected function get_filename()
110
-    {
111
-        return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
112
-    }
105
+	/**
106
+	 * Gets the filename
107
+	 * @return string
108
+	 */
109
+	protected function get_filename()
110
+	{
111
+		return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
112
+	}
113 113
 
114 114
 
115 115
 
116
-    /**
117
-     * Gets the questions which are to be used for this report, so they
118
-     * can be remembered for later
119
-     *
120
-     * @param array $registration_query_params
121
-     * @return array question admin labels to be used for this report
122
-     */
123
-    protected function _get_question_labels($registration_query_params)
124
-    {
125
-        $where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
126
-        $question_query_params = array();
127
-        if ($where !== null) {
128
-            $question_query_params = array(
129
-                $this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
130
-            );
131
-        }
132
-        $question_query_params[0]['Answer.ANS_ID'] = array( 'IS_NOT_NULL' );
133
-        $question_query_params['group_by'] = array( 'QST_ID' );
134
-        return array_unique( \EEM_Question::instance()->get_col( $question_query_params, 'QST_admin_label' ) );
135
-    }
116
+	/**
117
+	 * Gets the questions which are to be used for this report, so they
118
+	 * can be remembered for later
119
+	 *
120
+	 * @param array $registration_query_params
121
+	 * @return array question admin labels to be used for this report
122
+	 */
123
+	protected function _get_question_labels($registration_query_params)
124
+	{
125
+		$where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
126
+		$question_query_params = array();
127
+		if ($where !== null) {
128
+			$question_query_params = array(
129
+				$this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
130
+			);
131
+		}
132
+		$question_query_params[0]['Answer.ANS_ID'] = array( 'IS_NOT_NULL' );
133
+		$question_query_params['group_by'] = array( 'QST_ID' );
134
+		return array_unique( \EEM_Question::instance()->get_col( $question_query_params, 'QST_admin_label' ) );
135
+	}
136 136
 
137 137
 
138 138
 
139
-    /**
140
-     * Takes where params meant for registrations and changes them to work for questions
141
-     *
142
-     * @param array $reg_where_params
143
-     * @return array
144
-     */
145
-    protected function _change_registration_where_params_to_question_where_params($reg_where_params)
146
-    {
147
-        $question_where_params = array();
148
-        foreach ($reg_where_params as $key => $val) {
149
-            if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
150
-                $question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
151
-            } else {
152
-                //it's a normal where condition
153
-                $question_where_params['Question_Group.Event.Registration.' . $key] = $val;
154
-            }
155
-        }
156
-        return $question_where_params;
157
-    }
139
+	/**
140
+	 * Takes where params meant for registrations and changes them to work for questions
141
+	 *
142
+	 * @param array $reg_where_params
143
+	 * @return array
144
+	 */
145
+	protected function _change_registration_where_params_to_question_where_params($reg_where_params)
146
+	{
147
+		$question_where_params = array();
148
+		foreach ($reg_where_params as $key => $val) {
149
+			if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
150
+				$question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
151
+			} else {
152
+				//it's a normal where condition
153
+				$question_where_params['Question_Group.Event.Registration.' . $key] = $val;
154
+			}
155
+		}
156
+		return $question_where_params;
157
+	}
158 158
 
159 159
 
160 160
 
161
-    /**
162
-     * Performs another step of the job
163
-     *
164
-     * @param JobParameters $job_parameters
165
-     * @param int           $batch_size
166
-     * @return JobStepResponse
167
-     * @throws \EE_Error
168
-     */
169
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
170
-    {
171
-        if( $job_parameters->units_processed() < $job_parameters->job_size() ) {
172
-            $csv_data = $this->get_csv_data_for($job_parameters->request_datum('EVT_ID', '0'),
173
-                $job_parameters->units_processed(), $batch_size, $job_parameters->extra_datum('question_labels'),
174
-                $job_parameters->extra_datum('query_params'));
175
-            \EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
176
-            $units_processed = count($csv_data);
177
-        }else{
178
-            $units_processed = 0;
179
-        }
180
-        $job_parameters->mark_processed($units_processed);
181
-        $extra_response_data = array(
182
-            'file_url' => '',
183
-        );
184
-        if ($units_processed < $batch_size) {
185
-            $job_parameters->set_status(JobParameters::status_complete);
186
-            $extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
187
-        }
161
+	/**
162
+	 * Performs another step of the job
163
+	 *
164
+	 * @param JobParameters $job_parameters
165
+	 * @param int           $batch_size
166
+	 * @return JobStepResponse
167
+	 * @throws \EE_Error
168
+	 */
169
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
170
+	{
171
+		if( $job_parameters->units_processed() < $job_parameters->job_size() ) {
172
+			$csv_data = $this->get_csv_data_for($job_parameters->request_datum('EVT_ID', '0'),
173
+				$job_parameters->units_processed(), $batch_size, $job_parameters->extra_datum('question_labels'),
174
+				$job_parameters->extra_datum('query_params'));
175
+			\EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
176
+			$units_processed = count($csv_data);
177
+		}else{
178
+			$units_processed = 0;
179
+		}
180
+		$job_parameters->mark_processed($units_processed);
181
+		$extra_response_data = array(
182
+			'file_url' => '',
183
+		);
184
+		if ($units_processed < $batch_size) {
185
+			$job_parameters->set_status(JobParameters::status_complete);
186
+			$extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
187
+		}
188 188
 
189
-        return new JobStepResponse($job_parameters,
190
-            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
191
-            $extra_response_data);
192
-    }
189
+		return new JobStepResponse($job_parameters,
190
+			sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
191
+			$extra_response_data);
192
+	}
193 193
 
194 194
 
195 195
 
196
-    /**
197
-     * Gets the csv data for a batch of registrations
198
-
199
-     *
196
+	/**
197
+	 * Gets the csv data for a batch of registrations
198
+	 *
200 199
 *@param int|null    $event_id
201
-     * @param int   $offset
202
-     * @param int   $limit
203
-     * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
204
-     * @param array $query_params    for using where querying the model
205
-     * @return array top-level keys are numeric, next-level keys are column headers
206
-     */
207
-    function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
208
-    {
209
-        $reg_fields_to_include = array(
210
-            'TXN_ID',
211
-            'ATT_ID',
212
-            'REG_ID',
213
-            'REG_date',
214
-            'REG_code',
215
-            'REG_count',
216
-            'REG_final_price',
217
-        );
218
-        $att_fields_to_include = array(
219
-            'ATT_fname',
220
-            'ATT_lname',
221
-            'ATT_email',
222
-            'ATT_address',
223
-            'ATT_address2',
224
-            'ATT_city',
225
-            'STA_ID',
226
-            'CNT_ISO',
227
-            'ATT_zip',
228
-            'ATT_phone',
229
-        );
230
-        $registrations_csv_ready_array = array();
231
-        $reg_model = \EE_Registry::instance()->load_model('Registration');
232
-        $query_params['limit'] = array($offset, $limit);
233
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
234
-        $registration_ids = array();
235
-        foreach ($registration_rows as $reg_row) {
236
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
237
-        }
238
-        foreach ($registration_rows as $reg_row) {
239
-            if (is_array($reg_row)) {
240
-                $reg_csv_array = array();
241
-                if ( ! $event_id) {
242
-                    //get the event's name and Id
243
-                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(__('%1$s (%2$s)', 'event_espresso'),
244
-                        \EEH_Export::prepare_value_from_db_for_display(\EEM_Event::instance(), 'EVT_name',
245
-                            $reg_row['Event_CPT.post_title']), $reg_row['Event_CPT.ID']);
246
-                }
247
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
248
-                /*@var $reg_row EE_Registration */
249
-                foreach ($reg_fields_to_include as $field_name) {
250
-                    $field = $reg_model->field_settings_for($field_name);
251
-                    if ($field_name == 'REG_final_price') {
252
-                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
253
-                            $reg_row['Registration.REG_final_price'], 'localized_float');
254
-                    } elseif ($field_name == 'REG_count') {
255
-                        $value = sprintf(__('%s of %s', 'event_espresso'),
256
-                            \EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_count',
257
-                                $reg_row['Registration.REG_count']),
258
-                            \EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_group_size',
259
-                                $reg_row['Registration.REG_group_size']));
260
-                    } elseif ($field_name == 'REG_date') {
261
-                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
262
-                            $reg_row['Registration.REG_date'], 'no_html');
263
-                    } else {
264
-                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
265
-                            $reg_row[$field->get_qualified_column()]);
266
-                    }
267
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
268
-                    if ($field_name == 'REG_final_price') {
269
-                        //add a column named Currency after the final price
270
-                        $reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
271
-                    }
272
-                }
273
-                //get pretty status
274
-                $stati = \EEM_Status::instance()->localized_status(array(
275
-                    $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
276
-                    $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
277
-                ), false, 'sentence');
278
-                $reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
279
-                //get pretty transaction status
280
-                $reg_csv_array[__("Transaction Status",
281
-                    'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
282
-                $reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
283
-                    ? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_total',
284
-                        $reg_row['TransactionTable.TXN_total'], 'localized_float') : '0.00';
285
-                $reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
286
-                    ? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_paid',
287
-                        $reg_row['TransactionTable.TXN_paid'], 'localized_float') : '0.00';
288
-                $payment_methods = array();
289
-                $gateway_txn_ids_etc = array();
290
-                $payment_times = array();
291
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
292
-                    $payments_info = \EEM_Payment::instance()->get_all_wpdb_results(array(
293
-                        array(
294
-                            'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
295
-                            'STS_ID' => \EEM_Payment::status_id_approved,
296
-                        ),
297
-                        'force_join' => array('Payment_Method'),
298
-                    ), ARRAY_A,
299
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time');
300
-                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
301
-                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
302
-                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
303
-                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
304
-                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
305
-                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
306
-                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
307
-                    }
308
-                }
309
-                $reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
310
-                $reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
311
-                $reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
312
-                //get whether or not the user has checked in
313
-                $reg_csv_array[__("Check-Ins",
314
-                    "event_espresso")] = $reg_model->count_related($reg_row['Registration.REG_ID'], 'Checkin');
315
-                //get ticket of registration and its price
316
-                $ticket_model = \EE_Registry::instance()->load_model('Ticket');
317
-                if ($reg_row['Ticket.TKT_ID']) {
318
-                    $ticket_name = \EEH_Export::prepare_value_from_db_for_display($ticket_model, 'TKT_name',
319
-                        $reg_row['Ticket.TKT_name']);
320
-                    $datetimes_strings = array();
321
-                    foreach (
322
-                        \EEM_Datetime::instance()->get_all_wpdb_results(array(
323
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
324
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
325
-                            'default_where_conditions' => 'none',
326
-                        )) as $datetime
327
-                    ) {
328
-                        $datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(\EEM_Datetime::instance(),
329
-                            'DTT_EVT_start', $datetime['Datetime.DTT_EVT_start']);
330
-                    }
331
-                } else {
332
-                    $ticket_name = __('Unknown', 'event_espresso');
333
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
334
-                }
335
-                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
336
-                $reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
337
-                //get datetime(s) of registration
338
-                //add attendee columns
339
-                foreach ($att_fields_to_include as $att_field_name) {
340
-                    $field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
341
-                    if ($reg_row['Attendee_CPT.ID']) {
342
-                        if ($att_field_name == 'STA_ID') {
343
-                            $value = \EEM_State::instance()
344
-                                               ->get_var(array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
345
-                                                   'STA_name');
346
-                        } elseif ($att_field_name == 'CNT_ISO') {
347
-                            $value = \EEM_Country::instance()
348
-                                                 ->get_var(array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
349
-                                                     'CNT_name');
350
-                        } else {
351
-                            $value = \EEH_Export::prepare_value_from_db_for_display(\EEM_Attendee::instance(),
352
-                                $att_field_name, $reg_row[$field_obj->get_qualified_column()]);
353
-                        }
354
-                    } else {
355
-                        $value = '';
356
-                    }
357
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
358
-                }
359
-                //make sure each registration has the same questions in the same order
360
-                foreach ($question_labels as $question_label) {
361
-                    if ( ! isset($reg_csv_array[$question_label])) {
362
-                        $reg_csv_array[$question_label] = null;
363
-                    }
364
-                }
365
-                $answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
366
-                    array('REG_ID' => $reg_row['Registration.REG_ID']),
367
-                    'force_join' => array('Question'),
368
-                ));
369
-                //now fill out the questions THEY answered
370
-                foreach ($answers as $answer_row) {
371
-                    if ($answer_row['Question.QST_ID']) {
372
-                        $question_label = \EEH_Export::prepare_value_from_db_for_display(\EEM_Question::instance(),
373
-                            'QST_admin_label', $answer_row['Question.QST_admin_label']);
374
-                    } else {
375
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
376
-                    }
377
-                    if (isset($answer_row['Question.QST_type'])
378
-                        && $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
379
-                    ) {
380
-                        $reg_csv_array[$question_label] = \EEM_State::instance()
381
-                                                                    ->get_state_name_by_ID($answer_row['Answer.ANS_value']);
382
-                    } else {
383
-                        //this isn't for html, so don't show html entities
384
-                        $reg_csv_array[$question_label] = html_entity_decode(\EEH_Export::prepare_value_from_db_for_display(\EEM_Answer::instance(),
385
-                            'ANS_value', $answer_row['Answer.ANS_value']));
386
-                    }
387
-                }
388
-                $registrations_csv_ready_array[] = apply_filters('FHEE__EE_Export__report_registrations__reg_csv_array',
389
-                    $reg_csv_array, $reg_row);
390
-            }
391
-        }
392
-        //if we couldn't export anything, we want to at least show the column headers
393
-        if (empty($registrations_csv_ready_array)) {
394
-            $reg_csv_array = array();
395
-            $model_and_fields_to_include = array(
396
-                'Registration' => $reg_fields_to_include,
397
-                'Attendee'     => $att_fields_to_include,
398
-            );
399
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
400
-                $model = \EE_Registry::instance()->load_model($model_name);
401
-                foreach ($field_list as $field_name) {
402
-                    $field = $model->field_settings_for($field_name);
403
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
404
-                }
405
-            }
406
-            $registrations_csv_ready_array[] = $reg_csv_array;
407
-        }
408
-        return $registrations_csv_ready_array;
409
-    }
200
+	 * @param int   $offset
201
+	 * @param int   $limit
202
+	 * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
203
+	 * @param array $query_params    for using where querying the model
204
+	 * @return array top-level keys are numeric, next-level keys are column headers
205
+	 */
206
+	function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
207
+	{
208
+		$reg_fields_to_include = array(
209
+			'TXN_ID',
210
+			'ATT_ID',
211
+			'REG_ID',
212
+			'REG_date',
213
+			'REG_code',
214
+			'REG_count',
215
+			'REG_final_price',
216
+		);
217
+		$att_fields_to_include = array(
218
+			'ATT_fname',
219
+			'ATT_lname',
220
+			'ATT_email',
221
+			'ATT_address',
222
+			'ATT_address2',
223
+			'ATT_city',
224
+			'STA_ID',
225
+			'CNT_ISO',
226
+			'ATT_zip',
227
+			'ATT_phone',
228
+		);
229
+		$registrations_csv_ready_array = array();
230
+		$reg_model = \EE_Registry::instance()->load_model('Registration');
231
+		$query_params['limit'] = array($offset, $limit);
232
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
233
+		$registration_ids = array();
234
+		foreach ($registration_rows as $reg_row) {
235
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
236
+		}
237
+		foreach ($registration_rows as $reg_row) {
238
+			if (is_array($reg_row)) {
239
+				$reg_csv_array = array();
240
+				if ( ! $event_id) {
241
+					//get the event's name and Id
242
+					$reg_csv_array[__('Event', 'event_espresso')] = sprintf(__('%1$s (%2$s)', 'event_espresso'),
243
+						\EEH_Export::prepare_value_from_db_for_display(\EEM_Event::instance(), 'EVT_name',
244
+							$reg_row['Event_CPT.post_title']), $reg_row['Event_CPT.ID']);
245
+				}
246
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
247
+				/*@var $reg_row EE_Registration */
248
+				foreach ($reg_fields_to_include as $field_name) {
249
+					$field = $reg_model->field_settings_for($field_name);
250
+					if ($field_name == 'REG_final_price') {
251
+						$value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
252
+							$reg_row['Registration.REG_final_price'], 'localized_float');
253
+					} elseif ($field_name == 'REG_count') {
254
+						$value = sprintf(__('%s of %s', 'event_espresso'),
255
+							\EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_count',
256
+								$reg_row['Registration.REG_count']),
257
+							\EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_group_size',
258
+								$reg_row['Registration.REG_group_size']));
259
+					} elseif ($field_name == 'REG_date') {
260
+						$value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
261
+							$reg_row['Registration.REG_date'], 'no_html');
262
+					} else {
263
+						$value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
264
+							$reg_row[$field->get_qualified_column()]);
265
+					}
266
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
267
+					if ($field_name == 'REG_final_price') {
268
+						//add a column named Currency after the final price
269
+						$reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
270
+					}
271
+				}
272
+				//get pretty status
273
+				$stati = \EEM_Status::instance()->localized_status(array(
274
+					$reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
275
+					$reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
276
+				), false, 'sentence');
277
+				$reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
278
+				//get pretty transaction status
279
+				$reg_csv_array[__("Transaction Status",
280
+					'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
281
+				$reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
282
+					? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_total',
283
+						$reg_row['TransactionTable.TXN_total'], 'localized_float') : '0.00';
284
+				$reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
285
+					? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_paid',
286
+						$reg_row['TransactionTable.TXN_paid'], 'localized_float') : '0.00';
287
+				$payment_methods = array();
288
+				$gateway_txn_ids_etc = array();
289
+				$payment_times = array();
290
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
291
+					$payments_info = \EEM_Payment::instance()->get_all_wpdb_results(array(
292
+						array(
293
+							'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
294
+							'STS_ID' => \EEM_Payment::status_id_approved,
295
+						),
296
+						'force_join' => array('Payment_Method'),
297
+					), ARRAY_A,
298
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time');
299
+					foreach ($payments_info as $payment_method_and_gateway_txn_id) {
300
+						$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
301
+							? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
302
+						$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
303
+							? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
304
+						$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
305
+							? $payment_method_and_gateway_txn_id['payment_time'] : '';
306
+					}
307
+				}
308
+				$reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
309
+				$reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
310
+				$reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
311
+				//get whether or not the user has checked in
312
+				$reg_csv_array[__("Check-Ins",
313
+					"event_espresso")] = $reg_model->count_related($reg_row['Registration.REG_ID'], 'Checkin');
314
+				//get ticket of registration and its price
315
+				$ticket_model = \EE_Registry::instance()->load_model('Ticket');
316
+				if ($reg_row['Ticket.TKT_ID']) {
317
+					$ticket_name = \EEH_Export::prepare_value_from_db_for_display($ticket_model, 'TKT_name',
318
+						$reg_row['Ticket.TKT_name']);
319
+					$datetimes_strings = array();
320
+					foreach (
321
+						\EEM_Datetime::instance()->get_all_wpdb_results(array(
322
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
323
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
324
+							'default_where_conditions' => 'none',
325
+						)) as $datetime
326
+					) {
327
+						$datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(\EEM_Datetime::instance(),
328
+							'DTT_EVT_start', $datetime['Datetime.DTT_EVT_start']);
329
+					}
330
+				} else {
331
+					$ticket_name = __('Unknown', 'event_espresso');
332
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
333
+				}
334
+				$reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
335
+				$reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
336
+				//get datetime(s) of registration
337
+				//add attendee columns
338
+				foreach ($att_fields_to_include as $att_field_name) {
339
+					$field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
340
+					if ($reg_row['Attendee_CPT.ID']) {
341
+						if ($att_field_name == 'STA_ID') {
342
+							$value = \EEM_State::instance()
343
+											   ->get_var(array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
344
+												   'STA_name');
345
+						} elseif ($att_field_name == 'CNT_ISO') {
346
+							$value = \EEM_Country::instance()
347
+												 ->get_var(array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
348
+													 'CNT_name');
349
+						} else {
350
+							$value = \EEH_Export::prepare_value_from_db_for_display(\EEM_Attendee::instance(),
351
+								$att_field_name, $reg_row[$field_obj->get_qualified_column()]);
352
+						}
353
+					} else {
354
+						$value = '';
355
+					}
356
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
357
+				}
358
+				//make sure each registration has the same questions in the same order
359
+				foreach ($question_labels as $question_label) {
360
+					if ( ! isset($reg_csv_array[$question_label])) {
361
+						$reg_csv_array[$question_label] = null;
362
+					}
363
+				}
364
+				$answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
365
+					array('REG_ID' => $reg_row['Registration.REG_ID']),
366
+					'force_join' => array('Question'),
367
+				));
368
+				//now fill out the questions THEY answered
369
+				foreach ($answers as $answer_row) {
370
+					if ($answer_row['Question.QST_ID']) {
371
+						$question_label = \EEH_Export::prepare_value_from_db_for_display(\EEM_Question::instance(),
372
+							'QST_admin_label', $answer_row['Question.QST_admin_label']);
373
+					} else {
374
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
375
+					}
376
+					if (isset($answer_row['Question.QST_type'])
377
+						&& $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
378
+					) {
379
+						$reg_csv_array[$question_label] = \EEM_State::instance()
380
+																	->get_state_name_by_ID($answer_row['Answer.ANS_value']);
381
+					} else {
382
+						//this isn't for html, so don't show html entities
383
+						$reg_csv_array[$question_label] = html_entity_decode(\EEH_Export::prepare_value_from_db_for_display(\EEM_Answer::instance(),
384
+							'ANS_value', $answer_row['Answer.ANS_value']));
385
+					}
386
+				}
387
+				$registrations_csv_ready_array[] = apply_filters('FHEE__EE_Export__report_registrations__reg_csv_array',
388
+					$reg_csv_array, $reg_row);
389
+			}
390
+		}
391
+		//if we couldn't export anything, we want to at least show the column headers
392
+		if (empty($registrations_csv_ready_array)) {
393
+			$reg_csv_array = array();
394
+			$model_and_fields_to_include = array(
395
+				'Registration' => $reg_fields_to_include,
396
+				'Attendee'     => $att_fields_to_include,
397
+			);
398
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
399
+				$model = \EE_Registry::instance()->load_model($model_name);
400
+				foreach ($field_list as $field_name) {
401
+					$field = $model->field_settings_for($field_name);
402
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
403
+				}
404
+			}
405
+			$registrations_csv_ready_array[] = $reg_csv_array;
406
+		}
407
+		return $registrations_csv_ready_array;
408
+	}
410 409
 
411 410
 
412 411
 
413
-    /**
414
-     * Counts total unit to process
415
-     *
416
-     * @deprecated since 4.9.19
417
-     * @param int|array $event_id
418
-     * @return int
419
-     */
420
-    public function count_units_to_process($event_id)
421
-    {
422
-        //use the legacy filter
423
-        if ($event_id) {
424
-            $query_params[0]['EVT_ID'] = $event_id;
425
-        } else {
426
-            $query_params['force_join'][] = 'Event';
427
-        }
428
-        return \EEM_Registration::instance()->count($query_params);
429
-    }
412
+	/**
413
+	 * Counts total unit to process
414
+	 *
415
+	 * @deprecated since 4.9.19
416
+	 * @param int|array $event_id
417
+	 * @return int
418
+	 */
419
+	public function count_units_to_process($event_id)
420
+	{
421
+		//use the legacy filter
422
+		if ($event_id) {
423
+			$query_params[0]['EVT_ID'] = $event_id;
424
+		} else {
425
+			$query_params['force_join'][] = 'Event';
426
+		}
427
+		return \EEM_Registration::instance()->count($query_params);
428
+	}
430 429
 
431 430
 
432 431
 
433
-    /**
434
-     * Performs any clean-up logic when we know the job is completed.
435
-     * In this case, we delete the temporary file
436
-     *
437
-     * @param JobParameters $job_parameters
438
-     * @return boolean
439
-     */
440
-    public function cleanup_job(JobParameters $job_parameters)
441
-    {
442
-        $this->_file_helper->delete(\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
443
-            true, 'd');
444
-        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
445
-    }
432
+	/**
433
+	 * Performs any clean-up logic when we know the job is completed.
434
+	 * In this case, we delete the temporary file
435
+	 *
436
+	 * @param JobParameters $job_parameters
437
+	 * @return boolean
438
+	 */
439
+	public function cleanup_job(JobParameters $job_parameters)
440
+	{
441
+		$this->_file_helper->delete(\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
442
+			true, 'd');
443
+		return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
444
+	}
446 445
 }
447 446
 
448 447
 
Please login to merge, or discard this patch.