Completed
Branch master (d65695)
by
unknown
04:25
created
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 1 patch
Indentation   +544 added lines, -544 removed lines patch added patch discarded remove patch
@@ -12,548 +12,548 @@
 block discarded – undo
12 12
  */
13 13
 class EEG_Paypal_Express extends EE_Offsite_Gateway
14 14
 {
15
-    /**
16
-     * Merchant API Username.
17
-     *
18
-     * @var string
19
-     */
20
-    protected $_api_username;
21
-
22
-    /**
23
-     * Merchant API Password.
24
-     *
25
-     * @var string
26
-     */
27
-    protected $_api_password;
28
-
29
-    /**
30
-     * API Signature.
31
-     *
32
-     * @var string
33
-     */
34
-    protected $_api_signature;
35
-
36
-    /**
37
-     * Request Shipping address on PP checkout page.
38
-     *
39
-     * @var string
40
-     */
41
-    protected $_request_shipping_addr;
42
-
43
-    /**
44
-     * Business/personal logo.
45
-     *
46
-     * @var string
47
-     */
48
-    protected $_image_url = '';
49
-
50
-    /**
51
-     * gateway URL variable
52
-     *
53
-     * @var string
54
-     */
55
-    protected $_base_gateway_url = '';
56
-
57
-
58
-    /**
59
-     * number of decimal places to round numbers to when performing calculations
60
-     *
61
-     * @var integer
62
-     */
63
-    protected $decimal_precision = 6;
64
-
65
-    /**
66
-     * @var ItemizedOrder
67
-     * @since 5.0.0.p
68
-     */
69
-    protected $itemized_order;
70
-
71
-    /**
72
-     * @var TokenRequest
73
-     * @since 5.0.0.p
74
-     */
75
-    protected $token_request;
76
-
77
-
78
-    /**
79
-     * EEG_Paypal_Express constructor.
80
-     */
81
-    public function __construct()
82
-    {
83
-        require_once 'polyfills.php';
84
-        $this->_currencies_supported = [
85
-            'USD',
86
-            'AUD',
87
-            'BRL',
88
-            'CAD',
89
-            'CZK',
90
-            'DKK',
91
-            'EUR',
92
-            'HKD',
93
-            'HUF',
94
-            'ILS',
95
-            'JPY',
96
-            'MYR',
97
-            'MXN',
98
-            'NOK',
99
-            'NZD',
100
-            'PHP',
101
-            'PLN',
102
-            'GBP',
103
-            'RUB',
104
-            'SGD',
105
-            'SEK',
106
-            'CHF',
107
-            'TWD',
108
-            'THB',
109
-            'TRY',
110
-            'INR',
111
-        ];
112
-        parent::__construct();
113
-        $this->decimal_precision = EE_Registry::instance()->CFG->currency->dec_plc;
114
-    }
115
-
116
-
117
-    /**
118
-     * Sets the gateway URL variable based on whether debug mode is enabled or not.
119
-     *
120
-     * @param array $settings_array
121
-     */
122
-    public function set_settings(array $settings_array)
123
-    {
124
-        parent::set_settings($settings_array);
125
-        // Redirect URL.
126
-        $this->_base_gateway_url = $this->_debug_mode
127
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
128
-            : 'https://api-3t.paypal.com/nvp';
129
-    }
130
-
131
-
132
-    /**
133
-     * @param EE_Payment $payment
134
-     * @param array       $billing_info
135
-     * @param string      $return_url
136
-     * @param string      $notify_url
137
-     * @param string      $cancel_url
138
-     * @return EE_Payment
139
-     * @throws EE_Error
140
-     * @throws ReflectionException
141
-     * @throws Exception
142
-     */
143
-    public function set_redirection_info(
144
-        $payment,
145
-        $billing_info = [],
146
-        $return_url = null,
147
-        $notify_url = null,
148
-        $cancel_url = null
149
-    ) {
150
-        if (! $this->validatePayment($payment)) {
151
-            return $payment;
152
-        }
153
-        if (! $this->validateTransaction($payment)) {
154
-            return $payment;
155
-        }
156
-        $this->token_request = new TokenRequest($this->_get_gateway_formatter());
157
-        $token_request_details = apply_filters(
158
-            'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
159
-            $this->token_request->generateDetails(
160
-                $payment,
161
-                $this->getOrderItems($payment),
162
-                $return_url ?? '',
163
-                $cancel_url ?? '',
164
-                $this->_image_url ?? '',
165
-                $this->_request_shipping_addr ?? ''
166
-            ),
167
-            $this
168
-        );
169
-        // Request PayPal token.
170
-        $token_request_response = $this->_ppExpress_request($token_request_details, 'Payment Token', $payment);
171
-        $token_request_status   = $this->_ppExpress_check_response($token_request_response);
172
-        $this->token_request->processResponse($payment, $token_request_status, $this->isInSandboxMode());
173
-
174
-        return $payment;
175
-    }
176
-
177
-
178
-    /**
179
-     * @param array           $update_info {
180
-     * @type string           $gateway_txn_id
181
-     * @type string           $status      an EEMI_Payment status
182
-     *                                     }
183
-     * @param EE_Transaction $transaction
184
-     * @return EE_Payment
185
-     * @throws Exception
186
-     */
187
-    public function handle_payment_update($update_info, $transaction): EE_Payment
188
-    {
189
-        // if the supplied transaction is valid, we'll retrieve the actual payment object from it
190
-        // but we'll use a temporary payment for now that we can return with errors if things go wrong
191
-        $payment = EE_Payment::new_instance();
192
-        if (! $this->validateTransaction($payment, $transaction)) {
193
-            return $payment;
194
-        }
195
-        $payment = $transaction->last_payment();
196
-        if (! $this->validatePayment($payment)) {
197
-            return $payment;
198
-        }
199
-        // payment appears to be good... so far
200
-        $this->log(['Return from Authorization' => $update_info], $payment);
201
-        $payment_token = $this->getPaymentToken($payment);
202
-        $customer_details = $this->requestCustomerDetails($payment, $payment_token);
203
-        // We got the PayerID so now we can Complete the transaction.
204
-        $this->processPayment($payment, $payment_token, $customer_details);
205
-
206
-        return $payment;
207
-    }
208
-
209
-
210
-    /**
211
-     * @throws Exception
212
-     */
213
-    private function getOrderItems(EE_Payment $payment, array $request_response_args = []): array
214
-    {
215
-        $this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter());
216
-        try {
217
-            $itemized_order = $this->itemized_order->getExistingItemizedOrder($request_response_args);
218
-        } catch (Exception $exception) {
219
-            if (WP_DEBUG) {
220
-                throw $exception;
221
-            }
222
-            // Reset the list and log an error, maybe allow to try and generate a new list (below).
223
-            $itemized_order = [];
224
-            $this->log(
225
-                [
226
-                    esc_html__(
227
-                        'Could not generate a proper item list with:',
228
-                        'event_espresso'
229
-                    ) => $request_response_args,
230
-                ],
231
-                $payment
232
-            );
233
-        }
234
-        if (empty($itemized_order)) {
235
-            $itemized_order = $this->itemized_order->generateItemizedOrder($payment);
236
-        }
237
-        return $itemized_order;
238
-    }
239
-
240
-
241
-    /**
242
-     *  Make the Express checkout request.
243
-     *
244
-     * @param array       $request_params
245
-     * @param string      $request_text
246
-     * @param EE_Payment $payment
247
-     * @return array|WP_Error
248
-     */
249
-    public function _ppExpress_request(array $request_params, string $request_text, EE_Payment $payment)
250
-    {
251
-        $request_dtls = [
252
-            'VERSION'      => '204.0',
253
-            'USER'         => $this->_api_username,
254
-            'PWD'          => $this->_api_password,
255
-            'SIGNATURE'    => $this->_api_signature,
256
-            // EE will blow up if you change this
257
-            'BUTTONSOURCE' => 'EventEspresso_SP',
258
-        ];
259
-        $dtls         = array_merge($request_dtls, $request_params);
260
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
261
-        // Request Customer Details.
262
-        $request_response = wp_remote_post(
263
-            $this->_base_gateway_url,
264
-            [
265
-                'method'      => 'POST',
266
-                'timeout'     => 45,
267
-                'httpversion' => '1.1',
268
-                'cookies'     => [],
269
-                'headers'     => [],
270
-                'body'        => http_build_query($dtls),
271
-            ]
272
-        );
273
-        // Log the response.
274
-        $this->log([$request_text . ' Response' => $request_response], $payment);
275
-        return $request_response;
276
-    }
277
-
278
-
279
-    /**
280
-     *  Check the response status.
281
-     *
282
-     * @param mixed $request_response
283
-     * @return array
284
-     */
285
-    public function _ppExpress_check_response($request_response): array
286
-    {
287
-        if (is_wp_error($request_response) || empty($request_response['body'])) {
288
-            // If we got here then there was an error in this request.
289
-            return ['status' => false, 'args' => $request_response];
290
-        }
291
-        $response_args = [];
292
-        parse_str(urldecode($request_response['body']), $response_args);
293
-        if (! isset($response_args['ACK'])) {
294
-            return ['status' => false, 'args' => $request_response];
295
-        }
296
-        if (
297
-            (
298
-                isset($response_args['PAYERID'])
299
-                || isset($response_args['TOKEN'])
300
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
301
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
302
-            )
303
-            && in_array($response_args['ACK'], ['Success', 'SuccessWithWarning'], true)
304
-        ) {
305
-            // Response status OK, return response parameters for further processing.
306
-            return ['status' => true, 'args' => $response_args];
307
-        }
308
-        $errors = $this->_get_errors($response_args);
309
-        return ['status' => false, 'args' => $errors];
310
-    }
311
-
312
-
313
-    /**
314
-     *  Log a "Cleared" request.
315
-     *
316
-     * @param array       $request
317
-     * @param EE_Payment $payment
318
-     * @param string      $info
319
-     * @return void
320
-     */
321
-    private function _log_clean_request(array $request, EE_Payment $payment, string $info)
322
-    {
323
-        $cleaned_request_data = $request;
324
-        unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
325
-        $this->log([$info => $cleaned_request_data], $payment);
326
-    }
327
-
328
-
329
-    /**
330
-     *  Get error from the response data.
331
-     *
332
-     * @param array $data_array
333
-     * @return array
334
-     */
335
-    private function _get_errors(array $data_array): array
336
-    {
337
-        $errors = [];
338
-        $n      = 0;
339
-        while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
340
-            $l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
341
-            $l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
342
-            $l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
343
-            $l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
344
-            if ($n === 0) {
345
-                $errors = [
346
-                    'L_ERRORCODE'    => $l_error_code,
347
-                    'L_SHORTMESSAGE' => $l_short_message,
348
-                    'L_LONGMESSAGE'  => $l_long_message,
349
-                    'L_SEVERITYCODE' => $l_severity_code,
350
-                ];
351
-            } else {
352
-                $errors['L_ERRORCODE']    .= ', ' . $l_error_code;
353
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
354
-                $errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
355
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
356
-            }
357
-            $n++;
358
-        }
359
-        return $errors;
360
-    }
361
-
362
-
363
-    /**
364
-     * @param EE_Payment $payment
365
-     * @return mixed|null
366
-     * @throws EE_Error
367
-     * @since   5.0.0.p
368
-     */
369
-    private function getPaymentToken(EE_Payment $payment)
370
-    {
371
-        $payment_details = $payment->details();
372
-        // Check if we still have the token.
373
-        if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
374
-            $payment->set_status($this->_pay_model->failed_status());
375
-            return null;
376
-        }
377
-        return $payment_details['TOKEN'];
378
-    }
379
-
380
-    /**
381
-     * @param EE_Payment $payment
382
-     * @param array      $checkout_response
383
-     * @param array      $customer_data
384
-     * @throws EE_Error
385
-     * @throws ReflectionException
386
-     * @since   5.0.0.p
387
-     */
388
-    private function paymentApproved(EE_Payment $payment, array $checkout_response, array $customer_data)
389
-    {
390
-        $primary_registrant = $payment->transaction()->primary_registration();
391
-        $primary_registration_code = $primary_registrant instanceof EE_Registration ?
392
-            $primary_registrant->reg_code()
393
-            : '';
394
-        $payment->set_extra_accntng($primary_registration_code);
395
-        $payment_amount = $checkout_response['PAYMENTINFO_0_AMT'] ?? 0;
396
-        $payment->set_amount((float) $payment_amount);
397
-        $payment->set_txn_id_chq_nmbr($checkout_response['PAYMENTINFO_0_TRANSACTIONID'] ?? null);
398
-        $payment->set_details($customer_data);
399
-        $payment->set_gateway_response($checkout_response['PAYMENTINFO_0_ACK'] ?? '');
400
-        $payment->set_status($this->_pay_model->approved_status());
401
-    }
402
-
403
-
404
-    /**
405
-     * @param EE_Payment $payment
406
-     * @param array      $checkout_response
407
-     * @throws EE_Error
408
-     * @since   5.0.0.p
409
-     */
410
-    private function paymentDeclined(EE_Payment $payment, array $checkout_response)
411
-    {
412
-        $gateway_response = isset($checkout_response['L_ERRORCODE'])
413
-            ? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
414
-            : esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
415
-
416
-        $payment->set_gateway_response($gateway_response);
417
-        $payment->set_details($checkout_response);
418
-        $payment->set_status($this->_pay_model->declined_status());
419
-    }
420
-
421
-
422
-    /**
423
-     * @param EE_Payment $payment
424
-     * @param array $customer_data
425
-     * @throws EE_Error
426
-     * @since   5.0.0.p
427
-     */
428
-    private function paymentFailed(EE_Payment $payment, array $customer_data)
429
-    {
430
-        $gateway_response = isset($customer_data['L_ERRORCODE'])
431
-            ? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
432
-            : esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
433
-
434
-        $payment->set_gateway_response($gateway_response);
435
-        $payment->set_details($customer_data);
436
-        $payment->set_status($this->_pay_model->failed_status());
437
-    }
438
-
439
-
440
-    /**
441
-     * @param EE_Payment $payment
442
-     * @param string     $payment_token
443
-     * @param array      $customer_details
444
-     * @return void
445
-     * @throws EE_Error
446
-     * @throws ReflectionException
447
-     * @throws Exception
448
-     * @since   5.0.0.p
449
-     */
450
-    private function processPayment(EE_Payment $payment, string $payment_token, array $customer_details)
451
-    {
452
-        $checkout_request_dtls = [
453
-            'METHOD'                         => 'DoExpressCheckoutPayment',
454
-            'PAYERID'                        => $customer_details['PAYERID'],
455
-            'TOKEN'                          => $payment_token,
456
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
457
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
458
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
459
-        ];
460
-        // Include itemized list.
461
-        $itemized_list         = $this->getOrderItems($payment, $customer_details);
462
-        $checkout_request_dtls = array_merge($checkout_request_dtls, $itemized_list);
463
-        // Payment Checkout/Capture.
464
-        $checkout_request_response = $this->_ppExpress_request(
465
-            $checkout_request_dtls,
466
-            'Do Payment',
467
-            $payment
468
-        );
469
-        $checkout_request_status   = $this->_ppExpress_check_response($checkout_request_response);
470
-        $checkout_response         =
471
-            isset($checkout_request_status['args']) && is_array($checkout_request_status['args'])
472
-                ? $checkout_request_status['args']
473
-                : [];
474
-        if ($checkout_request_status['status']) {
475
-            // All is well, payment approved.
476
-            $this->paymentApproved($payment, $checkout_response, $customer_details);
477
-        } else {
478
-            $this->paymentDeclined($payment, $checkout_response);
479
-        }
480
-    }
481
-
482
-
483
-    /**
484
-     * @param EE_Payment $payment
485
-     * @param string $payment_token
486
-     * @return array
487
-     * @throws EE_Error
488
-     * @since   5.0.0.p
489
-     */
490
-    private function requestCustomerDetails(EE_Payment $payment, string $payment_token): array
491
-    {
492
-        $customer_details_request_dtls = [
493
-            'METHOD' => 'GetExpressCheckoutDetails',
494
-            'TOKEN'  => $payment_token,
495
-        ];
496
-        // Request Customer Details.
497
-        $customer_details_request_response = $this->_ppExpress_request(
498
-            $customer_details_request_dtls,
499
-            'Customer Details',
500
-            $payment
501
-        );
502
-        $customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
503
-        $customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
504
-            ? $customer_details_rstatus['args']
505
-            : [];
506
-        if (! $customer_details_rstatus['status']) {
507
-            $this->paymentFailed($payment, $customer_details);
508
-        }
509
-        return $customer_details;
510
-    }
511
-
512
-
513
-
514
-    /**
515
-     * @param EE_Payment|null $payment
516
-     * @return bool
517
-     * @throws EE_Error
518
-     * @since   5.0.0.p
519
-     */
520
-    private function validatePayment(?EE_Payment $payment): bool
521
-    {
522
-        if (! $payment instanceof EE_Payment) {
523
-            $payment = EE_Payment::new_instance();
524
-            $payment->set_gateway_response(
525
-                esc_html__(
526
-                    'An error occurred while trying to process the payment.',
527
-                    'event_espresso'
528
-                )
529
-            );
530
-            $payment->set_status($this->_pay_model->failed_status());
531
-            return false;
532
-        }
533
-        return true;
534
-    }
535
-
536
-
537
-    /**
538
-     * @param EE_Payment          $payment
539
-     * @param EE_Transaction|null $transaction
540
-     * @return bool
541
-     * @throws EE_Error
542
-     * @since   5.0.0.p
543
-     */
544
-    private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
545
-    {
546
-        $transaction = $transaction ?? $payment->transaction();
547
-        if (! $transaction instanceof EE_Transaction) {
548
-            $payment->set_gateway_response(
549
-                esc_html__(
550
-                    'Could not process this payment because it has no associated transaction.',
551
-                    'event_espresso'
552
-                )
553
-            );
554
-            $payment->set_status($this->_pay_model->failed_status());
555
-            return false;
556
-        }
557
-        return true;
558
-    }
15
+	/**
16
+	 * Merchant API Username.
17
+	 *
18
+	 * @var string
19
+	 */
20
+	protected $_api_username;
21
+
22
+	/**
23
+	 * Merchant API Password.
24
+	 *
25
+	 * @var string
26
+	 */
27
+	protected $_api_password;
28
+
29
+	/**
30
+	 * API Signature.
31
+	 *
32
+	 * @var string
33
+	 */
34
+	protected $_api_signature;
35
+
36
+	/**
37
+	 * Request Shipping address on PP checkout page.
38
+	 *
39
+	 * @var string
40
+	 */
41
+	protected $_request_shipping_addr;
42
+
43
+	/**
44
+	 * Business/personal logo.
45
+	 *
46
+	 * @var string
47
+	 */
48
+	protected $_image_url = '';
49
+
50
+	/**
51
+	 * gateway URL variable
52
+	 *
53
+	 * @var string
54
+	 */
55
+	protected $_base_gateway_url = '';
56
+
57
+
58
+	/**
59
+	 * number of decimal places to round numbers to when performing calculations
60
+	 *
61
+	 * @var integer
62
+	 */
63
+	protected $decimal_precision = 6;
64
+
65
+	/**
66
+	 * @var ItemizedOrder
67
+	 * @since 5.0.0.p
68
+	 */
69
+	protected $itemized_order;
70
+
71
+	/**
72
+	 * @var TokenRequest
73
+	 * @since 5.0.0.p
74
+	 */
75
+	protected $token_request;
76
+
77
+
78
+	/**
79
+	 * EEG_Paypal_Express constructor.
80
+	 */
81
+	public function __construct()
82
+	{
83
+		require_once 'polyfills.php';
84
+		$this->_currencies_supported = [
85
+			'USD',
86
+			'AUD',
87
+			'BRL',
88
+			'CAD',
89
+			'CZK',
90
+			'DKK',
91
+			'EUR',
92
+			'HKD',
93
+			'HUF',
94
+			'ILS',
95
+			'JPY',
96
+			'MYR',
97
+			'MXN',
98
+			'NOK',
99
+			'NZD',
100
+			'PHP',
101
+			'PLN',
102
+			'GBP',
103
+			'RUB',
104
+			'SGD',
105
+			'SEK',
106
+			'CHF',
107
+			'TWD',
108
+			'THB',
109
+			'TRY',
110
+			'INR',
111
+		];
112
+		parent::__construct();
113
+		$this->decimal_precision = EE_Registry::instance()->CFG->currency->dec_plc;
114
+	}
115
+
116
+
117
+	/**
118
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
119
+	 *
120
+	 * @param array $settings_array
121
+	 */
122
+	public function set_settings(array $settings_array)
123
+	{
124
+		parent::set_settings($settings_array);
125
+		// Redirect URL.
126
+		$this->_base_gateway_url = $this->_debug_mode
127
+			? 'https://api-3t.sandbox.paypal.com/nvp'
128
+			: 'https://api-3t.paypal.com/nvp';
129
+	}
130
+
131
+
132
+	/**
133
+	 * @param EE_Payment $payment
134
+	 * @param array       $billing_info
135
+	 * @param string      $return_url
136
+	 * @param string      $notify_url
137
+	 * @param string      $cancel_url
138
+	 * @return EE_Payment
139
+	 * @throws EE_Error
140
+	 * @throws ReflectionException
141
+	 * @throws Exception
142
+	 */
143
+	public function set_redirection_info(
144
+		$payment,
145
+		$billing_info = [],
146
+		$return_url = null,
147
+		$notify_url = null,
148
+		$cancel_url = null
149
+	) {
150
+		if (! $this->validatePayment($payment)) {
151
+			return $payment;
152
+		}
153
+		if (! $this->validateTransaction($payment)) {
154
+			return $payment;
155
+		}
156
+		$this->token_request = new TokenRequest($this->_get_gateway_formatter());
157
+		$token_request_details = apply_filters(
158
+			'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
159
+			$this->token_request->generateDetails(
160
+				$payment,
161
+				$this->getOrderItems($payment),
162
+				$return_url ?? '',
163
+				$cancel_url ?? '',
164
+				$this->_image_url ?? '',
165
+				$this->_request_shipping_addr ?? ''
166
+			),
167
+			$this
168
+		);
169
+		// Request PayPal token.
170
+		$token_request_response = $this->_ppExpress_request($token_request_details, 'Payment Token', $payment);
171
+		$token_request_status   = $this->_ppExpress_check_response($token_request_response);
172
+		$this->token_request->processResponse($payment, $token_request_status, $this->isInSandboxMode());
173
+
174
+		return $payment;
175
+	}
176
+
177
+
178
+	/**
179
+	 * @param array           $update_info {
180
+	 * @type string           $gateway_txn_id
181
+	 * @type string           $status      an EEMI_Payment status
182
+	 *                                     }
183
+	 * @param EE_Transaction $transaction
184
+	 * @return EE_Payment
185
+	 * @throws Exception
186
+	 */
187
+	public function handle_payment_update($update_info, $transaction): EE_Payment
188
+	{
189
+		// if the supplied transaction is valid, we'll retrieve the actual payment object from it
190
+		// but we'll use a temporary payment for now that we can return with errors if things go wrong
191
+		$payment = EE_Payment::new_instance();
192
+		if (! $this->validateTransaction($payment, $transaction)) {
193
+			return $payment;
194
+		}
195
+		$payment = $transaction->last_payment();
196
+		if (! $this->validatePayment($payment)) {
197
+			return $payment;
198
+		}
199
+		// payment appears to be good... so far
200
+		$this->log(['Return from Authorization' => $update_info], $payment);
201
+		$payment_token = $this->getPaymentToken($payment);
202
+		$customer_details = $this->requestCustomerDetails($payment, $payment_token);
203
+		// We got the PayerID so now we can Complete the transaction.
204
+		$this->processPayment($payment, $payment_token, $customer_details);
205
+
206
+		return $payment;
207
+	}
208
+
209
+
210
+	/**
211
+	 * @throws Exception
212
+	 */
213
+	private function getOrderItems(EE_Payment $payment, array $request_response_args = []): array
214
+	{
215
+		$this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter());
216
+		try {
217
+			$itemized_order = $this->itemized_order->getExistingItemizedOrder($request_response_args);
218
+		} catch (Exception $exception) {
219
+			if (WP_DEBUG) {
220
+				throw $exception;
221
+			}
222
+			// Reset the list and log an error, maybe allow to try and generate a new list (below).
223
+			$itemized_order = [];
224
+			$this->log(
225
+				[
226
+					esc_html__(
227
+						'Could not generate a proper item list with:',
228
+						'event_espresso'
229
+					) => $request_response_args,
230
+				],
231
+				$payment
232
+			);
233
+		}
234
+		if (empty($itemized_order)) {
235
+			$itemized_order = $this->itemized_order->generateItemizedOrder($payment);
236
+		}
237
+		return $itemized_order;
238
+	}
239
+
240
+
241
+	/**
242
+	 *  Make the Express checkout request.
243
+	 *
244
+	 * @param array       $request_params
245
+	 * @param string      $request_text
246
+	 * @param EE_Payment $payment
247
+	 * @return array|WP_Error
248
+	 */
249
+	public function _ppExpress_request(array $request_params, string $request_text, EE_Payment $payment)
250
+	{
251
+		$request_dtls = [
252
+			'VERSION'      => '204.0',
253
+			'USER'         => $this->_api_username,
254
+			'PWD'          => $this->_api_password,
255
+			'SIGNATURE'    => $this->_api_signature,
256
+			// EE will blow up if you change this
257
+			'BUTTONSOURCE' => 'EventEspresso_SP',
258
+		];
259
+		$dtls         = array_merge($request_dtls, $request_params);
260
+		$this->_log_clean_request($dtls, $payment, $request_text . ' Request');
261
+		// Request Customer Details.
262
+		$request_response = wp_remote_post(
263
+			$this->_base_gateway_url,
264
+			[
265
+				'method'      => 'POST',
266
+				'timeout'     => 45,
267
+				'httpversion' => '1.1',
268
+				'cookies'     => [],
269
+				'headers'     => [],
270
+				'body'        => http_build_query($dtls),
271
+			]
272
+		);
273
+		// Log the response.
274
+		$this->log([$request_text . ' Response' => $request_response], $payment);
275
+		return $request_response;
276
+	}
277
+
278
+
279
+	/**
280
+	 *  Check the response status.
281
+	 *
282
+	 * @param mixed $request_response
283
+	 * @return array
284
+	 */
285
+	public function _ppExpress_check_response($request_response): array
286
+	{
287
+		if (is_wp_error($request_response) || empty($request_response['body'])) {
288
+			// If we got here then there was an error in this request.
289
+			return ['status' => false, 'args' => $request_response];
290
+		}
291
+		$response_args = [];
292
+		parse_str(urldecode($request_response['body']), $response_args);
293
+		if (! isset($response_args['ACK'])) {
294
+			return ['status' => false, 'args' => $request_response];
295
+		}
296
+		if (
297
+			(
298
+				isset($response_args['PAYERID'])
299
+				|| isset($response_args['TOKEN'])
300
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
301
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
302
+			)
303
+			&& in_array($response_args['ACK'], ['Success', 'SuccessWithWarning'], true)
304
+		) {
305
+			// Response status OK, return response parameters for further processing.
306
+			return ['status' => true, 'args' => $response_args];
307
+		}
308
+		$errors = $this->_get_errors($response_args);
309
+		return ['status' => false, 'args' => $errors];
310
+	}
311
+
312
+
313
+	/**
314
+	 *  Log a "Cleared" request.
315
+	 *
316
+	 * @param array       $request
317
+	 * @param EE_Payment $payment
318
+	 * @param string      $info
319
+	 * @return void
320
+	 */
321
+	private function _log_clean_request(array $request, EE_Payment $payment, string $info)
322
+	{
323
+		$cleaned_request_data = $request;
324
+		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
325
+		$this->log([$info => $cleaned_request_data], $payment);
326
+	}
327
+
328
+
329
+	/**
330
+	 *  Get error from the response data.
331
+	 *
332
+	 * @param array $data_array
333
+	 * @return array
334
+	 */
335
+	private function _get_errors(array $data_array): array
336
+	{
337
+		$errors = [];
338
+		$n      = 0;
339
+		while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
340
+			$l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
341
+			$l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
342
+			$l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
343
+			$l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
344
+			if ($n === 0) {
345
+				$errors = [
346
+					'L_ERRORCODE'    => $l_error_code,
347
+					'L_SHORTMESSAGE' => $l_short_message,
348
+					'L_LONGMESSAGE'  => $l_long_message,
349
+					'L_SEVERITYCODE' => $l_severity_code,
350
+				];
351
+			} else {
352
+				$errors['L_ERRORCODE']    .= ', ' . $l_error_code;
353
+				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
354
+				$errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
355
+				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
356
+			}
357
+			$n++;
358
+		}
359
+		return $errors;
360
+	}
361
+
362
+
363
+	/**
364
+	 * @param EE_Payment $payment
365
+	 * @return mixed|null
366
+	 * @throws EE_Error
367
+	 * @since   5.0.0.p
368
+	 */
369
+	private function getPaymentToken(EE_Payment $payment)
370
+	{
371
+		$payment_details = $payment->details();
372
+		// Check if we still have the token.
373
+		if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
374
+			$payment->set_status($this->_pay_model->failed_status());
375
+			return null;
376
+		}
377
+		return $payment_details['TOKEN'];
378
+	}
379
+
380
+	/**
381
+	 * @param EE_Payment $payment
382
+	 * @param array      $checkout_response
383
+	 * @param array      $customer_data
384
+	 * @throws EE_Error
385
+	 * @throws ReflectionException
386
+	 * @since   5.0.0.p
387
+	 */
388
+	private function paymentApproved(EE_Payment $payment, array $checkout_response, array $customer_data)
389
+	{
390
+		$primary_registrant = $payment->transaction()->primary_registration();
391
+		$primary_registration_code = $primary_registrant instanceof EE_Registration ?
392
+			$primary_registrant->reg_code()
393
+			: '';
394
+		$payment->set_extra_accntng($primary_registration_code);
395
+		$payment_amount = $checkout_response['PAYMENTINFO_0_AMT'] ?? 0;
396
+		$payment->set_amount((float) $payment_amount);
397
+		$payment->set_txn_id_chq_nmbr($checkout_response['PAYMENTINFO_0_TRANSACTIONID'] ?? null);
398
+		$payment->set_details($customer_data);
399
+		$payment->set_gateway_response($checkout_response['PAYMENTINFO_0_ACK'] ?? '');
400
+		$payment->set_status($this->_pay_model->approved_status());
401
+	}
402
+
403
+
404
+	/**
405
+	 * @param EE_Payment $payment
406
+	 * @param array      $checkout_response
407
+	 * @throws EE_Error
408
+	 * @since   5.0.0.p
409
+	 */
410
+	private function paymentDeclined(EE_Payment $payment, array $checkout_response)
411
+	{
412
+		$gateway_response = isset($checkout_response['L_ERRORCODE'])
413
+			? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
414
+			: esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
415
+
416
+		$payment->set_gateway_response($gateway_response);
417
+		$payment->set_details($checkout_response);
418
+		$payment->set_status($this->_pay_model->declined_status());
419
+	}
420
+
421
+
422
+	/**
423
+	 * @param EE_Payment $payment
424
+	 * @param array $customer_data
425
+	 * @throws EE_Error
426
+	 * @since   5.0.0.p
427
+	 */
428
+	private function paymentFailed(EE_Payment $payment, array $customer_data)
429
+	{
430
+		$gateway_response = isset($customer_data['L_ERRORCODE'])
431
+			? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
432
+			: esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
433
+
434
+		$payment->set_gateway_response($gateway_response);
435
+		$payment->set_details($customer_data);
436
+		$payment->set_status($this->_pay_model->failed_status());
437
+	}
438
+
439
+
440
+	/**
441
+	 * @param EE_Payment $payment
442
+	 * @param string     $payment_token
443
+	 * @param array      $customer_details
444
+	 * @return void
445
+	 * @throws EE_Error
446
+	 * @throws ReflectionException
447
+	 * @throws Exception
448
+	 * @since   5.0.0.p
449
+	 */
450
+	private function processPayment(EE_Payment $payment, string $payment_token, array $customer_details)
451
+	{
452
+		$checkout_request_dtls = [
453
+			'METHOD'                         => 'DoExpressCheckoutPayment',
454
+			'PAYERID'                        => $customer_details['PAYERID'],
455
+			'TOKEN'                          => $payment_token,
456
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
457
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
458
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
459
+		];
460
+		// Include itemized list.
461
+		$itemized_list         = $this->getOrderItems($payment, $customer_details);
462
+		$checkout_request_dtls = array_merge($checkout_request_dtls, $itemized_list);
463
+		// Payment Checkout/Capture.
464
+		$checkout_request_response = $this->_ppExpress_request(
465
+			$checkout_request_dtls,
466
+			'Do Payment',
467
+			$payment
468
+		);
469
+		$checkout_request_status   = $this->_ppExpress_check_response($checkout_request_response);
470
+		$checkout_response         =
471
+			isset($checkout_request_status['args']) && is_array($checkout_request_status['args'])
472
+				? $checkout_request_status['args']
473
+				: [];
474
+		if ($checkout_request_status['status']) {
475
+			// All is well, payment approved.
476
+			$this->paymentApproved($payment, $checkout_response, $customer_details);
477
+		} else {
478
+			$this->paymentDeclined($payment, $checkout_response);
479
+		}
480
+	}
481
+
482
+
483
+	/**
484
+	 * @param EE_Payment $payment
485
+	 * @param string $payment_token
486
+	 * @return array
487
+	 * @throws EE_Error
488
+	 * @since   5.0.0.p
489
+	 */
490
+	private function requestCustomerDetails(EE_Payment $payment, string $payment_token): array
491
+	{
492
+		$customer_details_request_dtls = [
493
+			'METHOD' => 'GetExpressCheckoutDetails',
494
+			'TOKEN'  => $payment_token,
495
+		];
496
+		// Request Customer Details.
497
+		$customer_details_request_response = $this->_ppExpress_request(
498
+			$customer_details_request_dtls,
499
+			'Customer Details',
500
+			$payment
501
+		);
502
+		$customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
503
+		$customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
504
+			? $customer_details_rstatus['args']
505
+			: [];
506
+		if (! $customer_details_rstatus['status']) {
507
+			$this->paymentFailed($payment, $customer_details);
508
+		}
509
+		return $customer_details;
510
+	}
511
+
512
+
513
+
514
+	/**
515
+	 * @param EE_Payment|null $payment
516
+	 * @return bool
517
+	 * @throws EE_Error
518
+	 * @since   5.0.0.p
519
+	 */
520
+	private function validatePayment(?EE_Payment $payment): bool
521
+	{
522
+		if (! $payment instanceof EE_Payment) {
523
+			$payment = EE_Payment::new_instance();
524
+			$payment->set_gateway_response(
525
+				esc_html__(
526
+					'An error occurred while trying to process the payment.',
527
+					'event_espresso'
528
+				)
529
+			);
530
+			$payment->set_status($this->_pay_model->failed_status());
531
+			return false;
532
+		}
533
+		return true;
534
+	}
535
+
536
+
537
+	/**
538
+	 * @param EE_Payment          $payment
539
+	 * @param EE_Transaction|null $transaction
540
+	 * @return bool
541
+	 * @throws EE_Error
542
+	 * @since   5.0.0.p
543
+	 */
544
+	private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
545
+	{
546
+		$transaction = $transaction ?? $payment->transaction();
547
+		if (! $transaction instanceof EE_Transaction) {
548
+			$payment->set_gateway_response(
549
+				esc_html__(
550
+					'Could not process this payment because it has no associated transaction.',
551
+					'event_espresso'
552
+				)
553
+			);
554
+			$payment->set_status($this->_pay_model->failed_status());
555
+			return false;
556
+		}
557
+		return true;
558
+	}
559 559
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Standard/EEG_Paypal_Standard.gateway.php 1 patch
Indentation   +548 added lines, -548 removed lines patch added patch discarded remove patch
@@ -19,552 +19,552 @@
 block discarded – undo
19 19
  */
20 20
 class EEG_Paypal_Standard extends EE_Offsite_Gateway
21 21
 {
22
-    /**
23
-     * Name for the wp option used to save the itemized payment
24
-     */
25
-    const itemized_payment_option_name = '_itemized_payment';
26
-
27
-    protected $_paypal_id;
28
-
29
-    protected $_image_url;
30
-
31
-    protected $_shipping_details;
32
-
33
-    protected $_paypal_shipping;
34
-
35
-    protected $_paypal_taxes;
36
-
37
-    protected $_gateway_url;
38
-
39
-    protected $_currencies_supported = array(
40
-        'USD',
41
-        'GBP',
42
-        'CAD',
43
-        'AUD',
44
-        'BRL',
45
-        'CHF',
46
-        'CZK',
47
-        'DKK',
48
-        'EUR',
49
-        'HKD',
50
-        'HUF',
51
-        'ILS',
52
-        'JPY',
53
-        'MXN',
54
-        'MYR',
55
-        'NOK',
56
-        'NZD',
57
-        'PHP',
58
-        'PLN',
59
-        'SEK',
60
-        'SGD',
61
-        'THB',
62
-        'TRY',
63
-        'TWD',
64
-        'RUB'
65
-    );
66
-
67
-    /**
68
-     * @var ItemizedOrder
69
-     * @since 5.0.0.p
70
-     */
71
-    protected $itemized_order;
72
-
73
-
74
-    /**
75
-     * EEG_Paypal_Standard constructor.
76
-     */
77
-    public function __construct()
78
-    {
79
-        $this->set_uses_separate_IPN_request(true);
80
-        parent::__construct();
81
-    }
82
-
83
-
84
-    /**
85
-     * @return mixed
86
-     */
87
-    public function gatewayUrl()
88
-    {
89
-        return $this->_gateway_url;
90
-    }
91
-
92
-
93
-    /**
94
-     * @return mixed
95
-     */
96
-    public function imageUrl()
97
-    {
98
-        return $this->_image_url;
99
-    }
100
-
101
-
102
-    /**
103
-     * @return mixed
104
-     */
105
-    public function paypalId()
106
-    {
107
-        return $this->_paypal_id;
108
-    }
109
-
110
-
111
-    /**
112
-     * @return mixed
113
-     */
114
-    public function paypalShipping()
115
-    {
116
-        return $this->_paypal_shipping;
117
-    }
118
-
119
-
120
-
121
-    /**
122
-     * @return mixed
123
-     */
124
-    public function paypalTaxes()
125
-    {
126
-        return $this->_paypal_taxes;
127
-    }
128
-
129
-
130
-    /**
131
-     * @return mixed
132
-     */
133
-    public function shippingDetails()
134
-    {
135
-        return $this->_shipping_details;
136
-    }
137
-
138
-
139
-    /**
140
-     * Also sets the gateway url class variable based on whether debug mode is enabled or not.
141
-     *
142
-     * @param array $settings_array
143
-     */
144
-    public function set_settings(array $settings_array)
145
-    {
146
-        parent::set_settings($settings_array);
147
-        $this->_gateway_url = $this->_debug_mode
148
-            ? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
149
-            : 'https://www.paypal.com/cgi-bin/webscr';
150
-    }
151
-
152
-
153
-    /**
154
-     * @param EEI_Payment $payment      the payment to process
155
-     * @param array       $billing_info but should be empty for this gateway
156
-     * @param string      $return_url   URL to send the user to after payment on the payment provider's website
157
-     * @param string      $notify_url   URL to send the instant payment notification
158
-     * @param string      $cancel_url   URL to send the user to after a cancelled payment attempt
159
-     *                                  on the payment provider's website
160
-     * @return EEI_Payment
161
-     * @throws EE_Error
162
-     * @throws ReflectionException
163
-     */
164
-    public function set_redirection_info(
165
-        $payment,
166
-        $billing_info = array(),
167
-        $return_url = null,
168
-        $notify_url = null,
169
-        $cancel_url = null
170
-    ) {
171
-        $this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter(), $this);
172
-        $redirect_args = apply_filters(
173
-            "FHEE__EEG_Paypal_Standard__set_redirection_info__arguments",
174
-            $this->itemized_order->generateItemizedOrderForPayment(
175
-                $payment,
176
-                $return_url,
177
-                $notify_url,
178
-                $cancel_url
179
-            ),
180
-            $this
181
-        );
182
-
183
-        $payment->set_redirect_url($this->_gateway_url);
184
-        $payment->set_redirect_args($redirect_args);
185
-        // log the results
186
-        $this->log(
187
-            [
188
-                'message'     => esc_html__('PayPal payment request initiated.', 'event_espresso'),
189
-                'transaction' => $payment->transaction()->model_field_array(),
190
-            ],
191
-            $payment
192
-        );
193
-        return $payment;
194
-    }
195
-
196
-
197
-    /**
198
-     * Often used for IPNs. But applies the info in $update_info to the payment.
199
-     * What is $update_info? Often the contents of $_REQUEST, but not necessarily. Whatever
200
-     * the payment method passes in.
201
-     *
202
-     * @param array $update_info like $_POST
203
-     * @param EE_Transaction $transaction
204
-     * @return EEI_Payment updated
205
-     * @throws EE_Error, IpnException
206
-     */
207
-    public function handle_payment_update($update_info, $transaction)
208
-    {
209
-        // verify there's payment data that's been sent
210
-        if (empty($update_info['payment_status']) || empty($update_info['txn_id'])) {
211
-            // log the results
212
-            $this->log(
213
-                array(
214
-                    'message'     => esc_html__(
215
-                        'PayPal IPN response is missing critical payment data. This may indicate a PDT request and require your PayPal account settings to be corrected.',
216
-                        'event_espresso'
217
-                    ),
218
-                    'update_info' => $update_info,
219
-                ),
220
-                $transaction
221
-            );
222
-            // waaaait... is this a PDT request? (see https://developer.paypal.com/docs/classic/products/payment-data-transfer/)
223
-            // indicated by the "tx" argument? If so, we don't need it. We'll just use the IPN data when it comes
224
-            if (isset($update_info['tx'])) {
225
-                return $transaction->last_payment();
226
-            } else {
227
-                return null;
228
-            }
229
-        }
230
-        $payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr($update_info['txn_id']);
231
-        if (! $payment instanceof EEI_Payment) {
232
-            $payment = $transaction->last_payment();
233
-        }
234
-        // ok, then validate the IPN. Even if we've already processed this payment,
235
-        // let PayPal know we don't want to hear from them anymore!
236
-        if (! $this->validate_ipn($update_info, $payment)) {
237
-            return $payment;
238
-        }
239
-        // kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
240
-        // registrations, ticket counts, etc)
241
-        if (
242
-            (
243
-                $update_info['payment_status'] === 'Refunded'
244
-                || $update_info['payment_status'] === 'Partially_Refunded'
245
-            )
246
-            && apply_filters('FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true)
247
-        ) {
248
-            throw new EventEspresso\core\exceptions\IpnException(
249
-                sprintf(
250
-                    esc_html__('Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
251
-                    $update_info['payment_status']
252
-                ),
253
-                EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
254
-                null,
255
-                $payment,
256
-                $update_info
257
-            );
258
-        }
259
-        // ok, well let's process this payment then!
260
-        switch ($update_info['payment_status']) {
261
-            case 'Completed':
262
-                $status = $this->_pay_model->approved_status();
263
-                $gateway_response = esc_html__('The payment is approved.', 'event_espresso');
264
-                break;
265
-
266
-            case 'Pending':
267
-                $status = $this->_pay_model->pending_status();
268
-                $gateway_response = esc_html__(
269
-                    'The payment is in progress. Another message will be sent when payment is approved.',
270
-                    'event_espresso'
271
-                );
272
-                break;
273
-
274
-            case 'Denied':
275
-                $status = $this->_pay_model->declined_status();
276
-                $gateway_response = esc_html__('The payment has been declined.', 'event_espresso');
277
-                break;
278
-
279
-            case 'Expired':
280
-            case 'Failed':
281
-                $status = $this->_pay_model->failed_status();
282
-                $gateway_response = esc_html__('The payment failed for technical reasons or expired.', 'event_espresso');
283
-                break;
284
-
285
-            case 'Refunded':
286
-            case 'Partially_Refunded':
287
-                // even though it's a refund, we consider the payment as approved, it just has a negative value
288
-                $status = $this->_pay_model->approved_status();
289
-                $gateway_response = esc_html__(
290
-                    'The payment has been refunded. Please update registrations accordingly.',
291
-                    'event_espresso'
292
-                );
293
-                break;
294
-
295
-            case 'Voided':
296
-            case 'Reversed':
297
-            case 'Canceled_Reversal':
298
-            default:
299
-                $status = $this->_pay_model->cancelled_status();
300
-                $gateway_response = esc_html__(
301
-                    'The payment was cancelled, reversed, or voided. Please update registrations accordingly.',
302
-                    'event_espresso'
303
-                );
304
-                break;
305
-        }
306
-
307
-        // check if we've already processed this payment
308
-        if ($payment instanceof EEI_Payment) {
309
-            // payment exists. if this has the exact same status and amount, don't bother updating. just return
310
-            if ($payment->status() === $status && $payment->amount() === (float) $update_info['mc_gross']) {
311
-                // DUPLICATED IPN! don't bother updating transaction
312
-                throw new IpnException(
313
-                    sprintf(
314
-                        esc_html__(
315
-                            'It appears we have received a duplicate IPN from PayPal for payment %d',
316
-                            'event_espresso'
317
-                        ),
318
-                        $payment->ID()
319
-                    ),
320
-                    IpnException::DUPLICATE,
321
-                    null,
322
-                    $payment,
323
-                    $update_info
324
-                );
325
-            } else {
326
-                // new payment yippee !!!
327
-                $payment->set_status($status);
328
-                $payment->set_amount((float) $update_info['mc_gross']);
329
-                $payment->set_gateway_response($gateway_response);
330
-                $payment->set_details($update_info);
331
-                $payment->set_txn_id_chq_nmbr($update_info['txn_id']);
332
-                $this->log(
333
-                    array(
334
-                        'message'  => esc_html__(
335
-                            'Updated payment either from IPN or as part of POST from PayPal',
336
-                            'event_espresso'
337
-                        ),
338
-                        'url'      => $this->_process_response_url(),
339
-                        'payment'  => $payment->model_field_array(),
340
-                        'IPN_data' => $update_info
341
-                    ),
342
-                    $payment
343
-                );
344
-            }
345
-        }
346
-        do_action('FHEE__EEG_Paypal_Standard__handle_payment_update__payment_processed', $payment, $this);
347
-        return $payment;
348
-    }
349
-
350
-
351
-    /**
352
-     * Validate the IPN notification.
353
-     *
354
-     * @param array                  $update_info like $_REQUEST
355
-     * @param EE_Payment $payment
356
-     * @return boolean
357
-     * @throws EE_Error
358
-     */
359
-    public function validate_ipn($update_info, $payment)
360
-    {
361
-        // allow us to skip validating IPNs with PayPal (useful for testing)
362
-        if (apply_filters('FHEE__EEG_Paypal_Standard__validate_ipn__skip', false)) {
363
-            return true;
364
-        }
365
-        // ...otherwise, we actually don't care what the $update_info is, we need to look
366
-        // at the request directly because we can't use $update_info because it has issues with quotes
367
-        // Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
368
-        // Instead, read raw POST data from the input stream.
369
-        // @see https://gist.github.com/xcommerce-gists/3440401
370
-        $raw_post_data = file_get_contents('php://input');
371
-        $raw_post_array = explode('&', $raw_post_data);
372
-        $update_info = array();
373
-        foreach ($raw_post_array as $keyval) {
374
-            $keyval = explode('=', $keyval);
375
-            if (count($keyval) === 2) {
376
-                $update_info[ $keyval[0] ] = urldecode($keyval[1]);
377
-            }
378
-        }
379
-        // read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
380
-        $req = 'cmd=_notify-validate';
381
-        foreach ($update_info as $key => $value) {
382
-            $value = urlencode($value);
383
-            $req .= "&$key=$value";
384
-        }
385
-        // HTTP POST the complete, unaltered IPN back to PayPal
386
-        $response = wp_remote_post(
387
-            $this->_gateway_url,
388
-            array(
389
-                'body'              => $req,
390
-                'sslverify'         => false,
391
-                'timeout'           => 60,
392
-                // make sure to set a site specific unique "user-agent" string since the WordPres default gets declined by PayPal
393
-                // plz see: https://github.com/websharks/s2member/issues/610
394
-                'user-agent'        => 'Event Espresso v' . EVENT_ESPRESSO_VERSION . '; ' . home_url(),
395
-                'httpversion'       => '1.1'
396
-            )
397
-        );
398
-        // then check the response
399
-        if (
400
-            array_key_exists('body', $response)
401
-            && ! is_wp_error($response)
402
-            && strcmp($response['body'], "VERIFIED") === 0
403
-        ) {
404
-            return true;
405
-        }
406
-        // huh, something's wack... the IPN didn't validate. We must have replied to the IPN incorrectly,
407
-        // or their API must have changed: http://www.paypalobjects.com/en_US/ebook/PP_OrderManagement_IntegrationGuide/ipn.html
408
-        if ($response instanceof WP_Error) {
409
-            $error_msg = sprintf(
410
-                esc_html__('WP Error. Code: "%1$s", Message: "%2$s", Data: "%3$s"', 'event_espresso'),
411
-                $response->get_error_code(),
412
-                $response->get_error_message(),
413
-                print_r($response->get_error_data(), true)
414
-            );
415
-        } elseif (is_array($response) && isset($response['body'])) {
416
-            $error_msg = $response['body'];
417
-        } else {
418
-            $error_msg = print_r($response, true);
419
-        }
420
-        $payment->set_gateway_response(
421
-            sprintf(
422
-                esc_html__("IPN Validation failed! Paypal responded with '%s'", "event_espresso"),
423
-                $error_msg
424
-            )
425
-        );
426
-        $payment->set_details(array('REQUEST' => $update_info, 'VALIDATION_RESPONSE' => $response));
427
-        $payment->set_status(EEM_Payment::status_id_failed);
428
-        // log the results
429
-        $this->log(
430
-            array(
431
-                'url'     => $this->_process_response_url(),
432
-                'message' => $payment->gateway_response(),
433
-                'details' => $payment->details(),
434
-            ),
435
-            $payment
436
-        );
437
-        return false;
438
-    }
439
-
440
-
441
-    /**
442
-     * _process_response_url
443
-     * @return string
444
-     */
445
-    protected function _process_response_url(): string
446
-    {
447
-        if (isset($_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'])) {
448
-            $url = is_ssl() ? 'https://' : 'http://';
449
-            $url .= EEH_URL::filter_input_server_url('HTTP_HOST');
450
-            $url .= EEH_URL::filter_input_server_url();
451
-        } else {
452
-            $url = 'unknown';
453
-        }
454
-        return $url;
455
-    }
456
-
457
-
458
-    /**
459
-     * Updates the transaction and line items based on the payment IPN data from PayPal,
460
-     * like the taxes or shipping
461
-     *
462
-     * @param EE_Payment $payment
463
-     * @throws EE_Error
464
-     * @throws ReflectionException
465
-     */
466
-    public function update_txn_based_on_payment($payment)
467
-    {
468
-        $update_info = $payment->details();
469
-        $transaction = $payment->transaction();
470
-        $payment_was_itemized = $payment->get_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true, false);
471
-        if (! $transaction) {
472
-            $this->log(
473
-                esc_html__(
474
-                    // @codingStandardsIgnoreStart
475
-                    'Payment with ID %d has no related transaction, and so update_txn_based_on_payment couldn\'t be executed properly',
476
-                    // @codingStandardsIgnoreEnd
477
-                    'event_espresso'
478
-                ),
479
-                $payment
480
-            );
481
-            return;
482
-        }
483
-        if (
484
-            ! is_array($update_info)
485
-            || ! isset($update_info['mc_shipping'])
486
-            || ! isset($update_info['tax'])
487
-        ) {
488
-            $this->log(
489
-                array(
490
-                    'message' => esc_html__(
491
-                        // @codingStandardsIgnoreStart
492
-                        'Could not update transaction based on payment because the payment details have not yet been put on the payment. This normally happens during the IPN or returning from PayPal',
493
-                        // @codingStandardsIgnoreEnd
494
-                        'event_espresso'
495
-                    ),
496
-                    'url'     => $this->_process_response_url(),
497
-                    'payment' => $payment->model_field_array()
498
-                ),
499
-                $payment
500
-            );
501
-            return;
502
-        }
503
-        if ($payment->status() !== $this->_pay_model->approved_status()) {
504
-            $this->log(
505
-                array(
506
-                    'message' => esc_html__(
507
-                        'We shouldn\'t update transactions taxes or shipping data from non-approved payments',
508
-                        'event_espresso'
509
-                    ),
510
-                    'url'     => $this->_process_response_url(),
511
-                    'payment' => $payment->model_field_array()
512
-                ),
513
-                $payment
514
-            );
515
-            return;
516
-        }
517
-        $grand_total_needs_resaving = false;
518
-        /** @var EE_Line_Item $transaction_total_line_item */
519
-        $transaction_total_line_item = $transaction->total_line_item();
520
-
521
-        // might paypal have changed the taxes?
522
-        if ($this->_paypal_taxes && $payment_was_itemized) {
523
-            // note that we're doing this BEFORE adding shipping;
524
-            // we actually want PayPal's shipping to remain non-taxable
525
-            $this->_line_item->set_line_items_taxable($transaction_total_line_item, true, 'paypal_shipping');
526
-            $this->_line_item->set_total_tax_to(
527
-                $transaction_total_line_item,
528
-                (float) $update_info['tax'],
529
-                esc_html__('Taxes', 'event_espresso'),
530
-                esc_html__('Calculated by Paypal', 'event_espresso'),
531
-                'paypal_tax'
532
-            );
533
-            $grand_total_needs_resaving = true;
534
-        }
535
-
536
-        $shipping_amount = (float) $update_info['mc_shipping'];
537
-        // might paypal have added shipping?
538
-        if ($this->_paypal_shipping && $shipping_amount && $payment_was_itemized) {
539
-            $this->_line_item->add_unrelated_item(
540
-                $transaction_total_line_item,
541
-                sprintf(esc_html__('Shipping for transaction %1$s', 'event_espresso'), $transaction->ID()),
542
-                $shipping_amount,
543
-                esc_html__('Shipping charges calculated by Paypal', 'event_espresso'),
544
-                1,
545
-                false,
546
-                'paypal_shipping_' . $transaction->ID()
547
-            );
548
-            $grand_total_needs_resaving = true;
549
-        }
550
-
551
-        if ($grand_total_needs_resaving) {
552
-            $transaction_total_line_item->save_this_and_descendants_to_txn($transaction->ID());
553
-            /** @var EE_Registration_Processor $registration_processor */
554
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
555
-            $registration_processor->update_registration_final_prices($transaction);
556
-        }
557
-        $this->log(
558
-            array(
559
-                'message'                     => esc_html__('Updated transaction related to payment', 'event_espresso'),
560
-                'url'                         => $this->_process_response_url(),
561
-                'transaction (updated)'       => $transaction->model_field_array(),
562
-                'payment (updated)'           => $payment->model_field_array(),
563
-                'use_paypal_shipping'         => $this->_paypal_shipping,
564
-                'use_paypal_tax'              => $this->_paypal_taxes,
565
-                'grand_total_needed_resaving' => $grand_total_needs_resaving,
566
-            ),
567
-            $payment
568
-        );
569
-    }
22
+	/**
23
+	 * Name for the wp option used to save the itemized payment
24
+	 */
25
+	const itemized_payment_option_name = '_itemized_payment';
26
+
27
+	protected $_paypal_id;
28
+
29
+	protected $_image_url;
30
+
31
+	protected $_shipping_details;
32
+
33
+	protected $_paypal_shipping;
34
+
35
+	protected $_paypal_taxes;
36
+
37
+	protected $_gateway_url;
38
+
39
+	protected $_currencies_supported = array(
40
+		'USD',
41
+		'GBP',
42
+		'CAD',
43
+		'AUD',
44
+		'BRL',
45
+		'CHF',
46
+		'CZK',
47
+		'DKK',
48
+		'EUR',
49
+		'HKD',
50
+		'HUF',
51
+		'ILS',
52
+		'JPY',
53
+		'MXN',
54
+		'MYR',
55
+		'NOK',
56
+		'NZD',
57
+		'PHP',
58
+		'PLN',
59
+		'SEK',
60
+		'SGD',
61
+		'THB',
62
+		'TRY',
63
+		'TWD',
64
+		'RUB'
65
+	);
66
+
67
+	/**
68
+	 * @var ItemizedOrder
69
+	 * @since 5.0.0.p
70
+	 */
71
+	protected $itemized_order;
72
+
73
+
74
+	/**
75
+	 * EEG_Paypal_Standard constructor.
76
+	 */
77
+	public function __construct()
78
+	{
79
+		$this->set_uses_separate_IPN_request(true);
80
+		parent::__construct();
81
+	}
82
+
83
+
84
+	/**
85
+	 * @return mixed
86
+	 */
87
+	public function gatewayUrl()
88
+	{
89
+		return $this->_gateway_url;
90
+	}
91
+
92
+
93
+	/**
94
+	 * @return mixed
95
+	 */
96
+	public function imageUrl()
97
+	{
98
+		return $this->_image_url;
99
+	}
100
+
101
+
102
+	/**
103
+	 * @return mixed
104
+	 */
105
+	public function paypalId()
106
+	{
107
+		return $this->_paypal_id;
108
+	}
109
+
110
+
111
+	/**
112
+	 * @return mixed
113
+	 */
114
+	public function paypalShipping()
115
+	{
116
+		return $this->_paypal_shipping;
117
+	}
118
+
119
+
120
+
121
+	/**
122
+	 * @return mixed
123
+	 */
124
+	public function paypalTaxes()
125
+	{
126
+		return $this->_paypal_taxes;
127
+	}
128
+
129
+
130
+	/**
131
+	 * @return mixed
132
+	 */
133
+	public function shippingDetails()
134
+	{
135
+		return $this->_shipping_details;
136
+	}
137
+
138
+
139
+	/**
140
+	 * Also sets the gateway url class variable based on whether debug mode is enabled or not.
141
+	 *
142
+	 * @param array $settings_array
143
+	 */
144
+	public function set_settings(array $settings_array)
145
+	{
146
+		parent::set_settings($settings_array);
147
+		$this->_gateway_url = $this->_debug_mode
148
+			? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
149
+			: 'https://www.paypal.com/cgi-bin/webscr';
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param EEI_Payment $payment      the payment to process
155
+	 * @param array       $billing_info but should be empty for this gateway
156
+	 * @param string      $return_url   URL to send the user to after payment on the payment provider's website
157
+	 * @param string      $notify_url   URL to send the instant payment notification
158
+	 * @param string      $cancel_url   URL to send the user to after a cancelled payment attempt
159
+	 *                                  on the payment provider's website
160
+	 * @return EEI_Payment
161
+	 * @throws EE_Error
162
+	 * @throws ReflectionException
163
+	 */
164
+	public function set_redirection_info(
165
+		$payment,
166
+		$billing_info = array(),
167
+		$return_url = null,
168
+		$notify_url = null,
169
+		$cancel_url = null
170
+	) {
171
+		$this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter(), $this);
172
+		$redirect_args = apply_filters(
173
+			"FHEE__EEG_Paypal_Standard__set_redirection_info__arguments",
174
+			$this->itemized_order->generateItemizedOrderForPayment(
175
+				$payment,
176
+				$return_url,
177
+				$notify_url,
178
+				$cancel_url
179
+			),
180
+			$this
181
+		);
182
+
183
+		$payment->set_redirect_url($this->_gateway_url);
184
+		$payment->set_redirect_args($redirect_args);
185
+		// log the results
186
+		$this->log(
187
+			[
188
+				'message'     => esc_html__('PayPal payment request initiated.', 'event_espresso'),
189
+				'transaction' => $payment->transaction()->model_field_array(),
190
+			],
191
+			$payment
192
+		);
193
+		return $payment;
194
+	}
195
+
196
+
197
+	/**
198
+	 * Often used for IPNs. But applies the info in $update_info to the payment.
199
+	 * What is $update_info? Often the contents of $_REQUEST, but not necessarily. Whatever
200
+	 * the payment method passes in.
201
+	 *
202
+	 * @param array $update_info like $_POST
203
+	 * @param EE_Transaction $transaction
204
+	 * @return EEI_Payment updated
205
+	 * @throws EE_Error, IpnException
206
+	 */
207
+	public function handle_payment_update($update_info, $transaction)
208
+	{
209
+		// verify there's payment data that's been sent
210
+		if (empty($update_info['payment_status']) || empty($update_info['txn_id'])) {
211
+			// log the results
212
+			$this->log(
213
+				array(
214
+					'message'     => esc_html__(
215
+						'PayPal IPN response is missing critical payment data. This may indicate a PDT request and require your PayPal account settings to be corrected.',
216
+						'event_espresso'
217
+					),
218
+					'update_info' => $update_info,
219
+				),
220
+				$transaction
221
+			);
222
+			// waaaait... is this a PDT request? (see https://developer.paypal.com/docs/classic/products/payment-data-transfer/)
223
+			// indicated by the "tx" argument? If so, we don't need it. We'll just use the IPN data when it comes
224
+			if (isset($update_info['tx'])) {
225
+				return $transaction->last_payment();
226
+			} else {
227
+				return null;
228
+			}
229
+		}
230
+		$payment = $this->_pay_model->get_payment_by_txn_id_chq_nmbr($update_info['txn_id']);
231
+		if (! $payment instanceof EEI_Payment) {
232
+			$payment = $transaction->last_payment();
233
+		}
234
+		// ok, then validate the IPN. Even if we've already processed this payment,
235
+		// let PayPal know we don't want to hear from them anymore!
236
+		if (! $this->validate_ipn($update_info, $payment)) {
237
+			return $payment;
238
+		}
239
+		// kill request here if this is a refund, we don't support them yet (we'd need to adjust the transaction,
240
+		// registrations, ticket counts, etc)
241
+		if (
242
+			(
243
+				$update_info['payment_status'] === 'Refunded'
244
+				|| $update_info['payment_status'] === 'Partially_Refunded'
245
+			)
246
+			&& apply_filters('FHEE__EEG_Paypal_Standard__handle_payment_update__kill_refund_request', true)
247
+		) {
248
+			throw new EventEspresso\core\exceptions\IpnException(
249
+				sprintf(
250
+					esc_html__('Event Espresso does not yet support %1$s IPNs from PayPal', 'event_espresso'),
251
+					$update_info['payment_status']
252
+				),
253
+				EventEspresso\core\exceptions\IpnException::UNSUPPORTED,
254
+				null,
255
+				$payment,
256
+				$update_info
257
+			);
258
+		}
259
+		// ok, well let's process this payment then!
260
+		switch ($update_info['payment_status']) {
261
+			case 'Completed':
262
+				$status = $this->_pay_model->approved_status();
263
+				$gateway_response = esc_html__('The payment is approved.', 'event_espresso');
264
+				break;
265
+
266
+			case 'Pending':
267
+				$status = $this->_pay_model->pending_status();
268
+				$gateway_response = esc_html__(
269
+					'The payment is in progress. Another message will be sent when payment is approved.',
270
+					'event_espresso'
271
+				);
272
+				break;
273
+
274
+			case 'Denied':
275
+				$status = $this->_pay_model->declined_status();
276
+				$gateway_response = esc_html__('The payment has been declined.', 'event_espresso');
277
+				break;
278
+
279
+			case 'Expired':
280
+			case 'Failed':
281
+				$status = $this->_pay_model->failed_status();
282
+				$gateway_response = esc_html__('The payment failed for technical reasons or expired.', 'event_espresso');
283
+				break;
284
+
285
+			case 'Refunded':
286
+			case 'Partially_Refunded':
287
+				// even though it's a refund, we consider the payment as approved, it just has a negative value
288
+				$status = $this->_pay_model->approved_status();
289
+				$gateway_response = esc_html__(
290
+					'The payment has been refunded. Please update registrations accordingly.',
291
+					'event_espresso'
292
+				);
293
+				break;
294
+
295
+			case 'Voided':
296
+			case 'Reversed':
297
+			case 'Canceled_Reversal':
298
+			default:
299
+				$status = $this->_pay_model->cancelled_status();
300
+				$gateway_response = esc_html__(
301
+					'The payment was cancelled, reversed, or voided. Please update registrations accordingly.',
302
+					'event_espresso'
303
+				);
304
+				break;
305
+		}
306
+
307
+		// check if we've already processed this payment
308
+		if ($payment instanceof EEI_Payment) {
309
+			// payment exists. if this has the exact same status and amount, don't bother updating. just return
310
+			if ($payment->status() === $status && $payment->amount() === (float) $update_info['mc_gross']) {
311
+				// DUPLICATED IPN! don't bother updating transaction
312
+				throw new IpnException(
313
+					sprintf(
314
+						esc_html__(
315
+							'It appears we have received a duplicate IPN from PayPal for payment %d',
316
+							'event_espresso'
317
+						),
318
+						$payment->ID()
319
+					),
320
+					IpnException::DUPLICATE,
321
+					null,
322
+					$payment,
323
+					$update_info
324
+				);
325
+			} else {
326
+				// new payment yippee !!!
327
+				$payment->set_status($status);
328
+				$payment->set_amount((float) $update_info['mc_gross']);
329
+				$payment->set_gateway_response($gateway_response);
330
+				$payment->set_details($update_info);
331
+				$payment->set_txn_id_chq_nmbr($update_info['txn_id']);
332
+				$this->log(
333
+					array(
334
+						'message'  => esc_html__(
335
+							'Updated payment either from IPN or as part of POST from PayPal',
336
+							'event_espresso'
337
+						),
338
+						'url'      => $this->_process_response_url(),
339
+						'payment'  => $payment->model_field_array(),
340
+						'IPN_data' => $update_info
341
+					),
342
+					$payment
343
+				);
344
+			}
345
+		}
346
+		do_action('FHEE__EEG_Paypal_Standard__handle_payment_update__payment_processed', $payment, $this);
347
+		return $payment;
348
+	}
349
+
350
+
351
+	/**
352
+	 * Validate the IPN notification.
353
+	 *
354
+	 * @param array                  $update_info like $_REQUEST
355
+	 * @param EE_Payment $payment
356
+	 * @return boolean
357
+	 * @throws EE_Error
358
+	 */
359
+	public function validate_ipn($update_info, $payment)
360
+	{
361
+		// allow us to skip validating IPNs with PayPal (useful for testing)
362
+		if (apply_filters('FHEE__EEG_Paypal_Standard__validate_ipn__skip', false)) {
363
+			return true;
364
+		}
365
+		// ...otherwise, we actually don't care what the $update_info is, we need to look
366
+		// at the request directly because we can't use $update_info because it has issues with quotes
367
+		// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
368
+		// Instead, read raw POST data from the input stream.
369
+		// @see https://gist.github.com/xcommerce-gists/3440401
370
+		$raw_post_data = file_get_contents('php://input');
371
+		$raw_post_array = explode('&', $raw_post_data);
372
+		$update_info = array();
373
+		foreach ($raw_post_array as $keyval) {
374
+			$keyval = explode('=', $keyval);
375
+			if (count($keyval) === 2) {
376
+				$update_info[ $keyval[0] ] = urldecode($keyval[1]);
377
+			}
378
+		}
379
+		// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
380
+		$req = 'cmd=_notify-validate';
381
+		foreach ($update_info as $key => $value) {
382
+			$value = urlencode($value);
383
+			$req .= "&$key=$value";
384
+		}
385
+		// HTTP POST the complete, unaltered IPN back to PayPal
386
+		$response = wp_remote_post(
387
+			$this->_gateway_url,
388
+			array(
389
+				'body'              => $req,
390
+				'sslverify'         => false,
391
+				'timeout'           => 60,
392
+				// make sure to set a site specific unique "user-agent" string since the WordPres default gets declined by PayPal
393
+				// plz see: https://github.com/websharks/s2member/issues/610
394
+				'user-agent'        => 'Event Espresso v' . EVENT_ESPRESSO_VERSION . '; ' . home_url(),
395
+				'httpversion'       => '1.1'
396
+			)
397
+		);
398
+		// then check the response
399
+		if (
400
+			array_key_exists('body', $response)
401
+			&& ! is_wp_error($response)
402
+			&& strcmp($response['body'], "VERIFIED") === 0
403
+		) {
404
+			return true;
405
+		}
406
+		// huh, something's wack... the IPN didn't validate. We must have replied to the IPN incorrectly,
407
+		// or their API must have changed: http://www.paypalobjects.com/en_US/ebook/PP_OrderManagement_IntegrationGuide/ipn.html
408
+		if ($response instanceof WP_Error) {
409
+			$error_msg = sprintf(
410
+				esc_html__('WP Error. Code: "%1$s", Message: "%2$s", Data: "%3$s"', 'event_espresso'),
411
+				$response->get_error_code(),
412
+				$response->get_error_message(),
413
+				print_r($response->get_error_data(), true)
414
+			);
415
+		} elseif (is_array($response) && isset($response['body'])) {
416
+			$error_msg = $response['body'];
417
+		} else {
418
+			$error_msg = print_r($response, true);
419
+		}
420
+		$payment->set_gateway_response(
421
+			sprintf(
422
+				esc_html__("IPN Validation failed! Paypal responded with '%s'", "event_espresso"),
423
+				$error_msg
424
+			)
425
+		);
426
+		$payment->set_details(array('REQUEST' => $update_info, 'VALIDATION_RESPONSE' => $response));
427
+		$payment->set_status(EEM_Payment::status_id_failed);
428
+		// log the results
429
+		$this->log(
430
+			array(
431
+				'url'     => $this->_process_response_url(),
432
+				'message' => $payment->gateway_response(),
433
+				'details' => $payment->details(),
434
+			),
435
+			$payment
436
+		);
437
+		return false;
438
+	}
439
+
440
+
441
+	/**
442
+	 * _process_response_url
443
+	 * @return string
444
+	 */
445
+	protected function _process_response_url(): string
446
+	{
447
+		if (isset($_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'])) {
448
+			$url = is_ssl() ? 'https://' : 'http://';
449
+			$url .= EEH_URL::filter_input_server_url('HTTP_HOST');
450
+			$url .= EEH_URL::filter_input_server_url();
451
+		} else {
452
+			$url = 'unknown';
453
+		}
454
+		return $url;
455
+	}
456
+
457
+
458
+	/**
459
+	 * Updates the transaction and line items based on the payment IPN data from PayPal,
460
+	 * like the taxes or shipping
461
+	 *
462
+	 * @param EE_Payment $payment
463
+	 * @throws EE_Error
464
+	 * @throws ReflectionException
465
+	 */
466
+	public function update_txn_based_on_payment($payment)
467
+	{
468
+		$update_info = $payment->details();
469
+		$transaction = $payment->transaction();
470
+		$payment_was_itemized = $payment->get_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true, false);
471
+		if (! $transaction) {
472
+			$this->log(
473
+				esc_html__(
474
+					// @codingStandardsIgnoreStart
475
+					'Payment with ID %d has no related transaction, and so update_txn_based_on_payment couldn\'t be executed properly',
476
+					// @codingStandardsIgnoreEnd
477
+					'event_espresso'
478
+				),
479
+				$payment
480
+			);
481
+			return;
482
+		}
483
+		if (
484
+			! is_array($update_info)
485
+			|| ! isset($update_info['mc_shipping'])
486
+			|| ! isset($update_info['tax'])
487
+		) {
488
+			$this->log(
489
+				array(
490
+					'message' => esc_html__(
491
+						// @codingStandardsIgnoreStart
492
+						'Could not update transaction based on payment because the payment details have not yet been put on the payment. This normally happens during the IPN or returning from PayPal',
493
+						// @codingStandardsIgnoreEnd
494
+						'event_espresso'
495
+					),
496
+					'url'     => $this->_process_response_url(),
497
+					'payment' => $payment->model_field_array()
498
+				),
499
+				$payment
500
+			);
501
+			return;
502
+		}
503
+		if ($payment->status() !== $this->_pay_model->approved_status()) {
504
+			$this->log(
505
+				array(
506
+					'message' => esc_html__(
507
+						'We shouldn\'t update transactions taxes or shipping data from non-approved payments',
508
+						'event_espresso'
509
+					),
510
+					'url'     => $this->_process_response_url(),
511
+					'payment' => $payment->model_field_array()
512
+				),
513
+				$payment
514
+			);
515
+			return;
516
+		}
517
+		$grand_total_needs_resaving = false;
518
+		/** @var EE_Line_Item $transaction_total_line_item */
519
+		$transaction_total_line_item = $transaction->total_line_item();
520
+
521
+		// might paypal have changed the taxes?
522
+		if ($this->_paypal_taxes && $payment_was_itemized) {
523
+			// note that we're doing this BEFORE adding shipping;
524
+			// we actually want PayPal's shipping to remain non-taxable
525
+			$this->_line_item->set_line_items_taxable($transaction_total_line_item, true, 'paypal_shipping');
526
+			$this->_line_item->set_total_tax_to(
527
+				$transaction_total_line_item,
528
+				(float) $update_info['tax'],
529
+				esc_html__('Taxes', 'event_espresso'),
530
+				esc_html__('Calculated by Paypal', 'event_espresso'),
531
+				'paypal_tax'
532
+			);
533
+			$grand_total_needs_resaving = true;
534
+		}
535
+
536
+		$shipping_amount = (float) $update_info['mc_shipping'];
537
+		// might paypal have added shipping?
538
+		if ($this->_paypal_shipping && $shipping_amount && $payment_was_itemized) {
539
+			$this->_line_item->add_unrelated_item(
540
+				$transaction_total_line_item,
541
+				sprintf(esc_html__('Shipping for transaction %1$s', 'event_espresso'), $transaction->ID()),
542
+				$shipping_amount,
543
+				esc_html__('Shipping charges calculated by Paypal', 'event_espresso'),
544
+				1,
545
+				false,
546
+				'paypal_shipping_' . $transaction->ID()
547
+			);
548
+			$grand_total_needs_resaving = true;
549
+		}
550
+
551
+		if ($grand_total_needs_resaving) {
552
+			$transaction_total_line_item->save_this_and_descendants_to_txn($transaction->ID());
553
+			/** @var EE_Registration_Processor $registration_processor */
554
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
555
+			$registration_processor->update_registration_final_prices($transaction);
556
+		}
557
+		$this->log(
558
+			array(
559
+				'message'                     => esc_html__('Updated transaction related to payment', 'event_espresso'),
560
+				'url'                         => $this->_process_response_url(),
561
+				'transaction (updated)'       => $transaction->model_field_array(),
562
+				'payment (updated)'           => $payment->model_field_array(),
563
+				'use_paypal_shipping'         => $this->_paypal_shipping,
564
+				'use_paypal_tax'              => $this->_paypal_taxes,
565
+				'grand_total_needed_resaving' => $grand_total_needs_resaving,
566
+			),
567
+			$payment
568
+		);
569
+	}
570 570
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -37,120 +37,120 @@
 block discarded – undo
37 37
  * @since           4.0
38 38
  */
39 39
 if (function_exists('espresso_version')) {
40
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
-        /**
42
-         *    espresso_duplicate_plugin_error
43
-         *    displays if more than one version of EE is activated at the same time.
44
-         */
45
-        function espresso_duplicate_plugin_error()
46
-        {
47
-            ?>
40
+	if (! function_exists('espresso_duplicate_plugin_error')) {
41
+		/**
42
+		 *    espresso_duplicate_plugin_error
43
+		 *    displays if more than one version of EE is activated at the same time.
44
+		 */
45
+		function espresso_duplicate_plugin_error()
46
+		{
47
+			?>
48 48
             <div class="error">
49 49
                 <p>
50 50
                     <?php
51
-                    echo esc_html__(
52
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
-                        'event_espresso'
54
-                    ); ?>
51
+					echo esc_html__(
52
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
+						'event_espresso'
54
+					); ?>
55 55
                 </p>
56 56
             </div>
57 57
             <?php
58
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
59
-        }
60
-    }
61
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
58
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
59
+		}
60
+	}
61
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62 62
 } else {
63
-    define('EE_MIN_PHP_VER_REQUIRED', '7.4.0');
64
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
-        /**
66
-         * espresso_minimum_php_version_error
67
-         *
68
-         * @return void
69
-         */
70
-        function espresso_minimum_php_version_error()
71
-        {
72
-            ?>
63
+	define('EE_MIN_PHP_VER_REQUIRED', '7.4.0');
64
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
+		/**
66
+		 * espresso_minimum_php_version_error
67
+		 *
68
+		 * @return void
69
+		 */
70
+		function espresso_minimum_php_version_error()
71
+		{
72
+			?>
73 73
             <div class="error">
74 74
                 <p>
75 75
                     <?php
76
-                    printf(
77
-                        esc_html__(
78
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
-                            'event_espresso'
80
-                        ),
81
-                        EE_MIN_PHP_VER_REQUIRED,
82
-                        PHP_VERSION,
83
-                        '<br/>',
84
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
-                    );
86
-                    ?>
76
+					printf(
77
+						esc_html__(
78
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
+							'event_espresso'
80
+						),
81
+						EE_MIN_PHP_VER_REQUIRED,
82
+						PHP_VERSION,
83
+						'<br/>',
84
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
+					);
86
+					?>
87 87
                 </p>
88 88
             </div>
89 89
             <?php
90
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
91
-        }
90
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
91
+		}
92 92
 
93
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
-    } else {
95
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
93
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
+	} else {
95
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
96 96
 
97
-        require_once __DIR__ . '/vendor/autoload.php';
98
-        require_once __DIR__ . '/vendor/wp-graphql/wp-graphql/wp-graphql.php';
97
+		require_once __DIR__ . '/vendor/autoload.php';
98
+		require_once __DIR__ . '/vendor/wp-graphql/wp-graphql/wp-graphql.php';
99 99
 
100
-        /**
101
-         * espresso_version
102
-         * Returns the plugin version
103
-         *
104
-         * @return string
105
-         */
106
-        function espresso_version()
107
-        {
108
-            return apply_filters('FHEE__espresso__espresso_version', '5.0.1.rc.000');
109
-        }
100
+		/**
101
+		 * espresso_version
102
+		 * Returns the plugin version
103
+		 *
104
+		 * @return string
105
+		 */
106
+		function espresso_version()
107
+		{
108
+			return apply_filters('FHEE__espresso__espresso_version', '5.0.1.rc.000');
109
+		}
110 110
 
111
-        /**
112
-         * espresso_plugin_activation
113
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
114
-         */
115
-        function espresso_plugin_activation()
116
-        {
117
-            update_option('ee_espresso_activation', true);
118
-            // Run WP GraphQL activation callback
119
-            graphql_activation_callback();
120
-        }
111
+		/**
112
+		 * espresso_plugin_activation
113
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
114
+		 */
115
+		function espresso_plugin_activation()
116
+		{
117
+			update_option('ee_espresso_activation', true);
118
+			// Run WP GraphQL activation callback
119
+			graphql_activation_callback();
120
+		}
121 121
 
122
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
122
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
123 123
 
124
-        /**
125
-         * espresso_plugin_deactivation
126
-         */
127
-        function espresso_plugin_deactivation()
128
-        {
129
-            // Run WP GraphQL deactivation callback
130
-            graphql_deactivation_callback();
131
-        }
132
-        register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
124
+		/**
125
+		 * espresso_plugin_deactivation
126
+		 */
127
+		function espresso_plugin_deactivation()
128
+		{
129
+			// Run WP GraphQL deactivation callback
130
+			graphql_deactivation_callback();
131
+		}
132
+		register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
133 133
 
134
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
135
-        bootstrap_espresso();
136
-    }
134
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
135
+		bootstrap_espresso();
136
+	}
137 137
 }
138 138
 
139 139
 if (! function_exists('espresso_deactivate_plugin')) {
140
-    /**
141
-     *    deactivate_plugin
142
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
143
-     *
144
-     * @access public
145
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
146
-     * @return    void
147
-     */
148
-    function espresso_deactivate_plugin($plugin_basename = '')
149
-    {
150
-        if (! function_exists('deactivate_plugins')) {
151
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
152
-        }
153
-        unset($_GET['activate'], $_REQUEST['activate']);
154
-        deactivate_plugins($plugin_basename);
155
-    }
140
+	/**
141
+	 *    deactivate_plugin
142
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
143
+	 *
144
+	 * @access public
145
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
146
+	 * @return    void
147
+	 */
148
+	function espresso_deactivate_plugin($plugin_basename = '')
149
+	{
150
+		if (! function_exists('deactivate_plugins')) {
151
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
152
+		}
153
+		unset($_GET['activate'], $_REQUEST['activate']);
154
+		deactivate_plugins($plugin_basename);
155
+	}
156 156
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Form_Fields.helper.php 1 patch
Indentation   +2065 added lines, -2065 removed lines patch added patch discarded remove patch
@@ -27,1058 +27,1058 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class EEH_Form_Fields
29 29
 {
30
-    /**
31
-     *  Generates HTML for the forms used on admin pages
32
-     *
33
-     *
34
-     * @static
35
-     * @access public
36
-     * @param array $input_vars - array of input field details
37
-     *                          format:
38
-     *                          $template_form_fields['field-id'] = array(
39
-     *                          'name' => 'name_attribute',
40
-     *                          'label' => esc_html__('Field Label', 'event_espresso'), //or false
41
-     *                          'input' => 'hidden', //field input type can be 'text', 'select', 'textarea', 'hidden',
42
-     *                          'checkbox', 'wp_editor'
43
-     *                          'type' => 'int', //what "type" the value is (i.e. string, int etc)
44
-     *                          'required' => false, //boolean for whether the field is required
45
-     *                          'validation' => true, //boolean, whether to validate the field (todo)
46
-     *                          'value' => 'some_value_for_field', //what value is used for field
47
-     *                          'format' => '%d', //what format the value is (%d, %f, or %s)
48
-     *                          'db-col' => 'column_in_db' //used to indicate which column the field corresponds with
49
-     *                          in the db
50
-     *                          'options' => optiona, optionb || array('value' => 'label', '') //if the input type is
51
-     *                          "select", this allows you to set the args for the different <option> tags.
52
-     *                          'tabindex' => 1 //this allows you to set the tabindex for the field.
53
-     *                          'append_content' => '' //this allows you to send in html content to append to the
54
-     *                          field.
55
-     *                          )
56
-     * @param array $form_id    - used for defining unique identifiers for the form.
57
-     * @return string
58
-     * @todo   : at some point we can break this down into other static methods to abstract it a bit better.
59
-     */
60
-    public static function get_form_fields($input_vars = [], $form_id = false)
61
-    {
62
-
63
-        if (empty($input_vars)) {
64
-            EE_Error::add_error(
65
-                esc_html__('missing required variables for the form field generator', 'event_espresso'),
66
-                __FILE__,
67
-                __FUNCTION__,
68
-                __LINE__
69
-            );
70
-            return false;
71
-        }
72
-
73
-        $output        = "";
74
-        $inputs        = [];
75
-        $hidden_inputs = [];
76
-
77
-        // cycle thru inputs
78
-        foreach ($input_vars as $input_key => $input_value) {
79
-            $defaults = [
80
-                'append_content' => '',
81
-                'css_class'      => '',
82
-                'cols'           => 80,
83
-                'db-col'         => 'column_in_db',
84
-                'format'         => '%d',
85
-                'input'          => 'hidden',
86
-                'label'          => esc_html__('No label', 'event_espresso'),
87
-                'name'           => $input_key,
88
-                'options'        => [],
89
-                'required'       => false,
90
-                'tabindex'       => 0,
91
-                'rows'           => 10,
92
-                'type'           => 'int',
93
-                'validation'     => true,
94
-                'value'          => 'some_value_for_field',
95
-            ];
96
-
97
-            $input_value = wp_parse_args($input_value, $defaults);
98
-
99
-            $append_content = $input_value['append_content'];
100
-            $css_class      = $input_value['css_class'];
101
-            $cols           = $input_value['cols'];
102
-            $label          = $input_value['label'];
103
-            $name           = $input_value['name'];
104
-            $options        = $input_value['options'];
105
-            $required       = $input_value['required'];
106
-            $tab_index      = $input_value['tabindex'];
107
-            $rows           = $input_value['rows'];
108
-            $type           = $input_value['input'];
109
-            $value          = $input_value['value'];
110
-
111
-            $id    = $form_id ? $form_id . '-' . $input_key : $input_key;
112
-            $class = $required ? 'required ' . $css_class : $css_class;
113
-
114
-            // what type of input are we dealing with ?
115
-            switch ($type) {
116
-                case 'checkbox':
117
-                case 'radio':
118
-                    $field = self::adminMulti($value, $class, $id, $name, $required, $tab_index, $type, 1, $label);
119
-                    $field .= $append_content ?: '';
120
-                    break;
121
-
122
-                case 'hidden':
123
-                    $field           = null;
124
-                    $hidden_inputs[] = self::adminHidden($css_class, $id, $name, $value);
125
-                    break;
126
-
127
-                case 'select':
128
-                    $options = is_array($options) ? $options : explode(',', $options);
129
-                    $field   = self::adminLabel($id, $label, $required);
130
-                    $field   .= self::adminSelect($value, $class, $id, $name, $required, $tab_index, $options);
131
-                    $field   .= $append_content ?: '';
132
-                    break;
133
-
134
-                case 'textarea':
135
-                    $field = self::adminLabel($id, $label, $required);
136
-                    $field .= self::adminTextarea($class, $cols, $id, $name, $required, $rows, $tab_index, $value);
137
-                    $field .= $append_content ?: '';
138
-                    break;
139
-
140
-                case 'wp_editor':
141
-                    $label = esc_html($label);
142
-                    $field = "<h4>{$label}</h4>";
143
-                    $field .= $append_content ?: '';
144
-                    $field .= self::adminWpEditor(
145
-                        $class,
146
-                        $id,
147
-                        $name,
148
-                        $rows,
149
-                        $tab_index,
150
-                        $value
151
-                    );
152
-                    break;
153
-
154
-                default:
155
-                    $field = self::adminLabel($id, $label, $required);
156
-                    $field .= self::adminText($class, $id, $name, $required, $tab_index, $value);
157
-                    $field .= $append_content ?: '';
158
-            }
159
-            if ($field) {
160
-                $inputs[] = $field;
161
-            }
162
-        } // end foreach( $input_vars as $input_key => $input_value )
163
-
164
-        if (! empty($inputs)) {
165
-            $glue   = "
30
+	/**
31
+	 *  Generates HTML for the forms used on admin pages
32
+	 *
33
+	 *
34
+	 * @static
35
+	 * @access public
36
+	 * @param array $input_vars - array of input field details
37
+	 *                          format:
38
+	 *                          $template_form_fields['field-id'] = array(
39
+	 *                          'name' => 'name_attribute',
40
+	 *                          'label' => esc_html__('Field Label', 'event_espresso'), //or false
41
+	 *                          'input' => 'hidden', //field input type can be 'text', 'select', 'textarea', 'hidden',
42
+	 *                          'checkbox', 'wp_editor'
43
+	 *                          'type' => 'int', //what "type" the value is (i.e. string, int etc)
44
+	 *                          'required' => false, //boolean for whether the field is required
45
+	 *                          'validation' => true, //boolean, whether to validate the field (todo)
46
+	 *                          'value' => 'some_value_for_field', //what value is used for field
47
+	 *                          'format' => '%d', //what format the value is (%d, %f, or %s)
48
+	 *                          'db-col' => 'column_in_db' //used to indicate which column the field corresponds with
49
+	 *                          in the db
50
+	 *                          'options' => optiona, optionb || array('value' => 'label', '') //if the input type is
51
+	 *                          "select", this allows you to set the args for the different <option> tags.
52
+	 *                          'tabindex' => 1 //this allows you to set the tabindex for the field.
53
+	 *                          'append_content' => '' //this allows you to send in html content to append to the
54
+	 *                          field.
55
+	 *                          )
56
+	 * @param array $form_id    - used for defining unique identifiers for the form.
57
+	 * @return string
58
+	 * @todo   : at some point we can break this down into other static methods to abstract it a bit better.
59
+	 */
60
+	public static function get_form_fields($input_vars = [], $form_id = false)
61
+	{
62
+
63
+		if (empty($input_vars)) {
64
+			EE_Error::add_error(
65
+				esc_html__('missing required variables for the form field generator', 'event_espresso'),
66
+				__FILE__,
67
+				__FUNCTION__,
68
+				__LINE__
69
+			);
70
+			return false;
71
+		}
72
+
73
+		$output        = "";
74
+		$inputs        = [];
75
+		$hidden_inputs = [];
76
+
77
+		// cycle thru inputs
78
+		foreach ($input_vars as $input_key => $input_value) {
79
+			$defaults = [
80
+				'append_content' => '',
81
+				'css_class'      => '',
82
+				'cols'           => 80,
83
+				'db-col'         => 'column_in_db',
84
+				'format'         => '%d',
85
+				'input'          => 'hidden',
86
+				'label'          => esc_html__('No label', 'event_espresso'),
87
+				'name'           => $input_key,
88
+				'options'        => [],
89
+				'required'       => false,
90
+				'tabindex'       => 0,
91
+				'rows'           => 10,
92
+				'type'           => 'int',
93
+				'validation'     => true,
94
+				'value'          => 'some_value_for_field',
95
+			];
96
+
97
+			$input_value = wp_parse_args($input_value, $defaults);
98
+
99
+			$append_content = $input_value['append_content'];
100
+			$css_class      = $input_value['css_class'];
101
+			$cols           = $input_value['cols'];
102
+			$label          = $input_value['label'];
103
+			$name           = $input_value['name'];
104
+			$options        = $input_value['options'];
105
+			$required       = $input_value['required'];
106
+			$tab_index      = $input_value['tabindex'];
107
+			$rows           = $input_value['rows'];
108
+			$type           = $input_value['input'];
109
+			$value          = $input_value['value'];
110
+
111
+			$id    = $form_id ? $form_id . '-' . $input_key : $input_key;
112
+			$class = $required ? 'required ' . $css_class : $css_class;
113
+
114
+			// what type of input are we dealing with ?
115
+			switch ($type) {
116
+				case 'checkbox':
117
+				case 'radio':
118
+					$field = self::adminMulti($value, $class, $id, $name, $required, $tab_index, $type, 1, $label);
119
+					$field .= $append_content ?: '';
120
+					break;
121
+
122
+				case 'hidden':
123
+					$field           = null;
124
+					$hidden_inputs[] = self::adminHidden($css_class, $id, $name, $value);
125
+					break;
126
+
127
+				case 'select':
128
+					$options = is_array($options) ? $options : explode(',', $options);
129
+					$field   = self::adminLabel($id, $label, $required);
130
+					$field   .= self::adminSelect($value, $class, $id, $name, $required, $tab_index, $options);
131
+					$field   .= $append_content ?: '';
132
+					break;
133
+
134
+				case 'textarea':
135
+					$field = self::adminLabel($id, $label, $required);
136
+					$field .= self::adminTextarea($class, $cols, $id, $name, $required, $rows, $tab_index, $value);
137
+					$field .= $append_content ?: '';
138
+					break;
139
+
140
+				case 'wp_editor':
141
+					$label = esc_html($label);
142
+					$field = "<h4>{$label}</h4>";
143
+					$field .= $append_content ?: '';
144
+					$field .= self::adminWpEditor(
145
+						$class,
146
+						$id,
147
+						$name,
148
+						$rows,
149
+						$tab_index,
150
+						$value
151
+					);
152
+					break;
153
+
154
+				default:
155
+					$field = self::adminLabel($id, $label, $required);
156
+					$field .= self::adminText($class, $id, $name, $required, $tab_index, $value);
157
+					$field .= $append_content ?: '';
158
+			}
159
+			if ($field) {
160
+				$inputs[] = $field;
161
+			}
162
+		} // end foreach( $input_vars as $input_key => $input_value )
163
+
164
+		if (! empty($inputs)) {
165
+			$glue   = "
166 166
                 </li>
167 167
                 <li>
168 168
                     ";
169
-            $inputs = implode($glue, $inputs);
170
-            $output = "
169
+			$inputs = implode($glue, $inputs);
170
+			$output = "
171 171
             <ul>
172 172
                 <li>
173 173
                 {$inputs}
174 174
                 </li>
175 175
             </ul>
176 176
             ";
177
-        }
178
-        return $output . implode("\n", $hidden_inputs);
179
-    }
180
-
181
-
182
-    /**
183
-     * form_fields_array
184
-     * This utility function assembles form fields from a given structured array with field information.
185
-     * //TODO: This is an alternate generator that we may want to use instead.
186
-     *
187
-     * @param array $fields structured array of fields to assemble in the following format:
188
-     *                      [field_name] => array(
189
-     *                      ['label'] => 'label for field',
190
-     *                      ['labels'] => array('label_1', 'label_2'); //optional - if the field type is a multi select
191
-     *                      type of field you can indicated the labels for each option via this index
192
-     *                      ['extra_desc'] => 'extra description for the field', //optional
193
-     *                      ['type'] => 'textarea'|'text'|'wp_editor'|'checkbox'|'radio'|'hidden'|'select', //defaults
194
-     *                      to text
195
-     *                      ['value'] => 'value that goes in the field', //(if multi then this is an array of values
196
-     *                      and the 'default' paramater will be used for what is selected)
197
-     *                      ['default'] => 'default if the field type is multi (i.e. select or radios or checkboxes)',
198
-     *                      ['class'] => 'name-of-class(es)-for-input',
199
-     *                      ['classes'] => array('class_1', 'class_2'); //optional - if the field type is a multi
200
-     *                      select type of field you can indicate the css class for each option via this index.
201
-     *                      ['id'] => 'css-id-for-input') //defaults to 'field_name'
202
-     *                      ['unique_id'] => 1 //defaults to empty string.  This is useful for when the fields
203
-     *                      generated are going to be used in a loop and you want to make sure that the field
204
-     *                      identifiers are unique from each other.
205
-     *                      ['dimensions'] => array(100,300), //defaults to empty array.  This is used by field types
206
-     *                      such as textarea to indicate cols/rows.
207
-     *                      ['tabindex'] => '' //this allows you to set the tabindex for the field.
208
-     *                      ['wpeditor_args'] => array() //if the type of field is wpeditor then this can optionally
209
-     *                      contain an array of arguments for the editor setup.
210
-     *
211
-     * @return array         an array of inputs for form indexed by field name, and in the following structure:
212
-     *     [field_name] => array( 'label' => '{label_html}', 'field' => '{input_html}'
213
-     */
214
-    public static function get_form_fields_array($fields)
215
-    {
216
-
217
-        $form_fields = [];
218
-        $fields      = (array) $fields;
219
-
220
-        foreach ($fields as $field_name => $field_atts) {
221
-            // defaults:
222
-            $defaults = [
223
-                'class'         => '',
224
-                'classes'       => '',
225
-                'default'       => '',
226
-                'dimensions'    => ['10', '5'],
227
-                'extra_desc'    => '',
228
-                'id'            => $field_name,
229
-                'label'         => '',
230
-                'labels'        => '',
231
-                'required'      => false,
232
-                'tabindex'      => 0,
233
-                'type'          => 'text',
234
-                'unique_id'     => '',
235
-                'value'         => '',
236
-                'wpeditor_args' => [],
237
-            ];
238
-            // merge defaults with passed arguments
239
-            $_fields = wp_parse_args($field_atts, $defaults);
240
-
241
-            $class          = $_fields['class'];
242
-            $classes        = $_fields['classes'];
243
-            $default        = $_fields['default'];
244
-            $dims           = $_fields['dimensions'];
245
-            $extra_desc     = $_fields['extra_desc'];
246
-            $id             = $_fields['id'];
247
-            $label          = $_fields['label'];
248
-            $labels         = $_fields['labels'];
249
-            $required       = $_fields['required'];
250
-            $tab_index      = $_fields['tabindex'];
251
-            $type           = $_fields['type'];
252
-            $unique_id      = $_fields['unique_id'];
253
-            $value          = $_fields['value'];
254
-            $wp_editor_args = $_fields['wpeditor_args'];
255
-
256
-            // generate label
257
-            $label = ! empty($label) ? self::adminLabel($id, $label, $required) : '';
258
-            // generate field name
259
-            $name = ! empty($unique_id) ? $field_name . '[' . $unique_id . ']' : $field_name;
260
-
261
-            // we determine what we're building based on the type
262
-            switch ($type) {
263
-                case 'checkbox':
264
-                case 'radio':
265
-                    if (is_array($value)) {
266
-                        $c_input = '';
267
-                        foreach ($value as $key => $val) {
268
-                            $c_input .= self::adminMulti(
269
-                                $default,
270
-                                isset($classes[ $key ]) ? $classes[ $key ] : '',
271
-                                $field_name . '_' . $value,
272
-                                $name,
273
-                                $required,
274
-                                $tab_index,
275
-                                $type,
276
-                                $val,
277
-                                isset($labels[ $key ]) ? $labels[ $key ] : ''
278
-                            );
279
-                        }
280
-                        $field = $c_input;
281
-                    } else {
282
-                        $field = self::adminMulti(
283
-                            $default,
284
-                            $class,
285
-                            $id,
286
-                            $name,
287
-                            $required,
288
-                            $tab_index,
289
-                            $type,
290
-                            $value,
291
-                            $_fields['label']
292
-                        );
293
-                    }
294
-                    break;
295
-
296
-                case 'hidden':
297
-                    $field = self::adminHidden($class, $id, $name, $value);
298
-                    break;
299
-
300
-                case 'select':
301
-                    $options = [];
302
-                    foreach ($value as $key => $val) {
303
-                        $options[ $val ] = isset($labels[ $key ]) ? $labels[ $key ] : '';
304
-                    }
305
-                    $field = self::adminSelect($default, $class, $id, $name, $required, $tab_index, $options);
306
-                    break;
307
-
308
-                case 'textarea':
309
-                    $field =
310
-                        self::adminTextarea($class, $dims[0], $id, $name, $required, $dims[1], $tab_index, $value);
311
-                    break;
312
-
313
-                case 'wp_editor':
314
-                    $field = self::adminWpEditor(
315
-                        $class,
316
-                        $_fields['id'],
317
-                        $name,
318
-                        $dims[1],
319
-                        $tab_index,
320
-                        $value,
321
-                        $wp_editor_args
322
-                    );
323
-                    break;
324
-
325
-                default:
326
-                    $field = self::adminText($class, $id, $name, $required, $tab_index, $value);
327
-            }
328
-
329
-            $form_fields[ $field_name ] = ['label' => $label, 'field' => $field . $extra_desc];
330
-        }
331
-
332
-        return $form_fields;
333
-    }
334
-
335
-
336
-    /**
337
-     * @param string $class
338
-     * @param string $id
339
-     * @param string $name
340
-     * @param string $value
341
-     * @return string
342
-     * @since   4.10.14.p
343
-     */
344
-    private static function adminHidden($class, $id, $name, $value)
345
-    {
346
-        $id    = esc_attr($id);
347
-        $name  = esc_attr($name);
348
-        $class = esc_attr($class);
349
-        return "
177
+		}
178
+		return $output . implode("\n", $hidden_inputs);
179
+	}
180
+
181
+
182
+	/**
183
+	 * form_fields_array
184
+	 * This utility function assembles form fields from a given structured array with field information.
185
+	 * //TODO: This is an alternate generator that we may want to use instead.
186
+	 *
187
+	 * @param array $fields structured array of fields to assemble in the following format:
188
+	 *                      [field_name] => array(
189
+	 *                      ['label'] => 'label for field',
190
+	 *                      ['labels'] => array('label_1', 'label_2'); //optional - if the field type is a multi select
191
+	 *                      type of field you can indicated the labels for each option via this index
192
+	 *                      ['extra_desc'] => 'extra description for the field', //optional
193
+	 *                      ['type'] => 'textarea'|'text'|'wp_editor'|'checkbox'|'radio'|'hidden'|'select', //defaults
194
+	 *                      to text
195
+	 *                      ['value'] => 'value that goes in the field', //(if multi then this is an array of values
196
+	 *                      and the 'default' paramater will be used for what is selected)
197
+	 *                      ['default'] => 'default if the field type is multi (i.e. select or radios or checkboxes)',
198
+	 *                      ['class'] => 'name-of-class(es)-for-input',
199
+	 *                      ['classes'] => array('class_1', 'class_2'); //optional - if the field type is a multi
200
+	 *                      select type of field you can indicate the css class for each option via this index.
201
+	 *                      ['id'] => 'css-id-for-input') //defaults to 'field_name'
202
+	 *                      ['unique_id'] => 1 //defaults to empty string.  This is useful for when the fields
203
+	 *                      generated are going to be used in a loop and you want to make sure that the field
204
+	 *                      identifiers are unique from each other.
205
+	 *                      ['dimensions'] => array(100,300), //defaults to empty array.  This is used by field types
206
+	 *                      such as textarea to indicate cols/rows.
207
+	 *                      ['tabindex'] => '' //this allows you to set the tabindex for the field.
208
+	 *                      ['wpeditor_args'] => array() //if the type of field is wpeditor then this can optionally
209
+	 *                      contain an array of arguments for the editor setup.
210
+	 *
211
+	 * @return array         an array of inputs for form indexed by field name, and in the following structure:
212
+	 *     [field_name] => array( 'label' => '{label_html}', 'field' => '{input_html}'
213
+	 */
214
+	public static function get_form_fields_array($fields)
215
+	{
216
+
217
+		$form_fields = [];
218
+		$fields      = (array) $fields;
219
+
220
+		foreach ($fields as $field_name => $field_atts) {
221
+			// defaults:
222
+			$defaults = [
223
+				'class'         => '',
224
+				'classes'       => '',
225
+				'default'       => '',
226
+				'dimensions'    => ['10', '5'],
227
+				'extra_desc'    => '',
228
+				'id'            => $field_name,
229
+				'label'         => '',
230
+				'labels'        => '',
231
+				'required'      => false,
232
+				'tabindex'      => 0,
233
+				'type'          => 'text',
234
+				'unique_id'     => '',
235
+				'value'         => '',
236
+				'wpeditor_args' => [],
237
+			];
238
+			// merge defaults with passed arguments
239
+			$_fields = wp_parse_args($field_atts, $defaults);
240
+
241
+			$class          = $_fields['class'];
242
+			$classes        = $_fields['classes'];
243
+			$default        = $_fields['default'];
244
+			$dims           = $_fields['dimensions'];
245
+			$extra_desc     = $_fields['extra_desc'];
246
+			$id             = $_fields['id'];
247
+			$label          = $_fields['label'];
248
+			$labels         = $_fields['labels'];
249
+			$required       = $_fields['required'];
250
+			$tab_index      = $_fields['tabindex'];
251
+			$type           = $_fields['type'];
252
+			$unique_id      = $_fields['unique_id'];
253
+			$value          = $_fields['value'];
254
+			$wp_editor_args = $_fields['wpeditor_args'];
255
+
256
+			// generate label
257
+			$label = ! empty($label) ? self::adminLabel($id, $label, $required) : '';
258
+			// generate field name
259
+			$name = ! empty($unique_id) ? $field_name . '[' . $unique_id . ']' : $field_name;
260
+
261
+			// we determine what we're building based on the type
262
+			switch ($type) {
263
+				case 'checkbox':
264
+				case 'radio':
265
+					if (is_array($value)) {
266
+						$c_input = '';
267
+						foreach ($value as $key => $val) {
268
+							$c_input .= self::adminMulti(
269
+								$default,
270
+								isset($classes[ $key ]) ? $classes[ $key ] : '',
271
+								$field_name . '_' . $value,
272
+								$name,
273
+								$required,
274
+								$tab_index,
275
+								$type,
276
+								$val,
277
+								isset($labels[ $key ]) ? $labels[ $key ] : ''
278
+							);
279
+						}
280
+						$field = $c_input;
281
+					} else {
282
+						$field = self::adminMulti(
283
+							$default,
284
+							$class,
285
+							$id,
286
+							$name,
287
+							$required,
288
+							$tab_index,
289
+							$type,
290
+							$value,
291
+							$_fields['label']
292
+						);
293
+					}
294
+					break;
295
+
296
+				case 'hidden':
297
+					$field = self::adminHidden($class, $id, $name, $value);
298
+					break;
299
+
300
+				case 'select':
301
+					$options = [];
302
+					foreach ($value as $key => $val) {
303
+						$options[ $val ] = isset($labels[ $key ]) ? $labels[ $key ] : '';
304
+					}
305
+					$field = self::adminSelect($default, $class, $id, $name, $required, $tab_index, $options);
306
+					break;
307
+
308
+				case 'textarea':
309
+					$field =
310
+						self::adminTextarea($class, $dims[0], $id, $name, $required, $dims[1], $tab_index, $value);
311
+					break;
312
+
313
+				case 'wp_editor':
314
+					$field = self::adminWpEditor(
315
+						$class,
316
+						$_fields['id'],
317
+						$name,
318
+						$dims[1],
319
+						$tab_index,
320
+						$value,
321
+						$wp_editor_args
322
+					);
323
+					break;
324
+
325
+				default:
326
+					$field = self::adminText($class, $id, $name, $required, $tab_index, $value);
327
+			}
328
+
329
+			$form_fields[ $field_name ] = ['label' => $label, 'field' => $field . $extra_desc];
330
+		}
331
+
332
+		return $form_fields;
333
+	}
334
+
335
+
336
+	/**
337
+	 * @param string $class
338
+	 * @param string $id
339
+	 * @param string $name
340
+	 * @param string $value
341
+	 * @return string
342
+	 * @since   4.10.14.p
343
+	 */
344
+	private static function adminHidden($class, $id, $name, $value)
345
+	{
346
+		$id    = esc_attr($id);
347
+		$name  = esc_attr($name);
348
+		$class = esc_attr($class);
349
+		return "
350 350
         <input name='{$name}' type='hidden' id='{$id}' class='{$class}' value='{$value}' />";
351
-    }
352
-
353
-
354
-    /**
355
-     * @param string $id
356
-     * @param string $label
357
-     * @param string $required
358
-     * @return string
359
-     * @since   4.10.14.p
360
-     */
361
-    private static function adminLabel($id, $label, $required)
362
-    {
363
-        $id       = esc_attr($id);
364
-        $label    = esc_html($label);
365
-        $required = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? " <span>*</span>" : '';
366
-        return "<label for='{$id}'>{$label}{$required}</label>";
367
-    }
368
-
369
-
370
-    /**
371
-     * @param string $default
372
-     * @param string $class
373
-     * @param string $id
374
-     * @param string $name
375
-     * @param string $required
376
-     * @param int    $tab_index
377
-     * @param string $type
378
-     * @param string $value
379
-     * @param string $label
380
-     * @return string
381
-     * @since   4.10.14.p
382
-     */
383
-    private static function adminMulti($default, $class, $id, $name, $required, $tab_index, $type, $value, $label = '')
384
-    {
385
-        $id        = esc_attr($id);
386
-        $name      = esc_attr($name);
387
-        $class     = esc_attr($class);
388
-        $tab_index = absint($tab_index);
389
-        $checked   = ! empty($default) && $default == $value ? 'checked ' : '';
390
-        $required  = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
391
-        $input     = "
351
+	}
352
+
353
+
354
+	/**
355
+	 * @param string $id
356
+	 * @param string $label
357
+	 * @param string $required
358
+	 * @return string
359
+	 * @since   4.10.14.p
360
+	 */
361
+	private static function adminLabel($id, $label, $required)
362
+	{
363
+		$id       = esc_attr($id);
364
+		$label    = esc_html($label);
365
+		$required = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? " <span>*</span>" : '';
366
+		return "<label for='{$id}'>{$label}{$required}</label>";
367
+	}
368
+
369
+
370
+	/**
371
+	 * @param string $default
372
+	 * @param string $class
373
+	 * @param string $id
374
+	 * @param string $name
375
+	 * @param string $required
376
+	 * @param int    $tab_index
377
+	 * @param string $type
378
+	 * @param string $value
379
+	 * @param string $label
380
+	 * @return string
381
+	 * @since   4.10.14.p
382
+	 */
383
+	private static function adminMulti($default, $class, $id, $name, $required, $tab_index, $type, $value, $label = '')
384
+	{
385
+		$id        = esc_attr($id);
386
+		$name      = esc_attr($name);
387
+		$class     = esc_attr($class);
388
+		$tab_index = absint($tab_index);
389
+		$checked   = ! empty($default) && $default == $value ? 'checked ' : '';
390
+		$required  = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
391
+		$input     = "
392 392
         <input name='{$name}[]' type='{$type}' id='{$id}' class='{$class}' value='{$value}' {$checked} {$required} tabindex='{$tab_index}'/>";
393
-        if ($label === '') {
394
-            return $input;
395
-        }
396
-        $label = esc_html($label);
397
-        $label_class = self::appendInputSizeClass('', $label);
398
-        $label_class = $label_class ? ' class="' . $label_class . '"' : '';
399
-        return "
393
+		if ($label === '') {
394
+			return $input;
395
+		}
396
+		$label = esc_html($label);
397
+		$label_class = self::appendInputSizeClass('', $label);
398
+		$label_class = $label_class ? ' class="' . $label_class . '"' : '';
399
+		return "
400 400
         <label for='$id'{$label_class}>
401 401
             {$input}
402 402
             {$label}
403 403
         </label>";
404
-    }
405
-
406
-
407
-    /**
408
-     * @param string $default
409
-     * @param string $class
410
-     * @param string $id
411
-     * @param string $name
412
-     * @param string $required
413
-     * @param int    $tab_index
414
-     * @param array  $options
415
-     * @return string
416
-     * @since   4.10.14.p
417
-     */
418
-    private static function adminSelect($default, $class, $id, $name, $required, $tab_index, $options = [])
419
-    {
420
-        $options_array = [];
421
-        foreach ($options as $value => $label) {
422
-            $selected        = ! empty($default) && $default == $value ? 'selected' : '';
423
-            $value           = esc_attr($value);
424
-            $label           = wp_strip_all_tags($label);
425
-            $options_array[] = "<option value='{$value}' {$selected}>{$label}</option>";
426
-        }
427
-        $options_html = implode("\n", $options_array);
428
-        $id           = esc_attr($id);
429
-        $name         = esc_attr($name);
430
-        $class        = esc_attr($class);
431
-        $tab_index    = absint($tab_index);
432
-        $required     = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
433
-
434
-        $class = self::appendInputSizeClass($class, $options);
435
-
436
-        return "
404
+	}
405
+
406
+
407
+	/**
408
+	 * @param string $default
409
+	 * @param string $class
410
+	 * @param string $id
411
+	 * @param string $name
412
+	 * @param string $required
413
+	 * @param int    $tab_index
414
+	 * @param array  $options
415
+	 * @return string
416
+	 * @since   4.10.14.p
417
+	 */
418
+	private static function adminSelect($default, $class, $id, $name, $required, $tab_index, $options = [])
419
+	{
420
+		$options_array = [];
421
+		foreach ($options as $value => $label) {
422
+			$selected        = ! empty($default) && $default == $value ? 'selected' : '';
423
+			$value           = esc_attr($value);
424
+			$label           = wp_strip_all_tags($label);
425
+			$options_array[] = "<option value='{$value}' {$selected}>{$label}</option>";
426
+		}
427
+		$options_html = implode("\n", $options_array);
428
+		$id           = esc_attr($id);
429
+		$name         = esc_attr($name);
430
+		$class        = esc_attr($class);
431
+		$tab_index    = absint($tab_index);
432
+		$required     = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
433
+
434
+		$class = self::appendInputSizeClass($class, $options);
435
+
436
+		return "
437 437
         <select name='{$name}' id='{$id}' class='{$class}' {$required} tabindex='{$tab_index}'>
438 438
             {$options_html}
439 439
         </select>";
440
-    }
441
-
442
-
443
-    /**
444
-     * @param string $class
445
-     * @param string $id
446
-     * @param string $name
447
-     * @param string $required
448
-     * @param int    $tab_index
449
-     * @param string $value
450
-     * @return string
451
-     * @since   4.10.14.p
452
-     */
453
-    private static function adminText($class, $id, $name, $required, $tab_index, $value)
454
-    {
455
-        $id        = esc_attr($id);
456
-        $name      = esc_attr($name);
457
-        $class     = esc_attr($class);
458
-        $tab_index = absint($tab_index);
459
-        $required  = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
460
-        $class     = self::appendInputSizeClass($class, $value);
461
-        $value     = esc_attr($value);
462
-        return "
440
+	}
441
+
442
+
443
+	/**
444
+	 * @param string $class
445
+	 * @param string $id
446
+	 * @param string $name
447
+	 * @param string $required
448
+	 * @param int    $tab_index
449
+	 * @param string $value
450
+	 * @return string
451
+	 * @since   4.10.14.p
452
+	 */
453
+	private static function adminText($class, $id, $name, $required, $tab_index, $value)
454
+	{
455
+		$id        = esc_attr($id);
456
+		$name      = esc_attr($name);
457
+		$class     = esc_attr($class);
458
+		$tab_index = absint($tab_index);
459
+		$required  = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
460
+		$class     = self::appendInputSizeClass($class, $value);
461
+		$value     = esc_attr($value);
462
+		return "
463 463
         <input name='{$name}' type='text' id='{$id}' class='{$class}' value='{$value}' {$required} tabindex='{$tab_index}'/>";
464
-    }
465
-
466
-
467
-    /**
468
-     * @param string $class
469
-     * @param int    $cols
470
-     * @param string $id
471
-     * @param string $name
472
-     * @param string $required
473
-     * @param int    $rows
474
-     * @param int    $tab_index
475
-     * @param string $value
476
-     * @return string
477
-     * @since   4.10.14.p
478
-     */
479
-    private static function adminTextarea($class, $cols, $id, $name, $required, $rows, $tab_index, $value)
480
-    {
481
-        $id        = esc_attr($id);
482
-        $name      = esc_attr($name);
483
-        $class     = esc_attr($class);
484
-        $cols      = absint($cols);
485
-        $rows      = absint($rows);
486
-        $value     = esc_textarea($value);
487
-        $tab_index = absint($tab_index);
488
-        $required  = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
489
-        return "
464
+	}
465
+
466
+
467
+	/**
468
+	 * @param string $class
469
+	 * @param int    $cols
470
+	 * @param string $id
471
+	 * @param string $name
472
+	 * @param string $required
473
+	 * @param int    $rows
474
+	 * @param int    $tab_index
475
+	 * @param string $value
476
+	 * @return string
477
+	 * @since   4.10.14.p
478
+	 */
479
+	private static function adminTextarea($class, $cols, $id, $name, $required, $rows, $tab_index, $value)
480
+	{
481
+		$id        = esc_attr($id);
482
+		$name      = esc_attr($name);
483
+		$class     = esc_attr($class);
484
+		$cols      = absint($cols);
485
+		$rows      = absint($rows);
486
+		$value     = esc_textarea($value);
487
+		$tab_index = absint($tab_index);
488
+		$required  = filter_var($required, FILTER_VALIDATE_BOOLEAN) ? 'required' : '';
489
+		return "
490 490
         <textarea name='{$name}' id='{$id}' class='{$class}' rows='{$rows}' cols='{$cols}' {$required} tabindex='{$tab_index}'>{$value}</textarea>";
491
-    }
492
-
493
-
494
-    /**
495
-     * @param string $class
496
-     * @param string $id
497
-     * @param string $name
498
-     * @param int    $rows
499
-     * @param int    $tab_index
500
-     * @param string $value
501
-     * @param array  $wp_editor_args
502
-     * @return false|string
503
-     * @since   4.10.14.p
504
-     */
505
-    private static function adminWpEditor($class, $id, $name, $rows, $tab_index, $value, $wp_editor_args = [])
506
-    {
507
-        $editor_settings = $wp_editor_args + [
508
-                'textarea_name' => esc_attr($name),
509
-                'textarea_rows' => absint($rows),
510
-                'editor_class'  => esc_attr($class),
511
-                'tabindex'      => absint($tab_index),
512
-            ];
513
-        ob_start();
514
-        wp_editor($value, esc_attr($id), $editor_settings);
515
-        return ob_get_clean();
516
-    }
517
-
518
-
519
-    /**
520
-     * espresso admin page select_input
521
-     * Turns an array into a select fields
522
-     *
523
-     * @static
524
-     * @access public
525
-     * @param string  $name       field name
526
-     * @param array   $values     option values, numbered array starting at 0, where each value is an array with a key
527
-     *                            'text' (meaning text to display' and 'id' (meaning the internal value) eg:
528
-     *                            array(1=>array('text'=>'Monday','id'=>1),2=>array('text'=>'Tuesday','id'=>2)...). or
529
-     *                            as an array of key-value pairs, where the key is to be used for the select input's
530
-     *                            name, and the value will be the text shown to the user.  Optionally you can also
531
-     *                            include an additional key of "class" which will add a specific class to the option
532
-     *                            for that value.
533
-     * @param string  $default    default value
534
-     * @param string  $parameters extra parameters
535
-     * @param string  $class      css class
536
-     * @param boolean $autosize   whether to autosize the select or not
537
-     * @return string              html string for the select input
538
-     */
539
-    public static function select_input(
540
-        $name,
541
-        $values,
542
-        $default = '',
543
-        $parameters = '',
544
-        $class = '',
545
-        $autosize = true
546
-    ) {
547
-        // if $values was submitted in the wrong format, convert it over
548
-        if (! empty($values) && (! array_key_exists(0, $values) || ! is_array($values[0]))) {
549
-            $converted_values = [];
550
-            foreach ($values as $id => $text) {
551
-                $converted_values[] = ['id' => $id, 'text' => $text];
552
-            }
553
-            $values = $converted_values;
554
-        }
555
-
556
-        $field =
557
-            '<select id="' . EEH_Formatter::ee_tep_output_string($name)
558
-            . '" name="' . EEH_Formatter::ee_tep_output_string($name)
559
-            . '"';
560
-
561
-        if (EEH_Formatter::ee_tep_not_null($parameters)) {
562
-            $field .= ' ' . $parameters;
563
-        }
564
-        $class = $autosize ? self::appendInputSizeClass($class, $values) : '';
565
-
566
-        $field .= ' class="' . $class . '">';
567
-
568
-        if (empty($default) && isset($GLOBALS[ $name ])) {
569
-            $default = stripslashes($GLOBALS[ $name ]);
570
-        }
571
-
572
-        $field .= self::selectInputOption($values, $default);
573
-        $field .= '</select>';
574
-
575
-        return $field;
576
-    }
577
-
578
-
579
-    private static function selectInputOption(array $values, $default): string
580
-    {
581
-        if (isset($values['id'], $values['text'])) {
582
-            $id = is_scalar($values['id']) ? $values['id'] : '';
583
-            $text = is_scalar($values['text']) ? $values['text'] : '';
584
-            $selected = $default == $values['id'] ? ' selected = "selected"' : '';
585
-            $html_class = isset($values['class']) ? ' class="' . $values['class'] . '"' : '';
586
-            return "<option value='{$id}'{$selected}{$html_class}>{$text}</option>";
587
-        }
588
-        $options = '';
589
-        foreach ($values as $value) {
590
-            $options .= self::selectInputOption($value, $default);
591
-        }
592
-        return $options;
593
-    }
594
-
595
-
596
-    /**
597
-     * @param mixed $value
598
-     * @return int
599
-     * @since   5.0.0.p
600
-     */
601
-    private static function getInputValueLength($value): int
602
-    {
603
-        if ($value instanceof EE_Question_Option) {
604
-            return self::getInputValueLength($value->desc());
605
-        }
606
-        if (is_array($value)) {
607
-            $chars = 0;
608
-            foreach ($value as $val) {
609
-                $length = self::getInputValueLength($val);
610
-                $chars = max($length, $chars);
611
-            }
612
-            return $chars;
613
-        }
614
-        // not a primitive? return something big
615
-        if (! is_scalar($value)) {
616
-            return 500;
617
-        }
618
-        return strlen((string) $value);
619
-    }
620
-
621
-
622
-    /**
623
-     * @param string $class
624
-     * @param mixed $value
625
-     * @return string
626
-     * @since   5.0.0.p
627
-     */
628
-    private static function appendInputSizeClass(string $class, $value): string
629
-    {
630
-        if (strpos($class, 'ee-input-width--') !== false) {
631
-            return $class;
632
-        }
633
-        $chars = self::getInputValueLength($value);
634
-        if ($chars && $chars < 5) {
635
-            return "{$class} ee-input-width--tiny";
636
-        }
637
-        if ($chars && $chars < 25) {
638
-            return "{$class} ee-input-width--small";
639
-        }
640
-        if ($chars && $chars > 100) {
641
-            return "{$class} ee-input-width--big";
642
-        }
643
-        return "{$class} ee-input-width--reg";
644
-    }
645
-
646
-
647
-    /**
648
-     * generate_question_groups_html
649
-     *
650
-     * @param array  $question_groups
651
-     * @param string $group_wrapper
652
-     * @return string HTML
653
-     * @throws EE_Error
654
-     * @throws ReflectionException
655
-     */
656
-    public static function generate_question_groups_html($question_groups = [], $group_wrapper = 'fieldset')
657
-    {
658
-
659
-        $html                            = '';
660
-        $before_question_group_questions =
661
-            apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', '');
662
-        $after_question_group_questions  =
663
-            apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', '');
664
-
665
-        if (! empty($question_groups)) {
666
-            // loop thru question groups
667
-            foreach ($question_groups as $QSG) {
668
-                // check that questions exist
669
-                if (! empty($QSG['QSG_questions'])) {
670
-                    // use fieldsets
671
-                    $html .= "\n\t"
672
-                             . '<'
673
-                             . $group_wrapper
674
-                             . ' class="espresso-question-group-wrap" id="'
675
-                             . $QSG['QSG_identifier']
676
-                             . '">';
677
-                    // group_name
678
-                    $html .= $QSG['QSG_show_group_name']
679
-                        ? "\n\t\t"
680
-                          . '<h5 class="espresso-question-group-title-h5 section-title">'
681
-                          . self::prep_answer($QSG['QSG_name'])
682
-                          . '</h5>'
683
-                        : '';
684
-                    // group_desc
685
-                    $html .= $QSG['QSG_show_group_desc'] && ! empty($QSG['QSG_desc'])
686
-                        ? '<div class="espresso-question-group-desc-pg">'
687
-                          . self::prep_answer($QSG['QSG_desc'])
688
-                          . '</div>'
689
-                        : '';
690
-
691
-                    $html .= $before_question_group_questions;
692
-                    // loop thru questions
693
-                    foreach ($QSG['QSG_questions'] as $question) {
694
-                        $QFI  = new EE_Question_Form_Input(
695
-                            $question['qst_obj'],
696
-                            $question['ans_obj'],
697
-                            $question
698
-                        );
699
-                        $html .= self::generate_form_input($QFI);
700
-                    }
701
-                    $html .= $after_question_group_questions;
702
-                    $html .= "\n\t" . '</' . $group_wrapper . '>';
703
-                }
704
-            }
705
-        }
706
-
707
-        return $html;
708
-    }
709
-
710
-
711
-    /**
712
-     * generate_question_groups_html
713
-     *
714
-     * @param array  $question_groups
715
-     * @param array  $q_meta
716
-     * @param bool   $from_admin
717
-     * @param string $group_wrapper
718
-     * @return string HTML
719
-     * @throws EE_Error
720
-     * @throws ReflectionException
721
-     */
722
-    public static function generate_question_groups_html2(
723
-        $question_groups = [],
724
-        $q_meta = [],
725
-        $from_admin = false,
726
-        $group_wrapper = 'fieldset'
727
-    ) {
728
-
729
-        $html                            = '';
730
-        $before_question_group_questions =
731
-            apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', '');
732
-        $after_question_group_questions  =
733
-            apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', '');
734
-
735
-        $default_q_meta = [
736
-            'att_nmbr'    => 1,
737
-            'ticket_id'   => '',
738
-            'input_name'  => '',
739
-            'input_id'    => '',
740
-            'input_class' => '',
741
-        ];
742
-        $q_meta         = array_merge($default_q_meta, $q_meta);
743
-
744
-        if (! empty($question_groups)) {
745
-            // loop thru question groups
746
-            foreach ($question_groups as $QSG) {
747
-                if ($QSG instanceof EE_Question_Group) {
748
-                    // check that questions exist
749
-
750
-                    $where = ['QST_deleted' => 0];
751
-                    if (! $from_admin) {
752
-                        $where['QST_admin_only'] = 0;
753
-                    }
754
-                    $questions =
755
-                        $QSG->questions([$where, 'order_by' => ['Question_Group_Question.QGQ_order' => 'ASC']]);
756
-                    if (! empty($questions)) {
757
-                        // use fieldsets
758
-                        $html .= "\n\t"
759
-                                 . '<' . $group_wrapper . ' class="espresso-question-group-wrap" '
760
-                                 . 'id="' . $QSG->get('QSG_identifier') . '">';
761
-                        // group_name
762
-                        if ($QSG->show_group_name()) {
763
-                            $html .= "\n\t\t"
764
-                                     . '<h5 class="espresso-question-group-title-h5 section-title">'
765
-                                     . $QSG->get_pretty('QSG_name')
766
-                                     . '</h5>';
767
-                        }
768
-                        // group_desc
769
-                        if ($QSG->show_group_desc()) {
770
-                            $html .= '<div class="espresso-question-group-desc-pg">'
771
-                                     . $QSG->get_pretty('QSG_desc')
772
-                                     . '</div>';
773
-                        }
774
-
775
-                        $html .= $before_question_group_questions;
776
-                        // loop thru questions
777
-                        foreach ($questions as $QST) {
778
-                            $qstn_id = $QST->is_system_question() ? $QST->system_ID() : $QST->ID();
779
-
780
-                            $answer = null;
781
-
782
-                            /** @var RequestInterface $request */
783
-                            $request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
784
-                            $request_qstn = $request->getRequestParam('qstn', [], 'string', true);
785
-                            if (! empty($request_qstn) && isset($q_meta['input_id']) && isset($q_meta['att_nmbr'])) {
786
-                                // check for answer in $request_qstn in case we are reprocessing a form after an error
787
-                                if (isset($request_qstn[ $q_meta['input_id'] ][ $qstn_id ])) {
788
-                                    $answer = is_array($request_qstn[ $q_meta['input_id'] ][ $qstn_id ])
789
-                                        ? $request_qstn[ $q_meta['input_id'] ][ $qstn_id ]
790
-                                        : sanitize_text_field($request_qstn[ $q_meta['input_id'] ][ $qstn_id ]);
791
-                                }
792
-                            } elseif (isset($q_meta['attendee']) && $q_meta['attendee']) {
793
-                                // attendee data from the session
794
-                                $answer =
795
-                                    isset($q_meta['attendee'][ $qstn_id ]) ? $q_meta['attendee'][ $qstn_id ] : null;
796
-                            }
797
-
798
-
799
-                            $QFI  = new EE_Question_Form_Input(
800
-                                $QST,
801
-                                EE_Answer::new_instance(
802
-                                    [
803
-                                        'ANS_ID'    => 0,
804
-                                        'QST_ID'    => 0,
805
-                                        'REG_ID'    => 0,
806
-                                        'ANS_value' => $answer,
807
-                                    ]
808
-                                ),
809
-                                $q_meta
810
-                            );
811
-                            $html .= self::generate_form_input($QFI);
812
-                        }
813
-                        $html .= $after_question_group_questions;
814
-                        $html .= "\n\t" . '</' . $group_wrapper . '>';
815
-                    }
816
-                }
817
-            }
818
-        }
819
-        return $html;
820
-    }
821
-
822
-
823
-    /**
824
-     * generate_form_input
825
-     *
826
-     * @param EE_Question_Form_Input $QFI
827
-     * @return string HTML
828
-     * @throws EE_Error
829
-     * @throws ReflectionException
830
-     */
831
-    public static function generate_form_input(EE_Question_Form_Input $QFI)
832
-    {
833
-        if (isset($QFI->QST_admin_only) && $QFI->QST_admin_only && ! is_admin()) {
834
-            return '';
835
-        }
836
-        /** @var RequestInterface $request */
837
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
838
-
839
-        $QFI = self::_load_system_dropdowns($QFI);
840
-        $QFI = self::_load_specialized_dropdowns($QFI);
841
-
842
-        // we also need to verify
843
-
844
-        $display_text = $QFI->get('QST_display_text');
845
-        $input_name   = $QFI->get('QST_input_name');
846
-        $answer       = $request->getRequestParam($input_name, $QFI->get('ANS_value'));
847
-        $input_id     = $QFI->get('QST_input_id');
848
-        $input_class  = $QFI->get('QST_input_class');
849
-        //      $disabled = $QFI->get('QST_disabled') ? ' disabled="disabled"' : '';
850
-        $disabled          = $QFI->get('QST_disabled');
851
-        $required_label    = apply_filters(' FHEE__EEH_Form_Fields__generate_form_input__required_label', '<em>*</em>');
852
-        $QST_required      = $QFI->get('QST_required');
853
-        $required          =
854
-            $QST_required
855
-                ? ['label' => $required_label, 'class' => 'required needs-value', 'title' => $QST_required]
856
-                : [];
857
-        $use_html_entities = $QFI->get_meta('htmlentities');
858
-        $required_text     =
859
-            $QFI->get('QST_required_text') != ''
860
-                ? $QFI->get('QST_required_text')
861
-                : esc_html__('This field is required', 'event_espresso');
862
-        $required_text     = $QST_required
863
-            ? "\n\t\t\t"
864
-              . '<div class="required-text hidden">'
865
-              . self::prep_answer($required_text, $use_html_entities)
866
-              . '</div>'
867
-            : '';
868
-        $label_class       = $QFI->get('label_class');
869
-        $label_class       = $label_class ? "{$label_class} espresso-form-input-lbl" : 'espresso-form-input-lbl';
870
-        $QST_options       = $QFI->options(true, $answer);
871
-        $options           = is_array($QST_options) ? self::prep_answer_options($QST_options) : [];
872
-        $system_ID         = $QFI->get('QST_system');
873
-        $label_b4          = $QFI->get_meta('label_b4');
874
-        $use_desc_4_label  = $QFI->get_meta('use_desc_4_label');
875
-        $add_mobile_label  = $QFI->get_meta('add_mobile_label');
876
-
877
-
878
-        switch ($QFI->get('QST_type')) {
879
-            case 'TEXTAREA':
880
-                return EEH_Form_Fields::textarea(
881
-                    $display_text,
882
-                    $answer,
883
-                    $input_name,
884
-                    $input_id,
885
-                    $input_class,
886
-                    [],
887
-                    $required,
888
-                    $required_text,
889
-                    $label_class,
890
-                    $disabled,
891
-                    $system_ID,
892
-                    $use_html_entities,
893
-                    $add_mobile_label
894
-                );
895
-
896
-            case 'DROPDOWN':
897
-                return EEH_Form_Fields::select(
898
-                    $display_text,
899
-                    $answer,
900
-                    $options,
901
-                    $input_name,
902
-                    $input_id,
903
-                    $input_class,
904
-                    $required,
905
-                    $required_text,
906
-                    $label_class,
907
-                    $disabled,
908
-                    $system_ID,
909
-                    $use_html_entities,
910
-                    true,
911
-                    $add_mobile_label
912
-                );
913
-
914
-
915
-            case 'RADIO_BTN':
916
-                return EEH_Form_Fields::radio(
917
-                    $display_text,
918
-                    $answer,
919
-                    $options,
920
-                    $input_name,
921
-                    $input_id,
922
-                    $input_class,
923
-                    $required,
924
-                    $required_text,
925
-                    $label_class,
926
-                    $disabled,
927
-                    $system_ID,
928
-                    $use_html_entities,
929
-                    $label_b4,
930
-                    $use_desc_4_label,
931
-                    $add_mobile_label
932
-                );
933
-
934
-            case 'CHECKBOX':
935
-                return EEH_Form_Fields::checkbox(
936
-                    $display_text,
937
-                    $answer,
938
-                    $options,
939
-                    $input_name,
940
-                    $input_id,
941
-                    $input_class,
942
-                    $required,
943
-                    $required_text,
944
-                    $label_class,
945
-                    $disabled,
946
-                    $label_b4,
947
-                    $system_ID,
948
-                    $use_html_entities,
949
-                    $add_mobile_label
950
-                );
951
-
952
-            case 'DATE':
953
-                return EEH_Form_Fields::datepicker(
954
-                    $display_text,
955
-                    $answer,
956
-                    $input_name,
957
-                    $input_id,
958
-                    $input_class,
959
-                    $required,
960
-                    $required_text,
961
-                    $label_class,
962
-                    $disabled,
963
-                    $system_ID,
964
-                    $use_html_entities,
965
-                    $add_mobile_label
966
-                );
967
-
968
-            case 'TEXT':
969
-            default:
970
-                return EEH_Form_Fields::text(
971
-                    $display_text,
972
-                    $answer,
973
-                    $input_name,
974
-                    $input_id,
975
-                    $input_class,
976
-                    $required,
977
-                    $required_text,
978
-                    $label_class,
979
-                    $disabled,
980
-                    $system_ID,
981
-                    $use_html_entities,
982
-                    $add_mobile_label
983
-                );
984
-        }
985
-    }
986
-
987
-
988
-    public static function label(
989
-        string $question,
990
-        string $required_text = '',
991
-        string $required_label = '',
992
-        string $name = '',
993
-        string $label_class = '',
994
-        bool $filter = true
995
-    ): string {
996
-        $for   = ! empty($name) ? " for='{$name}'" : '';
997
-        $class = ! empty($label_class) ? " class='{$label_class}'" : '';
998
-        $label = self::prep_question($question) . $required_label;
999
-        $label_html = "
491
+	}
492
+
493
+
494
+	/**
495
+	 * @param string $class
496
+	 * @param string $id
497
+	 * @param string $name
498
+	 * @param int    $rows
499
+	 * @param int    $tab_index
500
+	 * @param string $value
501
+	 * @param array  $wp_editor_args
502
+	 * @return false|string
503
+	 * @since   4.10.14.p
504
+	 */
505
+	private static function adminWpEditor($class, $id, $name, $rows, $tab_index, $value, $wp_editor_args = [])
506
+	{
507
+		$editor_settings = $wp_editor_args + [
508
+				'textarea_name' => esc_attr($name),
509
+				'textarea_rows' => absint($rows),
510
+				'editor_class'  => esc_attr($class),
511
+				'tabindex'      => absint($tab_index),
512
+			];
513
+		ob_start();
514
+		wp_editor($value, esc_attr($id), $editor_settings);
515
+		return ob_get_clean();
516
+	}
517
+
518
+
519
+	/**
520
+	 * espresso admin page select_input
521
+	 * Turns an array into a select fields
522
+	 *
523
+	 * @static
524
+	 * @access public
525
+	 * @param string  $name       field name
526
+	 * @param array   $values     option values, numbered array starting at 0, where each value is an array with a key
527
+	 *                            'text' (meaning text to display' and 'id' (meaning the internal value) eg:
528
+	 *                            array(1=>array('text'=>'Monday','id'=>1),2=>array('text'=>'Tuesday','id'=>2)...). or
529
+	 *                            as an array of key-value pairs, where the key is to be used for the select input's
530
+	 *                            name, and the value will be the text shown to the user.  Optionally you can also
531
+	 *                            include an additional key of "class" which will add a specific class to the option
532
+	 *                            for that value.
533
+	 * @param string  $default    default value
534
+	 * @param string  $parameters extra parameters
535
+	 * @param string  $class      css class
536
+	 * @param boolean $autosize   whether to autosize the select or not
537
+	 * @return string              html string for the select input
538
+	 */
539
+	public static function select_input(
540
+		$name,
541
+		$values,
542
+		$default = '',
543
+		$parameters = '',
544
+		$class = '',
545
+		$autosize = true
546
+	) {
547
+		// if $values was submitted in the wrong format, convert it over
548
+		if (! empty($values) && (! array_key_exists(0, $values) || ! is_array($values[0]))) {
549
+			$converted_values = [];
550
+			foreach ($values as $id => $text) {
551
+				$converted_values[] = ['id' => $id, 'text' => $text];
552
+			}
553
+			$values = $converted_values;
554
+		}
555
+
556
+		$field =
557
+			'<select id="' . EEH_Formatter::ee_tep_output_string($name)
558
+			. '" name="' . EEH_Formatter::ee_tep_output_string($name)
559
+			. '"';
560
+
561
+		if (EEH_Formatter::ee_tep_not_null($parameters)) {
562
+			$field .= ' ' . $parameters;
563
+		}
564
+		$class = $autosize ? self::appendInputSizeClass($class, $values) : '';
565
+
566
+		$field .= ' class="' . $class . '">';
567
+
568
+		if (empty($default) && isset($GLOBALS[ $name ])) {
569
+			$default = stripslashes($GLOBALS[ $name ]);
570
+		}
571
+
572
+		$field .= self::selectInputOption($values, $default);
573
+		$field .= '</select>';
574
+
575
+		return $field;
576
+	}
577
+
578
+
579
+	private static function selectInputOption(array $values, $default): string
580
+	{
581
+		if (isset($values['id'], $values['text'])) {
582
+			$id = is_scalar($values['id']) ? $values['id'] : '';
583
+			$text = is_scalar($values['text']) ? $values['text'] : '';
584
+			$selected = $default == $values['id'] ? ' selected = "selected"' : '';
585
+			$html_class = isset($values['class']) ? ' class="' . $values['class'] . '"' : '';
586
+			return "<option value='{$id}'{$selected}{$html_class}>{$text}</option>";
587
+		}
588
+		$options = '';
589
+		foreach ($values as $value) {
590
+			$options .= self::selectInputOption($value, $default);
591
+		}
592
+		return $options;
593
+	}
594
+
595
+
596
+	/**
597
+	 * @param mixed $value
598
+	 * @return int
599
+	 * @since   5.0.0.p
600
+	 */
601
+	private static function getInputValueLength($value): int
602
+	{
603
+		if ($value instanceof EE_Question_Option) {
604
+			return self::getInputValueLength($value->desc());
605
+		}
606
+		if (is_array($value)) {
607
+			$chars = 0;
608
+			foreach ($value as $val) {
609
+				$length = self::getInputValueLength($val);
610
+				$chars = max($length, $chars);
611
+			}
612
+			return $chars;
613
+		}
614
+		// not a primitive? return something big
615
+		if (! is_scalar($value)) {
616
+			return 500;
617
+		}
618
+		return strlen((string) $value);
619
+	}
620
+
621
+
622
+	/**
623
+	 * @param string $class
624
+	 * @param mixed $value
625
+	 * @return string
626
+	 * @since   5.0.0.p
627
+	 */
628
+	private static function appendInputSizeClass(string $class, $value): string
629
+	{
630
+		if (strpos($class, 'ee-input-width--') !== false) {
631
+			return $class;
632
+		}
633
+		$chars = self::getInputValueLength($value);
634
+		if ($chars && $chars < 5) {
635
+			return "{$class} ee-input-width--tiny";
636
+		}
637
+		if ($chars && $chars < 25) {
638
+			return "{$class} ee-input-width--small";
639
+		}
640
+		if ($chars && $chars > 100) {
641
+			return "{$class} ee-input-width--big";
642
+		}
643
+		return "{$class} ee-input-width--reg";
644
+	}
645
+
646
+
647
+	/**
648
+	 * generate_question_groups_html
649
+	 *
650
+	 * @param array  $question_groups
651
+	 * @param string $group_wrapper
652
+	 * @return string HTML
653
+	 * @throws EE_Error
654
+	 * @throws ReflectionException
655
+	 */
656
+	public static function generate_question_groups_html($question_groups = [], $group_wrapper = 'fieldset')
657
+	{
658
+
659
+		$html                            = '';
660
+		$before_question_group_questions =
661
+			apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', '');
662
+		$after_question_group_questions  =
663
+			apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', '');
664
+
665
+		if (! empty($question_groups)) {
666
+			// loop thru question groups
667
+			foreach ($question_groups as $QSG) {
668
+				// check that questions exist
669
+				if (! empty($QSG['QSG_questions'])) {
670
+					// use fieldsets
671
+					$html .= "\n\t"
672
+							 . '<'
673
+							 . $group_wrapper
674
+							 . ' class="espresso-question-group-wrap" id="'
675
+							 . $QSG['QSG_identifier']
676
+							 . '">';
677
+					// group_name
678
+					$html .= $QSG['QSG_show_group_name']
679
+						? "\n\t\t"
680
+						  . '<h5 class="espresso-question-group-title-h5 section-title">'
681
+						  . self::prep_answer($QSG['QSG_name'])
682
+						  . '</h5>'
683
+						: '';
684
+					// group_desc
685
+					$html .= $QSG['QSG_show_group_desc'] && ! empty($QSG['QSG_desc'])
686
+						? '<div class="espresso-question-group-desc-pg">'
687
+						  . self::prep_answer($QSG['QSG_desc'])
688
+						  . '</div>'
689
+						: '';
690
+
691
+					$html .= $before_question_group_questions;
692
+					// loop thru questions
693
+					foreach ($QSG['QSG_questions'] as $question) {
694
+						$QFI  = new EE_Question_Form_Input(
695
+							$question['qst_obj'],
696
+							$question['ans_obj'],
697
+							$question
698
+						);
699
+						$html .= self::generate_form_input($QFI);
700
+					}
701
+					$html .= $after_question_group_questions;
702
+					$html .= "\n\t" . '</' . $group_wrapper . '>';
703
+				}
704
+			}
705
+		}
706
+
707
+		return $html;
708
+	}
709
+
710
+
711
+	/**
712
+	 * generate_question_groups_html
713
+	 *
714
+	 * @param array  $question_groups
715
+	 * @param array  $q_meta
716
+	 * @param bool   $from_admin
717
+	 * @param string $group_wrapper
718
+	 * @return string HTML
719
+	 * @throws EE_Error
720
+	 * @throws ReflectionException
721
+	 */
722
+	public static function generate_question_groups_html2(
723
+		$question_groups = [],
724
+		$q_meta = [],
725
+		$from_admin = false,
726
+		$group_wrapper = 'fieldset'
727
+	) {
728
+
729
+		$html                            = '';
730
+		$before_question_group_questions =
731
+			apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', '');
732
+		$after_question_group_questions  =
733
+			apply_filters('FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', '');
734
+
735
+		$default_q_meta = [
736
+			'att_nmbr'    => 1,
737
+			'ticket_id'   => '',
738
+			'input_name'  => '',
739
+			'input_id'    => '',
740
+			'input_class' => '',
741
+		];
742
+		$q_meta         = array_merge($default_q_meta, $q_meta);
743
+
744
+		if (! empty($question_groups)) {
745
+			// loop thru question groups
746
+			foreach ($question_groups as $QSG) {
747
+				if ($QSG instanceof EE_Question_Group) {
748
+					// check that questions exist
749
+
750
+					$where = ['QST_deleted' => 0];
751
+					if (! $from_admin) {
752
+						$where['QST_admin_only'] = 0;
753
+					}
754
+					$questions =
755
+						$QSG->questions([$where, 'order_by' => ['Question_Group_Question.QGQ_order' => 'ASC']]);
756
+					if (! empty($questions)) {
757
+						// use fieldsets
758
+						$html .= "\n\t"
759
+								 . '<' . $group_wrapper . ' class="espresso-question-group-wrap" '
760
+								 . 'id="' . $QSG->get('QSG_identifier') . '">';
761
+						// group_name
762
+						if ($QSG->show_group_name()) {
763
+							$html .= "\n\t\t"
764
+									 . '<h5 class="espresso-question-group-title-h5 section-title">'
765
+									 . $QSG->get_pretty('QSG_name')
766
+									 . '</h5>';
767
+						}
768
+						// group_desc
769
+						if ($QSG->show_group_desc()) {
770
+							$html .= '<div class="espresso-question-group-desc-pg">'
771
+									 . $QSG->get_pretty('QSG_desc')
772
+									 . '</div>';
773
+						}
774
+
775
+						$html .= $before_question_group_questions;
776
+						// loop thru questions
777
+						foreach ($questions as $QST) {
778
+							$qstn_id = $QST->is_system_question() ? $QST->system_ID() : $QST->ID();
779
+
780
+							$answer = null;
781
+
782
+							/** @var RequestInterface $request */
783
+							$request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
784
+							$request_qstn = $request->getRequestParam('qstn', [], 'string', true);
785
+							if (! empty($request_qstn) && isset($q_meta['input_id']) && isset($q_meta['att_nmbr'])) {
786
+								// check for answer in $request_qstn in case we are reprocessing a form after an error
787
+								if (isset($request_qstn[ $q_meta['input_id'] ][ $qstn_id ])) {
788
+									$answer = is_array($request_qstn[ $q_meta['input_id'] ][ $qstn_id ])
789
+										? $request_qstn[ $q_meta['input_id'] ][ $qstn_id ]
790
+										: sanitize_text_field($request_qstn[ $q_meta['input_id'] ][ $qstn_id ]);
791
+								}
792
+							} elseif (isset($q_meta['attendee']) && $q_meta['attendee']) {
793
+								// attendee data from the session
794
+								$answer =
795
+									isset($q_meta['attendee'][ $qstn_id ]) ? $q_meta['attendee'][ $qstn_id ] : null;
796
+							}
797
+
798
+
799
+							$QFI  = new EE_Question_Form_Input(
800
+								$QST,
801
+								EE_Answer::new_instance(
802
+									[
803
+										'ANS_ID'    => 0,
804
+										'QST_ID'    => 0,
805
+										'REG_ID'    => 0,
806
+										'ANS_value' => $answer,
807
+									]
808
+								),
809
+								$q_meta
810
+							);
811
+							$html .= self::generate_form_input($QFI);
812
+						}
813
+						$html .= $after_question_group_questions;
814
+						$html .= "\n\t" . '</' . $group_wrapper . '>';
815
+					}
816
+				}
817
+			}
818
+		}
819
+		return $html;
820
+	}
821
+
822
+
823
+	/**
824
+	 * generate_form_input
825
+	 *
826
+	 * @param EE_Question_Form_Input $QFI
827
+	 * @return string HTML
828
+	 * @throws EE_Error
829
+	 * @throws ReflectionException
830
+	 */
831
+	public static function generate_form_input(EE_Question_Form_Input $QFI)
832
+	{
833
+		if (isset($QFI->QST_admin_only) && $QFI->QST_admin_only && ! is_admin()) {
834
+			return '';
835
+		}
836
+		/** @var RequestInterface $request */
837
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
838
+
839
+		$QFI = self::_load_system_dropdowns($QFI);
840
+		$QFI = self::_load_specialized_dropdowns($QFI);
841
+
842
+		// we also need to verify
843
+
844
+		$display_text = $QFI->get('QST_display_text');
845
+		$input_name   = $QFI->get('QST_input_name');
846
+		$answer       = $request->getRequestParam($input_name, $QFI->get('ANS_value'));
847
+		$input_id     = $QFI->get('QST_input_id');
848
+		$input_class  = $QFI->get('QST_input_class');
849
+		//      $disabled = $QFI->get('QST_disabled') ? ' disabled="disabled"' : '';
850
+		$disabled          = $QFI->get('QST_disabled');
851
+		$required_label    = apply_filters(' FHEE__EEH_Form_Fields__generate_form_input__required_label', '<em>*</em>');
852
+		$QST_required      = $QFI->get('QST_required');
853
+		$required          =
854
+			$QST_required
855
+				? ['label' => $required_label, 'class' => 'required needs-value', 'title' => $QST_required]
856
+				: [];
857
+		$use_html_entities = $QFI->get_meta('htmlentities');
858
+		$required_text     =
859
+			$QFI->get('QST_required_text') != ''
860
+				? $QFI->get('QST_required_text')
861
+				: esc_html__('This field is required', 'event_espresso');
862
+		$required_text     = $QST_required
863
+			? "\n\t\t\t"
864
+			  . '<div class="required-text hidden">'
865
+			  . self::prep_answer($required_text, $use_html_entities)
866
+			  . '</div>'
867
+			: '';
868
+		$label_class       = $QFI->get('label_class');
869
+		$label_class       = $label_class ? "{$label_class} espresso-form-input-lbl" : 'espresso-form-input-lbl';
870
+		$QST_options       = $QFI->options(true, $answer);
871
+		$options           = is_array($QST_options) ? self::prep_answer_options($QST_options) : [];
872
+		$system_ID         = $QFI->get('QST_system');
873
+		$label_b4          = $QFI->get_meta('label_b4');
874
+		$use_desc_4_label  = $QFI->get_meta('use_desc_4_label');
875
+		$add_mobile_label  = $QFI->get_meta('add_mobile_label');
876
+
877
+
878
+		switch ($QFI->get('QST_type')) {
879
+			case 'TEXTAREA':
880
+				return EEH_Form_Fields::textarea(
881
+					$display_text,
882
+					$answer,
883
+					$input_name,
884
+					$input_id,
885
+					$input_class,
886
+					[],
887
+					$required,
888
+					$required_text,
889
+					$label_class,
890
+					$disabled,
891
+					$system_ID,
892
+					$use_html_entities,
893
+					$add_mobile_label
894
+				);
895
+
896
+			case 'DROPDOWN':
897
+				return EEH_Form_Fields::select(
898
+					$display_text,
899
+					$answer,
900
+					$options,
901
+					$input_name,
902
+					$input_id,
903
+					$input_class,
904
+					$required,
905
+					$required_text,
906
+					$label_class,
907
+					$disabled,
908
+					$system_ID,
909
+					$use_html_entities,
910
+					true,
911
+					$add_mobile_label
912
+				);
913
+
914
+
915
+			case 'RADIO_BTN':
916
+				return EEH_Form_Fields::radio(
917
+					$display_text,
918
+					$answer,
919
+					$options,
920
+					$input_name,
921
+					$input_id,
922
+					$input_class,
923
+					$required,
924
+					$required_text,
925
+					$label_class,
926
+					$disabled,
927
+					$system_ID,
928
+					$use_html_entities,
929
+					$label_b4,
930
+					$use_desc_4_label,
931
+					$add_mobile_label
932
+				);
933
+
934
+			case 'CHECKBOX':
935
+				return EEH_Form_Fields::checkbox(
936
+					$display_text,
937
+					$answer,
938
+					$options,
939
+					$input_name,
940
+					$input_id,
941
+					$input_class,
942
+					$required,
943
+					$required_text,
944
+					$label_class,
945
+					$disabled,
946
+					$label_b4,
947
+					$system_ID,
948
+					$use_html_entities,
949
+					$add_mobile_label
950
+				);
951
+
952
+			case 'DATE':
953
+				return EEH_Form_Fields::datepicker(
954
+					$display_text,
955
+					$answer,
956
+					$input_name,
957
+					$input_id,
958
+					$input_class,
959
+					$required,
960
+					$required_text,
961
+					$label_class,
962
+					$disabled,
963
+					$system_ID,
964
+					$use_html_entities,
965
+					$add_mobile_label
966
+				);
967
+
968
+			case 'TEXT':
969
+			default:
970
+				return EEH_Form_Fields::text(
971
+					$display_text,
972
+					$answer,
973
+					$input_name,
974
+					$input_id,
975
+					$input_class,
976
+					$required,
977
+					$required_text,
978
+					$label_class,
979
+					$disabled,
980
+					$system_ID,
981
+					$use_html_entities,
982
+					$add_mobile_label
983
+				);
984
+		}
985
+	}
986
+
987
+
988
+	public static function label(
989
+		string $question,
990
+		string $required_text = '',
991
+		string $required_label = '',
992
+		string $name = '',
993
+		string $label_class = '',
994
+		bool $filter = true
995
+	): string {
996
+		$for   = ! empty($name) ? " for='{$name}'" : '';
997
+		$class = ! empty($label_class) ? " class='{$label_class}'" : '';
998
+		$label = self::prep_question($question) . $required_label;
999
+		$label_html = "
1000 1000
             {$required_text}
1001 1001
             <label{$for}{$class}>{$label}</label>";
1002
-        // filter label but ensure required text comes before it
1003
-        return $filter
1004
-            ? apply_filters('FHEE__EEH_Form_Fields__label_html', $label_html, $required_text)
1005
-            : $label_html;
1006
-    }
1007
-
1008
-
1009
-
1010
-    public static function mobileLabel(
1011
-        bool $add_mobile_label,
1012
-        string $question,
1013
-        string $required_text = '',
1014
-        string $required_label = '',
1015
-        string $label_class = '',
1016
-        string $name = ''
1017
-    ): string {
1018
-        return $add_mobile_label
1019
-            ? self::label($question, $required_text, $required_label, $name, $label_class, false)
1020
-            : '';
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * generates HTML for a form text input
1026
-     *
1027
-     * @param string $question    label content
1028
-     * @param string $answer      form input value attribute
1029
-     * @param string $name        form input name attribute
1030
-     * @param string $id          form input css id attribute
1031
-     * @param string $class       form input css class attribute
1032
-     * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1033
-     *                            required 'class', and required 'msg' attribute
1034
-     * @param string $label_class css class attribute for the label
1035
-     * @param string $disabled    disabled="disabled" or null
1036
-     * @return string HTML
1037
-     */
1038
-    public static function text(
1039
-        $question = false,
1040
-        $answer = null,
1041
-        $name = false,
1042
-        $id = '',
1043
-        $class = '',
1044
-        $required = false,
1045
-        $required_text = '',
1046
-        $label_class = '',
1047
-        $disabled = false,
1048
-        $system_ID = false,
1049
-        $use_html_entities = true,
1050
-        $add_mobile_label = false,
1051
-        $extra_attributes = ''
1052
-    ) {
1053
-        // need these
1054
-        if (! $question || ! $name) {
1055
-            return null;
1056
-        }
1057
-        // prep the answer
1058
-        $answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1059
-        // prep the required array
1060
-        $required = self::prep_required($required);
1061
-        // set disabled tag
1062
-        $disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1063
-        // ya gots ta have style man!!!
1064
-        $txt_class = is_admin() ? 'regular-text' : 'espresso-text-inp';
1065
-        $class     = empty($class) ? $txt_class : $class;
1066
-        $class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1067
-        $class = self::appendInputSizeClass($class, $answer);
1068
-        $class .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1069
-        $extra_attributes = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', $extra_attributes);
1070
-
1071
-        $label_html = self::label($question, $required_text, $required['label'], $name, $label_class);
1072
-        $mobile_label = self::mobileLabel(
1073
-            $add_mobile_label,
1074
-            $question,
1075
-            $required_text,
1076
-            $required['label'],
1077
-            $label_class,
1078
-            $name
1079
-        );
1080
-
1081
-        $input_html = $mobile_label . '
1002
+		// filter label but ensure required text comes before it
1003
+		return $filter
1004
+			? apply_filters('FHEE__EEH_Form_Fields__label_html', $label_html, $required_text)
1005
+			: $label_html;
1006
+	}
1007
+
1008
+
1009
+
1010
+	public static function mobileLabel(
1011
+		bool $add_mobile_label,
1012
+		string $question,
1013
+		string $required_text = '',
1014
+		string $required_label = '',
1015
+		string $label_class = '',
1016
+		string $name = ''
1017
+	): string {
1018
+		return $add_mobile_label
1019
+			? self::label($question, $required_text, $required_label, $name, $label_class, false)
1020
+			: '';
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * generates HTML for a form text input
1026
+	 *
1027
+	 * @param string $question    label content
1028
+	 * @param string $answer      form input value attribute
1029
+	 * @param string $name        form input name attribute
1030
+	 * @param string $id          form input css id attribute
1031
+	 * @param string $class       form input css class attribute
1032
+	 * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1033
+	 *                            required 'class', and required 'msg' attribute
1034
+	 * @param string $label_class css class attribute for the label
1035
+	 * @param string $disabled    disabled="disabled" or null
1036
+	 * @return string HTML
1037
+	 */
1038
+	public static function text(
1039
+		$question = false,
1040
+		$answer = null,
1041
+		$name = false,
1042
+		$id = '',
1043
+		$class = '',
1044
+		$required = false,
1045
+		$required_text = '',
1046
+		$label_class = '',
1047
+		$disabled = false,
1048
+		$system_ID = false,
1049
+		$use_html_entities = true,
1050
+		$add_mobile_label = false,
1051
+		$extra_attributes = ''
1052
+	) {
1053
+		// need these
1054
+		if (! $question || ! $name) {
1055
+			return null;
1056
+		}
1057
+		// prep the answer
1058
+		$answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1059
+		// prep the required array
1060
+		$required = self::prep_required($required);
1061
+		// set disabled tag
1062
+		$disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1063
+		// ya gots ta have style man!!!
1064
+		$txt_class = is_admin() ? 'regular-text' : 'espresso-text-inp';
1065
+		$class     = empty($class) ? $txt_class : $class;
1066
+		$class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1067
+		$class = self::appendInputSizeClass($class, $answer);
1068
+		$class .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1069
+		$extra_attributes = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', $extra_attributes);
1070
+
1071
+		$label_html = self::label($question, $required_text, $required['label'], $name, $label_class);
1072
+		$mobile_label = self::mobileLabel(
1073
+			$add_mobile_label,
1074
+			$question,
1075
+			$required_text,
1076
+			$required['label'],
1077
+			$label_class,
1078
+			$name
1079
+		);
1080
+
1081
+		$input_html = $mobile_label . '
1082 1082
             <input  type="text"
1083 1083
                     name="' . $name . '"
1084 1084
                     id="' . $id . '"
@@ -1088,1039 +1088,1039 @@  discard block
 block discarded – undo
1088 1088
                     ' . $disabled . ' ' . $extra_attributes . '
1089 1089
             />';
1090 1090
 
1091
-        $input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1092
-        return $label_html . $input_html;
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     * generates HTML for a form textarea
1098
-     *
1099
-     * @param string $question    label content
1100
-     * @param string $answer      form input value attribute
1101
-     * @param string $name        form input name attribute
1102
-     * @param string $id          form input css id attribute
1103
-     * @param string $class       form input css class attribute
1104
-     * @param array  $dimensions  array of form input rows and cols attributes : array( 'rows' => 3, 'cols' => 40 )
1105
-     * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1106
-     *                            required 'class', and required 'msg' attribute
1107
-     * @param string $label_class css class attribute for the label
1108
-     * @param string $disabled    disabled="disabled" or null
1109
-     * @return string HTML
1110
-     */
1111
-    public static function textarea(
1112
-        $question = false,
1113
-        $answer = null,
1114
-        $name = false,
1115
-        $id = '',
1116
-        $class = '',
1117
-        $dimensions = false,
1118
-        $required = false,
1119
-        $required_text = '',
1120
-        $label_class = '',
1121
-        $disabled = false,
1122
-        $system_ID = false,
1123
-        $use_html_entities = true,
1124
-        $add_mobile_label = false
1125
-    ) {
1126
-        // need these
1127
-        if (! $question || ! $name) {
1128
-            return null;
1129
-        }
1130
-        // prep the answer
1131
-        $answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1132
-        // prep the required array
1133
-        $required = self::prep_required($required);
1134
-        // make sure $dimensions is an array
1135
-        $dimensions = is_array($dimensions) ? $dimensions : [];
1136
-        // and set some defaults
1137
-        $dimensions = array_merge(['rows' => 3, 'cols' => 40], $dimensions);
1138
-        // set disabled tag
1139
-        $disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1140
-        // ya gots ta have style man!!!
1141
-        $class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1142
-        $class     .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1143
-        $extra     = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1144
-
1145
-        $label_html   = self::label($question, $required_text, $required['label'], $name, $label_class);
1146
-        $mobile_label = self::mobileLabel(
1147
-            $add_mobile_label,
1148
-            $question,
1149
-            $required_text,
1150
-            $required['label'],
1151
-            $label_class,
1152
-            $name
1153
-        );
1154
-
1155
-        $input_html = $mobile_label
1156
-            . '<textarea name="' . $name . '" id="' . $id . '" class="' . trim($class) . '" '
1157
-            . 'rows="' . $dimensions['rows'] . '" cols="' . $dimensions['cols'] . '"  '
1158
-            . 'aria-label="' . $required['msg'] . '" ' . $disabled . ' ' . $extra . '>'
1159
-             . esc_textarea($answer)
1160
-              . '</textarea>';
1161
-
1162
-        $input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1163
-        return $label_html . $input_html;
1164
-    }
1165
-
1166
-
1167
-    /**
1168
-     * generates HTML for a form select input
1169
-     *
1170
-     * @param string $question    label content
1171
-     * @param string $answer      form input value attribute
1172
-     * @param array  $options     array of answer options where array key = option value and array value = option
1173
-     *                            display text
1174
-     * @param string $name        form input name attribute
1175
-     * @param string $id          form input css id attribute
1176
-     * @param string $class       form input css class attribute
1177
-     * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1178
-     *                            required 'class', and required 'msg' attribute
1179
-     * @param string $label_class css class attribute for the label
1180
-     * @param string $disabled    disabled="disabled" or null
1181
-     * @return string HTML
1182
-     */
1183
-    public static function select(
1184
-        $question = false,
1185
-        $answer = null,
1186
-        $options = false,
1187
-        $name = false,
1188
-        $id = '',
1189
-        $class = '',
1190
-        $required = false,
1191
-        $required_text = '',
1192
-        $label_class = '',
1193
-        $disabled = false,
1194
-        $system_ID = false,
1195
-        $use_html_entities = true,
1196
-        $add_please_select_option = false,
1197
-        $add_mobile_label = false
1198
-    ) {
1199
-
1200
-        // need these
1201
-        if (! $question || ! $name || ! $options || empty($options) || ! is_array($options)) {
1202
-            return null;
1203
-        }
1204
-        // prep the answer
1205
-        $answer = is_array($answer)
1206
-            ? self::prep_answer(array_shift($answer), $use_html_entities)
1207
-            : self::prep_answer($answer, $use_html_entities);
1208
-        // prep the required array
1209
-        $required = self::prep_required($required);
1210
-        // set disabled tag
1211
-        $disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1212
-        // ya gots ta have style man!!!
1213
-        $class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1214
-        $class = self::appendInputSizeClass($class, $options);
1215
-        $extra     = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1216
-
1217
-        $label_html   = self::label($question, $required_text, $required['label'], $name, $label_class);
1218
-        $mobile_label = self::mobileLabel(
1219
-            $add_mobile_label,
1220
-            $question,
1221
-            $required_text,
1222
-            $required['label'],
1223
-            $label_class,
1224
-            $name
1225
-        );
1226
-
1227
-        $input_html = $mobile_label
1228
-            . '<select name="' . $name . '" id="' . $id . '" class="' . trim($class) . ' ' . $required['class'] . '" '
1229
-            . 'aria-label="' . esc_attr($required['msg']) . '"' . $disabled . ' ' . $extra . '>';
1230
-        // recursively count array elements, to determine total number of options
1231
-        $only_option = count($options, 1) == 1;
1232
-        if (! $only_option) {
1233
-            // if there is NO answer set and there are multiple options to choose from, then set the "please select" message as selected
1234
-            $selected   = $answer === null ? ' selected' : '';
1235
-            $input_html .= $add_please_select_option
1236
-                ? "\n\t\t\t\t"
1237
-                  . '<option value=""' . $selected . '>'
1238
-                  . esc_html__(' - please select - ', 'event_espresso')
1239
-                  . '</option>'
1240
-                : '';
1241
-        }
1242
-        foreach ($options as $key => $value) {
1243
-            // if value is an array, then create option groups, else create regular ol' options
1244
-            $input_html .= is_array($value)
1245
-                ? self::_generate_select_option_group(
1246
-                    $key,
1247
-                    $value,
1248
-                    $answer,
1249
-                    $use_html_entities
1250
-                )
1251
-                : self::_generate_select_option(
1252
-                    $value->value(),
1253
-                    $value->desc(),
1254
-                    $answer,
1255
-                    $only_option,
1256
-                    $use_html_entities
1257
-                );
1258
-        }
1259
-
1260
-        $input_html .= "\n\t\t\t" . '</select>';
1261
-
1262
-        $input_html =
1263
-            apply_filters(
1264
-                'FHEE__EEH_Form_Fields__select__before_end_wrapper',
1265
-                $input_html,
1266
-                $question,
1267
-                $answer,
1268
-                $name,
1269
-                $id,
1270
-                $class,
1271
-                $system_ID
1272
-            );
1273
-
1274
-        $input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1275
-        return $label_html . $input_html;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     *  _generate_select_option_group
1281
-     *
1282
-     *  if  $value for a select box is an array, then the key will be used as the optgroup label
1283
-     *  and the value array will be looped thru and the elements sent to _generate_select_option
1284
-     *
1285
-     * @param mixed   $opt_group
1286
-     * @param mixed   $QSOs
1287
-     * @param mixed   $answer
1288
-     * @param boolean $use_html_entities
1289
-     * @return string
1290
-     */
1291
-    private static function _generate_select_option_group($opt_group, $QSOs, $answer, $use_html_entities = true)
1292
-    {
1293
-        $html = "\n\t\t\t\t" . '<optgroup label="' . self::prep_option_value($opt_group) . '">';
1294
-        foreach ($QSOs as $QSO) {
1295
-            $html .= self::_generate_select_option($QSO->value(), $QSO->desc(), $answer, false, $use_html_entities);
1296
-        }
1297
-        $html .= "\n\t\t\t\t" . '</optgroup>';
1298
-        return $html;
1299
-    }
1300
-
1301
-
1302
-    /**
1303
-     *  _generate_select_option
1304
-     *
1305
-     * @param mixed   $key
1306
-     * @param mixed   $value
1307
-     * @param mixed   $answer
1308
-     * @param int     $only_option
1309
-     * @param boolean $use_html_entities
1310
-     * @return string
1311
-     */
1312
-    private static function _generate_select_option(
1313
-        $key,
1314
-        $value,
1315
-        $answer,
1316
-        $only_option = false,
1317
-        $use_html_entities = true
1318
-    ) {
1319
-        $key      = self::prep_answer($key, $use_html_entities);
1320
-        $value    = self::prep_answer($value, $use_html_entities);
1321
-        $value    = ! empty($value) ? $value : $key;
1322
-        $selected = ($answer == $key || $only_option) ? 'selected' : '';
1323
-        return "\n\t\t\t\t"
1324
-               . '<option value="' . self::prep_option_value($key) . '" ' . $selected . '> '
1325
-               . $value
1326
-               . '&nbsp;&nbsp;&nbsp;</option>';
1327
-    }
1328
-
1329
-
1330
-    /**
1331
-     * generates HTML for form radio button inputs
1332
-     *
1333
-     * @param bool|string $question    label content
1334
-     * @param string      $answer      form input value attribute
1335
-     * @param array|bool  $options     array of answer options where array key = option value and array value = option
1336
-     *                                 display text
1337
-     * @param bool|string $name        form input name attribute
1338
-     * @param string      $id          form input css id attribute
1339
-     * @param string      $class       form input css class attribute
1340
-     * @param array|bool  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1341
-     *                                 required 'class', and required 'msg' attribute
1342
-     * @param string      $required_text
1343
-     * @param string      $label_class css class attribute for the label
1344
-     * @param bool|string $disabled    disabled="disabled" or null
1345
-     * @param bool        $system_ID
1346
-     * @param bool        $use_html_entities
1347
-     * @param bool        $label_b4
1348
-     * @param bool        $use_desc_4_label
1349
-     * @return string HTML
1350
-     */
1351
-    public static function radio(
1352
-        $question = false,
1353
-        $answer = null,
1354
-        $options = false,
1355
-        $name = false,
1356
-        $id = '',
1357
-        $class = '',
1358
-        $required = false,
1359
-        $required_text = '',
1360
-        $label_class = '',
1361
-        $disabled = false,
1362
-        $system_ID = false,
1363
-        $use_html_entities = true,
1364
-        $label_b4 = false,
1365
-        $use_desc_4_label = false,
1366
-        $add_mobile_label = false
1367
-    ) {
1368
-        // need these
1369
-        if (! $question || ! $name || ! $options || empty($options) || ! is_array($options)) {
1370
-            return null;
1371
-        }
1372
-        // prep the answer
1373
-        $answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1374
-        // prep the required array
1375
-        $required = self::prep_required($required);
1376
-        // set disabled tag
1377
-        $disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1378
-        // ya gots ta have style man!!!
1379
-        $radio_class = is_admin() ? 'ee-admin-radio-lbl' : $label_class;
1380
-        $class       = ! empty($class) ? $class : 'espresso-radio-btn-inp';
1381
-        $extra       = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1382
-
1383
-        $label_html = self::label($question, $required_text, $required['label'], '', $label_class);
1384
-        $mobile_label = self::mobileLabel(
1385
-            $add_mobile_label,
1386
-            $question,
1387
-            $required_text,
1388
-            $required['label'],
1389
-            $label_class
1390
-        );
1391
-
1392
-        $input_html = $mobile_label
1393
-            . '<ul id="' . $id . '-ul" class="espresso-radio-btn-options-ul ' . $class . '-ul">';
1394
-
1395
-        $class .= ! empty($system_ID) ? ' ' . $system_ID : '';
1396
-        $class .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1397
-
1398
-        foreach ($options as $OPT) {
1399
-            if ($OPT instanceof EE_Question_Option) {
1400
-                $value   = self::prep_option_value($OPT->value());
1401
-                $label   = $use_desc_4_label ? $OPT->desc() : $OPT->value();
1402
-                $size    = $use_desc_4_label
1403
-                    ? self::get_label_size_class($OPT->value() . ' ' . $OPT->desc())
1404
-                    : self::get_label_size_class($OPT->value());
1405
-                $desc    = $OPT->desc();// no self::prep_answer
1406
-                $answer  = is_numeric($value) && empty($answer) ? 0 : $answer;
1407
-                $checked = (string) $value == (string) $answer ? ' checked' : '';
1408
-                $opt     = '-' . sanitize_key($value);
1409
-
1410
-                $input_html .= "\n\t\t\t\t" . '<li' . $size . '>';
1411
-                $input_html .= "\n\t\t\t\t\t" . '<label class="' . $radio_class . ' espresso-radio-btn-lbl">';
1412
-                $input_html .= $label_b4 ? "\n\t\t\t\t\t\t" . '<span>' . $label . '</span>&nbsp;' : '';
1413
-                $input_html .= "\n\t\t\t\t\t\t"
1414
-                               . '<input type="radio" name="' . $name . '" id="' . $id . $opt . '" '
1415
-                               . 'class="' . $class . '" value="' . $value . '" '
1416
-                               . 'aria-label="' . esc_attr($required['msg']) . '" ' . $disabled
1417
-                               . $checked . ' ' . $extra . '/>';
1418
-                $input_html .= ! $label_b4
1419
-                    ? "\n\t\t\t\t\t\t"
1420
-                      . '&nbsp;<span class="espresso-radio-btn-desc">'
1421
-                      . $label
1422
-                      . '</span>'
1423
-                    : '';
1424
-                $input_html .= "\n\t\t\t\t\t" . '</label>';
1425
-                $input_html .= $use_desc_4_label
1426
-                    ? ''
1427
-                    : '<span class="espresso-radio-btn-option-desc small-text grey-text">' . $desc . '</span>';
1428
-                $input_html .= "\n\t\t\t\t" . '</li>';
1429
-            }
1430
-        }
1431
-
1432
-        $input_html .= "\n\t\t\t" . '</ul>';
1433
-
1434
-        $input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1435
-        return $label_html . $input_html;
1436
-    }
1437
-
1438
-
1439
-    /**
1440
-     * generates HTML for form checkbox inputs
1441
-     *
1442
-     * @param string $question    label content
1443
-     * @param string $answer      form input value attribute
1444
-     * @param array  $options     array of options where array key = option value and array value = option display text
1445
-     * @param string $name        form input name attribute
1446
-     * @param string $id          form input css id attribute
1447
-     * @param string $class       form input css class attribute
1448
-     * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1449
-     *                            required 'class', and required 'msg' attribute
1450
-     * @param string $label_class css class attribute for the label
1451
-     * @param string $disabled    disabled="disabled" or null
1452
-     * @return string HTML
1453
-     */
1454
-    public static function checkbox(
1455
-        $question = false,
1456
-        $answer = null,
1457
-        $options = false,
1458
-        $name = false,
1459
-        $id = '',
1460
-        $class = '',
1461
-        $required = false,
1462
-        $required_text = '',
1463
-        $label_class = '',
1464
-        $disabled = false,
1465
-        $label_b4 = false,
1466
-        $system_ID = false,
1467
-        $use_html_entities = true,
1468
-        $add_mobile_label = false
1469
-    ) {
1470
-        // need these
1471
-        if (! $question || ! $name || ! $options || empty($options) || ! is_array($options)) {
1472
-            return null;
1473
-        }
1474
-        $answer = maybe_unserialize($answer);
1475
-
1476
-        // prep the answer(s)
1477
-        $answer = is_array($answer) ? $answer : [sanitize_key($answer) => $answer];
1478
-
1479
-        foreach ($answer as $key => $value) {
1480
-            $key            = self::prep_option_value($key);
1481
-            $answer[ $key ] = self::prep_answer($value, $use_html_entities);
1482
-        }
1483
-
1484
-        // prep the required array
1485
-        $required = self::prep_required($required);
1486
-        // set disabled tag
1487
-        $disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1488
-        // ya gots ta have style man!!!
1489
-        $radio_class = is_admin() ? 'ee-admin-radio-lbl' : $label_class;
1490
-        $class       = empty($class) ? 'espresso-radio-btn-inp' : $class;
1491
-        $extra       = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1492
-
1493
-        $label_html   = self::label($question, $required_text, $required['label'], '', $label_class);
1494
-        $mobile_label = self::mobileLabel(
1495
-            $add_mobile_label,
1496
-            $question,
1497
-            $required_text,
1498
-            $required['label'],
1499
-            $label_class
1500
-        );
1501
-
1502
-        $input_html = $mobile_label
1503
-            . '<ul id="' . $id . '-ul" class="espresso-checkbox-options-ul ' . $class . '-ul">';
1504
-
1505
-        $class .= ! empty($system_ID) ? ' ' . $system_ID : '';
1506
-        $class .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1507
-
1508
-        foreach ($options as $OPT) {
1509
-            $value = $OPT->value();// self::prep_option_value( $OPT->value() );
1510
-            $size  = self::get_label_size_class($OPT->value() . ' ' . $OPT->desc());
1511
-            $text  = self::prep_answer($OPT->value());
1512
-            $desc  = $OPT->desc();
1513
-            $opt   = '-' . sanitize_key($value);
1514
-
1515
-            $checked = is_array($answer) && in_array($text, $answer) ? ' checked' : '';
1516
-
1517
-            $input_html .= "\n\t\t\t\t" . '<li' . $size . '>';
1518
-            $input_html .= "\n\t\t\t\t\t" . '<label class="' . $radio_class . ' espresso-checkbox-lbl">';
1519
-            $input_html .= $label_b4 ? "\n\t\t\t\t\t\t" . '<span>' . $text . '</span>&nbsp;' : '';
1520
-            $input_html .= "\n\t\t\t\t\t\t"
1521
-                           . '<input type="checkbox" name="' . $name . '[' . $OPT->ID() . ']" '
1522
-                           . 'id="' . $id . $opt . '" class="' . $class . '" value="' . $value . '" '
1523
-                           . 'aria-label="' . esc_attr($required['msg']) . '" ' . $disabled . $checked . ' ' . $extra . '/>';
1524
-            $input_html .= ! $label_b4 ? "\n\t\t\t\t\t\t" . '&nbsp;<span>' . $text . '</span>' : '';
1525
-            $input_html .= "\n\t\t\t\t\t" . '</label>';
1526
-            if (! empty($desc) && $desc != $text) {
1527
-                $input_html .= "\n\t\t\t\t\t"
1528
-                               . ' &nbsp; <br/><div class="espresso-checkbox-option-desc small-text grey-text">'
1529
-                               . $desc
1530
-                               . '</div>';
1531
-            }
1532
-            $input_html .= "\n\t\t\t\t" . '</li>';
1533
-        }
1534
-
1535
-        $input_html .= "\n\t\t\t" . '</ul>';
1536
-
1537
-        $input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1538
-        return $label_html . $input_html;
1539
-    }
1540
-
1541
-
1542
-    /**
1543
-     * generates HTML for a form datepicker input
1544
-     *
1545
-     * @param string $question    label content
1546
-     * @param string $answer      form input value attribute
1547
-     * @param string $name        form input name attribute
1548
-     * @param string $id          form input css id attribute
1549
-     * @param string $class       form input css class attribute
1550
-     * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1551
-     *                            required 'class', and required 'msg' attribute
1552
-     * @param string $label_class css class attribute for the label
1553
-     * @param string $disabled    disabled="disabled" or null
1554
-     * @return string HTML
1555
-     */
1556
-    public static function datepicker(
1557
-        $question = false,
1558
-        $answer = null,
1559
-        $name = false,
1560
-        $id = '',
1561
-        $class = '',
1562
-        $required = false,
1563
-        $required_text = '',
1564
-        $label_class = '',
1565
-        $disabled = false,
1566
-        $system_ID = false,
1567
-        $use_html_entities = true,
1568
-        $add_mobile_label = false
1569
-    ) {
1570
-        // need these
1571
-        if (! $question || ! $name) {
1572
-            return null;
1573
-        }
1574
-        // prep the answer
1575
-        $answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1576
-        // prep the required array
1577
-        $required = self::prep_required($required);
1578
-        // set disabled tag
1579
-        $disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1580
-        // ya gots ta have style man!!!
1581
-        $txt_class = is_admin() ? 'regular-text' : 'espresso-datepicker-inp';
1582
-        $class     = empty($class) ? $txt_class : $class;
1583
-        $class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1584
-        $class = self::appendInputSizeClass($class, $answer);
1585
-        $extra     = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1586
-
1587
-        $label_html   = self::label($question, $required_text, $required['label'], '', $label_class);
1588
-        $mobile_label = self::mobileLabel(
1589
-            $add_mobile_label,
1590
-            $question,
1591
-            $required_text,
1592
-            $required['label'],
1593
-            $label_class,
1594
-            $name
1595
-        );
1596
-
1597
-        $input_html = $mobile_label
1598
-            . '<input type="text" name="' . $name . '" id="' . $id . '" '
1599
-            . 'class="' . $class . ' ' . $required['class'] . ' datepicker" value="' . $answer . '"  '
1600
-            . 'aria-label="' . esc_attr($required['msg']) . '" ' . $disabled . ' ' . $extra . '/>';
1601
-
1602
-        // enqueue scripts
1603
-        wp_register_style(
1604
-            'espresso-ui-theme',
1605
-            EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1606
-            [],
1607
-            EVENT_ESPRESSO_VERSION
1608
-        );
1609
-        wp_enqueue_style('espresso-ui-theme');
1610
-        wp_enqueue_script('jquery-ui-datepicker');
1611
-
1612
-        $input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1613
-        return $label_html . $input_html;
1614
-    }
1615
-
1616
-
1617
-    /**
1618
-     *  remove_label_keep_required_msg
1619
-     *  this will strip out a form input's label HTML while keeping the required text HTML that MUST be before the label
1620
-     *
1621
-     * @access public
1622
-     * @return     string
1623
-     */
1624
-    public static function remove_label_keep_required_msg($label_html, $required_text)
1625
-    {
1626
-        return $required_text;
1627
-    }
1628
-
1629
-
1630
-    /**
1631
-     * Simply returns the HTML for a hidden input of the given name and value.
1632
-     *
1633
-     * @param string $name
1634
-     * @param string $value
1635
-     * @return string HTML
1636
-     */
1637
-    public static function hidden_input($name, $value, $id = '')
1638
-    {
1639
-        $id = ! empty($id) ? $id : $name;
1640
-        return '<input id="' . $id . '" type="hidden" name="' . $name . '" value="' . $value . '"/>';
1641
-    }
1642
-
1643
-
1644
-    /**
1645
-     * prep_question
1646
-     *
1647
-     * @param string $question
1648
-     * @return string
1649
-     */
1650
-    public static function prep_question($question)
1651
-    {
1652
-        return $question;
1653
-    }
1654
-
1655
-
1656
-    /**
1657
-     *  prep_answer
1658
-     *
1659
-     * @param mixed $answer
1660
-     * @return string
1661
-     */
1662
-    public static function prep_answer($answer, $use_html_entities = true)
1663
-    {
1664
-        // make sure we convert bools first.  Otherwise (bool) false becomes an empty string which is NOT desired,
1665
-        // we want "0".
1666
-        if (is_bool($answer)) {
1667
-            $answer = $answer ? 1 : 0;
1668
-        }
1669
-        $answer = trim(stripslashes(str_replace('&#039;', "'", $answer)));
1670
-        return $use_html_entities ? htmlentities($answer, ENT_QUOTES, 'UTF-8') : $answer;
1671
-    }
1672
-
1673
-
1674
-    /**
1675
-     *  prep_answer_options
1676
-     *
1677
-     * @param array $QSOs array of EE_Question_Option objects
1678
-     * @return array
1679
-     */
1680
-    public static function prep_answer_options($QSOs = [])
1681
-    {
1682
-        $prepped_answer_options = [];
1683
-        if (is_array($QSOs) && ! empty($QSOs)) {
1684
-            foreach ($QSOs as $key => $QSO) {
1685
-                if (! $QSO instanceof EE_Question_Option) {
1686
-                    $QSO = EE_Question_Option::new_instance(
1687
-                        [
1688
-                            'QSO_value' => is_array($QSO) && isset($QSO['id'])
1689
-                                ? (string) $QSO['id']
1690
-                                : (string) $key,
1691
-                            'QSO_desc'  => is_array($QSO) && isset($QSO['text'])
1692
-                                ? (string) $QSO['text']
1693
-                                : (string) $QSO,
1694
-                        ]
1695
-                    );
1696
-                }
1697
-                if ($QSO->opt_group()) {
1698
-                    $prepped_answer_options[ $QSO->opt_group() ][] = $QSO;
1699
-                } else {
1700
-                    $prepped_answer_options[] = $QSO;
1701
-                }
1702
-            }
1703
-        }
1704
-        //      d( $prepped_answer_options );
1705
-        return $prepped_answer_options;
1706
-    }
1707
-
1708
-
1709
-    /**
1710
-     *  prep_option_value
1711
-     *
1712
-     * @param string $option_value
1713
-     * @return string
1714
-     */
1715
-    public static function prep_option_value($option_value)
1716
-    {
1717
-        return esc_attr(trim(stripslashes($option_value)));
1718
-    }
1719
-
1720
-
1721
-    /**
1722
-     *  prep_required
1723
-     *
1724
-     * @param string|array $required
1725
-     * @return array
1726
-     */
1727
-    public static function prep_required($required = [])
1728
-    {
1729
-        // make sure required is an array
1730
-        $required = is_array($required) ? $required : [];
1731
-        // and set some defaults
1732
-        return array_merge(['label' => '', 'class' => '', 'msg' => ''], $required);
1733
-    }
1734
-
1735
-
1736
-    /**
1737
-     *  get_label_size_class
1738
-     *
1739
-     * @param string $value
1740
-     * @return string
1741
-     */
1742
-    public static function get_label_size_class($value = false)
1743
-    {
1744
-        if ($value === false || $value === '') {
1745
-            return ' class="medium-lbl"';
1746
-        }
1747
-        // determine length of option value
1748
-        $val_size = strlen($value);
1749
-        switch ($val_size) {
1750
-            case $val_size < 3:
1751
-                $size = ' class="nano-lbl"';
1752
-                break;
1753
-            case $val_size < 6:
1754
-                $size = ' class="micro-lbl"';
1755
-                break;
1756
-            case $val_size < 12:
1757
-                $size = ' class="tiny-lbl"';
1758
-                break;
1759
-            case $val_size < 25:
1760
-                $size = ' class="small-lbl"';
1761
-                break;
1762
-            case $val_size > 100:
1763
-                $size = ' class="big-lbl"';
1764
-                break;
1765
-            default:
1766
-                $size = ' class="medium-lbl"';
1767
-                break;
1768
-        }
1769
-        return $size;
1770
-    }
1771
-
1772
-
1773
-    /**
1774
-     *  _load_system_dropdowns
1775
-     *
1776
-     * @param EE_Question_Form_Input $QFI
1777
-     * @return array
1778
-     * @throws EE_Error
1779
-     * @throws ReflectionException
1780
-     */
1781
-    private static function _load_system_dropdowns($QFI)
1782
-    {
1783
-        $QST_system = $QFI->get('QST_system');
1784
-        switch ($QST_system) {
1785
-            case 'state':
1786
-                $QFI = self::generate_state_dropdown($QFI);
1787
-                break;
1788
-            case 'country':
1789
-                $QFI = self::generate_country_dropdown($QFI);
1790
-                break;
1791
-            case 'admin-state':
1792
-                $QFI = self::generate_state_dropdown($QFI, true);
1793
-                break;
1794
-            case 'admin-country':
1795
-                $QFI = self::generate_country_dropdown($QFI, true);
1796
-                break;
1797
-        }
1798
-        return $QFI;
1799
-    }
1800
-
1801
-
1802
-    /**
1803
-     * This preps dropdowns that are specialized.
1804
-     *
1805
-     * @param EE_Question_Form_Input $QFI
1806
-     *
1807
-     * @return EE_Question_Form_Input
1808
-     * @throws EE_Error
1809
-     * @throws ReflectionException
1810
-     * @since  4.6.0
1811
-     */
1812
-    protected static function _load_specialized_dropdowns($QFI)
1813
-    {
1814
-        switch ($QFI->get('QST_type')) {
1815
-            case 'STATE':
1816
-                $QFI = self::generate_state_dropdown($QFI);
1817
-                break;
1818
-            case 'COUNTRY':
1819
-                $QFI = self::generate_country_dropdown($QFI);
1820
-                break;
1821
-        }
1822
-        return $QFI;
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     *    generate_state_dropdown
1828
-     *
1829
-     * @param EE_Question_Form_Input $QST
1830
-     * @param bool                   $get_all
1831
-     * @return EE_Question_Form_Input
1832
-     * @throws EE_Error
1833
-     * @throws ReflectionException
1834
-     */
1835
-    public static function generate_state_dropdown($QST, $get_all = false)
1836
-    {
1837
-        $states = $get_all
1838
-            ? EEM_State::instance()->get_all_states()
1839
-            : EEM_State::instance()->get_all_states_of_active_countries();
1840
-        if ($states && count($states) != count($QST->options())) {
1841
-            $QST->set('QST_type', 'DROPDOWN');
1842
-            // if multiple countries, we'll create option groups within the dropdown
1843
-            foreach ($states as $state) {
1844
-                if ($state instanceof EE_State) {
1845
-                    $QSO = EE_Question_Option::new_instance(
1846
-                        [
1847
-                            'QSO_value'   => $state->ID(),
1848
-                            'QSO_desc'    => $state->name(),
1849
-                            'QST_ID'      => $QST->get('QST_ID'),
1850
-                            'QSO_deleted' => false,
1851
-                        ]
1852
-                    );
1853
-                    // set option group
1854
-                    $QSO->set_opt_group($state->country()->name());
1855
-                    // add option to question
1856
-                    $QST->add_temp_option($QSO);
1857
-                }
1858
-            }
1859
-        }
1860
-        return $QST;
1861
-    }
1862
-
1863
-
1864
-    /**
1865
-     *    generate_country_dropdown
1866
-     *
1867
-     * @param      $QST
1868
-     * @param bool $get_all
1869
-     * @return array
1870
-     * @throws EE_Error
1871
-     * @throws ReflectionException
1872
-     * @internal param array $question
1873
-     */
1874
-    public static function generate_country_dropdown($QST, $get_all = false)
1875
-    {
1876
-        $countries = $get_all
1877
-            ? EEM_Country::instance()->get_all_countries()
1878
-            : EEM_Country::instance()->get_all_active_countries();
1879
-        if ($countries && count($countries) != count($QST->options())) {
1880
-            $QST->set('QST_type', 'DROPDOWN');
1881
-            // now add countries
1882
-            foreach ($countries as $country) {
1883
-                if ($country instanceof EE_Country) {
1884
-                    $QSO = EE_Question_Option::new_instance(
1885
-                        [
1886
-                            'QSO_value'   => $country->ID(),
1887
-                            'QSO_desc'    => $country->name(),
1888
-                            'QST_ID'      => $QST->get('QST_ID'),
1889
-                            'QSO_deleted' => false,
1890
-                        ]
1891
-                    );
1892
-                    $QST->add_temp_option($QSO);
1893
-                }
1894
-            }
1895
-        }
1896
-        return $QST;
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     *  generates options for a month dropdown selector with numbers from 01 to 12
1902
-     *
1903
-     * @return array()
1904
-     */
1905
-    public static function two_digit_months_dropdown_options()
1906
-    {
1907
-        $options = [];
1908
-        for ($x = 1; $x <= 12; $x++) {
1909
-            $mm             = str_pad($x, 2, '0', STR_PAD_LEFT);
1910
-            $options[ $mm ] = $mm;
1911
-        }
1912
-        return EEH_Form_Fields::prep_answer_options($options);
1913
-    }
1914
-
1915
-
1916
-    /**
1917
-     *  generates a year dropdown selector with numbers for the next ten years
1918
-     *
1919
-     * @return array
1920
-     */
1921
-    public static function next_decade_two_digit_year_dropdown_options()
1922
-    {
1923
-        $options      = [];
1924
-        $current_year = date('y');
1925
-        $next_decade  = $current_year + 10;
1926
-        for ($x = $current_year; $x <= $next_decade; $x++) {
1927
-            $yy             = str_pad($x, 2, '0', STR_PAD_LEFT);
1928
-            $options[ $yy ] = $yy;
1929
-        }
1930
-        return EEH_Form_Fields::prep_answer_options($options);
1931
-    }
1932
-
1933
-
1934
-    /**
1935
-     * generates a month/year dropdown selector for all registrations matching the given criteria.  Typically used for
1936
-     * list table filter.
1937
-     *
1938
-     * @param string  $cur_date     any currently selected date can be entered here.
1939
-     * @param string  $status       Registration status
1940
-     * @param integer $evt_category Event Category ID if the Event Category filter is selected
1941
-     * @return string                html
1942
-     * @throws EE_Error
1943
-     */
1944
-    public static function generate_registration_months_dropdown($cur_date = '', $status = '', $evt_category = 0)
1945
-    {
1946
-        $_where = [];
1947
-        if (! empty($status)) {
1948
-            $_where['STS_ID'] = $status;
1949
-        }
1950
-
1951
-        if ($evt_category > 0) {
1952
-            $_where['Event.Term_Taxonomy.term_id'] = $evt_category;
1953
-        }
1954
-
1955
-        $regdtts = EEM_Registration::instance()->get_reg_months_and_years($_where);
1956
-
1957
-        // setup vals for select input helper
1958
-        $options = [
1959
-            0 => [
1960
-                'text' => esc_html__('Select a Month/Year', 'event_espresso'),
1961
-                'id'   => '',
1962
-            ],
1963
-        ];
1964
-
1965
-        foreach ($regdtts as $regdtt) {
1966
-            $date      = $regdtt->reg_month . ' ' . $regdtt->reg_year;
1967
-            $options[] = [
1968
-                'text' => $date,
1969
-                'id'   => $date,
1970
-            ];
1971
-        }
1972
-
1973
-        return self::select_input('month_range', $options, $cur_date);
1974
-    }
1975
-
1976
-
1977
-    /**
1978
-     * generates a month/year dropdown selector for all events matching the given criteria
1979
-     * Typically used for list table filter
1980
-     *
1981
-     * @param string $cur_date          any currently selected date can be entered here.
1982
-     * @param string $status            "view" (i.e. all, today, month, draft)
1983
-     * @param int    $evt_category      category event belongs to
1984
-     * @param string $evt_active_status "upcoming", "expired", "active", or "inactive"
1985
-     * @return string                    html
1986
-     * @throws EE_Error
1987
-     */
1988
-    public static function generate_event_months_dropdown(
1989
-        $cur_date = '',
1990
-        $status = null,
1991
-        $evt_category = null,
1992
-        $evt_active_status = null
1993
-    ) {
1994
-        // determine what post_status our condition will have for the query.
1995
-        // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
1996
-        switch ($status) {
1997
-            case 'month':
1998
-            case 'today':
1999
-            case null:
2000
-            case 'all':
2001
-                $where['Event.status'] = ['NOT IN', ['trash']];
2002
-                break;
2003
-            case 'draft':
2004
-                $where['Event.status'] = ['IN', ['draft', 'auto-draft']];
2005
-                break;
2006
-            default:
2007
-                $where['Event.status'] = $status;
2008
-        }
2009
-
2010
-        // phpcs:enable
2011
-
2012
-        // categories?
2013
-
2014
-
2015
-        if (! empty($evt_category) and $evt_category > 0) {
2016
-            $where['Event.Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
2017
-            $where['Event.Term_Taxonomy.term_id']  = $evt_category;
2018
-        }
2019
-
2020
-
2021
-        //      $where['DTT_is_primary'] = 1;
2022
-
2023
-        $DTTS = EEM_Datetime::instance()->get_dtt_months_and_years($where, $evt_active_status);
2024
-
2025
-        // let's setup vals for select input helper
2026
-        $options = [
2027
-            0 => [
2028
-                'text' => esc_html__('Select a Month/Year', 'event_espresso'),
2029
-                'id'   => "",
2030
-            ],
2031
-        ];
2032
-
2033
-
2034
-        // translate month and date
2035
-        global $wp_locale;
2036
-
2037
-        foreach ($DTTS as $DTT) {
2038
-            $localized_date = $wp_locale->get_month($DTT->dtt_month_num) . ' ' . $DTT->dtt_year;
2039
-            $id             = $DTT->dtt_month . ' ' . $DTT->dtt_year;
2040
-            $options[]      = [
2041
-                'text' => $localized_date,
2042
-                'id'   => $id,
2043
-            ];
2044
-        }
2045
-
2046
-
2047
-        return self::select_input('month_range', $options, $cur_date);
2048
-    }
2049
-
2050
-
2051
-    /**
2052
-     * generates the dropdown selector for event categories
2053
-     * typically used as a filter on list tables.
2054
-     *
2055
-     * @param integer $current_cat currently selected category
2056
-     * @return string               html for dropdown
2057
-     * @throws EE_Error
2058
-     * @throws ReflectionException
2059
-     */
2060
-    public static function generate_event_category_dropdown($current_cat = -1)
2061
-    {
2062
-        $categories = EEM_Term::instance()->get_all_ee_categories(true);
2063
-        $options    = [
2064
-            '0' => [
2065
-                'text' => esc_html__('All Categories', 'event_espresso'),
2066
-                'id'   => -1,
2067
-            ],
2068
-        ];
2069
-
2070
-        // setup categories for dropdown
2071
-        foreach ($categories as $category) {
2072
-            $options[] = [
2073
-                'text' => $category->get('name'),
2074
-                'id'   => $category->ID(),
2075
-            ];
2076
-        }
2077
-
2078
-        return self::select_input('EVT_CAT', $options, $current_cat);
2079
-    }
2080
-
2081
-
2082
-    /**
2083
-     *    generate a submit button with or without it's own microform
2084
-     *    this is the only way to create buttons that are compatible across all themes
2085
-     *
2086
-     * @access    public
2087
-     * @param string      $url              - the form action
2088
-     * @param string      $ID               - some kind of unique ID, appended with "-sbmt" for the input and "-frm"
2089
-     *                                      for the form
2090
-     * @param string      $class            - css classes (separated by spaces if more than one)
2091
-     * @param string      $text             - what appears on the button
2092
-     * @param string      $nonce_action     - if using nonces
2093
-     * @param bool|string $input_only       - whether to print form header and footer. TRUE returns the input without
2094
-     *                                      the form
2095
-     * @param string      $extra_attributes - any extra attributes that need to be attached to the form input
2096
-     * @return    string
2097
-     */
2098
-    public static function submit_button(
2099
-        $url = '',
2100
-        $ID = '',
2101
-        $class = '',
2102
-        $text = '',
2103
-        $nonce_action = '',
2104
-        $input_only = false,
2105
-        $extra_attributes = ''
2106
-    ) {
2107
-        $btn = '';
2108
-        if (empty($url) || empty($ID)) {
2109
-            return $btn;
2110
-        }
2111
-        $text = ! empty($text) ? $text : esc_html__('Submit', 'event_espresso');
2112
-        $btn  .= '<input id="' . $ID . '-btn" class="' . $class . '" '
2113
-                 . 'type="submit" value="' . $text . '" ' . $extra_attributes . '/>';
2114
-        if (! $input_only) {
2115
-            $btn_frm = '<form id="' . $ID . '-frm" method="POST" action="' . $url . '">';
2116
-            $btn_frm .= ! empty($nonce_action)
2117
-                ? wp_nonce_field($nonce_action, $nonce_action . '_nonce', true, false)
2118
-                : '';
2119
-            $btn_frm .= $btn;
2120
-            $btn_frm .= '</form>';
2121
-            $btn     = $btn_frm;
2122
-            unset($btn_frm);
2123
-        }
2124
-        return $btn;
2125
-    }
1091
+		$input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1092
+		return $label_html . $input_html;
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 * generates HTML for a form textarea
1098
+	 *
1099
+	 * @param string $question    label content
1100
+	 * @param string $answer      form input value attribute
1101
+	 * @param string $name        form input name attribute
1102
+	 * @param string $id          form input css id attribute
1103
+	 * @param string $class       form input css class attribute
1104
+	 * @param array  $dimensions  array of form input rows and cols attributes : array( 'rows' => 3, 'cols' => 40 )
1105
+	 * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1106
+	 *                            required 'class', and required 'msg' attribute
1107
+	 * @param string $label_class css class attribute for the label
1108
+	 * @param string $disabled    disabled="disabled" or null
1109
+	 * @return string HTML
1110
+	 */
1111
+	public static function textarea(
1112
+		$question = false,
1113
+		$answer = null,
1114
+		$name = false,
1115
+		$id = '',
1116
+		$class = '',
1117
+		$dimensions = false,
1118
+		$required = false,
1119
+		$required_text = '',
1120
+		$label_class = '',
1121
+		$disabled = false,
1122
+		$system_ID = false,
1123
+		$use_html_entities = true,
1124
+		$add_mobile_label = false
1125
+	) {
1126
+		// need these
1127
+		if (! $question || ! $name) {
1128
+			return null;
1129
+		}
1130
+		// prep the answer
1131
+		$answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1132
+		// prep the required array
1133
+		$required = self::prep_required($required);
1134
+		// make sure $dimensions is an array
1135
+		$dimensions = is_array($dimensions) ? $dimensions : [];
1136
+		// and set some defaults
1137
+		$dimensions = array_merge(['rows' => 3, 'cols' => 40], $dimensions);
1138
+		// set disabled tag
1139
+		$disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1140
+		// ya gots ta have style man!!!
1141
+		$class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1142
+		$class     .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1143
+		$extra     = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1144
+
1145
+		$label_html   = self::label($question, $required_text, $required['label'], $name, $label_class);
1146
+		$mobile_label = self::mobileLabel(
1147
+			$add_mobile_label,
1148
+			$question,
1149
+			$required_text,
1150
+			$required['label'],
1151
+			$label_class,
1152
+			$name
1153
+		);
1154
+
1155
+		$input_html = $mobile_label
1156
+			. '<textarea name="' . $name . '" id="' . $id . '" class="' . trim($class) . '" '
1157
+			. 'rows="' . $dimensions['rows'] . '" cols="' . $dimensions['cols'] . '"  '
1158
+			. 'aria-label="' . $required['msg'] . '" ' . $disabled . ' ' . $extra . '>'
1159
+			 . esc_textarea($answer)
1160
+			  . '</textarea>';
1161
+
1162
+		$input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1163
+		return $label_html . $input_html;
1164
+	}
1165
+
1166
+
1167
+	/**
1168
+	 * generates HTML for a form select input
1169
+	 *
1170
+	 * @param string $question    label content
1171
+	 * @param string $answer      form input value attribute
1172
+	 * @param array  $options     array of answer options where array key = option value and array value = option
1173
+	 *                            display text
1174
+	 * @param string $name        form input name attribute
1175
+	 * @param string $id          form input css id attribute
1176
+	 * @param string $class       form input css class attribute
1177
+	 * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1178
+	 *                            required 'class', and required 'msg' attribute
1179
+	 * @param string $label_class css class attribute for the label
1180
+	 * @param string $disabled    disabled="disabled" or null
1181
+	 * @return string HTML
1182
+	 */
1183
+	public static function select(
1184
+		$question = false,
1185
+		$answer = null,
1186
+		$options = false,
1187
+		$name = false,
1188
+		$id = '',
1189
+		$class = '',
1190
+		$required = false,
1191
+		$required_text = '',
1192
+		$label_class = '',
1193
+		$disabled = false,
1194
+		$system_ID = false,
1195
+		$use_html_entities = true,
1196
+		$add_please_select_option = false,
1197
+		$add_mobile_label = false
1198
+	) {
1199
+
1200
+		// need these
1201
+		if (! $question || ! $name || ! $options || empty($options) || ! is_array($options)) {
1202
+			return null;
1203
+		}
1204
+		// prep the answer
1205
+		$answer = is_array($answer)
1206
+			? self::prep_answer(array_shift($answer), $use_html_entities)
1207
+			: self::prep_answer($answer, $use_html_entities);
1208
+		// prep the required array
1209
+		$required = self::prep_required($required);
1210
+		// set disabled tag
1211
+		$disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1212
+		// ya gots ta have style man!!!
1213
+		$class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1214
+		$class = self::appendInputSizeClass($class, $options);
1215
+		$extra     = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1216
+
1217
+		$label_html   = self::label($question, $required_text, $required['label'], $name, $label_class);
1218
+		$mobile_label = self::mobileLabel(
1219
+			$add_mobile_label,
1220
+			$question,
1221
+			$required_text,
1222
+			$required['label'],
1223
+			$label_class,
1224
+			$name
1225
+		);
1226
+
1227
+		$input_html = $mobile_label
1228
+			. '<select name="' . $name . '" id="' . $id . '" class="' . trim($class) . ' ' . $required['class'] . '" '
1229
+			. 'aria-label="' . esc_attr($required['msg']) . '"' . $disabled . ' ' . $extra . '>';
1230
+		// recursively count array elements, to determine total number of options
1231
+		$only_option = count($options, 1) == 1;
1232
+		if (! $only_option) {
1233
+			// if there is NO answer set and there are multiple options to choose from, then set the "please select" message as selected
1234
+			$selected   = $answer === null ? ' selected' : '';
1235
+			$input_html .= $add_please_select_option
1236
+				? "\n\t\t\t\t"
1237
+				  . '<option value=""' . $selected . '>'
1238
+				  . esc_html__(' - please select - ', 'event_espresso')
1239
+				  . '</option>'
1240
+				: '';
1241
+		}
1242
+		foreach ($options as $key => $value) {
1243
+			// if value is an array, then create option groups, else create regular ol' options
1244
+			$input_html .= is_array($value)
1245
+				? self::_generate_select_option_group(
1246
+					$key,
1247
+					$value,
1248
+					$answer,
1249
+					$use_html_entities
1250
+				)
1251
+				: self::_generate_select_option(
1252
+					$value->value(),
1253
+					$value->desc(),
1254
+					$answer,
1255
+					$only_option,
1256
+					$use_html_entities
1257
+				);
1258
+		}
1259
+
1260
+		$input_html .= "\n\t\t\t" . '</select>';
1261
+
1262
+		$input_html =
1263
+			apply_filters(
1264
+				'FHEE__EEH_Form_Fields__select__before_end_wrapper',
1265
+				$input_html,
1266
+				$question,
1267
+				$answer,
1268
+				$name,
1269
+				$id,
1270
+				$class,
1271
+				$system_ID
1272
+			);
1273
+
1274
+		$input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1275
+		return $label_html . $input_html;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 *  _generate_select_option_group
1281
+	 *
1282
+	 *  if  $value for a select box is an array, then the key will be used as the optgroup label
1283
+	 *  and the value array will be looped thru and the elements sent to _generate_select_option
1284
+	 *
1285
+	 * @param mixed   $opt_group
1286
+	 * @param mixed   $QSOs
1287
+	 * @param mixed   $answer
1288
+	 * @param boolean $use_html_entities
1289
+	 * @return string
1290
+	 */
1291
+	private static function _generate_select_option_group($opt_group, $QSOs, $answer, $use_html_entities = true)
1292
+	{
1293
+		$html = "\n\t\t\t\t" . '<optgroup label="' . self::prep_option_value($opt_group) . '">';
1294
+		foreach ($QSOs as $QSO) {
1295
+			$html .= self::_generate_select_option($QSO->value(), $QSO->desc(), $answer, false, $use_html_entities);
1296
+		}
1297
+		$html .= "\n\t\t\t\t" . '</optgroup>';
1298
+		return $html;
1299
+	}
1300
+
1301
+
1302
+	/**
1303
+	 *  _generate_select_option
1304
+	 *
1305
+	 * @param mixed   $key
1306
+	 * @param mixed   $value
1307
+	 * @param mixed   $answer
1308
+	 * @param int     $only_option
1309
+	 * @param boolean $use_html_entities
1310
+	 * @return string
1311
+	 */
1312
+	private static function _generate_select_option(
1313
+		$key,
1314
+		$value,
1315
+		$answer,
1316
+		$only_option = false,
1317
+		$use_html_entities = true
1318
+	) {
1319
+		$key      = self::prep_answer($key, $use_html_entities);
1320
+		$value    = self::prep_answer($value, $use_html_entities);
1321
+		$value    = ! empty($value) ? $value : $key;
1322
+		$selected = ($answer == $key || $only_option) ? 'selected' : '';
1323
+		return "\n\t\t\t\t"
1324
+			   . '<option value="' . self::prep_option_value($key) . '" ' . $selected . '> '
1325
+			   . $value
1326
+			   . '&nbsp;&nbsp;&nbsp;</option>';
1327
+	}
1328
+
1329
+
1330
+	/**
1331
+	 * generates HTML for form radio button inputs
1332
+	 *
1333
+	 * @param bool|string $question    label content
1334
+	 * @param string      $answer      form input value attribute
1335
+	 * @param array|bool  $options     array of answer options where array key = option value and array value = option
1336
+	 *                                 display text
1337
+	 * @param bool|string $name        form input name attribute
1338
+	 * @param string      $id          form input css id attribute
1339
+	 * @param string      $class       form input css class attribute
1340
+	 * @param array|bool  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1341
+	 *                                 required 'class', and required 'msg' attribute
1342
+	 * @param string      $required_text
1343
+	 * @param string      $label_class css class attribute for the label
1344
+	 * @param bool|string $disabled    disabled="disabled" or null
1345
+	 * @param bool        $system_ID
1346
+	 * @param bool        $use_html_entities
1347
+	 * @param bool        $label_b4
1348
+	 * @param bool        $use_desc_4_label
1349
+	 * @return string HTML
1350
+	 */
1351
+	public static function radio(
1352
+		$question = false,
1353
+		$answer = null,
1354
+		$options = false,
1355
+		$name = false,
1356
+		$id = '',
1357
+		$class = '',
1358
+		$required = false,
1359
+		$required_text = '',
1360
+		$label_class = '',
1361
+		$disabled = false,
1362
+		$system_ID = false,
1363
+		$use_html_entities = true,
1364
+		$label_b4 = false,
1365
+		$use_desc_4_label = false,
1366
+		$add_mobile_label = false
1367
+	) {
1368
+		// need these
1369
+		if (! $question || ! $name || ! $options || empty($options) || ! is_array($options)) {
1370
+			return null;
1371
+		}
1372
+		// prep the answer
1373
+		$answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1374
+		// prep the required array
1375
+		$required = self::prep_required($required);
1376
+		// set disabled tag
1377
+		$disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1378
+		// ya gots ta have style man!!!
1379
+		$radio_class = is_admin() ? 'ee-admin-radio-lbl' : $label_class;
1380
+		$class       = ! empty($class) ? $class : 'espresso-radio-btn-inp';
1381
+		$extra       = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1382
+
1383
+		$label_html = self::label($question, $required_text, $required['label'], '', $label_class);
1384
+		$mobile_label = self::mobileLabel(
1385
+			$add_mobile_label,
1386
+			$question,
1387
+			$required_text,
1388
+			$required['label'],
1389
+			$label_class
1390
+		);
1391
+
1392
+		$input_html = $mobile_label
1393
+			. '<ul id="' . $id . '-ul" class="espresso-radio-btn-options-ul ' . $class . '-ul">';
1394
+
1395
+		$class .= ! empty($system_ID) ? ' ' . $system_ID : '';
1396
+		$class .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1397
+
1398
+		foreach ($options as $OPT) {
1399
+			if ($OPT instanceof EE_Question_Option) {
1400
+				$value   = self::prep_option_value($OPT->value());
1401
+				$label   = $use_desc_4_label ? $OPT->desc() : $OPT->value();
1402
+				$size    = $use_desc_4_label
1403
+					? self::get_label_size_class($OPT->value() . ' ' . $OPT->desc())
1404
+					: self::get_label_size_class($OPT->value());
1405
+				$desc    = $OPT->desc();// no self::prep_answer
1406
+				$answer  = is_numeric($value) && empty($answer) ? 0 : $answer;
1407
+				$checked = (string) $value == (string) $answer ? ' checked' : '';
1408
+				$opt     = '-' . sanitize_key($value);
1409
+
1410
+				$input_html .= "\n\t\t\t\t" . '<li' . $size . '>';
1411
+				$input_html .= "\n\t\t\t\t\t" . '<label class="' . $radio_class . ' espresso-radio-btn-lbl">';
1412
+				$input_html .= $label_b4 ? "\n\t\t\t\t\t\t" . '<span>' . $label . '</span>&nbsp;' : '';
1413
+				$input_html .= "\n\t\t\t\t\t\t"
1414
+							   . '<input type="radio" name="' . $name . '" id="' . $id . $opt . '" '
1415
+							   . 'class="' . $class . '" value="' . $value . '" '
1416
+							   . 'aria-label="' . esc_attr($required['msg']) . '" ' . $disabled
1417
+							   . $checked . ' ' . $extra . '/>';
1418
+				$input_html .= ! $label_b4
1419
+					? "\n\t\t\t\t\t\t"
1420
+					  . '&nbsp;<span class="espresso-radio-btn-desc">'
1421
+					  . $label
1422
+					  . '</span>'
1423
+					: '';
1424
+				$input_html .= "\n\t\t\t\t\t" . '</label>';
1425
+				$input_html .= $use_desc_4_label
1426
+					? ''
1427
+					: '<span class="espresso-radio-btn-option-desc small-text grey-text">' . $desc . '</span>';
1428
+				$input_html .= "\n\t\t\t\t" . '</li>';
1429
+			}
1430
+		}
1431
+
1432
+		$input_html .= "\n\t\t\t" . '</ul>';
1433
+
1434
+		$input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1435
+		return $label_html . $input_html;
1436
+	}
1437
+
1438
+
1439
+	/**
1440
+	 * generates HTML for form checkbox inputs
1441
+	 *
1442
+	 * @param string $question    label content
1443
+	 * @param string $answer      form input value attribute
1444
+	 * @param array  $options     array of options where array key = option value and array value = option display text
1445
+	 * @param string $name        form input name attribute
1446
+	 * @param string $id          form input css id attribute
1447
+	 * @param string $class       form input css class attribute
1448
+	 * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1449
+	 *                            required 'class', and required 'msg' attribute
1450
+	 * @param string $label_class css class attribute for the label
1451
+	 * @param string $disabled    disabled="disabled" or null
1452
+	 * @return string HTML
1453
+	 */
1454
+	public static function checkbox(
1455
+		$question = false,
1456
+		$answer = null,
1457
+		$options = false,
1458
+		$name = false,
1459
+		$id = '',
1460
+		$class = '',
1461
+		$required = false,
1462
+		$required_text = '',
1463
+		$label_class = '',
1464
+		$disabled = false,
1465
+		$label_b4 = false,
1466
+		$system_ID = false,
1467
+		$use_html_entities = true,
1468
+		$add_mobile_label = false
1469
+	) {
1470
+		// need these
1471
+		if (! $question || ! $name || ! $options || empty($options) || ! is_array($options)) {
1472
+			return null;
1473
+		}
1474
+		$answer = maybe_unserialize($answer);
1475
+
1476
+		// prep the answer(s)
1477
+		$answer = is_array($answer) ? $answer : [sanitize_key($answer) => $answer];
1478
+
1479
+		foreach ($answer as $key => $value) {
1480
+			$key            = self::prep_option_value($key);
1481
+			$answer[ $key ] = self::prep_answer($value, $use_html_entities);
1482
+		}
1483
+
1484
+		// prep the required array
1485
+		$required = self::prep_required($required);
1486
+		// set disabled tag
1487
+		$disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1488
+		// ya gots ta have style man!!!
1489
+		$radio_class = is_admin() ? 'ee-admin-radio-lbl' : $label_class;
1490
+		$class       = empty($class) ? 'espresso-radio-btn-inp' : $class;
1491
+		$extra       = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1492
+
1493
+		$label_html   = self::label($question, $required_text, $required['label'], '', $label_class);
1494
+		$mobile_label = self::mobileLabel(
1495
+			$add_mobile_label,
1496
+			$question,
1497
+			$required_text,
1498
+			$required['label'],
1499
+			$label_class
1500
+		);
1501
+
1502
+		$input_html = $mobile_label
1503
+			. '<ul id="' . $id . '-ul" class="espresso-checkbox-options-ul ' . $class . '-ul">';
1504
+
1505
+		$class .= ! empty($system_ID) ? ' ' . $system_ID : '';
1506
+		$class .= ! empty($required['class']) ? ' ' . $required['class'] : '';
1507
+
1508
+		foreach ($options as $OPT) {
1509
+			$value = $OPT->value();// self::prep_option_value( $OPT->value() );
1510
+			$size  = self::get_label_size_class($OPT->value() . ' ' . $OPT->desc());
1511
+			$text  = self::prep_answer($OPT->value());
1512
+			$desc  = $OPT->desc();
1513
+			$opt   = '-' . sanitize_key($value);
1514
+
1515
+			$checked = is_array($answer) && in_array($text, $answer) ? ' checked' : '';
1516
+
1517
+			$input_html .= "\n\t\t\t\t" . '<li' . $size . '>';
1518
+			$input_html .= "\n\t\t\t\t\t" . '<label class="' . $radio_class . ' espresso-checkbox-lbl">';
1519
+			$input_html .= $label_b4 ? "\n\t\t\t\t\t\t" . '<span>' . $text . '</span>&nbsp;' : '';
1520
+			$input_html .= "\n\t\t\t\t\t\t"
1521
+						   . '<input type="checkbox" name="' . $name . '[' . $OPT->ID() . ']" '
1522
+						   . 'id="' . $id . $opt . '" class="' . $class . '" value="' . $value . '" '
1523
+						   . 'aria-label="' . esc_attr($required['msg']) . '" ' . $disabled . $checked . ' ' . $extra . '/>';
1524
+			$input_html .= ! $label_b4 ? "\n\t\t\t\t\t\t" . '&nbsp;<span>' . $text . '</span>' : '';
1525
+			$input_html .= "\n\t\t\t\t\t" . '</label>';
1526
+			if (! empty($desc) && $desc != $text) {
1527
+				$input_html .= "\n\t\t\t\t\t"
1528
+							   . ' &nbsp; <br/><div class="espresso-checkbox-option-desc small-text grey-text">'
1529
+							   . $desc
1530
+							   . '</div>';
1531
+			}
1532
+			$input_html .= "\n\t\t\t\t" . '</li>';
1533
+		}
1534
+
1535
+		$input_html .= "\n\t\t\t" . '</ul>';
1536
+
1537
+		$input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1538
+		return $label_html . $input_html;
1539
+	}
1540
+
1541
+
1542
+	/**
1543
+	 * generates HTML for a form datepicker input
1544
+	 *
1545
+	 * @param string $question    label content
1546
+	 * @param string $answer      form input value attribute
1547
+	 * @param string $name        form input name attribute
1548
+	 * @param string $id          form input css id attribute
1549
+	 * @param string $class       form input css class attribute
1550
+	 * @param array  $required    'label', 'class', and 'msg' - array of values for required "label" content, css
1551
+	 *                            required 'class', and required 'msg' attribute
1552
+	 * @param string $label_class css class attribute for the label
1553
+	 * @param string $disabled    disabled="disabled" or null
1554
+	 * @return string HTML
1555
+	 */
1556
+	public static function datepicker(
1557
+		$question = false,
1558
+		$answer = null,
1559
+		$name = false,
1560
+		$id = '',
1561
+		$class = '',
1562
+		$required = false,
1563
+		$required_text = '',
1564
+		$label_class = '',
1565
+		$disabled = false,
1566
+		$system_ID = false,
1567
+		$use_html_entities = true,
1568
+		$add_mobile_label = false
1569
+	) {
1570
+		// need these
1571
+		if (! $question || ! $name) {
1572
+			return null;
1573
+		}
1574
+		// prep the answer
1575
+		$answer = is_array($answer) ? '' : self::prep_answer($answer, $use_html_entities);
1576
+		// prep the required array
1577
+		$required = self::prep_required($required);
1578
+		// set disabled tag
1579
+		$disabled = $answer === null || ! $disabled ? '' : ' disabled="disabled"';
1580
+		// ya gots ta have style man!!!
1581
+		$txt_class = is_admin() ? 'regular-text' : 'espresso-datepicker-inp';
1582
+		$class     = empty($class) ? $txt_class : $class;
1583
+		$class     .= ! empty($system_ID) ? ' ' . $system_ID : '';
1584
+		$class = self::appendInputSizeClass($class, $answer);
1585
+		$extra     = apply_filters('FHEE__EEH_Form_Fields__additional_form_field_attributes', '');
1586
+
1587
+		$label_html   = self::label($question, $required_text, $required['label'], '', $label_class);
1588
+		$mobile_label = self::mobileLabel(
1589
+			$add_mobile_label,
1590
+			$question,
1591
+			$required_text,
1592
+			$required['label'],
1593
+			$label_class,
1594
+			$name
1595
+		);
1596
+
1597
+		$input_html = $mobile_label
1598
+			. '<input type="text" name="' . $name . '" id="' . $id . '" '
1599
+			. 'class="' . $class . ' ' . $required['class'] . ' datepicker" value="' . $answer . '"  '
1600
+			. 'aria-label="' . esc_attr($required['msg']) . '" ' . $disabled . ' ' . $extra . '/>';
1601
+
1602
+		// enqueue scripts
1603
+		wp_register_style(
1604
+			'espresso-ui-theme',
1605
+			EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1606
+			[],
1607
+			EVENT_ESPRESSO_VERSION
1608
+		);
1609
+		wp_enqueue_style('espresso-ui-theme');
1610
+		wp_enqueue_script('jquery-ui-datepicker');
1611
+
1612
+		$input_html = apply_filters('FHEE__EEH_Form_Fields__input_html', $input_html, $label_html, $id);
1613
+		return $label_html . $input_html;
1614
+	}
1615
+
1616
+
1617
+	/**
1618
+	 *  remove_label_keep_required_msg
1619
+	 *  this will strip out a form input's label HTML while keeping the required text HTML that MUST be before the label
1620
+	 *
1621
+	 * @access public
1622
+	 * @return     string
1623
+	 */
1624
+	public static function remove_label_keep_required_msg($label_html, $required_text)
1625
+	{
1626
+		return $required_text;
1627
+	}
1628
+
1629
+
1630
+	/**
1631
+	 * Simply returns the HTML for a hidden input of the given name and value.
1632
+	 *
1633
+	 * @param string $name
1634
+	 * @param string $value
1635
+	 * @return string HTML
1636
+	 */
1637
+	public static function hidden_input($name, $value, $id = '')
1638
+	{
1639
+		$id = ! empty($id) ? $id : $name;
1640
+		return '<input id="' . $id . '" type="hidden" name="' . $name . '" value="' . $value . '"/>';
1641
+	}
1642
+
1643
+
1644
+	/**
1645
+	 * prep_question
1646
+	 *
1647
+	 * @param string $question
1648
+	 * @return string
1649
+	 */
1650
+	public static function prep_question($question)
1651
+	{
1652
+		return $question;
1653
+	}
1654
+
1655
+
1656
+	/**
1657
+	 *  prep_answer
1658
+	 *
1659
+	 * @param mixed $answer
1660
+	 * @return string
1661
+	 */
1662
+	public static function prep_answer($answer, $use_html_entities = true)
1663
+	{
1664
+		// make sure we convert bools first.  Otherwise (bool) false becomes an empty string which is NOT desired,
1665
+		// we want "0".
1666
+		if (is_bool($answer)) {
1667
+			$answer = $answer ? 1 : 0;
1668
+		}
1669
+		$answer = trim(stripslashes(str_replace('&#039;', "'", $answer)));
1670
+		return $use_html_entities ? htmlentities($answer, ENT_QUOTES, 'UTF-8') : $answer;
1671
+	}
1672
+
1673
+
1674
+	/**
1675
+	 *  prep_answer_options
1676
+	 *
1677
+	 * @param array $QSOs array of EE_Question_Option objects
1678
+	 * @return array
1679
+	 */
1680
+	public static function prep_answer_options($QSOs = [])
1681
+	{
1682
+		$prepped_answer_options = [];
1683
+		if (is_array($QSOs) && ! empty($QSOs)) {
1684
+			foreach ($QSOs as $key => $QSO) {
1685
+				if (! $QSO instanceof EE_Question_Option) {
1686
+					$QSO = EE_Question_Option::new_instance(
1687
+						[
1688
+							'QSO_value' => is_array($QSO) && isset($QSO['id'])
1689
+								? (string) $QSO['id']
1690
+								: (string) $key,
1691
+							'QSO_desc'  => is_array($QSO) && isset($QSO['text'])
1692
+								? (string) $QSO['text']
1693
+								: (string) $QSO,
1694
+						]
1695
+					);
1696
+				}
1697
+				if ($QSO->opt_group()) {
1698
+					$prepped_answer_options[ $QSO->opt_group() ][] = $QSO;
1699
+				} else {
1700
+					$prepped_answer_options[] = $QSO;
1701
+				}
1702
+			}
1703
+		}
1704
+		//      d( $prepped_answer_options );
1705
+		return $prepped_answer_options;
1706
+	}
1707
+
1708
+
1709
+	/**
1710
+	 *  prep_option_value
1711
+	 *
1712
+	 * @param string $option_value
1713
+	 * @return string
1714
+	 */
1715
+	public static function prep_option_value($option_value)
1716
+	{
1717
+		return esc_attr(trim(stripslashes($option_value)));
1718
+	}
1719
+
1720
+
1721
+	/**
1722
+	 *  prep_required
1723
+	 *
1724
+	 * @param string|array $required
1725
+	 * @return array
1726
+	 */
1727
+	public static function prep_required($required = [])
1728
+	{
1729
+		// make sure required is an array
1730
+		$required = is_array($required) ? $required : [];
1731
+		// and set some defaults
1732
+		return array_merge(['label' => '', 'class' => '', 'msg' => ''], $required);
1733
+	}
1734
+
1735
+
1736
+	/**
1737
+	 *  get_label_size_class
1738
+	 *
1739
+	 * @param string $value
1740
+	 * @return string
1741
+	 */
1742
+	public static function get_label_size_class($value = false)
1743
+	{
1744
+		if ($value === false || $value === '') {
1745
+			return ' class="medium-lbl"';
1746
+		}
1747
+		// determine length of option value
1748
+		$val_size = strlen($value);
1749
+		switch ($val_size) {
1750
+			case $val_size < 3:
1751
+				$size = ' class="nano-lbl"';
1752
+				break;
1753
+			case $val_size < 6:
1754
+				$size = ' class="micro-lbl"';
1755
+				break;
1756
+			case $val_size < 12:
1757
+				$size = ' class="tiny-lbl"';
1758
+				break;
1759
+			case $val_size < 25:
1760
+				$size = ' class="small-lbl"';
1761
+				break;
1762
+			case $val_size > 100:
1763
+				$size = ' class="big-lbl"';
1764
+				break;
1765
+			default:
1766
+				$size = ' class="medium-lbl"';
1767
+				break;
1768
+		}
1769
+		return $size;
1770
+	}
1771
+
1772
+
1773
+	/**
1774
+	 *  _load_system_dropdowns
1775
+	 *
1776
+	 * @param EE_Question_Form_Input $QFI
1777
+	 * @return array
1778
+	 * @throws EE_Error
1779
+	 * @throws ReflectionException
1780
+	 */
1781
+	private static function _load_system_dropdowns($QFI)
1782
+	{
1783
+		$QST_system = $QFI->get('QST_system');
1784
+		switch ($QST_system) {
1785
+			case 'state':
1786
+				$QFI = self::generate_state_dropdown($QFI);
1787
+				break;
1788
+			case 'country':
1789
+				$QFI = self::generate_country_dropdown($QFI);
1790
+				break;
1791
+			case 'admin-state':
1792
+				$QFI = self::generate_state_dropdown($QFI, true);
1793
+				break;
1794
+			case 'admin-country':
1795
+				$QFI = self::generate_country_dropdown($QFI, true);
1796
+				break;
1797
+		}
1798
+		return $QFI;
1799
+	}
1800
+
1801
+
1802
+	/**
1803
+	 * This preps dropdowns that are specialized.
1804
+	 *
1805
+	 * @param EE_Question_Form_Input $QFI
1806
+	 *
1807
+	 * @return EE_Question_Form_Input
1808
+	 * @throws EE_Error
1809
+	 * @throws ReflectionException
1810
+	 * @since  4.6.0
1811
+	 */
1812
+	protected static function _load_specialized_dropdowns($QFI)
1813
+	{
1814
+		switch ($QFI->get('QST_type')) {
1815
+			case 'STATE':
1816
+				$QFI = self::generate_state_dropdown($QFI);
1817
+				break;
1818
+			case 'COUNTRY':
1819
+				$QFI = self::generate_country_dropdown($QFI);
1820
+				break;
1821
+		}
1822
+		return $QFI;
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 *    generate_state_dropdown
1828
+	 *
1829
+	 * @param EE_Question_Form_Input $QST
1830
+	 * @param bool                   $get_all
1831
+	 * @return EE_Question_Form_Input
1832
+	 * @throws EE_Error
1833
+	 * @throws ReflectionException
1834
+	 */
1835
+	public static function generate_state_dropdown($QST, $get_all = false)
1836
+	{
1837
+		$states = $get_all
1838
+			? EEM_State::instance()->get_all_states()
1839
+			: EEM_State::instance()->get_all_states_of_active_countries();
1840
+		if ($states && count($states) != count($QST->options())) {
1841
+			$QST->set('QST_type', 'DROPDOWN');
1842
+			// if multiple countries, we'll create option groups within the dropdown
1843
+			foreach ($states as $state) {
1844
+				if ($state instanceof EE_State) {
1845
+					$QSO = EE_Question_Option::new_instance(
1846
+						[
1847
+							'QSO_value'   => $state->ID(),
1848
+							'QSO_desc'    => $state->name(),
1849
+							'QST_ID'      => $QST->get('QST_ID'),
1850
+							'QSO_deleted' => false,
1851
+						]
1852
+					);
1853
+					// set option group
1854
+					$QSO->set_opt_group($state->country()->name());
1855
+					// add option to question
1856
+					$QST->add_temp_option($QSO);
1857
+				}
1858
+			}
1859
+		}
1860
+		return $QST;
1861
+	}
1862
+
1863
+
1864
+	/**
1865
+	 *    generate_country_dropdown
1866
+	 *
1867
+	 * @param      $QST
1868
+	 * @param bool $get_all
1869
+	 * @return array
1870
+	 * @throws EE_Error
1871
+	 * @throws ReflectionException
1872
+	 * @internal param array $question
1873
+	 */
1874
+	public static function generate_country_dropdown($QST, $get_all = false)
1875
+	{
1876
+		$countries = $get_all
1877
+			? EEM_Country::instance()->get_all_countries()
1878
+			: EEM_Country::instance()->get_all_active_countries();
1879
+		if ($countries && count($countries) != count($QST->options())) {
1880
+			$QST->set('QST_type', 'DROPDOWN');
1881
+			// now add countries
1882
+			foreach ($countries as $country) {
1883
+				if ($country instanceof EE_Country) {
1884
+					$QSO = EE_Question_Option::new_instance(
1885
+						[
1886
+							'QSO_value'   => $country->ID(),
1887
+							'QSO_desc'    => $country->name(),
1888
+							'QST_ID'      => $QST->get('QST_ID'),
1889
+							'QSO_deleted' => false,
1890
+						]
1891
+					);
1892
+					$QST->add_temp_option($QSO);
1893
+				}
1894
+			}
1895
+		}
1896
+		return $QST;
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 *  generates options for a month dropdown selector with numbers from 01 to 12
1902
+	 *
1903
+	 * @return array()
1904
+	 */
1905
+	public static function two_digit_months_dropdown_options()
1906
+	{
1907
+		$options = [];
1908
+		for ($x = 1; $x <= 12; $x++) {
1909
+			$mm             = str_pad($x, 2, '0', STR_PAD_LEFT);
1910
+			$options[ $mm ] = $mm;
1911
+		}
1912
+		return EEH_Form_Fields::prep_answer_options($options);
1913
+	}
1914
+
1915
+
1916
+	/**
1917
+	 *  generates a year dropdown selector with numbers for the next ten years
1918
+	 *
1919
+	 * @return array
1920
+	 */
1921
+	public static function next_decade_two_digit_year_dropdown_options()
1922
+	{
1923
+		$options      = [];
1924
+		$current_year = date('y');
1925
+		$next_decade  = $current_year + 10;
1926
+		for ($x = $current_year; $x <= $next_decade; $x++) {
1927
+			$yy             = str_pad($x, 2, '0', STR_PAD_LEFT);
1928
+			$options[ $yy ] = $yy;
1929
+		}
1930
+		return EEH_Form_Fields::prep_answer_options($options);
1931
+	}
1932
+
1933
+
1934
+	/**
1935
+	 * generates a month/year dropdown selector for all registrations matching the given criteria.  Typically used for
1936
+	 * list table filter.
1937
+	 *
1938
+	 * @param string  $cur_date     any currently selected date can be entered here.
1939
+	 * @param string  $status       Registration status
1940
+	 * @param integer $evt_category Event Category ID if the Event Category filter is selected
1941
+	 * @return string                html
1942
+	 * @throws EE_Error
1943
+	 */
1944
+	public static function generate_registration_months_dropdown($cur_date = '', $status = '', $evt_category = 0)
1945
+	{
1946
+		$_where = [];
1947
+		if (! empty($status)) {
1948
+			$_where['STS_ID'] = $status;
1949
+		}
1950
+
1951
+		if ($evt_category > 0) {
1952
+			$_where['Event.Term_Taxonomy.term_id'] = $evt_category;
1953
+		}
1954
+
1955
+		$regdtts = EEM_Registration::instance()->get_reg_months_and_years($_where);
1956
+
1957
+		// setup vals for select input helper
1958
+		$options = [
1959
+			0 => [
1960
+				'text' => esc_html__('Select a Month/Year', 'event_espresso'),
1961
+				'id'   => '',
1962
+			],
1963
+		];
1964
+
1965
+		foreach ($regdtts as $regdtt) {
1966
+			$date      = $regdtt->reg_month . ' ' . $regdtt->reg_year;
1967
+			$options[] = [
1968
+				'text' => $date,
1969
+				'id'   => $date,
1970
+			];
1971
+		}
1972
+
1973
+		return self::select_input('month_range', $options, $cur_date);
1974
+	}
1975
+
1976
+
1977
+	/**
1978
+	 * generates a month/year dropdown selector for all events matching the given criteria
1979
+	 * Typically used for list table filter
1980
+	 *
1981
+	 * @param string $cur_date          any currently selected date can be entered here.
1982
+	 * @param string $status            "view" (i.e. all, today, month, draft)
1983
+	 * @param int    $evt_category      category event belongs to
1984
+	 * @param string $evt_active_status "upcoming", "expired", "active", or "inactive"
1985
+	 * @return string                    html
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public static function generate_event_months_dropdown(
1989
+		$cur_date = '',
1990
+		$status = null,
1991
+		$evt_category = null,
1992
+		$evt_active_status = null
1993
+	) {
1994
+		// determine what post_status our condition will have for the query.
1995
+		// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
1996
+		switch ($status) {
1997
+			case 'month':
1998
+			case 'today':
1999
+			case null:
2000
+			case 'all':
2001
+				$where['Event.status'] = ['NOT IN', ['trash']];
2002
+				break;
2003
+			case 'draft':
2004
+				$where['Event.status'] = ['IN', ['draft', 'auto-draft']];
2005
+				break;
2006
+			default:
2007
+				$where['Event.status'] = $status;
2008
+		}
2009
+
2010
+		// phpcs:enable
2011
+
2012
+		// categories?
2013
+
2014
+
2015
+		if (! empty($evt_category) and $evt_category > 0) {
2016
+			$where['Event.Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
2017
+			$where['Event.Term_Taxonomy.term_id']  = $evt_category;
2018
+		}
2019
+
2020
+
2021
+		//      $where['DTT_is_primary'] = 1;
2022
+
2023
+		$DTTS = EEM_Datetime::instance()->get_dtt_months_and_years($where, $evt_active_status);
2024
+
2025
+		// let's setup vals for select input helper
2026
+		$options = [
2027
+			0 => [
2028
+				'text' => esc_html__('Select a Month/Year', 'event_espresso'),
2029
+				'id'   => "",
2030
+			],
2031
+		];
2032
+
2033
+
2034
+		// translate month and date
2035
+		global $wp_locale;
2036
+
2037
+		foreach ($DTTS as $DTT) {
2038
+			$localized_date = $wp_locale->get_month($DTT->dtt_month_num) . ' ' . $DTT->dtt_year;
2039
+			$id             = $DTT->dtt_month . ' ' . $DTT->dtt_year;
2040
+			$options[]      = [
2041
+				'text' => $localized_date,
2042
+				'id'   => $id,
2043
+			];
2044
+		}
2045
+
2046
+
2047
+		return self::select_input('month_range', $options, $cur_date);
2048
+	}
2049
+
2050
+
2051
+	/**
2052
+	 * generates the dropdown selector for event categories
2053
+	 * typically used as a filter on list tables.
2054
+	 *
2055
+	 * @param integer $current_cat currently selected category
2056
+	 * @return string               html for dropdown
2057
+	 * @throws EE_Error
2058
+	 * @throws ReflectionException
2059
+	 */
2060
+	public static function generate_event_category_dropdown($current_cat = -1)
2061
+	{
2062
+		$categories = EEM_Term::instance()->get_all_ee_categories(true);
2063
+		$options    = [
2064
+			'0' => [
2065
+				'text' => esc_html__('All Categories', 'event_espresso'),
2066
+				'id'   => -1,
2067
+			],
2068
+		];
2069
+
2070
+		// setup categories for dropdown
2071
+		foreach ($categories as $category) {
2072
+			$options[] = [
2073
+				'text' => $category->get('name'),
2074
+				'id'   => $category->ID(),
2075
+			];
2076
+		}
2077
+
2078
+		return self::select_input('EVT_CAT', $options, $current_cat);
2079
+	}
2080
+
2081
+
2082
+	/**
2083
+	 *    generate a submit button with or without it's own microform
2084
+	 *    this is the only way to create buttons that are compatible across all themes
2085
+	 *
2086
+	 * @access    public
2087
+	 * @param string      $url              - the form action
2088
+	 * @param string      $ID               - some kind of unique ID, appended with "-sbmt" for the input and "-frm"
2089
+	 *                                      for the form
2090
+	 * @param string      $class            - css classes (separated by spaces if more than one)
2091
+	 * @param string      $text             - what appears on the button
2092
+	 * @param string      $nonce_action     - if using nonces
2093
+	 * @param bool|string $input_only       - whether to print form header and footer. TRUE returns the input without
2094
+	 *                                      the form
2095
+	 * @param string      $extra_attributes - any extra attributes that need to be attached to the form input
2096
+	 * @return    string
2097
+	 */
2098
+	public static function submit_button(
2099
+		$url = '',
2100
+		$ID = '',
2101
+		$class = '',
2102
+		$text = '',
2103
+		$nonce_action = '',
2104
+		$input_only = false,
2105
+		$extra_attributes = ''
2106
+	) {
2107
+		$btn = '';
2108
+		if (empty($url) || empty($ID)) {
2109
+			return $btn;
2110
+		}
2111
+		$text = ! empty($text) ? $text : esc_html__('Submit', 'event_espresso');
2112
+		$btn  .= '<input id="' . $ID . '-btn" class="' . $class . '" '
2113
+				 . 'type="submit" value="' . $text . '" ' . $extra_attributes . '/>';
2114
+		if (! $input_only) {
2115
+			$btn_frm = '<form id="' . $ID . '-frm" method="POST" action="' . $url . '">';
2116
+			$btn_frm .= ! empty($nonce_action)
2117
+				? wp_nonce_field($nonce_action, $nonce_action . '_nonce', true, false)
2118
+				: '';
2119
+			$btn_frm .= $btn;
2120
+			$btn_frm .= '</form>';
2121
+			$btn     = $btn_frm;
2122
+			unset($btn_frm);
2123
+		}
2124
+		return $btn;
2125
+	}
2126 2126
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Array.helper.php 1 patch
Indentation   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -11,313 +11,313 @@
 block discarded – undo
11 11
  */
12 12
 class EEH_Array extends EEH_Base
13 13
 {
14
-    /**
15
-     * This method basically works the same as the PHP core function array_diff except it allows you to compare arrays
16
-     * of EE_Base_Class objects NOTE: This will ONLY work on an array of EE_Base_Class objects
17
-     *
18
-     * @uses array_udiff core php function for setting up our own array comparison
19
-     * @uses self::_compare_objects as the custom method for array_udiff
20
-     * @param  array $array1 an array of objects
21
-     * @param  array $array2 an array of objects
22
-     * @return array         an array of objects found in array 1 that aren't found in array 2.
23
-     */
24
-    public static function object_array_diff($array1, $array2)
25
-    {
26
-        return array_udiff($array1, $array2, array('self', '_compare_objects'));
27
-    }
14
+	/**
15
+	 * This method basically works the same as the PHP core function array_diff except it allows you to compare arrays
16
+	 * of EE_Base_Class objects NOTE: This will ONLY work on an array of EE_Base_Class objects
17
+	 *
18
+	 * @uses array_udiff core php function for setting up our own array comparison
19
+	 * @uses self::_compare_objects as the custom method for array_udiff
20
+	 * @param  array $array1 an array of objects
21
+	 * @param  array $array2 an array of objects
22
+	 * @return array         an array of objects found in array 1 that aren't found in array 2.
23
+	 */
24
+	public static function object_array_diff($array1, $array2)
25
+	{
26
+		return array_udiff($array1, $array2, array('self', '_compare_objects'));
27
+	}
28 28
 
29
-    /**
30
-     * Given that $arr is an array, determines if it's associative or numerically AND sequentially indexed
31
-     *
32
-     * @param array $array
33
-     * @return boolean
34
-     */
35
-    public static function is_associative_array(array $array): bool
36
-    {
37
-        return ! empty($array) && array_keys($array) !== range(0, count($array) - 1);
38
-    }
29
+	/**
30
+	 * Given that $arr is an array, determines if it's associative or numerically AND sequentially indexed
31
+	 *
32
+	 * @param array $array
33
+	 * @return boolean
34
+	 */
35
+	public static function is_associative_array(array $array): bool
36
+	{
37
+		return ! empty($array) && array_keys($array) !== range(0, count($array) - 1);
38
+	}
39 39
 
40
-    /**
41
-     * Gets an item from the array and leave the array intact. Use in place of end()
42
-     * when you don't want to change the array
43
-     *
44
-     * @param array $arr
45
-     * @return mixed what ever is in the array
46
-     */
47
-    public static function get_one_item_from_array($arr)
48
-    {
49
-        $item = end($arr);
50
-        reset($arr);
51
-        return $item;
52
-    }
40
+	/**
41
+	 * Gets an item from the array and leave the array intact. Use in place of end()
42
+	 * when you don't want to change the array
43
+	 *
44
+	 * @param array $arr
45
+	 * @return mixed what ever is in the array
46
+	 */
47
+	public static function get_one_item_from_array($arr)
48
+	{
49
+		$item = end($arr);
50
+		reset($arr);
51
+		return $item;
52
+	}
53 53
 
54
-    /**
55
-     * Detects if this is a multi-dimensional array
56
-     * meaning that at least one top-level value is an array. Eg [ [], ...]
57
-     *
58
-     * @param mixed $arr
59
-     * @return boolean
60
-     */
61
-    public static function is_multi_dimensional_array($arr)
62
-    {
63
-        if (is_array($arr)) {
64
-            foreach ($arr as $item) {
65
-                if (is_array($item)) {
66
-                    return true; // yep, there's at least 2 levels to this array
67
-                }
68
-            }
69
-        }
70
-        return false; // there's only 1 level, or it's not an array at all!
71
-    }
54
+	/**
55
+	 * Detects if this is a multi-dimensional array
56
+	 * meaning that at least one top-level value is an array. Eg [ [], ...]
57
+	 *
58
+	 * @param mixed $arr
59
+	 * @return boolean
60
+	 */
61
+	public static function is_multi_dimensional_array($arr)
62
+	{
63
+		if (is_array($arr)) {
64
+			foreach ($arr as $item) {
65
+				if (is_array($item)) {
66
+					return true; // yep, there's at least 2 levels to this array
67
+				}
68
+			}
69
+		}
70
+		return false; // there's only 1 level, or it's not an array at all!
71
+	}
72 72
 
73
-    /**
74
-     * Shorthand for isset( $arr[ $index ] ) ? $arr[ $index ] : $default
75
-     *
76
-     * @param array $arr
77
-     * @param mixed $index
78
-     * @param mixed $default
79
-     * @return mixed
80
-     */
81
-    public static function is_set($arr, $index, $default)
82
-    {
83
-        return isset($arr[ $index ]) ? $arr[ $index ] : $default;
84
-    }
73
+	/**
74
+	 * Shorthand for isset( $arr[ $index ] ) ? $arr[ $index ] : $default
75
+	 *
76
+	 * @param array $arr
77
+	 * @param mixed $index
78
+	 * @param mixed $default
79
+	 * @return mixed
80
+	 */
81
+	public static function is_set($arr, $index, $default)
82
+	{
83
+		return isset($arr[ $index ]) ? $arr[ $index ] : $default;
84
+	}
85 85
 
86
-    /**
87
-     * Exactly like `maybe_unserialize`, but also accounts for a WP bug: http://core.trac.wordpress.org/ticket/26118
88
-     *
89
-     * @param mixed $value usually a string, but could be an array or object
90
-     * @return mixed the UN-serialized data
91
-     */
92
-    public static function maybe_unserialize($value)
93
-    {
94
-        $data = maybe_unserialize($value);
95
-        // it's possible that this still has serialized data if it's the session.
96
-        //  WP has a bug, http://core.trac.wordpress.org/ticket/26118 that doesn't unserialize this automatically.
97
-        $token = 'C';
98
-        $data = is_string($data) ? trim($data) : $data;
99
-        if (is_string($data) && strlen($data) > 1 && $data[0] == $token && preg_match("/^{$token}:[0-9]+:/s", $data)) {
100
-            return unserialize($data);
101
-        } else {
102
-            return $data;
103
-        }
104
-    }
86
+	/**
87
+	 * Exactly like `maybe_unserialize`, but also accounts for a WP bug: http://core.trac.wordpress.org/ticket/26118
88
+	 *
89
+	 * @param mixed $value usually a string, but could be an array or object
90
+	 * @return mixed the UN-serialized data
91
+	 */
92
+	public static function maybe_unserialize($value)
93
+	{
94
+		$data = maybe_unserialize($value);
95
+		// it's possible that this still has serialized data if it's the session.
96
+		//  WP has a bug, http://core.trac.wordpress.org/ticket/26118 that doesn't unserialize this automatically.
97
+		$token = 'C';
98
+		$data = is_string($data) ? trim($data) : $data;
99
+		if (is_string($data) && strlen($data) > 1 && $data[0] == $token && preg_match("/^{$token}:[0-9]+:/s", $data)) {
100
+			return unserialize($data);
101
+		} else {
102
+			return $data;
103
+		}
104
+	}
105 105
 
106 106
 
107
-    /**
108
-     * insert_into_array
109
-     *
110
-     * @param array        $target_array the array to insert new data into
111
-     * @param array        $array_to_insert the new data to be inserted
112
-     * @param int|string|null $offset a known key within $target_array where new data will be inserted
113
-     * @param bool         $add_before whether to add new data before or after the offset key
114
-     * @param bool         $preserve_keys whether or not to reset numerically indexed arrays
115
-     * @return array
116
-     */
117
-    public static function insert_into_array(
118
-        array $target_array = array(),
119
-        array $array_to_insert = array(),
120
-        $offset = null,
121
-        bool $add_before = true,
122
-        bool $preserve_keys = true
123
-    ) {
124
-        $target_array_keys = array_keys($target_array);
125
-        // if no offset key was supplied
126
-        if (empty($offset)) {
127
-            // use start or end of $target_array based on whether we are adding before or not
128
-            $offset = $add_before ? 0 : count($target_array);
129
-        }
130
-        // if offset key is a string, then find the corresponding numeric location for that element
131
-        $offset = is_int($offset) ? $offset : array_search($offset, $target_array_keys, true);
132
-        // add one to the offset if adding after
133
-        $offset = $add_before ? $offset : $offset + 1;
134
-        // but ensure offset does not exceed the length of the array
135
-        $offset = $offset > count($target_array) ? count($target_array) : $offset;
136
-        // reindex array ???
137
-        if ($preserve_keys) {
138
-            // take a slice of the target array from the beginning till the offset,
139
-            // then add the new data
140
-            // then add another slice that starts at the offset and goes till the end
141
-            return array_slice($target_array, 0, $offset, true) + $array_to_insert + array_slice(
142
-                $target_array,
143
-                $offset,
144
-                null,
145
-                true
146
-            );
147
-        } else {
148
-            // since we don't want to preserve keys, we can use array_splice
149
-            array_splice($target_array, $offset, 0, $array_to_insert);
150
-            return $target_array;
151
-        }
152
-    }
107
+	/**
108
+	 * insert_into_array
109
+	 *
110
+	 * @param array        $target_array the array to insert new data into
111
+	 * @param array        $array_to_insert the new data to be inserted
112
+	 * @param int|string|null $offset a known key within $target_array where new data will be inserted
113
+	 * @param bool         $add_before whether to add new data before or after the offset key
114
+	 * @param bool         $preserve_keys whether or not to reset numerically indexed arrays
115
+	 * @return array
116
+	 */
117
+	public static function insert_into_array(
118
+		array $target_array = array(),
119
+		array $array_to_insert = array(),
120
+		$offset = null,
121
+		bool $add_before = true,
122
+		bool $preserve_keys = true
123
+	) {
124
+		$target_array_keys = array_keys($target_array);
125
+		// if no offset key was supplied
126
+		if (empty($offset)) {
127
+			// use start or end of $target_array based on whether we are adding before or not
128
+			$offset = $add_before ? 0 : count($target_array);
129
+		}
130
+		// if offset key is a string, then find the corresponding numeric location for that element
131
+		$offset = is_int($offset) ? $offset : array_search($offset, $target_array_keys, true);
132
+		// add one to the offset if adding after
133
+		$offset = $add_before ? $offset : $offset + 1;
134
+		// but ensure offset does not exceed the length of the array
135
+		$offset = $offset > count($target_array) ? count($target_array) : $offset;
136
+		// reindex array ???
137
+		if ($preserve_keys) {
138
+			// take a slice of the target array from the beginning till the offset,
139
+			// then add the new data
140
+			// then add another slice that starts at the offset and goes till the end
141
+			return array_slice($target_array, 0, $offset, true) + $array_to_insert + array_slice(
142
+				$target_array,
143
+				$offset,
144
+				null,
145
+				true
146
+			);
147
+		} else {
148
+			// since we don't want to preserve keys, we can use array_splice
149
+			array_splice($target_array, $offset, 0, $array_to_insert);
150
+			return $target_array;
151
+		}
152
+	}
153 153
 
154 154
 
155
-    /**
156
-     * array_merge() is slow and should never be used while looping over data
157
-     * if you don't need to preserve keys from all arrays, then using a foreach loop is much faster
158
-     * so really this acts more like array_replace( $array1, $array2 )
159
-     * or a union with the arrays flipped ( $array2 + $array1 )
160
-     * this saves a few lines of code and improves readability
161
-     *
162
-     * @param array $array1
163
-     * @param array $array2
164
-     * @return array
165
-     */
166
-    public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
167
-    {
168
-        foreach ($array2 as $key => $value) {
169
-            $array1[ $key ] = $value;
170
-        }
171
-        return $array1;
172
-    }
155
+	/**
156
+	 * array_merge() is slow and should never be used while looping over data
157
+	 * if you don't need to preserve keys from all arrays, then using a foreach loop is much faster
158
+	 * so really this acts more like array_replace( $array1, $array2 )
159
+	 * or a union with the arrays flipped ( $array2 + $array1 )
160
+	 * this saves a few lines of code and improves readability
161
+	 *
162
+	 * @param array $array1
163
+	 * @param array $array2
164
+	 * @return array
165
+	 */
166
+	public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
167
+	{
168
+		foreach ($array2 as $key => $value) {
169
+			$array1[ $key ] = $value;
170
+		}
171
+		return $array1;
172
+	}
173 173
 
174 174
 
175
-    /**
176
-     * given a flat array like $array = array('A', 'B', 'C')
177
-     * will convert into a multidimensional array like $array[A][B][C]
178
-     * if $final_value is provided and is anything other than null,
179
-     * then that will be set as the value for the innermost array key
180
-     * like so: $array[A][B][C] = $final_value
181
-     *
182
-     * @param array $flat_array
183
-     * @param mixed $final_value
184
-     * @return array
185
-     */
186
-    public static function convert_array_values_to_keys(array $flat_array, $final_value = null)
187
-    {
188
-        $multidimensional = array();
189
-        $reference = &$multidimensional;
190
-        foreach ($flat_array as $key) {
191
-            $reference[ $key ] = array();
192
-            $reference = &$reference[ $key ];
193
-        }
194
-        if ($final_value !== null) {
195
-            $reference = $final_value;
196
-        }
197
-        return $multidimensional;
198
-    }
175
+	/**
176
+	 * given a flat array like $array = array('A', 'B', 'C')
177
+	 * will convert into a multidimensional array like $array[A][B][C]
178
+	 * if $final_value is provided and is anything other than null,
179
+	 * then that will be set as the value for the innermost array key
180
+	 * like so: $array[A][B][C] = $final_value
181
+	 *
182
+	 * @param array $flat_array
183
+	 * @param mixed $final_value
184
+	 * @return array
185
+	 */
186
+	public static function convert_array_values_to_keys(array $flat_array, $final_value = null)
187
+	{
188
+		$multidimensional = array();
189
+		$reference = &$multidimensional;
190
+		foreach ($flat_array as $key) {
191
+			$reference[ $key ] = array();
192
+			$reference = &$reference[ $key ];
193
+		}
194
+		if ($final_value !== null) {
195
+			$reference = $final_value;
196
+		}
197
+		return $multidimensional;
198
+	}
199 199
 
200 200
 
201
-    /**
202
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
203
-     * @param array $array
204
-     * @return bool
205
-     */
206
-    public static function is_array_numerically_and_sequentially_indexed(array $array)
207
-    {
208
-        return empty($array) || array_keys($array) === range(0, count($array) - 1);
209
-    }
201
+	/**
202
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
203
+	 * @param array $array
204
+	 * @return bool
205
+	 */
206
+	public static function is_array_numerically_and_sequentially_indexed(array $array)
207
+	{
208
+		return empty($array) || array_keys($array) === range(0, count($array) - 1);
209
+	}
210 210
 
211 211
 
212
-    /**
213
-     * recursively walks through an array and adds slashes to all no array elements
214
-     *
215
-     * @param mixed $element
216
-     * @return array|string
217
-     * @since   4.10.29.p
218
-     */
219
-    public static function addSlashesRecursively($element)
220
-    {
221
-        if (is_array($element)) {
222
-            foreach ($element as $key => $value) {
223
-                $element[ $key ] = EEH_Array::addSlashesRecursively($value);
224
-            }
225
-            return $element;
226
-        }
227
-        return is_string($element) ? addslashes($element) : $element;
228
-    }
212
+	/**
213
+	 * recursively walks through an array and adds slashes to all no array elements
214
+	 *
215
+	 * @param mixed $element
216
+	 * @return array|string
217
+	 * @since   4.10.29.p
218
+	 */
219
+	public static function addSlashesRecursively($element)
220
+	{
221
+		if (is_array($element)) {
222
+			foreach ($element as $key => $value) {
223
+				$element[ $key ] = EEH_Array::addSlashesRecursively($value);
224
+			}
225
+			return $element;
226
+		}
227
+		return is_string($element) ? addslashes($element) : $element;
228
+	}
229 229
 
230 230
 
231
-    /**
232
-     * link https://stackoverflow.com/a/3877494
233
-     *
234
-     * @param array $array_1
235
-     * @param array $array_2
236
-     * @return array
237
-     * @since   5.0.0.p
238
-     */
239
-    public static function array_diff_recursive(array $array_1, array $array_2): array
240
-    {
241
-        $diff = [];
242
-        foreach ($array_1 as $key => $value) {
243
-            if (array_key_exists($key, $array_2)) {
244
-                if (is_array($value)) {
245
-                    $inner_diff = EEH_Array::array_diff_recursive($value, $array_2[ $key ]);
246
-                    if (count($inner_diff)) {
247
-                        $diff[ $key ] = $inner_diff;
248
-                    }
249
-                } else {
250
-                    if ($value != $array_2[ $key ]) {
251
-                        $diff[ $key ] = $value;
252
-                    }
253
-                }
254
-            } else {
255
-                $diff[ $key ] = $value;
256
-            }
257
-        }
258
-        return $diff;
259
-    }
231
+	/**
232
+	 * link https://stackoverflow.com/a/3877494
233
+	 *
234
+	 * @param array $array_1
235
+	 * @param array $array_2
236
+	 * @return array
237
+	 * @since   5.0.0.p
238
+	 */
239
+	public static function array_diff_recursive(array $array_1, array $array_2): array
240
+	{
241
+		$diff = [];
242
+		foreach ($array_1 as $key => $value) {
243
+			if (array_key_exists($key, $array_2)) {
244
+				if (is_array($value)) {
245
+					$inner_diff = EEH_Array::array_diff_recursive($value, $array_2[ $key ]);
246
+					if (count($inner_diff)) {
247
+						$diff[ $key ] = $inner_diff;
248
+					}
249
+				} else {
250
+					if ($value != $array_2[ $key ]) {
251
+						$diff[ $key ] = $value;
252
+					}
253
+				}
254
+			} else {
255
+				$diff[ $key ] = $value;
256
+			}
257
+		}
258
+		return $diff;
259
+	}
260 260
 
261 261
 
262
-    /**
263
-     * converts multidimensional arrays into a single depth associative array
264
-     * or converts arrays of any depth into a readable string representation
265
-     *
266
-     *  $example = [
267
-     *      'a' => 'A',
268
-     *      'b' => 'B',
269
-     *      'c' => [
270
-     *          'd' => 'D',
271
-     *          'e' => 'E',
272
-     *          'f' => [ 'G', 'H', 'I' ],
273
-     *      ],
274
-     *      [ 'J', 'K' ],
275
-     *      'L',
276
-     *      'M',
277
-     *      'n' => [
278
-     *          'o' => 'P'
279
-     *      ],
280
-     *  ];
281
-     *
282
-     *  print_r( EEH_Array::flattenArray($example) );
283
-     *
284
-     *  Array (
285
-     *      [a] => A
286
-     *      [b] => B
287
-     *      [c] => [ d:D, e:E, f:[ G, H, I ] ]
288
-     *      [0] => [ J, K ]
289
-     *      [1] => L
290
-     *      [2] => M
291
-     *      [n] => [ o:P ]
292
-     *  )
293
-     *
294
-     *  print_r( EEH_Array::flattenArray($example, true) );
295
-     *
296
-     *  "a:A, b:B, c:[ d:D, e:E, f:[ G, H, I ] ], [ J, K ], L, M, n:[ o:P ]"
297
-     *
298
-     * @param array $array      the array to be flattened
299
-     * @param bool  $to_string  [true] will flatten the entire array down into a string
300
-     *                          [false] will only flatten sub-arrays down into strings and return a array
301
-     * @param bool  $top_level  used for formatting purposes only, best to leave this alone as it's set internally
302
-     * @return array|false|string
303
-     * @since 5.0.0.p
304
-     */
305
-    public static function flattenArray(array $array, bool $to_string = false, bool $top_level = true)
306
-    {
307
-        $flat_array = [];
308
-        foreach ($array as $key => $value) {
309
-            $flat_array[ $key ] = is_array($value)
310
-                ? EEH_Array::flattenArray($value, true, false)
311
-                : $value;
312
-        }
313
-        if (! $to_string) {
314
-            return $flat_array;
315
-        }
316
-        $flat = '';
317
-        foreach ($flat_array as $key => $value) {
318
-            $flat .= is_int($key) ? "$value, " : "$key:$value, ";
319
-        }
320
-        $flat = substr($flat, 0, -2);
321
-        return $top_level ? $flat : "[ $flat ]";
322
-    }
262
+	/**
263
+	 * converts multidimensional arrays into a single depth associative array
264
+	 * or converts arrays of any depth into a readable string representation
265
+	 *
266
+	 *  $example = [
267
+	 *      'a' => 'A',
268
+	 *      'b' => 'B',
269
+	 *      'c' => [
270
+	 *          'd' => 'D',
271
+	 *          'e' => 'E',
272
+	 *          'f' => [ 'G', 'H', 'I' ],
273
+	 *      ],
274
+	 *      [ 'J', 'K' ],
275
+	 *      'L',
276
+	 *      'M',
277
+	 *      'n' => [
278
+	 *          'o' => 'P'
279
+	 *      ],
280
+	 *  ];
281
+	 *
282
+	 *  print_r( EEH_Array::flattenArray($example) );
283
+	 *
284
+	 *  Array (
285
+	 *      [a] => A
286
+	 *      [b] => B
287
+	 *      [c] => [ d:D, e:E, f:[ G, H, I ] ]
288
+	 *      [0] => [ J, K ]
289
+	 *      [1] => L
290
+	 *      [2] => M
291
+	 *      [n] => [ o:P ]
292
+	 *  )
293
+	 *
294
+	 *  print_r( EEH_Array::flattenArray($example, true) );
295
+	 *
296
+	 *  "a:A, b:B, c:[ d:D, e:E, f:[ G, H, I ] ], [ J, K ], L, M, n:[ o:P ]"
297
+	 *
298
+	 * @param array $array      the array to be flattened
299
+	 * @param bool  $to_string  [true] will flatten the entire array down into a string
300
+	 *                          [false] will only flatten sub-arrays down into strings and return a array
301
+	 * @param bool  $top_level  used for formatting purposes only, best to leave this alone as it's set internally
302
+	 * @return array|false|string
303
+	 * @since 5.0.0.p
304
+	 */
305
+	public static function flattenArray(array $array, bool $to_string = false, bool $top_level = true)
306
+	{
307
+		$flat_array = [];
308
+		foreach ($array as $key => $value) {
309
+			$flat_array[ $key ] = is_array($value)
310
+				? EEH_Array::flattenArray($value, true, false)
311
+				: $value;
312
+		}
313
+		if (! $to_string) {
314
+			return $flat_array;
315
+		}
316
+		$flat = '';
317
+		foreach ($flat_array as $key => $value) {
318
+			$flat .= is_int($key) ? "$value, " : "$key:$value, ";
319
+		}
320
+		$flat = substr($flat, 0, -2);
321
+		return $top_level ? $flat : "[ $flat ]";
322
+	}
323 323
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Line_Item.helper.php 1 patch
Indentation   +2128 added lines, -2128 removed lines patch added patch discarded remove patch
@@ -21,2132 +21,2132 @@
 block discarded – undo
21 21
  */
22 22
 class EEH_Line_Item
23 23
 {
24
-    /**
25
-     * @var EE_Line_Item[]
26
-    */
27
-    private static $global_taxes;
28
-
29
-
30
-    /**
31
-     * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
32
-     * Does NOT automatically re-calculate the line item totals or update the related transaction.
33
-     * You should call recalculate_total_including_taxes() on the grant total line item after this
34
-     * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
35
-     * to keep the registration final prices in-sync with the transaction's total.
36
-     *
37
-     * @param EE_Line_Item $parent_line_item
38
-     * @param string       $name
39
-     * @param float        $unit_price
40
-     * @param string       $description
41
-     * @param int          $quantity
42
-     * @param boolean      $taxable
43
-     * @param string|null  $code if set to a value, ensures there is only one line item with that code
44
-     * @param bool         $return_item
45
-     * @param bool         $recalculate_totals
46
-     * @return boolean|EE_Line_Item success
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public static function add_unrelated_item(
51
-        EE_Line_Item $parent_line_item,
52
-        string $name,
53
-        float $unit_price,
54
-        string $description = '',
55
-        int $quantity = 1,
56
-        bool $taxable = false,
57
-        ?string $code = null,
58
-        bool $return_item = false,
59
-        bool $recalculate_totals = true
60
-    ) {
61
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
62
-        $line_item      = EE_Line_Item::new_instance(
63
-            [
64
-                'LIN_name'       => $name,
65
-                'LIN_desc'       => $description,
66
-                'LIN_unit_price' => $unit_price,
67
-                'LIN_quantity'   => $quantity,
68
-                'LIN_percent'    => null,
69
-                'LIN_is_taxable' => $taxable,
70
-                'LIN_order'      => $items_subtotal instanceof EE_Line_Item
71
-                    ? count($items_subtotal->children())
72
-                    : 0,
73
-                'LIN_total'      => (float) $unit_price * (int) $quantity,
74
-                'LIN_type'       => EEM_Line_Item::type_line_item,
75
-                'LIN_code'       => $code,
76
-            ]
77
-        );
78
-        $line_item      = apply_filters(
79
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
80
-            $line_item,
81
-            $parent_line_item
82
-        );
83
-        $added          = self::add_item($parent_line_item, $line_item, $recalculate_totals);
84
-        return $return_item ? $line_item : $added;
85
-    }
86
-
87
-
88
-    /**
89
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
90
-     * in the correct spot in the line item tree. Does not automatically
91
-     * re-calculate the line item totals, nor update the related transaction, nor upgrade the transaction's
92
-     * registrations' final prices (which should probably change because of this).
93
-     * You should call recalculate_total_including_taxes() on the grand total line item, then
94
-     * update the transaction's total, and EE_Registration_Processor::update_registration_final_prices()
95
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
96
-     *
97
-     * @param EE_Line_Item $parent_line_item
98
-     * @param string       $name
99
-     * @param float        $percentage_amount
100
-     * @param string       $description
101
-     * @param boolean      $taxable
102
-     * @param string|null  $code
103
-     * @param bool         $return_item
104
-     * @return boolean|EE_Line_Item success
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public static function add_percentage_based_item(
109
-        EE_Line_Item $parent_line_item,
110
-        string $name,
111
-        float $percentage_amount,
112
-        string $description = '',
113
-        bool $taxable = false,
114
-        ?string $code = null,
115
-        bool $return_item = false
116
-    ) {
117
-        $total = $percentage_amount * $parent_line_item->total() / 100;
118
-        $line_item = EE_Line_Item::new_instance(
119
-            [
120
-                'LIN_name'       => $name,
121
-                'LIN_desc'       => $description,
122
-                'LIN_unit_price' => 0,
123
-                'LIN_percent'    => $percentage_amount,
124
-                'LIN_quantity'   => 1,
125
-                'LIN_is_taxable' => $taxable,
126
-                'LIN_total'      => (float) $total,
127
-                'LIN_type'       => EEM_Line_Item::type_line_item,
128
-                'LIN_parent'     => $parent_line_item->ID(),
129
-                'LIN_code'       => $code,
130
-            ]
131
-        );
132
-        $line_item = apply_filters(
133
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
134
-            $line_item
135
-        );
136
-        $added     = $parent_line_item->add_child_line_item($line_item, false);
137
-        return $return_item ? $line_item : $added;
138
-    }
139
-
140
-
141
-    /**
142
-     * Returns the new line item created by adding a purchase of the ticket
143
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
144
-     * If this ticket has already been purchased, just increments its count.
145
-     * Automatically re-calculates the line item totals and updates the related transaction. But
146
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
147
-     * should probably change because of this).
148
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
149
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
150
-     *
151
-     * @param EE_Line_Item|null $total_line_item grand total line item of type EEM_Line_Item::type_total
152
-     * @param EE_Ticket         $ticket
153
-     * @param int               $qty
154
-     * @return EE_Line_Item
155
-     * @throws EE_Error
156
-     * @throws ReflectionException
157
-     */
158
-    public static function add_ticket_purchase(
159
-        ?EE_Line_Item $total_line_item,
160
-        EE_Ticket $ticket,
161
-        int $qty = 1
162
-    ): ?EE_Line_Item {
163
-        if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
164
-            throw new EE_Error(
165
-                sprintf(
166
-                    esc_html__(
167
-                        'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
168
-                        'event_espresso'
169
-                    ),
170
-                    $ticket->ID(),
171
-                    $total_line_item->ID()
172
-                )
173
-            );
174
-        }
175
-        // either increment the qty for an existing ticket
176
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
177
-        // or add a new one
178
-        if (! $line_item instanceof EE_Line_Item) {
179
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
180
-        }
181
-        $total_line_item->recalculate_total_including_taxes();
182
-        return $line_item;
183
-    }
184
-
185
-
186
-    /**
187
-     * Returns the new line item created by adding a purchase of the ticket
188
-     *
189
-     * @param EE_Line_Item $total_line_item
190
-     * @param EE_Ticket    $ticket
191
-     * @param int          $qty
192
-     * @return EE_Line_Item
193
-     * @throws EE_Error
194
-     * @throws InvalidArgumentException
195
-     * @throws InvalidDataTypeException
196
-     * @throws InvalidInterfaceException
197
-     * @throws ReflectionException
198
-     */
199
-    public static function increment_ticket_qty_if_already_in_cart(
200
-        EE_Line_Item $total_line_item,
201
-        EE_Ticket $ticket,
202
-        $qty = 1
203
-    ) {
204
-        $line_item = null;
205
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
206
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
207
-            foreach ($ticket_line_items as $ticket_line_item) {
208
-                if (
209
-                    $ticket_line_item instanceof EE_Line_Item
210
-                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
211
-                ) {
212
-                    $line_item = $ticket_line_item;
213
-                    break;
214
-                }
215
-            }
216
-        }
217
-        if ($line_item instanceof EE_Line_Item) {
218
-            EEH_Line_Item::increment_quantity($line_item, $qty);
219
-            return $line_item;
220
-        }
221
-        return null;
222
-    }
223
-
224
-
225
-    /**
226
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
227
-     * Does NOT save or recalculate other line items totals
228
-     *
229
-     * @param EE_Line_Item $line_item
230
-     * @param int          $qty
231
-     * @return void
232
-     * @throws EE_Error
233
-     * @throws InvalidArgumentException
234
-     * @throws InvalidDataTypeException
235
-     * @throws InvalidInterfaceException
236
-     * @throws ReflectionException
237
-     */
238
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
239
-    {
240
-        if (! $line_item->is_percent()) {
241
-            $qty += $line_item->quantity();
242
-            $line_item->set_quantity($qty);
243
-            $line_item->set_total($line_item->unit_price() * $qty);
244
-            $line_item->save();
245
-        }
246
-        foreach ($line_item->children() as $child) {
247
-            if ($child->is_sub_line_item()) {
248
-                EEH_Line_Item::update_quantity($child, $qty);
249
-            }
250
-        }
251
-    }
252
-
253
-
254
-    /**
255
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
256
-     * Does NOT save or recalculate other line items totals
257
-     *
258
-     * @param EE_Line_Item $line_item
259
-     * @param int          $qty
260
-     * @return void
261
-     * @throws EE_Error
262
-     * @throws InvalidArgumentException
263
-     * @throws InvalidDataTypeException
264
-     * @throws InvalidInterfaceException
265
-     * @throws ReflectionException
266
-     */
267
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
268
-    {
269
-        if (! $line_item->is_percent()) {
270
-            $qty = $line_item->quantity() - $qty;
271
-            $qty = max($qty, 0);
272
-            $line_item->set_quantity($qty);
273
-            $line_item->set_total($line_item->unit_price() * $qty);
274
-            $line_item->save();
275
-        }
276
-        foreach ($line_item->children() as $child) {
277
-            if ($child->is_sub_line_item()) {
278
-                EEH_Line_Item::update_quantity($child, $qty);
279
-            }
280
-        }
281
-    }
282
-
283
-
284
-    /**
285
-     * Updates the line item and its children's quantities to the specified number.
286
-     * Does NOT save them or recalculate totals.
287
-     *
288
-     * @param EE_Line_Item $line_item
289
-     * @param int          $new_quantity
290
-     * @throws EE_Error
291
-     * @throws InvalidArgumentException
292
-     * @throws InvalidDataTypeException
293
-     * @throws InvalidInterfaceException
294
-     * @throws ReflectionException
295
-     */
296
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
297
-    {
298
-        if (! $line_item->is_percent()) {
299
-            $line_item->set_quantity($new_quantity);
300
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
301
-            $line_item->save();
302
-        }
303
-        foreach ($line_item->children() as $child) {
304
-            if ($child->is_sub_line_item()) {
305
-                EEH_Line_Item::update_quantity($child, $new_quantity);
306
-            }
307
-        }
308
-    }
309
-
310
-
311
-    /**
312
-     * Returns the new line item created by adding a purchase of the ticket
313
-     *
314
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
315
-     * @param EE_Ticket    $ticket
316
-     * @param int          $qty
317
-     * @return EE_Line_Item
318
-     * @throws EE_Error
319
-     * @throws InvalidArgumentException
320
-     * @throws InvalidDataTypeException
321
-     * @throws InvalidInterfaceException
322
-     * @throws ReflectionException
323
-     */
324
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
325
-    {
326
-        $datetimes = $ticket->datetimes();
327
-        $first_datetime = reset($datetimes);
328
-        $first_datetime_name = esc_html__('Event', 'event_espresso');
329
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
330
-            $first_datetime_name = $first_datetime->event()->name();
331
-        }
332
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
333
-        // get event subtotal line
334
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
335
-        $taxes = $ticket->tax_price_modifiers();
336
-        // add $ticket to cart
337
-        $line_item = EE_Line_Item::new_instance(array(
338
-            'LIN_name'       => $ticket->name(),
339
-            'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
340
-            'LIN_unit_price' => $ticket->price(),
341
-            'LIN_quantity'   => $qty,
342
-            'LIN_is_taxable' => empty($taxes) && $ticket->taxable(),
343
-            'LIN_order'      => count($events_sub_total->children()),
344
-            'LIN_total'      => $ticket->price() * $qty,
345
-            'LIN_type'       => EEM_Line_Item::type_line_item,
346
-            'OBJ_ID'         => $ticket->ID(),
347
-            'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
348
-        ));
349
-        $line_item = apply_filters(
350
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
351
-            $line_item
352
-        );
353
-        if (!$line_item instanceof EE_Line_Item) {
354
-            throw new DomainException(
355
-                esc_html__('Invalid EE_Line_Item received.', 'event_espresso')
356
-            );
357
-        }
358
-        $events_sub_total->add_child_line_item($line_item);
359
-        // now add the sub-line items
360
-        $running_total = 0;
361
-        $running_pre_tax_total = 0;
362
-        foreach ($ticket->prices() as $price) {
363
-            $sign = $price->is_discount() ? -1 : 1;
364
-            $price_total = $price->is_percent()
365
-                ? $running_pre_tax_total * $price->amount() / 100
366
-                : $price->amount() * $qty;
367
-            if ($price->is_percent()) {
368
-                $percent = $sign * $price->amount();
369
-                $unit_price = 0;
370
-            } else {
371
-                $percent    = 0;
372
-                $unit_price = $sign * $price->amount();
373
-            }
374
-            $sub_line_item = EE_Line_Item::new_instance(array(
375
-                'LIN_name'       => $price->name(),
376
-                'LIN_desc'       => $price->desc(),
377
-                'LIN_quantity'   => $price->is_percent() ? null : $qty,
378
-                'LIN_is_taxable' => false,
379
-                'LIN_order'      => $price->order(),
380
-                'LIN_total'      => $price_total,
381
-                'LIN_pretax'     => 0,
382
-                'LIN_unit_price' => $unit_price,
383
-                'LIN_percent'    => $percent,
384
-                'LIN_type'       => $price->is_tax() ? EEM_Line_Item::type_sub_tax : EEM_Line_Item::type_sub_line_item,
385
-                'OBJ_ID'         => $price->ID(),
386
-                'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
387
-            ));
388
-            $sub_line_item = apply_filters(
389
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
390
-                $sub_line_item
391
-            );
392
-            $running_total += $sign * $price_total;
393
-            $running_pre_tax_total += ! $price->is_tax() ? $sign * $price_total : 0;
394
-            $line_item->add_child_line_item($sub_line_item);
395
-        }
396
-        $line_item->setPretaxTotal($running_pre_tax_total);
397
-        return $line_item;
398
-    }
399
-
400
-
401
-    /**
402
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
403
-     * re-calculates the line item totals and updates the related transaction. But
404
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
405
-     * should probably change because of this).
406
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
407
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
408
-     *
409
-     * @param EE_Line_Item $total_line_item
410
-     * @param EE_Line_Item $item to be added
411
-     * @return boolean
412
-     * @throws EE_Error
413
-     * @throws InvalidArgumentException
414
-     * @throws InvalidDataTypeException
415
-     * @throws InvalidInterfaceException
416
-     * @throws ReflectionException
417
-     */
418
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item, $recalculate_totals = true)
419
-    {
420
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
421
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
422
-            $success = $pre_tax_subtotal->add_child_line_item($item);
423
-        } else {
424
-            return false;
425
-        }
426
-        if ($recalculate_totals) {
427
-            $total_line_item->recalculate_total_including_taxes();
428
-        }
429
-        return $success;
430
-    }
431
-
432
-
433
-    /**
434
-     * cancels an existing ticket line item,
435
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
436
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
437
-     *
438
-     * @param EE_Line_Item $ticket_line_item
439
-     * @param int          $qty
440
-     * @return bool success
441
-     * @throws EE_Error
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidDataTypeException
444
-     * @throws InvalidInterfaceException
445
-     * @throws ReflectionException
446
-     */
447
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
448
-    {
449
-        // validate incoming line_item
450
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
451
-            throw new EE_Error(
452
-                sprintf(
453
-                    esc_html__(
454
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
455
-                        'event_espresso'
456
-                    ),
457
-                    $ticket_line_item->type()
458
-                )
459
-            );
460
-        }
461
-        if ($ticket_line_item->quantity() < $qty) {
462
-            throw new EE_Error(
463
-                sprintf(
464
-                    esc_html__(
465
-                        'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
466
-                        'event_espresso'
467
-                    ),
468
-                    $qty,
469
-                    $ticket_line_item->quantity()
470
-                )
471
-            );
472
-        }
473
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
474
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
475
-        foreach ($ticket_line_item->children() as $child_line_item) {
476
-            if (
477
-                $child_line_item->is_sub_line_item()
478
-                && ! $child_line_item->is_percent()
479
-                && ! $child_line_item->is_cancellation()
480
-            ) {
481
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
482
-            }
483
-        }
484
-        // get cancellation sub line item
485
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
486
-            $ticket_line_item,
487
-            EEM_Line_Item::type_cancellation
488
-        );
489
-        $cancellation_line_item = reset($cancellation_line_item);
490
-        // verify that this ticket was indeed previously cancelled
491
-        if ($cancellation_line_item instanceof EE_Line_Item) {
492
-            // increment cancelled quantity
493
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
494
-        } else {
495
-            // create cancellation sub line item
496
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
497
-                'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
498
-                'LIN_desc'       => sprintf(
499
-                    esc_html_x(
500
-                        'Cancelled %1$s : %2$s',
501
-                        'Cancelled Ticket Name : 2015-01-01 11:11',
502
-                        'event_espresso'
503
-                    ),
504
-                    $ticket_line_item->name(),
505
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
506
-                ),
507
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
508
-                'LIN_quantity'   => $qty,
509
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
510
-                'LIN_order'      => count($ticket_line_item->children()),
511
-                'LIN_total'      => 0, // $ticket_line_item->unit_price()
512
-                'LIN_type'       => EEM_Line_Item::type_cancellation,
513
-            ));
514
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
515
-        }
516
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
517
-            // decrement parent line item quantity
518
-            $event_line_item = $ticket_line_item->parent();
519
-            if (
520
-                $event_line_item instanceof EE_Line_Item
521
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
522
-            ) {
523
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
524
-                $event_line_item->save();
525
-            }
526
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
527
-            return true;
528
-        }
529
-        return false;
530
-    }
531
-
532
-
533
-    /**
534
-     * reinstates (un-cancels?) a previously canceled ticket line item,
535
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
536
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
537
-     *
538
-     * @param EE_Line_Item $ticket_line_item
539
-     * @param int          $qty
540
-     * @return bool success
541
-     * @throws EE_Error
542
-     * @throws InvalidArgumentException
543
-     * @throws InvalidDataTypeException
544
-     * @throws InvalidInterfaceException
545
-     * @throws ReflectionException
546
-     */
547
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
548
-    {
549
-        // validate incoming line_item
550
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
551
-            throw new EE_Error(
552
-                sprintf(
553
-                    esc_html__(
554
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
555
-                        'event_espresso'
556
-                    ),
557
-                    $ticket_line_item->type()
558
-                )
559
-            );
560
-        }
561
-        // get cancellation sub line item
562
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
563
-            $ticket_line_item,
564
-            EEM_Line_Item::type_cancellation
565
-        );
566
-        $cancellation_line_item = reset($cancellation_line_item);
567
-        // verify that this ticket was indeed previously cancelled
568
-        if (! $cancellation_line_item instanceof EE_Line_Item) {
569
-            return false;
570
-        }
571
-        if ($cancellation_line_item->quantity() > $qty) {
572
-            // decrement cancelled quantity
573
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
574
-        } elseif ($cancellation_line_item->quantity() === $qty) {
575
-            // decrement cancelled quantity in case anyone still has the object kicking around
576
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
577
-            // delete because quantity will end up as 0
578
-            $cancellation_line_item->delete();
579
-            // and attempt to destroy the object,
580
-            // even though PHP won't actually destroy it until it needs the memory
581
-            unset($cancellation_line_item);
582
-        } else {
583
-            // what ?!?! negative quantity ?!?!
584
-            throw new EE_Error(
585
-                sprintf(
586
-                    esc_html__(
587
-                        'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
588
-                        'event_espresso'
589
-                    ),
590
-                    $qty,
591
-                    $cancellation_line_item->quantity()
592
-                )
593
-            );
594
-        }
595
-        // increment ticket quantity
596
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
597
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
598
-            // increment parent line item quantity
599
-            $event_line_item = $ticket_line_item->parent();
600
-            if (
601
-                $event_line_item instanceof EE_Line_Item
602
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
603
-            ) {
604
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
605
-            }
606
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
607
-            return true;
608
-        }
609
-        return false;
610
-    }
611
-
612
-
613
-    /**
614
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
615
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
616
-     *
617
-     * @param EE_Line_Item $line_item
618
-     * @return float
619
-     * @throws EE_Error
620
-     * @throws InvalidArgumentException
621
-     * @throws InvalidDataTypeException
622
-     * @throws InvalidInterfaceException
623
-     * @throws ReflectionException
624
-     */
625
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
626
-    {
627
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
628
-        return $grand_total_line_item->recalculate_total_including_taxes();
629
-    }
630
-
631
-
632
-    /**
633
-     * Gets the line item which contains the subtotal of all the items
634
-     *
635
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
636
-     * @return EE_Line_Item
637
-     * @throws EE_Error
638
-     * @throws InvalidArgumentException
639
-     * @throws InvalidDataTypeException
640
-     * @throws InvalidInterfaceException
641
-     * @throws ReflectionException
642
-     */
643
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
644
-    {
645
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
646
-        return $pre_tax_subtotal instanceof EE_Line_Item
647
-            ? $pre_tax_subtotal
648
-            : self::create_pre_tax_subtotal($total_line_item);
649
-    }
650
-
651
-
652
-    /**
653
-     * Gets the line item for the taxes subtotal
654
-     *
655
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
656
-     * @return EE_Line_Item
657
-     * @throws EE_Error
658
-     * @throws InvalidArgumentException
659
-     * @throws InvalidDataTypeException
660
-     * @throws InvalidInterfaceException
661
-     * @throws ReflectionException
662
-     */
663
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
664
-    {
665
-        $taxes = $total_line_item->get_child_line_item('taxes');
666
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
667
-    }
668
-
669
-
670
-    /**
671
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
672
-     *
673
-     * @param EE_Line_Item   $line_item
674
-     * @param EE_Transaction $transaction
675
-     * @return void
676
-     * @throws EE_Error
677
-     * @throws InvalidArgumentException
678
-     * @throws InvalidDataTypeException
679
-     * @throws InvalidInterfaceException
680
-     * @throws ReflectionException
681
-     */
682
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
683
-    {
684
-        if ($transaction) {
685
-            /** @type EEM_Transaction $EEM_Transaction */
686
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
687
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
688
-            $line_item->set_TXN_ID($TXN_ID);
689
-        }
690
-    }
691
-
692
-
693
-    /**
694
-     * Creates a new default total line item for the transaction,
695
-     * and its tickets subtotal and taxes subtotal line items (and adds the
696
-     * existing taxes as children of the taxes subtotal line item)
697
-     *
698
-     * @param EE_Transaction $transaction
699
-     * @return EE_Line_Item of type total
700
-     * @throws EE_Error
701
-     * @throws InvalidArgumentException
702
-     * @throws InvalidDataTypeException
703
-     * @throws InvalidInterfaceException
704
-     * @throws ReflectionException
705
-     */
706
-    public static function create_total_line_item($transaction = null)
707
-    {
708
-        $total_line_item = EE_Line_Item::new_instance(array(
709
-            'LIN_code' => 'total',
710
-            'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
711
-            'LIN_type' => EEM_Line_Item::type_total,
712
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
713
-        ));
714
-        $total_line_item = apply_filters(
715
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
716
-            $total_line_item
717
-        );
718
-        self::set_TXN_ID($total_line_item, $transaction);
719
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
720
-        self::create_taxes_subtotal($total_line_item, $transaction);
721
-        return $total_line_item;
722
-    }
723
-
724
-
725
-    /**
726
-     * Creates a default items subtotal line item
727
-     *
728
-     * @param EE_Line_Item   $total_line_item
729
-     * @param EE_Transaction $transaction
730
-     * @return EE_Line_Item
731
-     * @throws EE_Error
732
-     * @throws InvalidArgumentException
733
-     * @throws InvalidDataTypeException
734
-     * @throws InvalidInterfaceException
735
-     * @throws ReflectionException
736
-     */
737
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
738
-    {
739
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
740
-            'LIN_code' => 'pre-tax-subtotal',
741
-            'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
742
-            'LIN_type' => EEM_Line_Item::type_sub_total,
743
-        ));
744
-        $pre_tax_line_item = apply_filters(
745
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
746
-            $pre_tax_line_item
747
-        );
748
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
749
-        $total_line_item->add_child_line_item($pre_tax_line_item);
750
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
751
-        return $pre_tax_line_item;
752
-    }
753
-
754
-
755
-    /**
756
-     * Creates a line item for the taxes subtotal and finds all the tax prices
757
-     * and applies taxes to it
758
-     *
759
-     * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
760
-     * @param EE_Transaction $transaction
761
-     * @return EE_Line_Item
762
-     * @throws EE_Error
763
-     * @throws InvalidArgumentException
764
-     * @throws InvalidDataTypeException
765
-     * @throws InvalidInterfaceException
766
-     * @throws ReflectionException
767
-     */
768
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
769
-    {
770
-        $tax_line_item = EE_Line_Item::new_instance(array(
771
-            'LIN_code'  => 'taxes',
772
-            'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
773
-            'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
774
-            'LIN_order' => 1000,// this should always come last
775
-        ));
776
-        $tax_line_item = apply_filters(
777
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
778
-            $tax_line_item
779
-        );
780
-        self::set_TXN_ID($tax_line_item, $transaction);
781
-        $total_line_item->add_child_line_item($tax_line_item);
782
-        // and lastly, add the actual taxes
783
-        self::apply_taxes($total_line_item);
784
-        return $tax_line_item;
785
-    }
786
-
787
-
788
-    /**
789
-     * Creates a default items subtotal line item
790
-     *
791
-     * @param EE_Line_Item   $pre_tax_line_item
792
-     * @param EE_Transaction $transaction
793
-     * @param EE_Event       $event
794
-     * @return EE_Line_Item
795
-     * @throws EE_Error
796
-     * @throws InvalidArgumentException
797
-     * @throws InvalidDataTypeException
798
-     * @throws InvalidInterfaceException
799
-     * @throws ReflectionException
800
-     */
801
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
802
-    {
803
-        $event_line_item = EE_Line_Item::new_instance(array(
804
-            'LIN_code' => self::get_event_code($event),
805
-            'LIN_name' => self::get_event_name($event),
806
-            'LIN_desc' => self::get_event_desc($event),
807
-            'LIN_type' => EEM_Line_Item::type_sub_total,
808
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
809
-            'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
810
-        ));
811
-        $event_line_item = apply_filters(
812
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
813
-            $event_line_item
814
-        );
815
-        self::set_TXN_ID($event_line_item, $transaction);
816
-        $pre_tax_line_item->add_child_line_item($event_line_item);
817
-        return $event_line_item;
818
-    }
819
-
820
-
821
-    /**
822
-     * Gets what the event ticket's code SHOULD be
823
-     *
824
-     * @param EE_Event $event
825
-     * @return string
826
-     * @throws EE_Error
827
-     */
828
-    public static function get_event_code($event)
829
-    {
830
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets the event name
836
-     *
837
-     * @param EE_Event $event
838
-     * @return string
839
-     * @throws EE_Error
840
-     */
841
-    public static function get_event_name($event)
842
-    {
843
-        return $event instanceof EE_Event
844
-            ? mb_substr($event->name(), 0, 245)
845
-            : esc_html__('Event', 'event_espresso');
846
-    }
847
-
848
-
849
-    /**
850
-     * Gets the event excerpt
851
-     *
852
-     * @param EE_Event $event
853
-     * @return string
854
-     * @throws EE_Error
855
-     */
856
-    public static function get_event_desc($event)
857
-    {
858
-        return $event instanceof EE_Event ? $event->short_description() : '';
859
-    }
860
-
861
-
862
-    /**
863
-     * Given the grand total line item and a ticket, finds the event sub-total
864
-     * line item the ticket's purchase should be added onto
865
-     *
866
-     * @access public
867
-     * @param EE_Line_Item $grand_total the grand total line item
868
-     * @param EE_Ticket    $ticket
869
-     * @return EE_Line_Item
870
-     * @throws EE_Error
871
-     * @throws InvalidArgumentException
872
-     * @throws InvalidDataTypeException
873
-     * @throws InvalidInterfaceException
874
-     * @throws ReflectionException
875
-     */
876
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
877
-    {
878
-        $first_datetime = $ticket->first_datetime();
879
-        if (! $first_datetime instanceof EE_Datetime) {
880
-            throw new EE_Error(
881
-                sprintf(
882
-                    esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
883
-                    $ticket->ID()
884
-                )
885
-            );
886
-        }
887
-        $event = $first_datetime->event();
888
-        if (! $event instanceof EE_Event) {
889
-            throw new EE_Error(
890
-                sprintf(
891
-                    esc_html__(
892
-                        'The supplied ticket (ID %d) has no event data associated with it.',
893
-                        'event_espresso'
894
-                    ),
895
-                    $ticket->ID()
896
-                )
897
-            );
898
-        }
899
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
900
-        if (! $events_sub_total instanceof EE_Line_Item) {
901
-            throw new EE_Error(
902
-                sprintf(
903
-                    esc_html__(
904
-                        'There is no events sub-total for ticket %s on total line item %d',
905
-                        'event_espresso'
906
-                    ),
907
-                    $ticket->ID(),
908
-                    $grand_total->ID()
909
-                )
910
-            );
911
-        }
912
-        return $events_sub_total;
913
-    }
914
-
915
-
916
-    /**
917
-     * Gets the event line item
918
-     *
919
-     * @param EE_Line_Item $grand_total
920
-     * @param EE_Event     $event
921
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
922
-     * @throws EE_Error
923
-     * @throws InvalidArgumentException
924
-     * @throws InvalidDataTypeException
925
-     * @throws InvalidInterfaceException
926
-     * @throws ReflectionException
927
-     */
928
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
929
-    {
930
-        /** @type EE_Event $event */
931
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
932
-        $event_line_item = null;
933
-        $found = false;
934
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
935
-            // default event subtotal, we should only ever find this the first time this method is called
936
-            if (! $event_line_item->OBJ_ID()) {
937
-                // let's use this! but first... set the event details
938
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
939
-                $found = true;
940
-                break;
941
-            }
942
-            if ($event_line_item->OBJ_ID() === $event->ID()) {
943
-                // found existing line item for this event in the cart, so break out of loop and use this one
944
-                $found = true;
945
-                break;
946
-            }
947
-        }
948
-        if (! $found) {
949
-            // there is no event sub-total yet, so add it
950
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
951
-            // create a new "event" subtotal below that
952
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
953
-            // and set the event details
954
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
955
-        }
956
-        return $event_line_item;
957
-    }
958
-
959
-
960
-    /**
961
-     * Creates a default items subtotal line item
962
-     *
963
-     * @param EE_Line_Item   $event_line_item
964
-     * @param EE_Event       $event
965
-     * @param EE_Transaction $transaction
966
-     * @return void
967
-     * @throws EE_Error
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidDataTypeException
970
-     * @throws InvalidInterfaceException
971
-     * @throws ReflectionException
972
-     */
973
-    public static function set_event_subtotal_details(
974
-        EE_Line_Item $event_line_item,
975
-        EE_Event $event,
976
-        $transaction = null
977
-    ) {
978
-        if ($event instanceof EE_Event) {
979
-            $event_line_item->set_code(self::get_event_code($event));
980
-            $event_line_item->set_name(self::get_event_name($event));
981
-            $event_line_item->set_desc(self::get_event_desc($event));
982
-            $event_line_item->set_OBJ_ID($event->ID());
983
-        }
984
-        self::set_TXN_ID($event_line_item, $transaction);
985
-    }
986
-
987
-
988
-    /**
989
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
990
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
991
-     * any old taxes are removed
992
-     *
993
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
994
-     * @param bool         $update_txn_status
995
-     * @return bool
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws InvalidDataTypeException
999
-     * @throws InvalidInterfaceException
1000
-     * @throws ReflectionException
1001
-     * @throws RuntimeException
1002
-     */
1003
-    public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
1004
-    {
1005
-        $total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($total_line_item);
1006
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
1007
-        $existing_global_taxes = $taxes_line_item->tax_descendants();
1008
-        $updates = false;
1009
-        // loop thru taxes
1010
-        $global_taxes = EEH_Line_Item::getGlobalTaxes();
1011
-        foreach ($global_taxes as $order => $taxes) {
1012
-            foreach ($taxes as $tax) {
1013
-                if ($tax instanceof EE_Price) {
1014
-                    $found = false;
1015
-                    // check if this is already an existing tax
1016
-                    foreach ($existing_global_taxes as $existing_global_tax) {
1017
-                        if ($tax->ID() === $existing_global_tax->OBJ_ID()) {
1018
-                            // maybe update the tax rate in case it has changed
1019
-                            if ($existing_global_tax->percent() !== $tax->amount()) {
1020
-                                $existing_global_tax->set_percent($tax->amount());
1021
-                                $existing_global_tax->save();
1022
-                                $updates = true;
1023
-                            }
1024
-                            $found = true;
1025
-                            break;
1026
-                        }
1027
-                    }
1028
-                    if (! $found) {
1029
-                        // add a new line item for this global tax
1030
-                        $tax_line_item = apply_filters(
1031
-                            'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
1032
-                            EE_Line_Item::new_instance(
1033
-                                [
1034
-                                    'LIN_name'       => $tax->name(),
1035
-                                    'LIN_desc'       => $tax->desc(),
1036
-                                    'LIN_percent'    => $tax->amount(),
1037
-                                    'LIN_is_taxable' => false,
1038
-                                    'LIN_order'      => $order,
1039
-                                    'LIN_total'      => 0,
1040
-                                    'LIN_type'       => EEM_Line_Item::type_tax,
1041
-                                    'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
1042
-                                    'OBJ_ID'         => $tax->ID(),
1043
-                                ]
1044
-                            )
1045
-                        );
1046
-                        $updates = $taxes_line_item->add_child_line_item($tax_line_item) ? true : $updates;
1047
-                    }
1048
-                }
1049
-            }
1050
-        }
1051
-        // only recalculate totals if something changed
1052
-        if ($updates) {
1053
-            $total_line_item->recalculate_total_including_taxes($update_txn_status);
1054
-            return true;
1055
-        }
1056
-        return false;
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * Ensures that taxes have been applied to the order, if not applies them.
1062
-     * Returns the total amount of tax
1063
-     *
1064
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1065
-     * @return float
1066
-     * @throws EE_Error
1067
-     * @throws InvalidArgumentException
1068
-     * @throws InvalidDataTypeException
1069
-     * @throws InvalidInterfaceException
1070
-     * @throws ReflectionException
1071
-     */
1072
-    public static function ensure_taxes_applied($total_line_item)
1073
-    {
1074
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1075
-        if (! $taxes_subtotal->children()) {
1076
-            self::apply_taxes($total_line_item);
1077
-        }
1078
-        return $taxes_subtotal->total();
1079
-    }
1080
-
1081
-
1082
-    /**
1083
-     * Deletes ALL children of the passed line item
1084
-     *
1085
-     * @param EE_Line_Item $parent_line_item
1086
-     * @return bool
1087
-     * @throws EE_Error
1088
-     * @throws InvalidArgumentException
1089
-     * @throws InvalidDataTypeException
1090
-     * @throws InvalidInterfaceException
1091
-     * @throws ReflectionException
1092
-     */
1093
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1094
-    {
1095
-        $deleted = 0;
1096
-        foreach ($parent_line_item->children() as $child_line_item) {
1097
-            if ($child_line_item instanceof EE_Line_Item) {
1098
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1099
-                if ($child_line_item->ID()) {
1100
-                    $child_line_item->delete();
1101
-                    unset($child_line_item);
1102
-                } else {
1103
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
1104
-                }
1105
-                $deleted++;
1106
-            }
1107
-        }
1108
-        return $deleted;
1109
-    }
1110
-
1111
-
1112
-    /**
1113
-     * Deletes the line items as indicated by the line item code(s) provided,
1114
-     * regardless of where they're found in the line item tree. Automatically
1115
-     * re-calculates the line item totals and updates the related transaction. But
1116
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1117
-     * should probably change because of this).
1118
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1119
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
1120
-     *
1121
-     * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1122
-     * @param array|bool|string $line_item_codes
1123
-     * @return int number of items successfully removed
1124
-     * @throws EE_Error
1125
-     */
1126
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1127
-    {
1128
-
1129
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1130
-            EE_Error::doing_it_wrong(
1131
-                'EEH_Line_Item::delete_items',
1132
-                esc_html__(
1133
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1134
-                    'event_espresso'
1135
-                ),
1136
-                '4.6.18'
1137
-            );
1138
-        }
1139
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1140
-
1141
-        // check if only a single line_item_id was passed
1142
-        if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1143
-            // place single line_item_id in an array to appear as multiple line_item_ids
1144
-            $line_item_codes = array($line_item_codes);
1145
-        }
1146
-        $removals = 0;
1147
-        // cycle thru line_item_ids
1148
-        foreach ($line_item_codes as $line_item_id) {
1149
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
1150
-        }
1151
-
1152
-        if ($removals > 0) {
1153
-            $total_line_item->recalculate_taxes_and_tax_total();
1154
-            return $removals;
1155
-        } else {
1156
-            return false;
1157
-        }
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
1163
-     * tax and updates the total line item accordingly
1164
-     *
1165
-     * @param EE_Line_Item $total_line_item
1166
-     * @param float        $amount
1167
-     * @param string       $name
1168
-     * @param string       $description
1169
-     * @param string       $code
1170
-     * @param boolean      $add_to_existing_line_item
1171
-     *                          if true, and a duplicate line item with the same code is found,
1172
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1173
-     * @return EE_Line_Item the new tax line item created
1174
-     * @throws EE_Error
1175
-     * @throws InvalidArgumentException
1176
-     * @throws InvalidDataTypeException
1177
-     * @throws InvalidInterfaceException
1178
-     * @throws ReflectionException
1179
-     */
1180
-    public static function set_total_tax_to(
1181
-        EE_Line_Item $total_line_item,
1182
-        $amount,
1183
-        $name = null,
1184
-        $description = null,
1185
-        $code = null,
1186
-        $add_to_existing_line_item = false
1187
-    ) {
1188
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
1189
-        $taxable_total = $total_line_item->taxable_total();
1190
-
1191
-        if ($add_to_existing_line_item) {
1192
-            $new_tax = $tax_subtotal->get_child_line_item($code);
1193
-            EEM_Line_Item::instance()->delete(
1194
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1195
-            );
1196
-        } else {
1197
-            $new_tax = null;
1198
-            $tax_subtotal->delete_children_line_items();
1199
-        }
1200
-        if ($new_tax) {
1201
-            $new_tax->set_total($new_tax->total() + $amount);
1202
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1203
-        } else {
1204
-            // no existing tax item. Create it
1205
-            $new_tax = EE_Line_Item::new_instance(array(
1206
-                'TXN_ID'      => $total_line_item->TXN_ID(),
1207
-                'LIN_name'    => $name ?: esc_html__('Tax', 'event_espresso'),
1208
-                'LIN_desc'    => $description ?: '',
1209
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1210
-                'LIN_total'   => $amount,
1211
-                'LIN_parent'  => $tax_subtotal->ID(),
1212
-                'LIN_type'    => EEM_Line_Item::type_tax,
1213
-                'LIN_code'    => $code,
1214
-            ));
1215
-        }
1216
-
1217
-        $new_tax = apply_filters(
1218
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1219
-            $new_tax,
1220
-            $total_line_item
1221
-        );
1222
-        $new_tax->save();
1223
-        $tax_subtotal->set_total($new_tax->total());
1224
-        $tax_subtotal->save();
1225
-        $total_line_item->recalculate_total_including_taxes();
1226
-        return $new_tax;
1227
-    }
1228
-
1229
-
1230
-    /**
1231
-     * Makes all the line items which are children of $line_item taxable (or not).
1232
-     * Does NOT save the line items
1233
-     *
1234
-     * @param EE_Line_Item $line_item
1235
-     * @param boolean      $taxable
1236
-     * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1237
-     *                                                   it will be whitelisted (ie, except from becoming taxable)
1238
-     * @throws EE_Error
1239
-     */
1240
-    public static function set_line_items_taxable(
1241
-        EE_Line_Item $line_item,
1242
-        $taxable = true,
1243
-        $code_substring_for_whitelist = null
1244
-    ) {
1245
-        $whitelisted = false;
1246
-        if ($code_substring_for_whitelist !== null) {
1247
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1248
-        }
1249
-        if (! $whitelisted && $line_item->is_line_item()) {
1250
-            $line_item->set_is_taxable($taxable);
1251
-        }
1252
-        foreach ($line_item->children() as $child_line_item) {
1253
-            EEH_Line_Item::set_line_items_taxable(
1254
-                $child_line_item,
1255
-                $taxable,
1256
-                $code_substring_for_whitelist
1257
-            );
1258
-        }
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Gets all descendants that are event subtotals
1264
-     *
1265
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1266
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1267
-     * @return EE_Line_Item[]
1268
-     * @throws EE_Error
1269
-     */
1270
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1271
-    {
1272
-        return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1273
-    }
1274
-
1275
-
1276
-    /**
1277
-     * Gets all descendants subtotals that match the supplied object type
1278
-     *
1279
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1280
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1281
-     * @param string       $obj_type
1282
-     * @return EE_Line_Item[]
1283
-     * @throws EE_Error
1284
-     */
1285
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1286
-    {
1287
-        return self::_get_descendants_by_type_and_object_type(
1288
-            $parent_line_item,
1289
-            EEM_Line_Item::type_sub_total,
1290
-            $obj_type
1291
-        );
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Gets all descendants that are tickets
1297
-     *
1298
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1299
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1300
-     * @return EE_Line_Item[]
1301
-     * @throws EE_Error
1302
-     */
1303
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1304
-    {
1305
-        return self::get_line_items_of_object_type(
1306
-            $parent_line_item,
1307
-            EEM_Line_Item::OBJ_TYPE_TICKET
1308
-        );
1309
-    }
1310
-
1311
-
1312
-    /**
1313
-     * Gets all descendants subtotals that match the supplied object type
1314
-     *
1315
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1316
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1317
-     * @param string       $obj_type
1318
-     * @return EE_Line_Item[]
1319
-     * @throws EE_Error
1320
-     */
1321
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1322
-    {
1323
-        return self::_get_descendants_by_type_and_object_type(
1324
-            $parent_line_item,
1325
-            EEM_Line_Item::type_line_item,
1326
-            $obj_type
1327
-        );
1328
-    }
1329
-
1330
-
1331
-    /**
1332
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1333
-     *
1334
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1335
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1336
-     * @return EE_Line_Item[]
1337
-     * @throws EE_Error
1338
-     */
1339
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1340
-    {
1341
-        return EEH_Line_Item::get_descendants_of_type(
1342
-            $parent_line_item,
1343
-            EEM_Line_Item::type_tax
1344
-        );
1345
-    }
1346
-
1347
-
1348
-    /**
1349
-     * Gets all the real items purchased which are children of this item
1350
-     *
1351
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1352
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1353
-     * @return EE_Line_Item[]
1354
-     * @throws EE_Error
1355
-     */
1356
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1357
-    {
1358
-        return EEH_Line_Item::get_descendants_of_type(
1359
-            $parent_line_item,
1360
-            EEM_Line_Item::type_line_item
1361
-        );
1362
-    }
1363
-
1364
-
1365
-    /**
1366
-     * Gets all descendants of supplied line item that match the supplied line item type
1367
-     *
1368
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1369
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1370
-     * @param string       $line_item_type   one of the EEM_Line_Item constants
1371
-     * @return EE_Line_Item[]
1372
-     * @throws EE_Error
1373
-     */
1374
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1375
-    {
1376
-        return self::_get_descendants_by_type_and_object_type(
1377
-            $parent_line_item,
1378
-            $line_item_type,
1379
-            null
1380
-        );
1381
-    }
1382
-
1383
-
1384
-    /**
1385
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1386
-     * as well
1387
-     *
1388
-     * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1389
-     * @param string        $line_item_type   one of the EEM_Line_Item constants
1390
-     * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1391
-     *                                        searching
1392
-     * @return EE_Line_Item[]
1393
-     * @throws EE_Error
1394
-     */
1395
-    protected static function _get_descendants_by_type_and_object_type(
1396
-        EE_Line_Item $parent_line_item,
1397
-        $line_item_type,
1398
-        $obj_type = null
1399
-    ) {
1400
-        $objects = array();
1401
-        foreach ($parent_line_item->children() as $child_line_item) {
1402
-            if ($child_line_item instanceof EE_Line_Item) {
1403
-                if (
1404
-                    $child_line_item->type() === $line_item_type
1405
-                    && (
1406
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1407
-                    )
1408
-                ) {
1409
-                    $objects[] = $child_line_item;
1410
-                } else {
1411
-                    // go-through-all-its children looking for more matches
1412
-                    $objects = array_merge(
1413
-                        $objects,
1414
-                        self::_get_descendants_by_type_and_object_type(
1415
-                            $child_line_item,
1416
-                            $line_item_type,
1417
-                            $obj_type
1418
-                        )
1419
-                    );
1420
-                }
1421
-            }
1422
-        }
1423
-        return $objects;
1424
-    }
1425
-
1426
-
1427
-    /**
1428
-     * Gets all descendants subtotals that match the supplied object type
1429
-     *
1430
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1431
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1432
-     * @param string       $OBJ_type         object type (like Event)
1433
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1434
-     * @return EE_Line_Item[]
1435
-     * @throws EE_Error
1436
-     */
1437
-    public static function get_line_items_by_object_type_and_IDs(
1438
-        EE_Line_Item $parent_line_item,
1439
-        $OBJ_type = '',
1440
-        $OBJ_IDs = array()
1441
-    ) {
1442
-        return self::_get_descendants_by_object_type_and_object_ID(
1443
-            $parent_line_item,
1444
-            $OBJ_type,
1445
-            $OBJ_IDs
1446
-        );
1447
-    }
1448
-
1449
-
1450
-    /**
1451
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1452
-     * as well
1453
-     *
1454
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1455
-     * @param string       $OBJ_type         object type (like Event)
1456
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1457
-     * @return EE_Line_Item[]
1458
-     * @throws EE_Error
1459
-     */
1460
-    protected static function _get_descendants_by_object_type_and_object_ID(
1461
-        EE_Line_Item $parent_line_item,
1462
-        $OBJ_type,
1463
-        $OBJ_IDs
1464
-    ) {
1465
-        $objects = array();
1466
-        foreach ($parent_line_item->children() as $child_line_item) {
1467
-            if ($child_line_item instanceof EE_Line_Item) {
1468
-                if (
1469
-                    $child_line_item->OBJ_type() === $OBJ_type
1470
-                    && is_array($OBJ_IDs)
1471
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1472
-                ) {
1473
-                    $objects[] = $child_line_item;
1474
-                } else {
1475
-                    // go-through-all-its children looking for more matches
1476
-                    $objects = array_merge(
1477
-                        $objects,
1478
-                        self::_get_descendants_by_object_type_and_object_ID(
1479
-                            $child_line_item,
1480
-                            $OBJ_type,
1481
-                            $OBJ_IDs
1482
-                        )
1483
-                    );
1484
-                }
1485
-            }
1486
-        }
1487
-        return $objects;
1488
-    }
1489
-
1490
-
1491
-    /**
1492
-     * Uses a breadth-first-search in order to find the nearest descendant of
1493
-     * the specified type and returns it, else NULL
1494
-     *
1495
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1496
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1497
-     * @param string       $type             like one of the EEM_Line_Item::type_*
1498
-     * @return EE_Line_Item
1499
-     * @throws EE_Error
1500
-     * @throws InvalidArgumentException
1501
-     * @throws InvalidDataTypeException
1502
-     * @throws InvalidInterfaceException
1503
-     * @throws ReflectionException
1504
-     */
1505
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1506
-    {
1507
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1508
-    }
1509
-
1510
-
1511
-    /**
1512
-     * Uses a breadth-first-search in order to find the nearest descendant
1513
-     * having the specified LIN_code and returns it, else NULL
1514
-     *
1515
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1516
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1517
-     * @param string       $code             any value used for LIN_code
1518
-     * @return EE_Line_Item
1519
-     * @throws EE_Error
1520
-     * @throws InvalidArgumentException
1521
-     * @throws InvalidDataTypeException
1522
-     * @throws InvalidInterfaceException
1523
-     * @throws ReflectionException
1524
-     */
1525
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1526
-    {
1527
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1528
-    }
1529
-
1530
-
1531
-    /**
1532
-     * Uses a breadth-first-search in order to find the nearest descendant
1533
-     * having the specified LIN_code and returns it, else NULL
1534
-     *
1535
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1536
-     * @param string       $search_field     name of EE_Line_Item property
1537
-     * @param string       $value            any value stored in $search_field
1538
-     * @return EE_Line_Item
1539
-     * @throws EE_Error
1540
-     * @throws InvalidArgumentException
1541
-     * @throws InvalidDataTypeException
1542
-     * @throws InvalidInterfaceException
1543
-     * @throws ReflectionException
1544
-     */
1545
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1546
-    {
1547
-        foreach ($parent_line_item->children() as $child) {
1548
-            if ($child->get($search_field) == $value) {
1549
-                return $child;
1550
-            }
1551
-        }
1552
-        foreach ($parent_line_item->children() as $child) {
1553
-            $descendant_found = self::_get_nearest_descendant(
1554
-                $child,
1555
-                $search_field,
1556
-                $value
1557
-            );
1558
-            if ($descendant_found) {
1559
-                return $descendant_found;
1560
-            }
1561
-        }
1562
-        return null;
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1568
-     * else recursively walks up the line item tree until a parent of type total is found,
1569
-     *
1570
-     * @param EE_Line_Item $line_item
1571
-     * @return EE_Line_Item
1572
-     * @throws EE_Error
1573
-     * @throws ReflectionException
1574
-     */
1575
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item): EE_Line_Item
1576
-    {
1577
-        if ($line_item->is_total()) {
1578
-            return $line_item;
1579
-        }
1580
-        if ($line_item->TXN_ID()) {
1581
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1582
-            if ($total_line_item instanceof EE_Line_Item) {
1583
-                return $total_line_item;
1584
-            }
1585
-        } else {
1586
-            $line_item_parent = $line_item->parent();
1587
-            if ($line_item_parent instanceof EE_Line_Item) {
1588
-                if ($line_item_parent->is_total()) {
1589
-                    return $line_item_parent;
1590
-                }
1591
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1592
-            }
1593
-        }
1594
-        throw new EE_Error(
1595
-            sprintf(
1596
-                esc_html__(
1597
-                    'A valid grand total for line item %1$d was not found.',
1598
-                    'event_espresso'
1599
-                ),
1600
-                $line_item->ID()
1601
-            )
1602
-        );
1603
-    }
1604
-
1605
-
1606
-    /**
1607
-     * Prints out a representation of the line item tree
1608
-     *
1609
-     * @param EE_Line_Item $line_item
1610
-     * @param int          $indentation
1611
-     * @return void
1612
-     * @throws EE_Error
1613
-     */
1614
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1615
-    {
1616
-        $new_line = defined('EE_TESTS_DIR') ? "\n" : '<br />';
1617
-        echo $new_line;
1618
-        if (! $indentation) {
1619
-            echo $new_line;
1620
-        }
1621
-        echo str_repeat('. ', $indentation);
1622
-        $breakdown = '';
1623
-        if ($line_item->is_line_item() || $line_item->is_sub_line_item() || $line_item->isSubTax()) {
1624
-            if ($line_item->is_percent()) {
1625
-                $breakdown = "{$line_item->percent()}%";
1626
-            } else {
1627
-                $breakdown = "\${$line_item->unit_price()} x {$line_item->quantity()}";
1628
-            }
1629
-        }
1630
-        echo wp_kses($line_item->name(), AllowedTags::getAllowedTags());
1631
-        echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1632
-        echo "\${$line_item->total()}";
1633
-        if ($breakdown) {
1634
-            echo " ( {$breakdown} )";
1635
-        }
1636
-        if ($line_item->is_taxable()) {
1637
-            echo '  * taxable';
1638
-        }
1639
-        if ($line_item->children()) {
1640
-            foreach ($line_item->children() as $child) {
1641
-                self::visualize($child, $indentation + 1);
1642
-            }
1643
-        }
1644
-        if (! $indentation) {
1645
-            echo $new_line . $new_line;
1646
-        }
1647
-    }
1648
-
1649
-
1650
-    /**
1651
-     * Calculates the registration's final price, taking into account that they
1652
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1653
-     * and receive a portion of any transaction-wide discounts.
1654
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1655
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1656
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1657
-     * and brent's final price should be $5.50.
1658
-     * In order to do this, we basically need to traverse the line item tree calculating
1659
-     * the running totals (just as if we were recalculating the total), but when we identify
1660
-     * regular line items, we need to keep track of their share of the grand total.
1661
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1662
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1663
-     * when there are non-taxable items; otherwise they would be the same)
1664
-     *
1665
-     * @param EE_Line_Item $line_item
1666
-     * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1667
-     *                                                  can be included in price calculations at this moment
1668
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1669
-     *                                                  plus the key 'total', and 'taxable' which also has keys of all
1670
-     *                                                  the ticket IDs.
1671
-     *                                                  Eg array(
1672
-     *                                                      12 => 4.3
1673
-     *                                                      23 => 8.0
1674
-     *                                                      'total' => 16.6,
1675
-     *                                                      'taxable' => array(
1676
-     *                                                          12 => 10,
1677
-     *                                                          23 => 4
1678
-     *                                                      ).
1679
-     *                                                  So to find which registrations have which final price, we need
1680
-     *                                                  to find which line item is theirs, which can be done with
1681
-     *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1682
-     *                                                  $registration );`
1683
-     * @throws EE_Error
1684
-     * @throws InvalidArgumentException
1685
-     * @throws InvalidDataTypeException
1686
-     * @throws InvalidInterfaceException
1687
-     * @throws ReflectionException
1688
-     */
1689
-    public static function calculate_reg_final_prices_per_line_item(
1690
-        EE_Line_Item $line_item,
1691
-        $billable_ticket_quantities = array()
1692
-    ) {
1693
-        $running_totals = [
1694
-            'total'   => 0,
1695
-            'taxable' => ['total' => 0]
1696
-        ];
1697
-        foreach ($line_item->children() as $child_line_item) {
1698
-            switch ($child_line_item->type()) {
1699
-                case EEM_Line_Item::type_sub_total:
1700
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1701
-                        $child_line_item,
1702
-                        $billable_ticket_quantities
1703
-                    );
1704
-                    // combine arrays but preserve numeric keys
1705
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1706
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1707
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1708
-                    break;
1709
-
1710
-                case EEM_Line_Item::type_tax_sub_total:
1711
-                    // find how much the taxes percentage is
1712
-                    if ($child_line_item->percent() !== 0) {
1713
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1714
-                    } else {
1715
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1716
-                    }
1717
-                    // and apply to all the taxable totals, and add to the pretax totals
1718
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1719
-                        // "total" and "taxable" array key is an exception
1720
-                        if ($line_item_id === 'taxable') {
1721
-                            continue;
1722
-                        }
1723
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1724
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1725
-                    }
1726
-                    break;
1727
-
1728
-                case EEM_Line_Item::type_line_item:
1729
-                    // ticket line items or ????
1730
-                    if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1731
-                        // kk it's a ticket
1732
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1733
-                            // huh? that shouldn't happen.
1734
-                            $running_totals['total'] += $child_line_item->total();
1735
-                        } else {
1736
-                            // its not in our running totals yet. great.
1737
-                            if ($child_line_item->is_taxable()) {
1738
-                                $taxable_amount = $child_line_item->unit_price();
1739
-                            } else {
1740
-                                $taxable_amount = 0;
1741
-                            }
1742
-                            // are we only calculating totals for some tickets?
1743
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1744
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1745
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1746
-                                    ? $child_line_item->unit_price()
1747
-                                    : 0;
1748
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1749
-                                    ? $taxable_amount
1750
-                                    : 0;
1751
-                            } else {
1752
-                                $quantity = $child_line_item->quantity();
1753
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1754
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1755
-                            }
1756
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1757
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1758
-                        }
1759
-                    } else {
1760
-                        // it's some other type of item added to the cart
1761
-                        // it should affect the running totals
1762
-                        // basically we want to convert it into a PERCENT modifier. Because
1763
-                        // more clearly affect all registration's final price equally
1764
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1765
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1766
-                            : 1;
1767
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1768
-                            // the "taxable" array key is an exception
1769
-                            if ($line_item_id === 'taxable') {
1770
-                                continue;
1771
-                            }
1772
-                            // update the running totals
1773
-                            // yes this actually even works for the running grand total!
1774
-                            $running_totals[ $line_item_id ] =
1775
-                                $line_items_percent_of_running_total * $this_running_total;
1776
-
1777
-                            if ($child_line_item->is_taxable()) {
1778
-                                $running_totals['taxable'][ $line_item_id ] =
1779
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1780
-                            }
1781
-                        }
1782
-                    }
1783
-                    break;
1784
-            }
1785
-        }
1786
-        return $running_totals;
1787
-    }
1788
-
1789
-
1790
-    /**
1791
-     * @param EE_Line_Item $total_line_item
1792
-     * @param EE_Line_Item $ticket_line_item
1793
-     * @return float | null
1794
-     * @throws EE_Error
1795
-     * @throws InvalidArgumentException
1796
-     * @throws InvalidDataTypeException
1797
-     * @throws InvalidInterfaceException
1798
-     * @throws OutOfRangeException
1799
-     * @throws ReflectionException
1800
-     */
1801
-    public static function calculate_final_price_for_ticket_line_item(
1802
-        EE_Line_Item $total_line_item,
1803
-        EE_Line_Item $ticket_line_item
1804
-    ) {
1805
-        static $final_prices_per_ticket_line_item = array();
1806
-        if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1807
-            $final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1808
-                $total_line_item
1809
-            );
1810
-        }
1811
-        // ok now find this new registration's final price
1812
-        if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1813
-            return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1814
-        }
1815
-        $message = sprintf(
1816
-            esc_html__(
1817
-                'The final price for the ticket line item (ID:%1$d) on the total line item (ID:%2$d) could not be calculated.',
1818
-                'event_espresso'
1819
-            ),
1820
-            $ticket_line_item->ID(),
1821
-            $total_line_item->ID()
1822
-        );
1823
-        if (WP_DEBUG) {
1824
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1825
-            throw new OutOfRangeException($message);
1826
-        }
1827
-        EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1828
-        return null;
1829
-    }
1830
-
1831
-
1832
-    /**
1833
-     * Creates a duplicate of the line item tree, except only includes billable items
1834
-     * and the portion of line items attributed to billable things
1835
-     *
1836
-     * @param EE_Line_Item      $line_item
1837
-     * @param EE_Registration[] $registrations
1838
-     * @return EE_Line_Item
1839
-     * @throws EE_Error
1840
-     * @throws InvalidArgumentException
1841
-     * @throws InvalidDataTypeException
1842
-     * @throws InvalidInterfaceException
1843
-     * @throws ReflectionException
1844
-     */
1845
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1846
-    {
1847
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1848
-        foreach ($line_item->children() as $child_li) {
1849
-            $copy_li->add_child_line_item(
1850
-                EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1851
-            );
1852
-        }
1853
-        // if this is the grand total line item, make sure the totals all add up
1854
-        // (we could have duplicated this logic AS we copied the line items, but
1855
-        // it seems DRYer this way)
1856
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1857
-            $copy_li->recalculate_total_including_taxes();
1858
-        }
1859
-        return $copy_li;
1860
-    }
1861
-
1862
-
1863
-    /**
1864
-     * Creates a new, unsaved line item from $line_item that factors in the
1865
-     * number of billable registrations on $registrations.
1866
-     *
1867
-     * @param EE_Line_Item      $line_item
1868
-     * @param EE_Registration[] $registrations
1869
-     * @return EE_Line_Item
1870
-     * @throws EE_Error
1871
-     * @throws InvalidArgumentException
1872
-     * @throws InvalidDataTypeException
1873
-     * @throws InvalidInterfaceException
1874
-     * @throws ReflectionException
1875
-     */
1876
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1877
-    {
1878
-        $new_li_fields = $line_item->model_field_array();
1879
-        if (
1880
-            $line_item->type() === EEM_Line_Item::type_line_item &&
1881
-            $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1882
-        ) {
1883
-            $count = 0;
1884
-            foreach ($registrations as $registration) {
1885
-                if (
1886
-                    $line_item->OBJ_ID() === $registration->ticket_ID() &&
1887
-                    in_array(
1888
-                        $registration->status_ID(),
1889
-                        EEM_Registration::reg_statuses_that_allow_payment(),
1890
-                        true
1891
-                    )
1892
-                ) {
1893
-                    $count++;
1894
-                }
1895
-            }
1896
-            $new_li_fields['LIN_quantity'] = $count;
1897
-        }
1898
-        // don't set the total. We'll leave that up to the code that calculates it
1899
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1900
-        return EE_Line_Item::new_instance($new_li_fields);
1901
-    }
1902
-
1903
-
1904
-    /**
1905
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1906
-     * are removed, and line items with a quantity of 0
1907
-     *
1908
-     * @param EE_Line_Item $line_item |null
1909
-     * @return EE_Line_Item|null
1910
-     * @throws EE_Error
1911
-     * @throws InvalidArgumentException
1912
-     * @throws InvalidDataTypeException
1913
-     * @throws InvalidInterfaceException
1914
-     * @throws ReflectionException
1915
-     */
1916
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1917
-    {
1918
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1919
-        if ($copied_li === null) {
1920
-            return null;
1921
-        }
1922
-        // if this is an event subtotal, we want to only include it if it
1923
-        // has a non-zero total and at least one ticket line item child
1924
-        $ticket_children = 0;
1925
-        foreach ($line_item->children() as $child_li) {
1926
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1927
-            if ($child_li_copy !== null) {
1928
-                $copied_li->add_child_line_item($child_li_copy);
1929
-                if (
1930
-                    $child_li_copy->type() === EEM_Line_Item::type_line_item &&
1931
-                    $child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1932
-                ) {
1933
-                    $ticket_children++;
1934
-                }
1935
-            }
1936
-        }
1937
-        // if this is an event subtotal with NO ticket children
1938
-        // we basically want to ignore it
1939
-        if (
1940
-            $ticket_children === 0
1941
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1942
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1943
-            && $line_item->total() === 0
1944
-        ) {
1945
-            return null;
1946
-        }
1947
-        return $copied_li;
1948
-    }
1949
-
1950
-
1951
-    /**
1952
-     * Creates a new, unsaved line item, but if it's a ticket line item
1953
-     * with a total of 0, or a subtotal of 0, returns null instead
1954
-     *
1955
-     * @param EE_Line_Item $line_item
1956
-     * @return EE_Line_Item
1957
-     * @throws EE_Error
1958
-     * @throws InvalidArgumentException
1959
-     * @throws InvalidDataTypeException
1960
-     * @throws InvalidInterfaceException
1961
-     * @throws ReflectionException
1962
-     */
1963
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1964
-    {
1965
-        if (
1966
-            $line_item->type() === EEM_Line_Item::type_line_item
1967
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1968
-            && $line_item->quantity() === 0
1969
-        ) {
1970
-            return null;
1971
-        }
1972
-        $new_li_fields = $line_item->model_field_array();
1973
-        // don't set the total. We'll leave that up to the code that calculates it
1974
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1975
-        return EE_Line_Item::new_instance($new_li_fields);
1976
-    }
1977
-
1978
-
1979
-    /**
1980
-     * Cycles through all of the ticket line items for the supplied total line item
1981
-     * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1982
-     *
1983
-     * @param EE_Line_Item $total_line_item
1984
-     * @since 4.9.79.p
1985
-     * @throws EE_Error
1986
-     * @throws InvalidArgumentException
1987
-     * @throws InvalidDataTypeException
1988
-     * @throws InvalidInterfaceException
1989
-     * @throws ReflectionException
1990
-     */
1991
-    public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1992
-    {
1993
-        $ticket_line_items = self::get_ticket_line_items($total_line_item);
1994
-        foreach ($ticket_line_items as $ticket_line_item) {
1995
-            if (
1996
-                $ticket_line_item instanceof EE_Line_Item
1997
-                && $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1998
-            ) {
1999
-                $ticket = $ticket_line_item->ticket();
2000
-                if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
2001
-                    $ticket_line_item->set_is_taxable($ticket->taxable());
2002
-                    $ticket_line_item->save();
2003
-                }
2004
-            }
2005
-        }
2006
-    }
2007
-
2008
-
2009
-    /**
2010
-     * @return EE_Line_Item[]
2011
-     * @throws EE_Error
2012
-     * @throws ReflectionException
2013
-     * @since   5.0.0.p
2014
-     */
2015
-    private static function getGlobalTaxes(): array
2016
-    {
2017
-        if (EEH_Line_Item::$global_taxes === null) {
2018
-
2019
-            /** @type EEM_Price $EEM_Price */
2020
-            $EEM_Price = EE_Registry::instance()->load_model('Price');
2021
-            // get array of taxes via Price Model
2022
-            EEH_Line_Item::$global_taxes = $EEM_Price->get_all_prices_that_are_taxes();
2023
-            ksort(EEH_Line_Item::$global_taxes);
2024
-        }
2025
-        return EEH_Line_Item::$global_taxes;
2026
-    }
2027
-
2028
-
2029
-
2030
-    /**************************************** @DEPRECATED METHODS *************************************** */
2031
-    /**
2032
-     * @deprecated
2033
-     * @param EE_Line_Item $total_line_item
2034
-     * @return EE_Line_Item
2035
-     * @throws EE_Error
2036
-     * @throws InvalidArgumentException
2037
-     * @throws InvalidDataTypeException
2038
-     * @throws InvalidInterfaceException
2039
-     * @throws ReflectionException
2040
-     */
2041
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
2042
-    {
2043
-        EE_Error::doing_it_wrong(
2044
-            'EEH_Line_Item::get_items_subtotal()',
2045
-            sprintf(
2046
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2047
-                'EEH_Line_Item::get_pre_tax_subtotal()'
2048
-            ),
2049
-            '4.6.0'
2050
-        );
2051
-        return self::get_pre_tax_subtotal($total_line_item);
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * @deprecated
2057
-     * @param EE_Transaction $transaction
2058
-     * @return EE_Line_Item
2059
-     * @throws EE_Error
2060
-     * @throws InvalidArgumentException
2061
-     * @throws InvalidDataTypeException
2062
-     * @throws InvalidInterfaceException
2063
-     * @throws ReflectionException
2064
-     */
2065
-    public static function create_default_total_line_item($transaction = null)
2066
-    {
2067
-        EE_Error::doing_it_wrong(
2068
-            'EEH_Line_Item::create_default_total_line_item()',
2069
-            sprintf(
2070
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2071
-                'EEH_Line_Item::create_total_line_item()'
2072
-            ),
2073
-            '4.6.0'
2074
-        );
2075
-        return self::create_total_line_item($transaction);
2076
-    }
2077
-
2078
-
2079
-    /**
2080
-     * @deprecated
2081
-     * @param EE_Line_Item   $total_line_item
2082
-     * @param EE_Transaction $transaction
2083
-     * @return EE_Line_Item
2084
-     * @throws EE_Error
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidDataTypeException
2087
-     * @throws InvalidInterfaceException
2088
-     * @throws ReflectionException
2089
-     */
2090
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2091
-    {
2092
-        EE_Error::doing_it_wrong(
2093
-            'EEH_Line_Item::create_default_tickets_subtotal()',
2094
-            sprintf(
2095
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2096
-                'EEH_Line_Item::create_pre_tax_subtotal()'
2097
-            ),
2098
-            '4.6.0'
2099
-        );
2100
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
2101
-    }
2102
-
2103
-
2104
-    /**
2105
-     * @deprecated
2106
-     * @param EE_Line_Item   $total_line_item
2107
-     * @param EE_Transaction $transaction
2108
-     * @return EE_Line_Item
2109
-     * @throws EE_Error
2110
-     * @throws InvalidArgumentException
2111
-     * @throws InvalidDataTypeException
2112
-     * @throws InvalidInterfaceException
2113
-     * @throws ReflectionException
2114
-     */
2115
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2116
-    {
2117
-        EE_Error::doing_it_wrong(
2118
-            'EEH_Line_Item::create_default_taxes_subtotal()',
2119
-            sprintf(
2120
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2121
-                'EEH_Line_Item::create_taxes_subtotal()'
2122
-            ),
2123
-            '4.6.0'
2124
-        );
2125
-        return self::create_taxes_subtotal($total_line_item, $transaction);
2126
-    }
2127
-
2128
-
2129
-    /**
2130
-     * @deprecated
2131
-     * @param EE_Line_Item   $total_line_item
2132
-     * @param EE_Transaction $transaction
2133
-     * @return EE_Line_Item
2134
-     * @throws EE_Error
2135
-     * @throws InvalidArgumentException
2136
-     * @throws InvalidDataTypeException
2137
-     * @throws InvalidInterfaceException
2138
-     * @throws ReflectionException
2139
-     */
2140
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2141
-    {
2142
-        EE_Error::doing_it_wrong(
2143
-            'EEH_Line_Item::create_default_event_subtotal()',
2144
-            sprintf(
2145
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2146
-                'EEH_Line_Item::create_event_subtotal()'
2147
-            ),
2148
-            '4.6.0'
2149
-        );
2150
-        return self::create_event_subtotal($total_line_item, $transaction);
2151
-    }
24
+	/**
25
+	 * @var EE_Line_Item[]
26
+	 */
27
+	private static $global_taxes;
28
+
29
+
30
+	/**
31
+	 * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
32
+	 * Does NOT automatically re-calculate the line item totals or update the related transaction.
33
+	 * You should call recalculate_total_including_taxes() on the grant total line item after this
34
+	 * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
35
+	 * to keep the registration final prices in-sync with the transaction's total.
36
+	 *
37
+	 * @param EE_Line_Item $parent_line_item
38
+	 * @param string       $name
39
+	 * @param float        $unit_price
40
+	 * @param string       $description
41
+	 * @param int          $quantity
42
+	 * @param boolean      $taxable
43
+	 * @param string|null  $code if set to a value, ensures there is only one line item with that code
44
+	 * @param bool         $return_item
45
+	 * @param bool         $recalculate_totals
46
+	 * @return boolean|EE_Line_Item success
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public static function add_unrelated_item(
51
+		EE_Line_Item $parent_line_item,
52
+		string $name,
53
+		float $unit_price,
54
+		string $description = '',
55
+		int $quantity = 1,
56
+		bool $taxable = false,
57
+		?string $code = null,
58
+		bool $return_item = false,
59
+		bool $recalculate_totals = true
60
+	) {
61
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
62
+		$line_item      = EE_Line_Item::new_instance(
63
+			[
64
+				'LIN_name'       => $name,
65
+				'LIN_desc'       => $description,
66
+				'LIN_unit_price' => $unit_price,
67
+				'LIN_quantity'   => $quantity,
68
+				'LIN_percent'    => null,
69
+				'LIN_is_taxable' => $taxable,
70
+				'LIN_order'      => $items_subtotal instanceof EE_Line_Item
71
+					? count($items_subtotal->children())
72
+					: 0,
73
+				'LIN_total'      => (float) $unit_price * (int) $quantity,
74
+				'LIN_type'       => EEM_Line_Item::type_line_item,
75
+				'LIN_code'       => $code,
76
+			]
77
+		);
78
+		$line_item      = apply_filters(
79
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
80
+			$line_item,
81
+			$parent_line_item
82
+		);
83
+		$added          = self::add_item($parent_line_item, $line_item, $recalculate_totals);
84
+		return $return_item ? $line_item : $added;
85
+	}
86
+
87
+
88
+	/**
89
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
90
+	 * in the correct spot in the line item tree. Does not automatically
91
+	 * re-calculate the line item totals, nor update the related transaction, nor upgrade the transaction's
92
+	 * registrations' final prices (which should probably change because of this).
93
+	 * You should call recalculate_total_including_taxes() on the grand total line item, then
94
+	 * update the transaction's total, and EE_Registration_Processor::update_registration_final_prices()
95
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
96
+	 *
97
+	 * @param EE_Line_Item $parent_line_item
98
+	 * @param string       $name
99
+	 * @param float        $percentage_amount
100
+	 * @param string       $description
101
+	 * @param boolean      $taxable
102
+	 * @param string|null  $code
103
+	 * @param bool         $return_item
104
+	 * @return boolean|EE_Line_Item success
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public static function add_percentage_based_item(
109
+		EE_Line_Item $parent_line_item,
110
+		string $name,
111
+		float $percentage_amount,
112
+		string $description = '',
113
+		bool $taxable = false,
114
+		?string $code = null,
115
+		bool $return_item = false
116
+	) {
117
+		$total = $percentage_amount * $parent_line_item->total() / 100;
118
+		$line_item = EE_Line_Item::new_instance(
119
+			[
120
+				'LIN_name'       => $name,
121
+				'LIN_desc'       => $description,
122
+				'LIN_unit_price' => 0,
123
+				'LIN_percent'    => $percentage_amount,
124
+				'LIN_quantity'   => 1,
125
+				'LIN_is_taxable' => $taxable,
126
+				'LIN_total'      => (float) $total,
127
+				'LIN_type'       => EEM_Line_Item::type_line_item,
128
+				'LIN_parent'     => $parent_line_item->ID(),
129
+				'LIN_code'       => $code,
130
+			]
131
+		);
132
+		$line_item = apply_filters(
133
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
134
+			$line_item
135
+		);
136
+		$added     = $parent_line_item->add_child_line_item($line_item, false);
137
+		return $return_item ? $line_item : $added;
138
+	}
139
+
140
+
141
+	/**
142
+	 * Returns the new line item created by adding a purchase of the ticket
143
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
144
+	 * If this ticket has already been purchased, just increments its count.
145
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
146
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
147
+	 * should probably change because of this).
148
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
149
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
150
+	 *
151
+	 * @param EE_Line_Item|null $total_line_item grand total line item of type EEM_Line_Item::type_total
152
+	 * @param EE_Ticket         $ticket
153
+	 * @param int               $qty
154
+	 * @return EE_Line_Item
155
+	 * @throws EE_Error
156
+	 * @throws ReflectionException
157
+	 */
158
+	public static function add_ticket_purchase(
159
+		?EE_Line_Item $total_line_item,
160
+		EE_Ticket $ticket,
161
+		int $qty = 1
162
+	): ?EE_Line_Item {
163
+		if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
164
+			throw new EE_Error(
165
+				sprintf(
166
+					esc_html__(
167
+						'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
168
+						'event_espresso'
169
+					),
170
+					$ticket->ID(),
171
+					$total_line_item->ID()
172
+				)
173
+			);
174
+		}
175
+		// either increment the qty for an existing ticket
176
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
177
+		// or add a new one
178
+		if (! $line_item instanceof EE_Line_Item) {
179
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
180
+		}
181
+		$total_line_item->recalculate_total_including_taxes();
182
+		return $line_item;
183
+	}
184
+
185
+
186
+	/**
187
+	 * Returns the new line item created by adding a purchase of the ticket
188
+	 *
189
+	 * @param EE_Line_Item $total_line_item
190
+	 * @param EE_Ticket    $ticket
191
+	 * @param int          $qty
192
+	 * @return EE_Line_Item
193
+	 * @throws EE_Error
194
+	 * @throws InvalidArgumentException
195
+	 * @throws InvalidDataTypeException
196
+	 * @throws InvalidInterfaceException
197
+	 * @throws ReflectionException
198
+	 */
199
+	public static function increment_ticket_qty_if_already_in_cart(
200
+		EE_Line_Item $total_line_item,
201
+		EE_Ticket $ticket,
202
+		$qty = 1
203
+	) {
204
+		$line_item = null;
205
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
206
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
207
+			foreach ($ticket_line_items as $ticket_line_item) {
208
+				if (
209
+					$ticket_line_item instanceof EE_Line_Item
210
+					&& (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
211
+				) {
212
+					$line_item = $ticket_line_item;
213
+					break;
214
+				}
215
+			}
216
+		}
217
+		if ($line_item instanceof EE_Line_Item) {
218
+			EEH_Line_Item::increment_quantity($line_item, $qty);
219
+			return $line_item;
220
+		}
221
+		return null;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
227
+	 * Does NOT save or recalculate other line items totals
228
+	 *
229
+	 * @param EE_Line_Item $line_item
230
+	 * @param int          $qty
231
+	 * @return void
232
+	 * @throws EE_Error
233
+	 * @throws InvalidArgumentException
234
+	 * @throws InvalidDataTypeException
235
+	 * @throws InvalidInterfaceException
236
+	 * @throws ReflectionException
237
+	 */
238
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
239
+	{
240
+		if (! $line_item->is_percent()) {
241
+			$qty += $line_item->quantity();
242
+			$line_item->set_quantity($qty);
243
+			$line_item->set_total($line_item->unit_price() * $qty);
244
+			$line_item->save();
245
+		}
246
+		foreach ($line_item->children() as $child) {
247
+			if ($child->is_sub_line_item()) {
248
+				EEH_Line_Item::update_quantity($child, $qty);
249
+			}
250
+		}
251
+	}
252
+
253
+
254
+	/**
255
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
256
+	 * Does NOT save or recalculate other line items totals
257
+	 *
258
+	 * @param EE_Line_Item $line_item
259
+	 * @param int          $qty
260
+	 * @return void
261
+	 * @throws EE_Error
262
+	 * @throws InvalidArgumentException
263
+	 * @throws InvalidDataTypeException
264
+	 * @throws InvalidInterfaceException
265
+	 * @throws ReflectionException
266
+	 */
267
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
268
+	{
269
+		if (! $line_item->is_percent()) {
270
+			$qty = $line_item->quantity() - $qty;
271
+			$qty = max($qty, 0);
272
+			$line_item->set_quantity($qty);
273
+			$line_item->set_total($line_item->unit_price() * $qty);
274
+			$line_item->save();
275
+		}
276
+		foreach ($line_item->children() as $child) {
277
+			if ($child->is_sub_line_item()) {
278
+				EEH_Line_Item::update_quantity($child, $qty);
279
+			}
280
+		}
281
+	}
282
+
283
+
284
+	/**
285
+	 * Updates the line item and its children's quantities to the specified number.
286
+	 * Does NOT save them or recalculate totals.
287
+	 *
288
+	 * @param EE_Line_Item $line_item
289
+	 * @param int          $new_quantity
290
+	 * @throws EE_Error
291
+	 * @throws InvalidArgumentException
292
+	 * @throws InvalidDataTypeException
293
+	 * @throws InvalidInterfaceException
294
+	 * @throws ReflectionException
295
+	 */
296
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
297
+	{
298
+		if (! $line_item->is_percent()) {
299
+			$line_item->set_quantity($new_quantity);
300
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
301
+			$line_item->save();
302
+		}
303
+		foreach ($line_item->children() as $child) {
304
+			if ($child->is_sub_line_item()) {
305
+				EEH_Line_Item::update_quantity($child, $new_quantity);
306
+			}
307
+		}
308
+	}
309
+
310
+
311
+	/**
312
+	 * Returns the new line item created by adding a purchase of the ticket
313
+	 *
314
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
315
+	 * @param EE_Ticket    $ticket
316
+	 * @param int          $qty
317
+	 * @return EE_Line_Item
318
+	 * @throws EE_Error
319
+	 * @throws InvalidArgumentException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws InvalidInterfaceException
322
+	 * @throws ReflectionException
323
+	 */
324
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
325
+	{
326
+		$datetimes = $ticket->datetimes();
327
+		$first_datetime = reset($datetimes);
328
+		$first_datetime_name = esc_html__('Event', 'event_espresso');
329
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
330
+			$first_datetime_name = $first_datetime->event()->name();
331
+		}
332
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
333
+		// get event subtotal line
334
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
335
+		$taxes = $ticket->tax_price_modifiers();
336
+		// add $ticket to cart
337
+		$line_item = EE_Line_Item::new_instance(array(
338
+			'LIN_name'       => $ticket->name(),
339
+			'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
340
+			'LIN_unit_price' => $ticket->price(),
341
+			'LIN_quantity'   => $qty,
342
+			'LIN_is_taxable' => empty($taxes) && $ticket->taxable(),
343
+			'LIN_order'      => count($events_sub_total->children()),
344
+			'LIN_total'      => $ticket->price() * $qty,
345
+			'LIN_type'       => EEM_Line_Item::type_line_item,
346
+			'OBJ_ID'         => $ticket->ID(),
347
+			'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
348
+		));
349
+		$line_item = apply_filters(
350
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
351
+			$line_item
352
+		);
353
+		if (!$line_item instanceof EE_Line_Item) {
354
+			throw new DomainException(
355
+				esc_html__('Invalid EE_Line_Item received.', 'event_espresso')
356
+			);
357
+		}
358
+		$events_sub_total->add_child_line_item($line_item);
359
+		// now add the sub-line items
360
+		$running_total = 0;
361
+		$running_pre_tax_total = 0;
362
+		foreach ($ticket->prices() as $price) {
363
+			$sign = $price->is_discount() ? -1 : 1;
364
+			$price_total = $price->is_percent()
365
+				? $running_pre_tax_total * $price->amount() / 100
366
+				: $price->amount() * $qty;
367
+			if ($price->is_percent()) {
368
+				$percent = $sign * $price->amount();
369
+				$unit_price = 0;
370
+			} else {
371
+				$percent    = 0;
372
+				$unit_price = $sign * $price->amount();
373
+			}
374
+			$sub_line_item = EE_Line_Item::new_instance(array(
375
+				'LIN_name'       => $price->name(),
376
+				'LIN_desc'       => $price->desc(),
377
+				'LIN_quantity'   => $price->is_percent() ? null : $qty,
378
+				'LIN_is_taxable' => false,
379
+				'LIN_order'      => $price->order(),
380
+				'LIN_total'      => $price_total,
381
+				'LIN_pretax'     => 0,
382
+				'LIN_unit_price' => $unit_price,
383
+				'LIN_percent'    => $percent,
384
+				'LIN_type'       => $price->is_tax() ? EEM_Line_Item::type_sub_tax : EEM_Line_Item::type_sub_line_item,
385
+				'OBJ_ID'         => $price->ID(),
386
+				'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
387
+			));
388
+			$sub_line_item = apply_filters(
389
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
390
+				$sub_line_item
391
+			);
392
+			$running_total += $sign * $price_total;
393
+			$running_pre_tax_total += ! $price->is_tax() ? $sign * $price_total : 0;
394
+			$line_item->add_child_line_item($sub_line_item);
395
+		}
396
+		$line_item->setPretaxTotal($running_pre_tax_total);
397
+		return $line_item;
398
+	}
399
+
400
+
401
+	/**
402
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
403
+	 * re-calculates the line item totals and updates the related transaction. But
404
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
405
+	 * should probably change because of this).
406
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
407
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
408
+	 *
409
+	 * @param EE_Line_Item $total_line_item
410
+	 * @param EE_Line_Item $item to be added
411
+	 * @return boolean
412
+	 * @throws EE_Error
413
+	 * @throws InvalidArgumentException
414
+	 * @throws InvalidDataTypeException
415
+	 * @throws InvalidInterfaceException
416
+	 * @throws ReflectionException
417
+	 */
418
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item, $recalculate_totals = true)
419
+	{
420
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
421
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
422
+			$success = $pre_tax_subtotal->add_child_line_item($item);
423
+		} else {
424
+			return false;
425
+		}
426
+		if ($recalculate_totals) {
427
+			$total_line_item->recalculate_total_including_taxes();
428
+		}
429
+		return $success;
430
+	}
431
+
432
+
433
+	/**
434
+	 * cancels an existing ticket line item,
435
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
436
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
437
+	 *
438
+	 * @param EE_Line_Item $ticket_line_item
439
+	 * @param int          $qty
440
+	 * @return bool success
441
+	 * @throws EE_Error
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws InvalidInterfaceException
445
+	 * @throws ReflectionException
446
+	 */
447
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
448
+	{
449
+		// validate incoming line_item
450
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
451
+			throw new EE_Error(
452
+				sprintf(
453
+					esc_html__(
454
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
455
+						'event_espresso'
456
+					),
457
+					$ticket_line_item->type()
458
+				)
459
+			);
460
+		}
461
+		if ($ticket_line_item->quantity() < $qty) {
462
+			throw new EE_Error(
463
+				sprintf(
464
+					esc_html__(
465
+						'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
466
+						'event_espresso'
467
+					),
468
+					$qty,
469
+					$ticket_line_item->quantity()
470
+				)
471
+			);
472
+		}
473
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
474
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
475
+		foreach ($ticket_line_item->children() as $child_line_item) {
476
+			if (
477
+				$child_line_item->is_sub_line_item()
478
+				&& ! $child_line_item->is_percent()
479
+				&& ! $child_line_item->is_cancellation()
480
+			) {
481
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
482
+			}
483
+		}
484
+		// get cancellation sub line item
485
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
486
+			$ticket_line_item,
487
+			EEM_Line_Item::type_cancellation
488
+		);
489
+		$cancellation_line_item = reset($cancellation_line_item);
490
+		// verify that this ticket was indeed previously cancelled
491
+		if ($cancellation_line_item instanceof EE_Line_Item) {
492
+			// increment cancelled quantity
493
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
494
+		} else {
495
+			// create cancellation sub line item
496
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
497
+				'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
498
+				'LIN_desc'       => sprintf(
499
+					esc_html_x(
500
+						'Cancelled %1$s : %2$s',
501
+						'Cancelled Ticket Name : 2015-01-01 11:11',
502
+						'event_espresso'
503
+					),
504
+					$ticket_line_item->name(),
505
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
506
+				),
507
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
508
+				'LIN_quantity'   => $qty,
509
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
510
+				'LIN_order'      => count($ticket_line_item->children()),
511
+				'LIN_total'      => 0, // $ticket_line_item->unit_price()
512
+				'LIN_type'       => EEM_Line_Item::type_cancellation,
513
+			));
514
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
515
+		}
516
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
517
+			// decrement parent line item quantity
518
+			$event_line_item = $ticket_line_item->parent();
519
+			if (
520
+				$event_line_item instanceof EE_Line_Item
521
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
522
+			) {
523
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
524
+				$event_line_item->save();
525
+			}
526
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
527
+			return true;
528
+		}
529
+		return false;
530
+	}
531
+
532
+
533
+	/**
534
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
535
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
536
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
537
+	 *
538
+	 * @param EE_Line_Item $ticket_line_item
539
+	 * @param int          $qty
540
+	 * @return bool success
541
+	 * @throws EE_Error
542
+	 * @throws InvalidArgumentException
543
+	 * @throws InvalidDataTypeException
544
+	 * @throws InvalidInterfaceException
545
+	 * @throws ReflectionException
546
+	 */
547
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
548
+	{
549
+		// validate incoming line_item
550
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
551
+			throw new EE_Error(
552
+				sprintf(
553
+					esc_html__(
554
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
555
+						'event_espresso'
556
+					),
557
+					$ticket_line_item->type()
558
+				)
559
+			);
560
+		}
561
+		// get cancellation sub line item
562
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
563
+			$ticket_line_item,
564
+			EEM_Line_Item::type_cancellation
565
+		);
566
+		$cancellation_line_item = reset($cancellation_line_item);
567
+		// verify that this ticket was indeed previously cancelled
568
+		if (! $cancellation_line_item instanceof EE_Line_Item) {
569
+			return false;
570
+		}
571
+		if ($cancellation_line_item->quantity() > $qty) {
572
+			// decrement cancelled quantity
573
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
574
+		} elseif ($cancellation_line_item->quantity() === $qty) {
575
+			// decrement cancelled quantity in case anyone still has the object kicking around
576
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
577
+			// delete because quantity will end up as 0
578
+			$cancellation_line_item->delete();
579
+			// and attempt to destroy the object,
580
+			// even though PHP won't actually destroy it until it needs the memory
581
+			unset($cancellation_line_item);
582
+		} else {
583
+			// what ?!?! negative quantity ?!?!
584
+			throw new EE_Error(
585
+				sprintf(
586
+					esc_html__(
587
+						'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
588
+						'event_espresso'
589
+					),
590
+					$qty,
591
+					$cancellation_line_item->quantity()
592
+				)
593
+			);
594
+		}
595
+		// increment ticket quantity
596
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
597
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
598
+			// increment parent line item quantity
599
+			$event_line_item = $ticket_line_item->parent();
600
+			if (
601
+				$event_line_item instanceof EE_Line_Item
602
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
603
+			) {
604
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
605
+			}
606
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
607
+			return true;
608
+		}
609
+		return false;
610
+	}
611
+
612
+
613
+	/**
614
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
615
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
616
+	 *
617
+	 * @param EE_Line_Item $line_item
618
+	 * @return float
619
+	 * @throws EE_Error
620
+	 * @throws InvalidArgumentException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws InvalidInterfaceException
623
+	 * @throws ReflectionException
624
+	 */
625
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
626
+	{
627
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
628
+		return $grand_total_line_item->recalculate_total_including_taxes();
629
+	}
630
+
631
+
632
+	/**
633
+	 * Gets the line item which contains the subtotal of all the items
634
+	 *
635
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
636
+	 * @return EE_Line_Item
637
+	 * @throws EE_Error
638
+	 * @throws InvalidArgumentException
639
+	 * @throws InvalidDataTypeException
640
+	 * @throws InvalidInterfaceException
641
+	 * @throws ReflectionException
642
+	 */
643
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
644
+	{
645
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
646
+		return $pre_tax_subtotal instanceof EE_Line_Item
647
+			? $pre_tax_subtotal
648
+			: self::create_pre_tax_subtotal($total_line_item);
649
+	}
650
+
651
+
652
+	/**
653
+	 * Gets the line item for the taxes subtotal
654
+	 *
655
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
656
+	 * @return EE_Line_Item
657
+	 * @throws EE_Error
658
+	 * @throws InvalidArgumentException
659
+	 * @throws InvalidDataTypeException
660
+	 * @throws InvalidInterfaceException
661
+	 * @throws ReflectionException
662
+	 */
663
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
664
+	{
665
+		$taxes = $total_line_item->get_child_line_item('taxes');
666
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
667
+	}
668
+
669
+
670
+	/**
671
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
672
+	 *
673
+	 * @param EE_Line_Item   $line_item
674
+	 * @param EE_Transaction $transaction
675
+	 * @return void
676
+	 * @throws EE_Error
677
+	 * @throws InvalidArgumentException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws InvalidInterfaceException
680
+	 * @throws ReflectionException
681
+	 */
682
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
683
+	{
684
+		if ($transaction) {
685
+			/** @type EEM_Transaction $EEM_Transaction */
686
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
687
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
688
+			$line_item->set_TXN_ID($TXN_ID);
689
+		}
690
+	}
691
+
692
+
693
+	/**
694
+	 * Creates a new default total line item for the transaction,
695
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
696
+	 * existing taxes as children of the taxes subtotal line item)
697
+	 *
698
+	 * @param EE_Transaction $transaction
699
+	 * @return EE_Line_Item of type total
700
+	 * @throws EE_Error
701
+	 * @throws InvalidArgumentException
702
+	 * @throws InvalidDataTypeException
703
+	 * @throws InvalidInterfaceException
704
+	 * @throws ReflectionException
705
+	 */
706
+	public static function create_total_line_item($transaction = null)
707
+	{
708
+		$total_line_item = EE_Line_Item::new_instance(array(
709
+			'LIN_code' => 'total',
710
+			'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
711
+			'LIN_type' => EEM_Line_Item::type_total,
712
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
713
+		));
714
+		$total_line_item = apply_filters(
715
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
716
+			$total_line_item
717
+		);
718
+		self::set_TXN_ID($total_line_item, $transaction);
719
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
720
+		self::create_taxes_subtotal($total_line_item, $transaction);
721
+		return $total_line_item;
722
+	}
723
+
724
+
725
+	/**
726
+	 * Creates a default items subtotal line item
727
+	 *
728
+	 * @param EE_Line_Item   $total_line_item
729
+	 * @param EE_Transaction $transaction
730
+	 * @return EE_Line_Item
731
+	 * @throws EE_Error
732
+	 * @throws InvalidArgumentException
733
+	 * @throws InvalidDataTypeException
734
+	 * @throws InvalidInterfaceException
735
+	 * @throws ReflectionException
736
+	 */
737
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
738
+	{
739
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
740
+			'LIN_code' => 'pre-tax-subtotal',
741
+			'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
742
+			'LIN_type' => EEM_Line_Item::type_sub_total,
743
+		));
744
+		$pre_tax_line_item = apply_filters(
745
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
746
+			$pre_tax_line_item
747
+		);
748
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
749
+		$total_line_item->add_child_line_item($pre_tax_line_item);
750
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
751
+		return $pre_tax_line_item;
752
+	}
753
+
754
+
755
+	/**
756
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
757
+	 * and applies taxes to it
758
+	 *
759
+	 * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
760
+	 * @param EE_Transaction $transaction
761
+	 * @return EE_Line_Item
762
+	 * @throws EE_Error
763
+	 * @throws InvalidArgumentException
764
+	 * @throws InvalidDataTypeException
765
+	 * @throws InvalidInterfaceException
766
+	 * @throws ReflectionException
767
+	 */
768
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
769
+	{
770
+		$tax_line_item = EE_Line_Item::new_instance(array(
771
+			'LIN_code'  => 'taxes',
772
+			'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
773
+			'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
774
+			'LIN_order' => 1000,// this should always come last
775
+		));
776
+		$tax_line_item = apply_filters(
777
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
778
+			$tax_line_item
779
+		);
780
+		self::set_TXN_ID($tax_line_item, $transaction);
781
+		$total_line_item->add_child_line_item($tax_line_item);
782
+		// and lastly, add the actual taxes
783
+		self::apply_taxes($total_line_item);
784
+		return $tax_line_item;
785
+	}
786
+
787
+
788
+	/**
789
+	 * Creates a default items subtotal line item
790
+	 *
791
+	 * @param EE_Line_Item   $pre_tax_line_item
792
+	 * @param EE_Transaction $transaction
793
+	 * @param EE_Event       $event
794
+	 * @return EE_Line_Item
795
+	 * @throws EE_Error
796
+	 * @throws InvalidArgumentException
797
+	 * @throws InvalidDataTypeException
798
+	 * @throws InvalidInterfaceException
799
+	 * @throws ReflectionException
800
+	 */
801
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
802
+	{
803
+		$event_line_item = EE_Line_Item::new_instance(array(
804
+			'LIN_code' => self::get_event_code($event),
805
+			'LIN_name' => self::get_event_name($event),
806
+			'LIN_desc' => self::get_event_desc($event),
807
+			'LIN_type' => EEM_Line_Item::type_sub_total,
808
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
809
+			'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
810
+		));
811
+		$event_line_item = apply_filters(
812
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
813
+			$event_line_item
814
+		);
815
+		self::set_TXN_ID($event_line_item, $transaction);
816
+		$pre_tax_line_item->add_child_line_item($event_line_item);
817
+		return $event_line_item;
818
+	}
819
+
820
+
821
+	/**
822
+	 * Gets what the event ticket's code SHOULD be
823
+	 *
824
+	 * @param EE_Event $event
825
+	 * @return string
826
+	 * @throws EE_Error
827
+	 */
828
+	public static function get_event_code($event)
829
+	{
830
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets the event name
836
+	 *
837
+	 * @param EE_Event $event
838
+	 * @return string
839
+	 * @throws EE_Error
840
+	 */
841
+	public static function get_event_name($event)
842
+	{
843
+		return $event instanceof EE_Event
844
+			? mb_substr($event->name(), 0, 245)
845
+			: esc_html__('Event', 'event_espresso');
846
+	}
847
+
848
+
849
+	/**
850
+	 * Gets the event excerpt
851
+	 *
852
+	 * @param EE_Event $event
853
+	 * @return string
854
+	 * @throws EE_Error
855
+	 */
856
+	public static function get_event_desc($event)
857
+	{
858
+		return $event instanceof EE_Event ? $event->short_description() : '';
859
+	}
860
+
861
+
862
+	/**
863
+	 * Given the grand total line item and a ticket, finds the event sub-total
864
+	 * line item the ticket's purchase should be added onto
865
+	 *
866
+	 * @access public
867
+	 * @param EE_Line_Item $grand_total the grand total line item
868
+	 * @param EE_Ticket    $ticket
869
+	 * @return EE_Line_Item
870
+	 * @throws EE_Error
871
+	 * @throws InvalidArgumentException
872
+	 * @throws InvalidDataTypeException
873
+	 * @throws InvalidInterfaceException
874
+	 * @throws ReflectionException
875
+	 */
876
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
877
+	{
878
+		$first_datetime = $ticket->first_datetime();
879
+		if (! $first_datetime instanceof EE_Datetime) {
880
+			throw new EE_Error(
881
+				sprintf(
882
+					esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
883
+					$ticket->ID()
884
+				)
885
+			);
886
+		}
887
+		$event = $first_datetime->event();
888
+		if (! $event instanceof EE_Event) {
889
+			throw new EE_Error(
890
+				sprintf(
891
+					esc_html__(
892
+						'The supplied ticket (ID %d) has no event data associated with it.',
893
+						'event_espresso'
894
+					),
895
+					$ticket->ID()
896
+				)
897
+			);
898
+		}
899
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
900
+		if (! $events_sub_total instanceof EE_Line_Item) {
901
+			throw new EE_Error(
902
+				sprintf(
903
+					esc_html__(
904
+						'There is no events sub-total for ticket %s on total line item %d',
905
+						'event_espresso'
906
+					),
907
+					$ticket->ID(),
908
+					$grand_total->ID()
909
+				)
910
+			);
911
+		}
912
+		return $events_sub_total;
913
+	}
914
+
915
+
916
+	/**
917
+	 * Gets the event line item
918
+	 *
919
+	 * @param EE_Line_Item $grand_total
920
+	 * @param EE_Event     $event
921
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
922
+	 * @throws EE_Error
923
+	 * @throws InvalidArgumentException
924
+	 * @throws InvalidDataTypeException
925
+	 * @throws InvalidInterfaceException
926
+	 * @throws ReflectionException
927
+	 */
928
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
929
+	{
930
+		/** @type EE_Event $event */
931
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
932
+		$event_line_item = null;
933
+		$found = false;
934
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
935
+			// default event subtotal, we should only ever find this the first time this method is called
936
+			if (! $event_line_item->OBJ_ID()) {
937
+				// let's use this! but first... set the event details
938
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
939
+				$found = true;
940
+				break;
941
+			}
942
+			if ($event_line_item->OBJ_ID() === $event->ID()) {
943
+				// found existing line item for this event in the cart, so break out of loop and use this one
944
+				$found = true;
945
+				break;
946
+			}
947
+		}
948
+		if (! $found) {
949
+			// there is no event sub-total yet, so add it
950
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
951
+			// create a new "event" subtotal below that
952
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
953
+			// and set the event details
954
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
955
+		}
956
+		return $event_line_item;
957
+	}
958
+
959
+
960
+	/**
961
+	 * Creates a default items subtotal line item
962
+	 *
963
+	 * @param EE_Line_Item   $event_line_item
964
+	 * @param EE_Event       $event
965
+	 * @param EE_Transaction $transaction
966
+	 * @return void
967
+	 * @throws EE_Error
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidDataTypeException
970
+	 * @throws InvalidInterfaceException
971
+	 * @throws ReflectionException
972
+	 */
973
+	public static function set_event_subtotal_details(
974
+		EE_Line_Item $event_line_item,
975
+		EE_Event $event,
976
+		$transaction = null
977
+	) {
978
+		if ($event instanceof EE_Event) {
979
+			$event_line_item->set_code(self::get_event_code($event));
980
+			$event_line_item->set_name(self::get_event_name($event));
981
+			$event_line_item->set_desc(self::get_event_desc($event));
982
+			$event_line_item->set_OBJ_ID($event->ID());
983
+		}
984
+		self::set_TXN_ID($event_line_item, $transaction);
985
+	}
986
+
987
+
988
+	/**
989
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
990
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
991
+	 * any old taxes are removed
992
+	 *
993
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
994
+	 * @param bool         $update_txn_status
995
+	 * @return bool
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws InvalidDataTypeException
999
+	 * @throws InvalidInterfaceException
1000
+	 * @throws ReflectionException
1001
+	 * @throws RuntimeException
1002
+	 */
1003
+	public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
1004
+	{
1005
+		$total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($total_line_item);
1006
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
1007
+		$existing_global_taxes = $taxes_line_item->tax_descendants();
1008
+		$updates = false;
1009
+		// loop thru taxes
1010
+		$global_taxes = EEH_Line_Item::getGlobalTaxes();
1011
+		foreach ($global_taxes as $order => $taxes) {
1012
+			foreach ($taxes as $tax) {
1013
+				if ($tax instanceof EE_Price) {
1014
+					$found = false;
1015
+					// check if this is already an existing tax
1016
+					foreach ($existing_global_taxes as $existing_global_tax) {
1017
+						if ($tax->ID() === $existing_global_tax->OBJ_ID()) {
1018
+							// maybe update the tax rate in case it has changed
1019
+							if ($existing_global_tax->percent() !== $tax->amount()) {
1020
+								$existing_global_tax->set_percent($tax->amount());
1021
+								$existing_global_tax->save();
1022
+								$updates = true;
1023
+							}
1024
+							$found = true;
1025
+							break;
1026
+						}
1027
+					}
1028
+					if (! $found) {
1029
+						// add a new line item for this global tax
1030
+						$tax_line_item = apply_filters(
1031
+							'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
1032
+							EE_Line_Item::new_instance(
1033
+								[
1034
+									'LIN_name'       => $tax->name(),
1035
+									'LIN_desc'       => $tax->desc(),
1036
+									'LIN_percent'    => $tax->amount(),
1037
+									'LIN_is_taxable' => false,
1038
+									'LIN_order'      => $order,
1039
+									'LIN_total'      => 0,
1040
+									'LIN_type'       => EEM_Line_Item::type_tax,
1041
+									'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
1042
+									'OBJ_ID'         => $tax->ID(),
1043
+								]
1044
+							)
1045
+						);
1046
+						$updates = $taxes_line_item->add_child_line_item($tax_line_item) ? true : $updates;
1047
+					}
1048
+				}
1049
+			}
1050
+		}
1051
+		// only recalculate totals if something changed
1052
+		if ($updates) {
1053
+			$total_line_item->recalculate_total_including_taxes($update_txn_status);
1054
+			return true;
1055
+		}
1056
+		return false;
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * Ensures that taxes have been applied to the order, if not applies them.
1062
+	 * Returns the total amount of tax
1063
+	 *
1064
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1065
+	 * @return float
1066
+	 * @throws EE_Error
1067
+	 * @throws InvalidArgumentException
1068
+	 * @throws InvalidDataTypeException
1069
+	 * @throws InvalidInterfaceException
1070
+	 * @throws ReflectionException
1071
+	 */
1072
+	public static function ensure_taxes_applied($total_line_item)
1073
+	{
1074
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1075
+		if (! $taxes_subtotal->children()) {
1076
+			self::apply_taxes($total_line_item);
1077
+		}
1078
+		return $taxes_subtotal->total();
1079
+	}
1080
+
1081
+
1082
+	/**
1083
+	 * Deletes ALL children of the passed line item
1084
+	 *
1085
+	 * @param EE_Line_Item $parent_line_item
1086
+	 * @return bool
1087
+	 * @throws EE_Error
1088
+	 * @throws InvalidArgumentException
1089
+	 * @throws InvalidDataTypeException
1090
+	 * @throws InvalidInterfaceException
1091
+	 * @throws ReflectionException
1092
+	 */
1093
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1094
+	{
1095
+		$deleted = 0;
1096
+		foreach ($parent_line_item->children() as $child_line_item) {
1097
+			if ($child_line_item instanceof EE_Line_Item) {
1098
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1099
+				if ($child_line_item->ID()) {
1100
+					$child_line_item->delete();
1101
+					unset($child_line_item);
1102
+				} else {
1103
+					$parent_line_item->delete_child_line_item($child_line_item->code());
1104
+				}
1105
+				$deleted++;
1106
+			}
1107
+		}
1108
+		return $deleted;
1109
+	}
1110
+
1111
+
1112
+	/**
1113
+	 * Deletes the line items as indicated by the line item code(s) provided,
1114
+	 * regardless of where they're found in the line item tree. Automatically
1115
+	 * re-calculates the line item totals and updates the related transaction. But
1116
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1117
+	 * should probably change because of this).
1118
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1119
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
1120
+	 *
1121
+	 * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1122
+	 * @param array|bool|string $line_item_codes
1123
+	 * @return int number of items successfully removed
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1127
+	{
1128
+
1129
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1130
+			EE_Error::doing_it_wrong(
1131
+				'EEH_Line_Item::delete_items',
1132
+				esc_html__(
1133
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1134
+					'event_espresso'
1135
+				),
1136
+				'4.6.18'
1137
+			);
1138
+		}
1139
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1140
+
1141
+		// check if only a single line_item_id was passed
1142
+		if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1143
+			// place single line_item_id in an array to appear as multiple line_item_ids
1144
+			$line_item_codes = array($line_item_codes);
1145
+		}
1146
+		$removals = 0;
1147
+		// cycle thru line_item_ids
1148
+		foreach ($line_item_codes as $line_item_id) {
1149
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
1150
+		}
1151
+
1152
+		if ($removals > 0) {
1153
+			$total_line_item->recalculate_taxes_and_tax_total();
1154
+			return $removals;
1155
+		} else {
1156
+			return false;
1157
+		}
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
1163
+	 * tax and updates the total line item accordingly
1164
+	 *
1165
+	 * @param EE_Line_Item $total_line_item
1166
+	 * @param float        $amount
1167
+	 * @param string       $name
1168
+	 * @param string       $description
1169
+	 * @param string       $code
1170
+	 * @param boolean      $add_to_existing_line_item
1171
+	 *                          if true, and a duplicate line item with the same code is found,
1172
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1173
+	 * @return EE_Line_Item the new tax line item created
1174
+	 * @throws EE_Error
1175
+	 * @throws InvalidArgumentException
1176
+	 * @throws InvalidDataTypeException
1177
+	 * @throws InvalidInterfaceException
1178
+	 * @throws ReflectionException
1179
+	 */
1180
+	public static function set_total_tax_to(
1181
+		EE_Line_Item $total_line_item,
1182
+		$amount,
1183
+		$name = null,
1184
+		$description = null,
1185
+		$code = null,
1186
+		$add_to_existing_line_item = false
1187
+	) {
1188
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
1189
+		$taxable_total = $total_line_item->taxable_total();
1190
+
1191
+		if ($add_to_existing_line_item) {
1192
+			$new_tax = $tax_subtotal->get_child_line_item($code);
1193
+			EEM_Line_Item::instance()->delete(
1194
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1195
+			);
1196
+		} else {
1197
+			$new_tax = null;
1198
+			$tax_subtotal->delete_children_line_items();
1199
+		}
1200
+		if ($new_tax) {
1201
+			$new_tax->set_total($new_tax->total() + $amount);
1202
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1203
+		} else {
1204
+			// no existing tax item. Create it
1205
+			$new_tax = EE_Line_Item::new_instance(array(
1206
+				'TXN_ID'      => $total_line_item->TXN_ID(),
1207
+				'LIN_name'    => $name ?: esc_html__('Tax', 'event_espresso'),
1208
+				'LIN_desc'    => $description ?: '',
1209
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1210
+				'LIN_total'   => $amount,
1211
+				'LIN_parent'  => $tax_subtotal->ID(),
1212
+				'LIN_type'    => EEM_Line_Item::type_tax,
1213
+				'LIN_code'    => $code,
1214
+			));
1215
+		}
1216
+
1217
+		$new_tax = apply_filters(
1218
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1219
+			$new_tax,
1220
+			$total_line_item
1221
+		);
1222
+		$new_tax->save();
1223
+		$tax_subtotal->set_total($new_tax->total());
1224
+		$tax_subtotal->save();
1225
+		$total_line_item->recalculate_total_including_taxes();
1226
+		return $new_tax;
1227
+	}
1228
+
1229
+
1230
+	/**
1231
+	 * Makes all the line items which are children of $line_item taxable (or not).
1232
+	 * Does NOT save the line items
1233
+	 *
1234
+	 * @param EE_Line_Item $line_item
1235
+	 * @param boolean      $taxable
1236
+	 * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1237
+	 *                                                   it will be whitelisted (ie, except from becoming taxable)
1238
+	 * @throws EE_Error
1239
+	 */
1240
+	public static function set_line_items_taxable(
1241
+		EE_Line_Item $line_item,
1242
+		$taxable = true,
1243
+		$code_substring_for_whitelist = null
1244
+	) {
1245
+		$whitelisted = false;
1246
+		if ($code_substring_for_whitelist !== null) {
1247
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1248
+		}
1249
+		if (! $whitelisted && $line_item->is_line_item()) {
1250
+			$line_item->set_is_taxable($taxable);
1251
+		}
1252
+		foreach ($line_item->children() as $child_line_item) {
1253
+			EEH_Line_Item::set_line_items_taxable(
1254
+				$child_line_item,
1255
+				$taxable,
1256
+				$code_substring_for_whitelist
1257
+			);
1258
+		}
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Gets all descendants that are event subtotals
1264
+	 *
1265
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1266
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1267
+	 * @return EE_Line_Item[]
1268
+	 * @throws EE_Error
1269
+	 */
1270
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1271
+	{
1272
+		return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1273
+	}
1274
+
1275
+
1276
+	/**
1277
+	 * Gets all descendants subtotals that match the supplied object type
1278
+	 *
1279
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1280
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1281
+	 * @param string       $obj_type
1282
+	 * @return EE_Line_Item[]
1283
+	 * @throws EE_Error
1284
+	 */
1285
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1286
+	{
1287
+		return self::_get_descendants_by_type_and_object_type(
1288
+			$parent_line_item,
1289
+			EEM_Line_Item::type_sub_total,
1290
+			$obj_type
1291
+		);
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Gets all descendants that are tickets
1297
+	 *
1298
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1299
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1300
+	 * @return EE_Line_Item[]
1301
+	 * @throws EE_Error
1302
+	 */
1303
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1304
+	{
1305
+		return self::get_line_items_of_object_type(
1306
+			$parent_line_item,
1307
+			EEM_Line_Item::OBJ_TYPE_TICKET
1308
+		);
1309
+	}
1310
+
1311
+
1312
+	/**
1313
+	 * Gets all descendants subtotals that match the supplied object type
1314
+	 *
1315
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1316
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1317
+	 * @param string       $obj_type
1318
+	 * @return EE_Line_Item[]
1319
+	 * @throws EE_Error
1320
+	 */
1321
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1322
+	{
1323
+		return self::_get_descendants_by_type_and_object_type(
1324
+			$parent_line_item,
1325
+			EEM_Line_Item::type_line_item,
1326
+			$obj_type
1327
+		);
1328
+	}
1329
+
1330
+
1331
+	/**
1332
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1333
+	 *
1334
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1335
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1336
+	 * @return EE_Line_Item[]
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1340
+	{
1341
+		return EEH_Line_Item::get_descendants_of_type(
1342
+			$parent_line_item,
1343
+			EEM_Line_Item::type_tax
1344
+		);
1345
+	}
1346
+
1347
+
1348
+	/**
1349
+	 * Gets all the real items purchased which are children of this item
1350
+	 *
1351
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1352
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1353
+	 * @return EE_Line_Item[]
1354
+	 * @throws EE_Error
1355
+	 */
1356
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1357
+	{
1358
+		return EEH_Line_Item::get_descendants_of_type(
1359
+			$parent_line_item,
1360
+			EEM_Line_Item::type_line_item
1361
+		);
1362
+	}
1363
+
1364
+
1365
+	/**
1366
+	 * Gets all descendants of supplied line item that match the supplied line item type
1367
+	 *
1368
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1369
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1370
+	 * @param string       $line_item_type   one of the EEM_Line_Item constants
1371
+	 * @return EE_Line_Item[]
1372
+	 * @throws EE_Error
1373
+	 */
1374
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1375
+	{
1376
+		return self::_get_descendants_by_type_and_object_type(
1377
+			$parent_line_item,
1378
+			$line_item_type,
1379
+			null
1380
+		);
1381
+	}
1382
+
1383
+
1384
+	/**
1385
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1386
+	 * as well
1387
+	 *
1388
+	 * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1389
+	 * @param string        $line_item_type   one of the EEM_Line_Item constants
1390
+	 * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1391
+	 *                                        searching
1392
+	 * @return EE_Line_Item[]
1393
+	 * @throws EE_Error
1394
+	 */
1395
+	protected static function _get_descendants_by_type_and_object_type(
1396
+		EE_Line_Item $parent_line_item,
1397
+		$line_item_type,
1398
+		$obj_type = null
1399
+	) {
1400
+		$objects = array();
1401
+		foreach ($parent_line_item->children() as $child_line_item) {
1402
+			if ($child_line_item instanceof EE_Line_Item) {
1403
+				if (
1404
+					$child_line_item->type() === $line_item_type
1405
+					&& (
1406
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1407
+					)
1408
+				) {
1409
+					$objects[] = $child_line_item;
1410
+				} else {
1411
+					// go-through-all-its children looking for more matches
1412
+					$objects = array_merge(
1413
+						$objects,
1414
+						self::_get_descendants_by_type_and_object_type(
1415
+							$child_line_item,
1416
+							$line_item_type,
1417
+							$obj_type
1418
+						)
1419
+					);
1420
+				}
1421
+			}
1422
+		}
1423
+		return $objects;
1424
+	}
1425
+
1426
+
1427
+	/**
1428
+	 * Gets all descendants subtotals that match the supplied object type
1429
+	 *
1430
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1431
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1432
+	 * @param string       $OBJ_type         object type (like Event)
1433
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1434
+	 * @return EE_Line_Item[]
1435
+	 * @throws EE_Error
1436
+	 */
1437
+	public static function get_line_items_by_object_type_and_IDs(
1438
+		EE_Line_Item $parent_line_item,
1439
+		$OBJ_type = '',
1440
+		$OBJ_IDs = array()
1441
+	) {
1442
+		return self::_get_descendants_by_object_type_and_object_ID(
1443
+			$parent_line_item,
1444
+			$OBJ_type,
1445
+			$OBJ_IDs
1446
+		);
1447
+	}
1448
+
1449
+
1450
+	/**
1451
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1452
+	 * as well
1453
+	 *
1454
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1455
+	 * @param string       $OBJ_type         object type (like Event)
1456
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1457
+	 * @return EE_Line_Item[]
1458
+	 * @throws EE_Error
1459
+	 */
1460
+	protected static function _get_descendants_by_object_type_and_object_ID(
1461
+		EE_Line_Item $parent_line_item,
1462
+		$OBJ_type,
1463
+		$OBJ_IDs
1464
+	) {
1465
+		$objects = array();
1466
+		foreach ($parent_line_item->children() as $child_line_item) {
1467
+			if ($child_line_item instanceof EE_Line_Item) {
1468
+				if (
1469
+					$child_line_item->OBJ_type() === $OBJ_type
1470
+					&& is_array($OBJ_IDs)
1471
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1472
+				) {
1473
+					$objects[] = $child_line_item;
1474
+				} else {
1475
+					// go-through-all-its children looking for more matches
1476
+					$objects = array_merge(
1477
+						$objects,
1478
+						self::_get_descendants_by_object_type_and_object_ID(
1479
+							$child_line_item,
1480
+							$OBJ_type,
1481
+							$OBJ_IDs
1482
+						)
1483
+					);
1484
+				}
1485
+			}
1486
+		}
1487
+		return $objects;
1488
+	}
1489
+
1490
+
1491
+	/**
1492
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1493
+	 * the specified type and returns it, else NULL
1494
+	 *
1495
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1496
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1497
+	 * @param string       $type             like one of the EEM_Line_Item::type_*
1498
+	 * @return EE_Line_Item
1499
+	 * @throws EE_Error
1500
+	 * @throws InvalidArgumentException
1501
+	 * @throws InvalidDataTypeException
1502
+	 * @throws InvalidInterfaceException
1503
+	 * @throws ReflectionException
1504
+	 */
1505
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1506
+	{
1507
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1508
+	}
1509
+
1510
+
1511
+	/**
1512
+	 * Uses a breadth-first-search in order to find the nearest descendant
1513
+	 * having the specified LIN_code and returns it, else NULL
1514
+	 *
1515
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1516
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1517
+	 * @param string       $code             any value used for LIN_code
1518
+	 * @return EE_Line_Item
1519
+	 * @throws EE_Error
1520
+	 * @throws InvalidArgumentException
1521
+	 * @throws InvalidDataTypeException
1522
+	 * @throws InvalidInterfaceException
1523
+	 * @throws ReflectionException
1524
+	 */
1525
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1526
+	{
1527
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1528
+	}
1529
+
1530
+
1531
+	/**
1532
+	 * Uses a breadth-first-search in order to find the nearest descendant
1533
+	 * having the specified LIN_code and returns it, else NULL
1534
+	 *
1535
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1536
+	 * @param string       $search_field     name of EE_Line_Item property
1537
+	 * @param string       $value            any value stored in $search_field
1538
+	 * @return EE_Line_Item
1539
+	 * @throws EE_Error
1540
+	 * @throws InvalidArgumentException
1541
+	 * @throws InvalidDataTypeException
1542
+	 * @throws InvalidInterfaceException
1543
+	 * @throws ReflectionException
1544
+	 */
1545
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1546
+	{
1547
+		foreach ($parent_line_item->children() as $child) {
1548
+			if ($child->get($search_field) == $value) {
1549
+				return $child;
1550
+			}
1551
+		}
1552
+		foreach ($parent_line_item->children() as $child) {
1553
+			$descendant_found = self::_get_nearest_descendant(
1554
+				$child,
1555
+				$search_field,
1556
+				$value
1557
+			);
1558
+			if ($descendant_found) {
1559
+				return $descendant_found;
1560
+			}
1561
+		}
1562
+		return null;
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1568
+	 * else recursively walks up the line item tree until a parent of type total is found,
1569
+	 *
1570
+	 * @param EE_Line_Item $line_item
1571
+	 * @return EE_Line_Item
1572
+	 * @throws EE_Error
1573
+	 * @throws ReflectionException
1574
+	 */
1575
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item): EE_Line_Item
1576
+	{
1577
+		if ($line_item->is_total()) {
1578
+			return $line_item;
1579
+		}
1580
+		if ($line_item->TXN_ID()) {
1581
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1582
+			if ($total_line_item instanceof EE_Line_Item) {
1583
+				return $total_line_item;
1584
+			}
1585
+		} else {
1586
+			$line_item_parent = $line_item->parent();
1587
+			if ($line_item_parent instanceof EE_Line_Item) {
1588
+				if ($line_item_parent->is_total()) {
1589
+					return $line_item_parent;
1590
+				}
1591
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1592
+			}
1593
+		}
1594
+		throw new EE_Error(
1595
+			sprintf(
1596
+				esc_html__(
1597
+					'A valid grand total for line item %1$d was not found.',
1598
+					'event_espresso'
1599
+				),
1600
+				$line_item->ID()
1601
+			)
1602
+		);
1603
+	}
1604
+
1605
+
1606
+	/**
1607
+	 * Prints out a representation of the line item tree
1608
+	 *
1609
+	 * @param EE_Line_Item $line_item
1610
+	 * @param int          $indentation
1611
+	 * @return void
1612
+	 * @throws EE_Error
1613
+	 */
1614
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1615
+	{
1616
+		$new_line = defined('EE_TESTS_DIR') ? "\n" : '<br />';
1617
+		echo $new_line;
1618
+		if (! $indentation) {
1619
+			echo $new_line;
1620
+		}
1621
+		echo str_repeat('. ', $indentation);
1622
+		$breakdown = '';
1623
+		if ($line_item->is_line_item() || $line_item->is_sub_line_item() || $line_item->isSubTax()) {
1624
+			if ($line_item->is_percent()) {
1625
+				$breakdown = "{$line_item->percent()}%";
1626
+			} else {
1627
+				$breakdown = "\${$line_item->unit_price()} x {$line_item->quantity()}";
1628
+			}
1629
+		}
1630
+		echo wp_kses($line_item->name(), AllowedTags::getAllowedTags());
1631
+		echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1632
+		echo "\${$line_item->total()}";
1633
+		if ($breakdown) {
1634
+			echo " ( {$breakdown} )";
1635
+		}
1636
+		if ($line_item->is_taxable()) {
1637
+			echo '  * taxable';
1638
+		}
1639
+		if ($line_item->children()) {
1640
+			foreach ($line_item->children() as $child) {
1641
+				self::visualize($child, $indentation + 1);
1642
+			}
1643
+		}
1644
+		if (! $indentation) {
1645
+			echo $new_line . $new_line;
1646
+		}
1647
+	}
1648
+
1649
+
1650
+	/**
1651
+	 * Calculates the registration's final price, taking into account that they
1652
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1653
+	 * and receive a portion of any transaction-wide discounts.
1654
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1655
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1656
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1657
+	 * and brent's final price should be $5.50.
1658
+	 * In order to do this, we basically need to traverse the line item tree calculating
1659
+	 * the running totals (just as if we were recalculating the total), but when we identify
1660
+	 * regular line items, we need to keep track of their share of the grand total.
1661
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1662
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1663
+	 * when there are non-taxable items; otherwise they would be the same)
1664
+	 *
1665
+	 * @param EE_Line_Item $line_item
1666
+	 * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1667
+	 *                                                  can be included in price calculations at this moment
1668
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1669
+	 *                                                  plus the key 'total', and 'taxable' which also has keys of all
1670
+	 *                                                  the ticket IDs.
1671
+	 *                                                  Eg array(
1672
+	 *                                                      12 => 4.3
1673
+	 *                                                      23 => 8.0
1674
+	 *                                                      'total' => 16.6,
1675
+	 *                                                      'taxable' => array(
1676
+	 *                                                          12 => 10,
1677
+	 *                                                          23 => 4
1678
+	 *                                                      ).
1679
+	 *                                                  So to find which registrations have which final price, we need
1680
+	 *                                                  to find which line item is theirs, which can be done with
1681
+	 *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1682
+	 *                                                  $registration );`
1683
+	 * @throws EE_Error
1684
+	 * @throws InvalidArgumentException
1685
+	 * @throws InvalidDataTypeException
1686
+	 * @throws InvalidInterfaceException
1687
+	 * @throws ReflectionException
1688
+	 */
1689
+	public static function calculate_reg_final_prices_per_line_item(
1690
+		EE_Line_Item $line_item,
1691
+		$billable_ticket_quantities = array()
1692
+	) {
1693
+		$running_totals = [
1694
+			'total'   => 0,
1695
+			'taxable' => ['total' => 0]
1696
+		];
1697
+		foreach ($line_item->children() as $child_line_item) {
1698
+			switch ($child_line_item->type()) {
1699
+				case EEM_Line_Item::type_sub_total:
1700
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1701
+						$child_line_item,
1702
+						$billable_ticket_quantities
1703
+					);
1704
+					// combine arrays but preserve numeric keys
1705
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1706
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1707
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1708
+					break;
1709
+
1710
+				case EEM_Line_Item::type_tax_sub_total:
1711
+					// find how much the taxes percentage is
1712
+					if ($child_line_item->percent() !== 0) {
1713
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1714
+					} else {
1715
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1716
+					}
1717
+					// and apply to all the taxable totals, and add to the pretax totals
1718
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1719
+						// "total" and "taxable" array key is an exception
1720
+						if ($line_item_id === 'taxable') {
1721
+							continue;
1722
+						}
1723
+						$taxable_total = $running_totals['taxable'][ $line_item_id ];
1724
+						$running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1725
+					}
1726
+					break;
1727
+
1728
+				case EEM_Line_Item::type_line_item:
1729
+					// ticket line items or ????
1730
+					if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1731
+						// kk it's a ticket
1732
+						if (isset($running_totals[ $child_line_item->ID() ])) {
1733
+							// huh? that shouldn't happen.
1734
+							$running_totals['total'] += $child_line_item->total();
1735
+						} else {
1736
+							// its not in our running totals yet. great.
1737
+							if ($child_line_item->is_taxable()) {
1738
+								$taxable_amount = $child_line_item->unit_price();
1739
+							} else {
1740
+								$taxable_amount = 0;
1741
+							}
1742
+							// are we only calculating totals for some tickets?
1743
+							if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1744
+								$quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1745
+								$running_totals[ $child_line_item->ID() ] = $quantity
1746
+									? $child_line_item->unit_price()
1747
+									: 0;
1748
+								$running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1749
+									? $taxable_amount
1750
+									: 0;
1751
+							} else {
1752
+								$quantity = $child_line_item->quantity();
1753
+								$running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1754
+								$running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1755
+							}
1756
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1757
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1758
+						}
1759
+					} else {
1760
+						// it's some other type of item added to the cart
1761
+						// it should affect the running totals
1762
+						// basically we want to convert it into a PERCENT modifier. Because
1763
+						// more clearly affect all registration's final price equally
1764
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1765
+							? ($child_line_item->total() / $running_totals['total']) + 1
1766
+							: 1;
1767
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1768
+							// the "taxable" array key is an exception
1769
+							if ($line_item_id === 'taxable') {
1770
+								continue;
1771
+							}
1772
+							// update the running totals
1773
+							// yes this actually even works for the running grand total!
1774
+							$running_totals[ $line_item_id ] =
1775
+								$line_items_percent_of_running_total * $this_running_total;
1776
+
1777
+							if ($child_line_item->is_taxable()) {
1778
+								$running_totals['taxable'][ $line_item_id ] =
1779
+									$line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1780
+							}
1781
+						}
1782
+					}
1783
+					break;
1784
+			}
1785
+		}
1786
+		return $running_totals;
1787
+	}
1788
+
1789
+
1790
+	/**
1791
+	 * @param EE_Line_Item $total_line_item
1792
+	 * @param EE_Line_Item $ticket_line_item
1793
+	 * @return float | null
1794
+	 * @throws EE_Error
1795
+	 * @throws InvalidArgumentException
1796
+	 * @throws InvalidDataTypeException
1797
+	 * @throws InvalidInterfaceException
1798
+	 * @throws OutOfRangeException
1799
+	 * @throws ReflectionException
1800
+	 */
1801
+	public static function calculate_final_price_for_ticket_line_item(
1802
+		EE_Line_Item $total_line_item,
1803
+		EE_Line_Item $ticket_line_item
1804
+	) {
1805
+		static $final_prices_per_ticket_line_item = array();
1806
+		if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1807
+			$final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1808
+				$total_line_item
1809
+			);
1810
+		}
1811
+		// ok now find this new registration's final price
1812
+		if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1813
+			return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1814
+		}
1815
+		$message = sprintf(
1816
+			esc_html__(
1817
+				'The final price for the ticket line item (ID:%1$d) on the total line item (ID:%2$d) could not be calculated.',
1818
+				'event_espresso'
1819
+			),
1820
+			$ticket_line_item->ID(),
1821
+			$total_line_item->ID()
1822
+		);
1823
+		if (WP_DEBUG) {
1824
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1825
+			throw new OutOfRangeException($message);
1826
+		}
1827
+		EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1828
+		return null;
1829
+	}
1830
+
1831
+
1832
+	/**
1833
+	 * Creates a duplicate of the line item tree, except only includes billable items
1834
+	 * and the portion of line items attributed to billable things
1835
+	 *
1836
+	 * @param EE_Line_Item      $line_item
1837
+	 * @param EE_Registration[] $registrations
1838
+	 * @return EE_Line_Item
1839
+	 * @throws EE_Error
1840
+	 * @throws InvalidArgumentException
1841
+	 * @throws InvalidDataTypeException
1842
+	 * @throws InvalidInterfaceException
1843
+	 * @throws ReflectionException
1844
+	 */
1845
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1846
+	{
1847
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1848
+		foreach ($line_item->children() as $child_li) {
1849
+			$copy_li->add_child_line_item(
1850
+				EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1851
+			);
1852
+		}
1853
+		// if this is the grand total line item, make sure the totals all add up
1854
+		// (we could have duplicated this logic AS we copied the line items, but
1855
+		// it seems DRYer this way)
1856
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1857
+			$copy_li->recalculate_total_including_taxes();
1858
+		}
1859
+		return $copy_li;
1860
+	}
1861
+
1862
+
1863
+	/**
1864
+	 * Creates a new, unsaved line item from $line_item that factors in the
1865
+	 * number of billable registrations on $registrations.
1866
+	 *
1867
+	 * @param EE_Line_Item      $line_item
1868
+	 * @param EE_Registration[] $registrations
1869
+	 * @return EE_Line_Item
1870
+	 * @throws EE_Error
1871
+	 * @throws InvalidArgumentException
1872
+	 * @throws InvalidDataTypeException
1873
+	 * @throws InvalidInterfaceException
1874
+	 * @throws ReflectionException
1875
+	 */
1876
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1877
+	{
1878
+		$new_li_fields = $line_item->model_field_array();
1879
+		if (
1880
+			$line_item->type() === EEM_Line_Item::type_line_item &&
1881
+			$line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1882
+		) {
1883
+			$count = 0;
1884
+			foreach ($registrations as $registration) {
1885
+				if (
1886
+					$line_item->OBJ_ID() === $registration->ticket_ID() &&
1887
+					in_array(
1888
+						$registration->status_ID(),
1889
+						EEM_Registration::reg_statuses_that_allow_payment(),
1890
+						true
1891
+					)
1892
+				) {
1893
+					$count++;
1894
+				}
1895
+			}
1896
+			$new_li_fields['LIN_quantity'] = $count;
1897
+		}
1898
+		// don't set the total. We'll leave that up to the code that calculates it
1899
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1900
+		return EE_Line_Item::new_instance($new_li_fields);
1901
+	}
1902
+
1903
+
1904
+	/**
1905
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1906
+	 * are removed, and line items with a quantity of 0
1907
+	 *
1908
+	 * @param EE_Line_Item $line_item |null
1909
+	 * @return EE_Line_Item|null
1910
+	 * @throws EE_Error
1911
+	 * @throws InvalidArgumentException
1912
+	 * @throws InvalidDataTypeException
1913
+	 * @throws InvalidInterfaceException
1914
+	 * @throws ReflectionException
1915
+	 */
1916
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1917
+	{
1918
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1919
+		if ($copied_li === null) {
1920
+			return null;
1921
+		}
1922
+		// if this is an event subtotal, we want to only include it if it
1923
+		// has a non-zero total and at least one ticket line item child
1924
+		$ticket_children = 0;
1925
+		foreach ($line_item->children() as $child_li) {
1926
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1927
+			if ($child_li_copy !== null) {
1928
+				$copied_li->add_child_line_item($child_li_copy);
1929
+				if (
1930
+					$child_li_copy->type() === EEM_Line_Item::type_line_item &&
1931
+					$child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1932
+				) {
1933
+					$ticket_children++;
1934
+				}
1935
+			}
1936
+		}
1937
+		// if this is an event subtotal with NO ticket children
1938
+		// we basically want to ignore it
1939
+		if (
1940
+			$ticket_children === 0
1941
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1942
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1943
+			&& $line_item->total() === 0
1944
+		) {
1945
+			return null;
1946
+		}
1947
+		return $copied_li;
1948
+	}
1949
+
1950
+
1951
+	/**
1952
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1953
+	 * with a total of 0, or a subtotal of 0, returns null instead
1954
+	 *
1955
+	 * @param EE_Line_Item $line_item
1956
+	 * @return EE_Line_Item
1957
+	 * @throws EE_Error
1958
+	 * @throws InvalidArgumentException
1959
+	 * @throws InvalidDataTypeException
1960
+	 * @throws InvalidInterfaceException
1961
+	 * @throws ReflectionException
1962
+	 */
1963
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1964
+	{
1965
+		if (
1966
+			$line_item->type() === EEM_Line_Item::type_line_item
1967
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1968
+			&& $line_item->quantity() === 0
1969
+		) {
1970
+			return null;
1971
+		}
1972
+		$new_li_fields = $line_item->model_field_array();
1973
+		// don't set the total. We'll leave that up to the code that calculates it
1974
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1975
+		return EE_Line_Item::new_instance($new_li_fields);
1976
+	}
1977
+
1978
+
1979
+	/**
1980
+	 * Cycles through all of the ticket line items for the supplied total line item
1981
+	 * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1982
+	 *
1983
+	 * @param EE_Line_Item $total_line_item
1984
+	 * @since 4.9.79.p
1985
+	 * @throws EE_Error
1986
+	 * @throws InvalidArgumentException
1987
+	 * @throws InvalidDataTypeException
1988
+	 * @throws InvalidInterfaceException
1989
+	 * @throws ReflectionException
1990
+	 */
1991
+	public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1992
+	{
1993
+		$ticket_line_items = self::get_ticket_line_items($total_line_item);
1994
+		foreach ($ticket_line_items as $ticket_line_item) {
1995
+			if (
1996
+				$ticket_line_item instanceof EE_Line_Item
1997
+				&& $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1998
+			) {
1999
+				$ticket = $ticket_line_item->ticket();
2000
+				if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
2001
+					$ticket_line_item->set_is_taxable($ticket->taxable());
2002
+					$ticket_line_item->save();
2003
+				}
2004
+			}
2005
+		}
2006
+	}
2007
+
2008
+
2009
+	/**
2010
+	 * @return EE_Line_Item[]
2011
+	 * @throws EE_Error
2012
+	 * @throws ReflectionException
2013
+	 * @since   5.0.0.p
2014
+	 */
2015
+	private static function getGlobalTaxes(): array
2016
+	{
2017
+		if (EEH_Line_Item::$global_taxes === null) {
2018
+
2019
+			/** @type EEM_Price $EEM_Price */
2020
+			$EEM_Price = EE_Registry::instance()->load_model('Price');
2021
+			// get array of taxes via Price Model
2022
+			EEH_Line_Item::$global_taxes = $EEM_Price->get_all_prices_that_are_taxes();
2023
+			ksort(EEH_Line_Item::$global_taxes);
2024
+		}
2025
+		return EEH_Line_Item::$global_taxes;
2026
+	}
2027
+
2028
+
2029
+
2030
+	/**************************************** @DEPRECATED METHODS *************************************** */
2031
+	/**
2032
+	 * @deprecated
2033
+	 * @param EE_Line_Item $total_line_item
2034
+	 * @return EE_Line_Item
2035
+	 * @throws EE_Error
2036
+	 * @throws InvalidArgumentException
2037
+	 * @throws InvalidDataTypeException
2038
+	 * @throws InvalidInterfaceException
2039
+	 * @throws ReflectionException
2040
+	 */
2041
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
2042
+	{
2043
+		EE_Error::doing_it_wrong(
2044
+			'EEH_Line_Item::get_items_subtotal()',
2045
+			sprintf(
2046
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2047
+				'EEH_Line_Item::get_pre_tax_subtotal()'
2048
+			),
2049
+			'4.6.0'
2050
+		);
2051
+		return self::get_pre_tax_subtotal($total_line_item);
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * @deprecated
2057
+	 * @param EE_Transaction $transaction
2058
+	 * @return EE_Line_Item
2059
+	 * @throws EE_Error
2060
+	 * @throws InvalidArgumentException
2061
+	 * @throws InvalidDataTypeException
2062
+	 * @throws InvalidInterfaceException
2063
+	 * @throws ReflectionException
2064
+	 */
2065
+	public static function create_default_total_line_item($transaction = null)
2066
+	{
2067
+		EE_Error::doing_it_wrong(
2068
+			'EEH_Line_Item::create_default_total_line_item()',
2069
+			sprintf(
2070
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2071
+				'EEH_Line_Item::create_total_line_item()'
2072
+			),
2073
+			'4.6.0'
2074
+		);
2075
+		return self::create_total_line_item($transaction);
2076
+	}
2077
+
2078
+
2079
+	/**
2080
+	 * @deprecated
2081
+	 * @param EE_Line_Item   $total_line_item
2082
+	 * @param EE_Transaction $transaction
2083
+	 * @return EE_Line_Item
2084
+	 * @throws EE_Error
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidDataTypeException
2087
+	 * @throws InvalidInterfaceException
2088
+	 * @throws ReflectionException
2089
+	 */
2090
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2091
+	{
2092
+		EE_Error::doing_it_wrong(
2093
+			'EEH_Line_Item::create_default_tickets_subtotal()',
2094
+			sprintf(
2095
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2096
+				'EEH_Line_Item::create_pre_tax_subtotal()'
2097
+			),
2098
+			'4.6.0'
2099
+		);
2100
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
2101
+	}
2102
+
2103
+
2104
+	/**
2105
+	 * @deprecated
2106
+	 * @param EE_Line_Item   $total_line_item
2107
+	 * @param EE_Transaction $transaction
2108
+	 * @return EE_Line_Item
2109
+	 * @throws EE_Error
2110
+	 * @throws InvalidArgumentException
2111
+	 * @throws InvalidDataTypeException
2112
+	 * @throws InvalidInterfaceException
2113
+	 * @throws ReflectionException
2114
+	 */
2115
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2116
+	{
2117
+		EE_Error::doing_it_wrong(
2118
+			'EEH_Line_Item::create_default_taxes_subtotal()',
2119
+			sprintf(
2120
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2121
+				'EEH_Line_Item::create_taxes_subtotal()'
2122
+			),
2123
+			'4.6.0'
2124
+		);
2125
+		return self::create_taxes_subtotal($total_line_item, $transaction);
2126
+	}
2127
+
2128
+
2129
+	/**
2130
+	 * @deprecated
2131
+	 * @param EE_Line_Item   $total_line_item
2132
+	 * @param EE_Transaction $transaction
2133
+	 * @return EE_Line_Item
2134
+	 * @throws EE_Error
2135
+	 * @throws InvalidArgumentException
2136
+	 * @throws InvalidDataTypeException
2137
+	 * @throws InvalidInterfaceException
2138
+	 * @throws ReflectionException
2139
+	 */
2140
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2141
+	{
2142
+		EE_Error::doing_it_wrong(
2143
+			'EEH_Line_Item::create_default_event_subtotal()',
2144
+			sprintf(
2145
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2146
+				'EEH_Line_Item::create_event_subtotal()'
2147
+			),
2148
+			'4.6.0'
2149
+		);
2150
+		return self::create_event_subtotal($total_line_item, $transaction);
2151
+	}
2152 2152
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Money.helper.php 1 patch
Indentation   +220 added lines, -220 removed lines patch added patch discarded remove patch
@@ -10,236 +10,236 @@
 block discarded – undo
10 10
  */
11 11
 class EEH_Money extends EEH_Base
12 12
 {
13
-    /**
14
-     * This removes all localized money formatting from the incoming value
15
-     * Note: uses this site's currency settings for deciding what is considered a
16
-     * "thousands separator" (usually the character "," )
17
-     * and what is a "decimal mark" (usually the character ".")
18
-     *
19
-     * @param int|float|string $money_value
20
-     * @param string|null      $CNT_ISO
21
-     * @return float
22
-     * @throws EE_Error
23
-     * @throws ReflectionException
24
-     */
25
-    public static function strip_localized_money_formatting($money_value, ?string $CNT_ISO = ''): float
26
-    {
27
-        $currency_config = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
28
-        $money_value     = str_replace(
29
-            [
30
-                $currency_config->thsnds,
31
-                $currency_config->dec_mrk,
32
-            ],
33
-            [
34
-                '', // remove thousands separator
35
-                '.', // convert decimal mark to what PHP expects
36
-            ],
37
-            $money_value
38
-        );
39
-        return (float) filter_var(
40
-            $money_value,
41
-            FILTER_SANITIZE_NUMBER_FLOAT,
42
-            FILTER_FLAG_ALLOW_FRACTION
43
-        );
44
-    }
13
+	/**
14
+	 * This removes all localized money formatting from the incoming value
15
+	 * Note: uses this site's currency settings for deciding what is considered a
16
+	 * "thousands separator" (usually the character "," )
17
+	 * and what is a "decimal mark" (usually the character ".")
18
+	 *
19
+	 * @param int|float|string $money_value
20
+	 * @param string|null      $CNT_ISO
21
+	 * @return float
22
+	 * @throws EE_Error
23
+	 * @throws ReflectionException
24
+	 */
25
+	public static function strip_localized_money_formatting($money_value, ?string $CNT_ISO = ''): float
26
+	{
27
+		$currency_config = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
28
+		$money_value     = str_replace(
29
+			[
30
+				$currency_config->thsnds,
31
+				$currency_config->dec_mrk,
32
+			],
33
+			[
34
+				'', // remove thousands separator
35
+				'.', // convert decimal mark to what PHP expects
36
+			],
37
+			$money_value
38
+		);
39
+		return (float) filter_var(
40
+			$money_value,
41
+			FILTER_SANITIZE_NUMBER_FLOAT,
42
+			FILTER_FLAG_ALLOW_FRACTION
43
+		);
44
+	}
45 45
 
46 46
 
47
-    /**
48
-     * This converts an incoming localized money value into a standard float item (to three decimal places)
49
-     * Only use this if you know the $money_value follows your currency configuration's
50
-     * settings. Note: this uses this site's currency settings for deciding what is considered a
51
-     * "thousands separator" (usually the character "," )
52
-     * and what is a "decimal mark" (usually the character ".")
53
-     *
54
-     * @param int|float|string $money_value
55
-     * @return float
56
-     * @throws EE_Error
57
-     * @throws ReflectionException
58
-     */
59
-    public static function convert_to_float_from_localized_money($money_value): float
60
-    {
61
-        // float it! and round to three decimal places
62
-        return round(EEH_Money::strip_localized_money_formatting($money_value), 3);
63
-    }
47
+	/**
48
+	 * This converts an incoming localized money value into a standard float item (to three decimal places)
49
+	 * Only use this if you know the $money_value follows your currency configuration's
50
+	 * settings. Note: this uses this site's currency settings for deciding what is considered a
51
+	 * "thousands separator" (usually the character "," )
52
+	 * and what is a "decimal mark" (usually the character ".")
53
+	 *
54
+	 * @param int|float|string $money_value
55
+	 * @return float
56
+	 * @throws EE_Error
57
+	 * @throws ReflectionException
58
+	 */
59
+	public static function convert_to_float_from_localized_money($money_value): float
60
+	{
61
+		// float it! and round to three decimal places
62
+		return round(EEH_Money::strip_localized_money_formatting($money_value), 3);
63
+	}
64 64
 
65 65
 
66
-    /**
67
-     * For comparing floats. Default operator is '=', but see the $operator below for all options.
68
-     * This should be used to compare floats instead of normal '==' because floats
69
-     * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
70
-     * but actually differ by 0.00000001.
71
-     *
72
-     * @see http://biostall.com/php-function-to-compare-floating-point-numbers
73
-     * @param int|float|string $float1
74
-     * @param int|float|string $float2
75
-     * @param string|null      $operator The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
76
-     * @return bool whether the equation is true or false
77
-     * @throws EE_Error
78
-     */
79
-    public static function compare_floats($float1, $float2, ?string $operator = '='): bool
80
-    {
81
-        // Check numbers to 5 digits of precision
82
-        $epsilon = 0.00001;
83
-        $float1  = (float) $float1;
84
-        $float2  = (float) $float2;
85
-        switch ($operator) {
86
-            // equal
87
-            case '=':
88
-            case '==':
89
-            case '===':
90
-            case 'eq':
91
-                if (abs($float1 - $float2) < $epsilon) {
92
-                    return true;
93
-                }
94
-                break;
95
-            // less than
96
-            case '<':
97
-            case 'lt':
98
-                if (abs($float1 - $float2) < $epsilon) {
99
-                    return false;
100
-                }
101
-                if ($float1 < $float2) {
102
-                    return true;
103
-                }
104
-                break;
105
-            // less than or equal
106
-            case '<=':
107
-            case 'lte':
108
-                if (
109
-                    self::compare_floats($float1, $float2, '<')
110
-                    || self::compare_floats($float1, $float2)
111
-                ) {
112
-                    return true;
113
-                }
114
-                break;
115
-            // greater than
116
-            case '>':
117
-            case 'gt':
118
-                if (abs($float1 - $float2) < $epsilon) {
119
-                    return false;
120
-                }
121
-                if ($float1 > $float2) {
122
-                    return true;
123
-                }
124
-                break;
125
-            // greater than or equal
126
-            case '>=':
127
-            case 'gte':
128
-                if (
129
-                    self::compare_floats($float1, $float2, '>')
130
-                    || self::compare_floats($float1, $float2)
131
-                ) {
132
-                    return true;
133
-                }
134
-                break;
135
-            case '<>':
136
-            case '!=':
137
-            case '!==':
138
-            case 'ne':
139
-                if (abs($float1 - $float2) > $epsilon) {
140
-                    return true;
141
-                }
142
-                break;
143
-            default:
144
-                throw new EE_Error(
145
-                    sprintf(
146
-                        esc_html__(
147
-                            "Unknown operator %s in EEH_Money::compare_floats()",
148
-                            'event_espresso'
149
-                        ),
150
-                        $operator
151
-                    )
152
-                );
153
-        }
154
-        return false;
155
-    }
66
+	/**
67
+	 * For comparing floats. Default operator is '=', but see the $operator below for all options.
68
+	 * This should be used to compare floats instead of normal '==' because floats
69
+	 * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
70
+	 * but actually differ by 0.00000001.
71
+	 *
72
+	 * @see http://biostall.com/php-function-to-compare-floating-point-numbers
73
+	 * @param int|float|string $float1
74
+	 * @param int|float|string $float2
75
+	 * @param string|null      $operator The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
76
+	 * @return bool whether the equation is true or false
77
+	 * @throws EE_Error
78
+	 */
79
+	public static function compare_floats($float1, $float2, ?string $operator = '='): bool
80
+	{
81
+		// Check numbers to 5 digits of precision
82
+		$epsilon = 0.00001;
83
+		$float1  = (float) $float1;
84
+		$float2  = (float) $float2;
85
+		switch ($operator) {
86
+			// equal
87
+			case '=':
88
+			case '==':
89
+			case '===':
90
+			case 'eq':
91
+				if (abs($float1 - $float2) < $epsilon) {
92
+					return true;
93
+				}
94
+				break;
95
+			// less than
96
+			case '<':
97
+			case 'lt':
98
+				if (abs($float1 - $float2) < $epsilon) {
99
+					return false;
100
+				}
101
+				if ($float1 < $float2) {
102
+					return true;
103
+				}
104
+				break;
105
+			// less than or equal
106
+			case '<=':
107
+			case 'lte':
108
+				if (
109
+					self::compare_floats($float1, $float2, '<')
110
+					|| self::compare_floats($float1, $float2)
111
+				) {
112
+					return true;
113
+				}
114
+				break;
115
+			// greater than
116
+			case '>':
117
+			case 'gt':
118
+				if (abs($float1 - $float2) < $epsilon) {
119
+					return false;
120
+				}
121
+				if ($float1 > $float2) {
122
+					return true;
123
+				}
124
+				break;
125
+			// greater than or equal
126
+			case '>=':
127
+			case 'gte':
128
+				if (
129
+					self::compare_floats($float1, $float2, '>')
130
+					|| self::compare_floats($float1, $float2)
131
+				) {
132
+					return true;
133
+				}
134
+				break;
135
+			case '<>':
136
+			case '!=':
137
+			case '!==':
138
+			case 'ne':
139
+				if (abs($float1 - $float2) > $epsilon) {
140
+					return true;
141
+				}
142
+				break;
143
+			default:
144
+				throw new EE_Error(
145
+					sprintf(
146
+						esc_html__(
147
+							"Unknown operator %s in EEH_Money::compare_floats()",
148
+							'event_espresso'
149
+						),
150
+						$operator
151
+					)
152
+				);
153
+		}
154
+		return false;
155
+	}
156 156
 
157 157
 
158
-    /**
159
-     * This returns a localized format string suitable for jQplot.
160
-     *
161
-     * @param string|null $CNT_ISO If this is provided, then will attempt to get the currency settings for the country.
162
-     *                             Otherwise will use currency settings for current active country on site.
163
-     * @return string
164
-     * @throws EE_Error
165
-     * @throws ReflectionException
166
-     */
167
-    public static function get_format_for_jqplot(?string $CNT_ISO = ''): string
168
-    {
169
-        // default format
170
-        $format          = 'f';
171
-        $currency_config = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
172
-        // first get the decimal place and number of places
173
-        $format = "%'." . $currency_config->dec_plc . $format;
174
-        // currency symbol on right side.
175
-        return $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
176
-    }
158
+	/**
159
+	 * This returns a localized format string suitable for jQplot.
160
+	 *
161
+	 * @param string|null $CNT_ISO If this is provided, then will attempt to get the currency settings for the country.
162
+	 *                             Otherwise will use currency settings for current active country on site.
163
+	 * @return string
164
+	 * @throws EE_Error
165
+	 * @throws ReflectionException
166
+	 */
167
+	public static function get_format_for_jqplot(?string $CNT_ISO = ''): string
168
+	{
169
+		// default format
170
+		$format          = 'f';
171
+		$currency_config = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
172
+		// first get the decimal place and number of places
173
+		$format = "%'." . $currency_config->dec_plc . $format;
174
+		// currency symbol on right side.
175
+		return $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
176
+	}
177 177
 
178 178
 
179
-    /**
180
-     * This returns a localized format string suitable for usage with the Google Charts API format param.
181
-     *
182
-     * @param string|null $CNT_ISO If this is provided, then will attempt to get the currency settings for the country.
183
-     *                             Otherwise will use currency settings for current active country on site.
184
-     *                             Note: GoogleCharts uses ICU pattern set
185
-     *                             (@return array
186
-     * @return array
187
-     * @throws EE_Error
188
-     * @throws ReflectionException
189
-     * @see http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
190
-     */
191
-    public static function get_format_for_google_charts(?string $CNT_ISO = ''): array
192
-    {
193
-        $currency_config            = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
194
-        $decimal_places_placeholder = str_pad('', $currency_config->dec_plc, '0');
195
-        // first get the decimal place and number of places
196
-        $format = '#,##0.' . $decimal_places_placeholder;
197
-        // currency symbol on right side.
198
-        $format          = $currency_config->sign_b4
199
-            ? $currency_config->sign . $format
200
-            : $format
201
-              . $currency_config->sign;
202
-        $formatterObject = [
203
-            'decimalSymbol'  => $currency_config->dec_mrk,
204
-            'groupingSymbol' => $currency_config->thsnds,
205
-            'fractionDigits' => $currency_config->dec_plc,
206
-        ];
207
-        if ($currency_config->sign_b4) {
208
-            $formatterObject['prefix'] = $currency_config->sign;
209
-        } else {
210
-            $formatterObject['suffix'] = $currency_config->sign;
211
-        }
212
-        return [
213
-            'format'          => $format,
214
-            'formatterObject' => $formatterObject,
215
-        ];
216
-    }
179
+	/**
180
+	 * This returns a localized format string suitable for usage with the Google Charts API format param.
181
+	 *
182
+	 * @param string|null $CNT_ISO If this is provided, then will attempt to get the currency settings for the country.
183
+	 *                             Otherwise will use currency settings for current active country on site.
184
+	 *                             Note: GoogleCharts uses ICU pattern set
185
+	 *                             (@return array
186
+	 * @return array
187
+	 * @throws EE_Error
188
+	 * @throws ReflectionException
189
+	 * @see http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
190
+	 */
191
+	public static function get_format_for_google_charts(?string $CNT_ISO = ''): array
192
+	{
193
+		$currency_config            = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
194
+		$decimal_places_placeholder = str_pad('', $currency_config->dec_plc, '0');
195
+		// first get the decimal place and number of places
196
+		$format = '#,##0.' . $decimal_places_placeholder;
197
+		// currency symbol on right side.
198
+		$format          = $currency_config->sign_b4
199
+			? $currency_config->sign . $format
200
+			: $format
201
+			  . $currency_config->sign;
202
+		$formatterObject = [
203
+			'decimalSymbol'  => $currency_config->dec_mrk,
204
+			'groupingSymbol' => $currency_config->thsnds,
205
+			'fractionDigits' => $currency_config->dec_plc,
206
+		];
207
+		if ($currency_config->sign_b4) {
208
+			$formatterObject['prefix'] = $currency_config->sign;
209
+		} else {
210
+			$formatterObject['suffix'] = $currency_config->sign;
211
+		}
212
+		return [
213
+			'format'          => $format,
214
+			'formatterObject' => $formatterObject,
215
+		];
216
+	}
217 217
 
218 218
 
219
-    /**
220
-     * @param string|null $CNT_ISO
221
-     * @return EE_Currency_Config
222
-     * @throws EE_Error
223
-     * @throws ReflectionException
224
-     */
225
-    public static function get_currency_config(?string $CNT_ISO = ''): EE_Currency_Config
226
-    {
227
-        return EE_Currency_Config::getCurrencyConfig($CNT_ISO);
228
-    }
219
+	/**
220
+	 * @param string|null $CNT_ISO
221
+	 * @return EE_Currency_Config
222
+	 * @throws EE_Error
223
+	 * @throws ReflectionException
224
+	 */
225
+	public static function get_currency_config(?string $CNT_ISO = ''): EE_Currency_Config
226
+	{
227
+		return EE_Currency_Config::getCurrencyConfig($CNT_ISO);
228
+	}
229 229
 
230 230
 
231
-    /**
232
-     * @param string|null $CNT_ISO
233
-     * @param bool        $as_decimal if false [default] will return the number of decimal places ex: 1, 2, 3
234
-     *                                if true, will return the subunits as a decimal fraction ex: .1, .01, .001
235
-     * @return float
236
-     * @throws EE_Error
237
-     * @throws ReflectionException
238
-     * @since 5.0.0.p
239
-     */
240
-    public static function getCurrencySubUnits(?string $CNT_ISO = '', bool $as_decimal = false): float
241
-    {
242
-        $currency_config = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
243
-        return $as_decimal ? pow(10, ($currency_config->dec_plc * -1)) : $currency_config->dec_plc;
244
-    }
231
+	/**
232
+	 * @param string|null $CNT_ISO
233
+	 * @param bool        $as_decimal if false [default] will return the number of decimal places ex: 1, 2, 3
234
+	 *                                if true, will return the subunits as a decimal fraction ex: .1, .01, .001
235
+	 * @return float
236
+	 * @throws EE_Error
237
+	 * @throws ReflectionException
238
+	 * @since 5.0.0.p
239
+	 */
240
+	public static function getCurrencySubUnits(?string $CNT_ISO = '', bool $as_decimal = false): float
241
+	{
242
+		$currency_config = EE_Currency_Config::getCurrencyConfig($CNT_ISO);
243
+		return $as_decimal ? pow(10, ($currency_config->dec_plc * -1)) : $currency_config->dec_plc;
244
+	}
245 245
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Event_Message_Template.model.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -11,134 +11,134 @@
 block discarded – undo
11 11
  */
12 12
 class EEM_Event_Message_Template extends EEM_Base
13 13
 {
14
-    // private instance of the EEM_Event_Message_Template object
15
-    protected static $_instance = null;
14
+	// private instance of the EEM_Event_Message_Template object
15
+	protected static $_instance = null;
16 16
 
17 17
 
18
-    /**
19
-     * protected constructor to prevent direct creation
20
-     *
21
-     * @param null $timezone
22
-     * @throws EE_Error
23
-     */
24
-    protected function __construct($timezone = null)
25
-    {
26
-        $this->singular_item = esc_html__('Event Message Template', 'event_espresso');
27
-        $this->plural_item = esc_html__('Event Message Templates', 'event_espresso');
18
+	/**
19
+	 * protected constructor to prevent direct creation
20
+	 *
21
+	 * @param null $timezone
22
+	 * @throws EE_Error
23
+	 */
24
+	protected function __construct($timezone = null)
25
+	{
26
+		$this->singular_item = esc_html__('Event Message Template', 'event_espresso');
27
+		$this->plural_item = esc_html__('Event Message Templates', 'event_espresso');
28 28
 
29
-        $this->_tables = [
30
-            'Event_Message_Template' => new EE_Primary_Table('esp_event_message_template', 'EMT_ID'),
31
-        ];
32
-        $this->_fields = [
33
-            'Event_Message_Template' => [
34
-                'EMT_ID' => new EE_Primary_Key_Int_Field(
35
-                    'EMT_ID',
36
-                    esc_html__('Event Message Template ID', 'event_espresso')
37
-                ),
38
-                'EVT_ID' => new EE_Foreign_Key_Int_Field(
39
-                    'EVT_ID',
40
-                    esc_html__('The ID to the Event', 'event_espresso'),
41
-                    false,
42
-                    0,
43
-                    'Event'
44
-                ),
45
-                'GRP_ID' => new EE_Foreign_Key_Int_Field(
46
-                    'GRP_ID',
47
-                    esc_html__('The ID to the Message Template Group', 'event_espresso'),
48
-                    false,
49
-                    0,
50
-                    'Message_Template_Group'
51
-                ),
52
-            ],
53
-        ];
54
-        $this->_model_relations = [
55
-            'Event'                  => new EE_Belongs_To_Relation(),
56
-            'Message_Template_Group' => new EE_Belongs_To_Relation(),
57
-        ];
58
-        $path_to_event = 'Event';
59
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
60
-            $path_to_event
61
-        );
62
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
63
-            $path_to_event
64
-        );
65
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
66
-            $path_to_event
67
-        );
68
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
69
-            $path_to_event,
70
-            EEM_Base::caps_edit
71
-        );
72
-        parent::__construct($timezone);
73
-    }
29
+		$this->_tables = [
30
+			'Event_Message_Template' => new EE_Primary_Table('esp_event_message_template', 'EMT_ID'),
31
+		];
32
+		$this->_fields = [
33
+			'Event_Message_Template' => [
34
+				'EMT_ID' => new EE_Primary_Key_Int_Field(
35
+					'EMT_ID',
36
+					esc_html__('Event Message Template ID', 'event_espresso')
37
+				),
38
+				'EVT_ID' => new EE_Foreign_Key_Int_Field(
39
+					'EVT_ID',
40
+					esc_html__('The ID to the Event', 'event_espresso'),
41
+					false,
42
+					0,
43
+					'Event'
44
+				),
45
+				'GRP_ID' => new EE_Foreign_Key_Int_Field(
46
+					'GRP_ID',
47
+					esc_html__('The ID to the Message Template Group', 'event_espresso'),
48
+					false,
49
+					0,
50
+					'Message_Template_Group'
51
+				),
52
+			],
53
+		];
54
+		$this->_model_relations = [
55
+			'Event'                  => new EE_Belongs_To_Relation(),
56
+			'Message_Template_Group' => new EE_Belongs_To_Relation(),
57
+		];
58
+		$path_to_event = 'Event';
59
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
60
+			$path_to_event
61
+		);
62
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
63
+			$path_to_event
64
+		);
65
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
66
+			$path_to_event
67
+		);
68
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
69
+			$path_to_event,
70
+			EEM_Base::caps_edit
71
+		);
72
+		parent::__construct($timezone);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * helper method to simply return an array of event ids for events attached to the given
78
-     * message template group.
79
-     *
80
-     * @param int $GRP_ID The MTP group we want attached events for.
81
-     * @return  array               An array of event ids.
82
-     * @throws EE_Error
83
-     * @since 4.3.0
84
-     */
85
-    public function get_attached_event_ids($GRP_ID)
86
-    {
87
-        $event_ids = $this->_get_all_wpdb_results([['GRP_ID' => $GRP_ID]], ARRAY_N, 'EVT_ID');
88
-        $event_ids = call_user_func_array('array_merge', $event_ids);
89
-        return $event_ids;
90
-    }
76
+	/**
77
+	 * helper method to simply return an array of event ids for events attached to the given
78
+	 * message template group.
79
+	 *
80
+	 * @param int $GRP_ID The MTP group we want attached events for.
81
+	 * @return  array               An array of event ids.
82
+	 * @throws EE_Error
83
+	 * @since 4.3.0
84
+	 */
85
+	public function get_attached_event_ids($GRP_ID)
86
+	{
87
+		$event_ids = $this->_get_all_wpdb_results([['GRP_ID' => $GRP_ID]], ARRAY_N, 'EVT_ID');
88
+		$event_ids = call_user_func_array('array_merge', $event_ids);
89
+		return $event_ids;
90
+	}
91 91
 
92 92
 
93
-    /**
94
-     * helper method for clearing event/group relations for the given event ids and grp ids.
95
-     *
96
-     * @param array $GRP_IDs An array of GRP_IDs. Optional. If empty then there must be EVT IDs.
97
-     * @param array $EVT_IDs An array of EVT_IDs.  Optional. If empty then there must be GRP IDs.
98
-     * @return int             How many rows were deleted.
99
-     * @throws EE_Error
100
-     * @throws EE_Error
101
-     */
102
-    public function delete_event_group_relations($GRP_IDs = [], $EVT_IDs = [])
103
-    {
104
-        if (empty($GRP_IDs) && empty($EVT_IDs)) {
105
-            throw new EE_Error(
106
-                sprintf(
107
-                    esc_html__(
108
-                        '%s requires either an array of GRP_IDs or EVT_IDs or both, but both cannot be empty.',
109
-                        'event_espresso'
110
-                    ),
111
-                    __METHOD__
112
-                )
113
-            );
114
-        }
93
+	/**
94
+	 * helper method for clearing event/group relations for the given event ids and grp ids.
95
+	 *
96
+	 * @param array $GRP_IDs An array of GRP_IDs. Optional. If empty then there must be EVT IDs.
97
+	 * @param array $EVT_IDs An array of EVT_IDs.  Optional. If empty then there must be GRP IDs.
98
+	 * @return int             How many rows were deleted.
99
+	 * @throws EE_Error
100
+	 * @throws EE_Error
101
+	 */
102
+	public function delete_event_group_relations($GRP_IDs = [], $EVT_IDs = [])
103
+	{
104
+		if (empty($GRP_IDs) && empty($EVT_IDs)) {
105
+			throw new EE_Error(
106
+				sprintf(
107
+					esc_html__(
108
+						'%s requires either an array of GRP_IDs or EVT_IDs or both, but both cannot be empty.',
109
+						'event_espresso'
110
+					),
111
+					__METHOD__
112
+				)
113
+			);
114
+		}
115 115
 
116
-        $where = [];
117
-        if (! empty($GRP_IDs)) {
118
-            $where['GRP_ID'] = ['IN', (array) $GRP_IDs];
119
-        }
120
-        if (! empty($EVT_IDs)) {
121
-            $where['EVT_ID'] = ['IN', (array) $EVT_IDs];
122
-        }
116
+		$where = [];
117
+		if (! empty($GRP_IDs)) {
118
+			$where['GRP_ID'] = ['IN', (array) $GRP_IDs];
119
+		}
120
+		if (! empty($EVT_IDs)) {
121
+			$where['EVT_ID'] = ['IN', (array) $EVT_IDs];
122
+		}
123 123
 
124
-        return $this->delete([$where], false);
125
-    }
124
+		return $this->delete([$where], false);
125
+	}
126 126
 
127 127
 
128
-    /**
129
-     * returns a numerically indexed array
130
-     * with values that correspond to the 'GRP_ID' column
131
-     * where the 'EVT_ID' column matches that of the supplied event
132
-     *
133
-     * @param EE_Event $event
134
-     * @return array
135
-     * @throws EE_Error
136
-     * @throws ReflectionException
137
-     * @since   5.0.0.p
138
-     */
139
-    public function messageTemplateGroupIDsForEvent(EE_Event $event): array
140
-    {
141
-        $results = $this->get_col([['EVT_ID' => $event->ID()]], 'GRP_ID');
142
-        return $results !== false ? $results : [];
143
-    }
128
+	/**
129
+	 * returns a numerically indexed array
130
+	 * with values that correspond to the 'GRP_ID' column
131
+	 * where the 'EVT_ID' column matches that of the supplied event
132
+	 *
133
+	 * @param EE_Event $event
134
+	 * @return array
135
+	 * @throws EE_Error
136
+	 * @throws ReflectionException
137
+	 * @since   5.0.0.p
138
+	 */
139
+	public function messageTemplateGroupIDsForEvent(EE_Event $event): array
140
+	{
141
+		$results = $this->get_col([['EVT_ID' => $event->ID()]], 'GRP_ID');
142
+		return $results !== false ? $results : [];
143
+	}
144 144
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6593 added lines, -6593 removed lines patch added patch discarded remove patch
@@ -37,6599 +37,6599 @@
 block discarded – undo
37 37
  */
38 38
 abstract class EEM_Base extends EE_Base implements ResettableInterface
39 39
 {
40
-    /**
41
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
-     * They almost always WILL NOT, but it's not necessarily a requirement.
44
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
-     *
46
-     * @var boolean
47
-     */
48
-    private $_values_already_prepared_by_model_object = 0;
49
-
50
-    /**
51
-     * when $_values_already_prepared_by_model_object equals this, we assume
52
-     * the data is just like form input that needs to have the model fields'
53
-     * prepare_for_set and prepare_for_use_in_db called on it
54
-     */
55
-    const not_prepared_by_model_object = 0;
56
-
57
-    /**
58
-     * when $_values_already_prepared_by_model_object equals this, we
59
-     * assume this value is coming from a model object and doesn't need to have
60
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
61
-     */
62
-    const prepared_by_model_object = 1;
63
-
64
-    /**
65
-     * when $_values_already_prepared_by_model_object equals this, we assume
66
-     * the values are already to be used in the database (ie no processing is done
67
-     * on them by the model's fields)
68
-     */
69
-    const prepared_for_use_in_db = 2;
70
-
71
-
72
-    protected $singular_item = 'Item';
73
-
74
-    protected $plural_item   = 'Items';
75
-
76
-    /**
77
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
-     */
79
-    protected $_tables;
80
-
81
-    /**
82
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
-     *
86
-     * @var EE_Model_Field_Base[][] $_fields
87
-     */
88
-    protected $_fields;
89
-
90
-    /**
91
-     * array of different kinds of relations
92
-     *
93
-     * @var EE_Model_Relation_Base[] $_model_relations
94
-     */
95
-    protected $_model_relations = [];
96
-
97
-    /**
98
-     * @var EE_Index[] $_indexes
99
-     */
100
-    protected $_indexes = [];
101
-
102
-    /**
103
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
104
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
-     * by setting the same columns as used in these queries in the query yourself.
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_default_where_conditions_strategy;
110
-
111
-    /**
112
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
-     * This is particularly useful when you want something between 'none' and 'default'
114
-     *
115
-     * @var EE_Default_Where_Conditions
116
-     */
117
-    protected $_minimum_where_conditions_strategy;
118
-
119
-    /**
120
-     * String describing how to find the "owner" of this model's objects.
121
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
-     * But when there isn't, this indicates which related model, or transiently-related model,
123
-     * has the foreign key to the wp_users table.
124
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
-     * related to events, and events have a foreign key to wp_users.
126
-     * On EEM_Transaction, this would be 'Transaction.Event'
127
-     *
128
-     * @var string
129
-     */
130
-    protected $_model_chain_to_wp_user = '';
131
-
132
-    /**
133
-     * String describing how to find the model with a password controlling access to this model. This property has the
134
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
-     * This value is the path of models to follow to arrive at the model with the password field.
136
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
-     * model with a password that should affect reading this on the front-end.
138
-     * Eg this is an empty string for the Event model because it has a password.
139
-     * This is null for the Registration model, because its event's password has no bearing on whether
140
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
-     * should hide tickets for datetimes for events that have a password set.
143
-     *
144
-     * @var string |null
145
-     */
146
-    protected $model_chain_to_password = null;
147
-
148
-    /**
149
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
-     * don't need it (particularly CPT models)
151
-     *
152
-     * @var bool
153
-     */
154
-    protected $_ignore_where_strategy = false;
155
-
156
-    /**
157
-     * String used in caps relating to this model. Eg, if the caps relating to this
158
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
-     *
160
-     * @var string. If null it hasn't been initialized yet. If false then we
161
-     * have indicated capabilities don't apply to this
162
-     */
163
-    protected $_caps_slug = null;
164
-
165
-    /**
166
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
-     * and next-level keys are capability names, and each's value is a
168
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
-     * they specify which context to use (ie, frontend, backend, edit or delete)
170
-     * and then each capability in the corresponding sub-array that they're missing
171
-     * adds the where conditions onto the query.
172
-     *
173
-     * @var array
174
-     */
175
-    protected $_cap_restrictions = [
176
-        self::caps_read       => [],
177
-        self::caps_read_admin => [],
178
-        self::caps_edit       => [],
179
-        self::caps_delete     => [],
180
-    ];
181
-
182
-    /**
183
-     * Array defining which cap restriction generators to use to create default
184
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
185
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
-     * automatically set this to false (not just null).
188
-     *
189
-     * @var EE_Restriction_Generator_Base[]
190
-     */
191
-    protected $_cap_restriction_generators = [];
192
-
193
-    /**
194
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
-     */
196
-    const caps_read       = 'read';
197
-
198
-    const caps_read_admin = 'read_admin';
199
-
200
-    const caps_edit       = 'edit';
201
-
202
-    const caps_delete     = 'delete';
203
-
204
-    /**
205
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
-     * maps to 'read' because when looking for relevant permissions we're going to use
208
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
209
-     *
210
-     * @var array
211
-     */
212
-    protected $_cap_contexts_to_cap_action_map = [
213
-        self::caps_read       => 'read',
214
-        self::caps_read_admin => 'read',
215
-        self::caps_edit       => 'edit',
216
-        self::caps_delete     => 'delete',
217
-    ];
218
-
219
-    /**
220
-     * Timezone
221
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
-     * EE_Datetime_Field data type will have access to it.
225
-     *
226
-     * @var string
227
-     */
228
-    protected $_timezone;
229
-
230
-
231
-    /**
232
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
-     * multisite.
234
-     *
235
-     * @var int
236
-     */
237
-    protected static $_model_query_blog_id;
238
-
239
-    /**
240
-     * A copy of _fields, except the array keys are the model names pointed to by
241
-     * the field
242
-     *
243
-     * @var EE_Model_Field_Base[]
244
-     */
245
-    private $_cache_foreign_key_to_fields = [];
246
-
247
-    /**
248
-     * Cached list of all the fields on the model, indexed by their name
249
-     *
250
-     * @var EE_Model_Field_Base[]
251
-     */
252
-    private $_cached_fields = null;
253
-
254
-    /**
255
-     * Cached list of all the fields on the model, except those that are
256
-     * marked as only pertinent to the database
257
-     *
258
-     * @var EE_Model_Field_Base[]
259
-     */
260
-    private $_cached_fields_non_db_only = null;
261
-
262
-    /**
263
-     * A cached reference to the primary key for quick lookup
264
-     *
265
-     * @var EE_Model_Field_Base
266
-     */
267
-    private $_primary_key_field = null;
268
-
269
-    /**
270
-     * Flag indicating whether this model has a primary key or not
271
-     *
272
-     * @var boolean
273
-     */
274
-    protected $_has_primary_key_field = null;
275
-
276
-    /**
277
-     * array in the format:  [ FK alias => full PK ]
278
-     * where keys are local column name aliases for foreign keys
279
-     * and values are the fully qualified column name for the primary key they represent
280
-     *  ex:
281
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
-     *
283
-     * @var array $foreign_key_aliases
284
-     */
285
-    protected $foreign_key_aliases = [];
286
-
287
-    /**
288
-     * Whether or not this model is based off a table in WP core only (CPTs should set
289
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
-     * This should be true for models that deal with data that should exist independent of EE.
291
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
293
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
295
-     *
296
-     * @var boolean
297
-     */
298
-    protected $_wp_core_model = false;
299
-
300
-    /**
301
-     * @var bool stores whether this model has a password field or not.
302
-     * null until initialized by hasPasswordField()
303
-     */
304
-    protected $has_password_field;
305
-
306
-    /**
307
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
-     */
309
-    protected $password_field;
310
-
311
-    /**
312
-     *    List of valid operators that can be used for querying.
313
-     * The keys are all operators we'll accept, the values are the real SQL
314
-     * operators used
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_valid_operators = [
319
-        '='           => '=',
320
-        '<='          => '<=',
321
-        '<'           => '<',
322
-        '>='          => '>=',
323
-        '>'           => '>',
324
-        '!='          => '!=',
325
-        'LIKE'        => 'LIKE',
326
-        'like'        => 'LIKE',
327
-        'NOT_LIKE'    => 'NOT LIKE',
328
-        'not_like'    => 'NOT LIKE',
329
-        'NOT LIKE'    => 'NOT LIKE',
330
-        'not like'    => 'NOT LIKE',
331
-        'IN'          => 'IN',
332
-        'in'          => 'IN',
333
-        'NOT_IN'      => 'NOT IN',
334
-        'not_in'      => 'NOT IN',
335
-        'NOT IN'      => 'NOT IN',
336
-        'not in'      => 'NOT IN',
337
-        'between'     => 'BETWEEN',
338
-        'BETWEEN'     => 'BETWEEN',
339
-        'IS_NOT_NULL' => 'IS NOT NULL',
340
-        'is_not_null' => 'IS NOT NULL',
341
-        'IS NOT NULL' => 'IS NOT NULL',
342
-        'is not null' => 'IS NOT NULL',
343
-        'IS_NULL'     => 'IS NULL',
344
-        'is_null'     => 'IS NULL',
345
-        'IS NULL'     => 'IS NULL',
346
-        'is null'     => 'IS NULL',
347
-        'REGEXP'      => 'REGEXP',
348
-        'regexp'      => 'REGEXP',
349
-        'NOT_REGEXP'  => 'NOT REGEXP',
350
-        'not_regexp'  => 'NOT REGEXP',
351
-        'NOT REGEXP'  => 'NOT REGEXP',
352
-        'not regexp'  => 'NOT REGEXP',
353
-    ];
354
-
355
-    /**
356
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
-     *
358
-     * @var array
359
-     */
360
-    protected $_in_style_operators = ['IN', 'NOT IN'];
361
-
362
-    /**
363
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
-     * '12-31-2012'"
365
-     *
366
-     * @var array
367
-     */
368
-    protected $_between_style_operators = ['BETWEEN'];
369
-
370
-    /**
371
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
-     *
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
-
377
-    /**
378
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
-     * on a join table.
380
-     *
381
-     * @var array
382
-     */
383
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
-
385
-    /**
386
-     * Allowed values for $query_params['order'] for ordering in queries
387
-     *
388
-     * @var array
389
-     */
390
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
-
392
-    /**
393
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
395
-     *
396
-     * @var array
397
-     */
398
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
-
400
-    /**
401
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
403
-     *
404
-     * @var array
405
-     */
406
-    private $_allowed_query_params = [
407
-        0,
408
-        'limit',
409
-        'order_by',
410
-        'group_by',
411
-        'having',
412
-        'force_join',
413
-        'order',
414
-        'on_join_limit',
415
-        'default_where_conditions',
416
-        'caps',
417
-        'extra_selects',
418
-        'exclude_protected',
419
-    ];
420
-
421
-    /**
422
-     * All the data types that can be used in $wpdb->prepare statements.
423
-     *
424
-     * @var array
425
-     */
426
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
-
428
-    /**
429
-     * @var EE_Registry $EE
430
-     */
431
-    protected $EE = null;
432
-
433
-
434
-    /**
435
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
-     *
437
-     * @var int
438
-     */
439
-    protected $_show_next_x_db_queries = 0;
440
-
441
-    /**
442
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
-     * WHERE, GROUP_BY, etc.
445
-     *
446
-     * @var CustomSelects
447
-     */
448
-    protected $_custom_selections = [];
449
-
450
-    /**
451
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
-     * caches every model object we've fetched from the DB on this request
453
-     *
454
-     * @var array
455
-     */
456
-    protected $_entity_map;
457
-
458
-    /**
459
-     * @var LoaderInterface
460
-     */
461
-    protected static $loader;
462
-
463
-    /**
464
-     * @var Mirror
465
-     */
466
-    private static $mirror;
467
-
468
-
469
-    /**
470
-     * constant used to show EEM_Base has not yet verified the db on this http request
471
-     */
472
-    const db_verified_none = 0;
473
-
474
-    /**
475
-     * constant used to show EEM_Base has verified the EE core db on this http request,
476
-     * but not the addons' dbs
477
-     */
478
-    const db_verified_core = 1;
479
-
480
-    /**
481
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
-     * the EE core db too)
483
-     */
484
-    const db_verified_addons = 2;
485
-
486
-    /**
487
-     * indicates whether an EEM_Base child has already re-verified the DB
488
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
489
-     * looking like EEM_Base::db_verified_*
490
-     *
491
-     * @var int - 0 = none, 1 = core, 2 = addons
492
-     */
493
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
494
-
495
-    /**
496
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
-     *        registrations for non-trashed tickets for non-trashed datetimes)
499
-     */
500
-    const default_where_conditions_all = 'all';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
-     *        models which share tables with other models, this can return data for the wrong model.
508
-     */
509
-    const default_where_conditions_this_only = 'this_model_only';
510
-
511
-    /**
512
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
-     */
516
-    const default_where_conditions_others_only = 'other_models_only';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
522
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
-     *        (regardless of whether those events and venues are trashed)
524
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
-     *        events.
526
-     */
527
-    const default_where_conditions_minimum_all = 'minimum';
528
-
529
-    /**
530
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
-     *        not)
534
-     */
535
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
-
537
-    /**
538
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
-     *        it's possible it will return table entries for other models. You should use
541
-     *        EEM_Base::default_where_conditions_minimum_all instead.
542
-     */
543
-    const default_where_conditions_none = 'none';
544
-
545
-
546
-    /**
547
-     * About all child constructors:
548
-     * they should define the _tables, _fields and _model_relations arrays.
549
-     * Should ALWAYS be called after child constructor.
550
-     * In order to make the child constructors to be as simple as possible, this parent constructor
551
-     * finalizes constructing all the object's attributes.
552
-     * Generally, rather than requiring a child to code
553
-     * $this->_tables = array(
554
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
-     *        ...);
556
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
-     * each EE_Table has a function to set the table's alias after the constructor, using
558
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
-     * do something similar.
560
-     *
561
-     * @param null $timezone
562
-     * @throws EE_Error
563
-     */
564
-    protected function __construct($timezone = null)
565
-    {
566
-        // check that the model has not been loaded too soon
567
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
-            throw new EE_Error(
569
-                sprintf(
570
-                    esc_html__(
571
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
572
-                        'event_espresso'
573
-                    ),
574
-                    get_class($this)
575
-                )
576
-            );
577
-        }
578
-        /**
579
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
580
-         */
581
-        if (empty(EEM_Base::$_model_query_blog_id)) {
582
-            EEM_Base::set_model_query_blog_id();
583
-        }
584
-        /**
585
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
586
-         * just use EE_Register_Model_Extension
587
-         *
588
-         * @var EE_Table_Base[] $_tables
589
-         */
590
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
-        foreach ($this->_tables as $table_alias => $table_obj) {
592
-            /** @var $table_obj EE_Table_Base */
593
-            $table_obj->_construct_finalize_with_alias($table_alias);
594
-            if ($table_obj instanceof EE_Secondary_Table) {
595
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
596
-            }
597
-        }
598
-        /**
599
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
600
-         * EE_Register_Model_Extension
601
-         *
602
-         * @param EE_Model_Field_Base[] $_fields
603
-         */
604
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
605
-        $this->_invalidate_field_caches();
606
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
607
-            if (! array_key_exists($table_alias, $this->_tables)) {
608
-                throw new EE_Error(
609
-                    sprintf(
610
-                        esc_html__(
611
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
-                            'event_espresso'
613
-                        ),
614
-                        $table_alias,
615
-                        implode(",", $this->_fields)
616
-                    )
617
-                );
618
-            }
619
-            foreach ($fields_for_table as $field_name => $field_obj) {
620
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
621
-                // primary key field base has a slightly different _construct_finalize
622
-                /** @var $field_obj EE_Model_Field_Base */
623
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
624
-            }
625
-        }
626
-        // everything is related to Extra_Meta
627
-        if (get_class($this) !== 'EEM_Extra_Meta') {
628
-            // make extra meta related to everything, but don't block deleting things just
629
-            // because they have related extra meta info. For now just orphan those extra meta
630
-            // in the future we should automatically delete them
631
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
632
-        }
633
-        // and change logs
634
-        if (get_class($this) !== 'EEM_Change_Log') {
635
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
636
-        }
637
-        /**
638
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
639
-         * EE_Register_Model_Extension
640
-         *
641
-         * @param EE_Model_Relation_Base[] $_model_relations
642
-         */
643
-        $this->_model_relations = (array) apply_filters(
644
-            'FHEE__' . get_class($this) . '__construct__model_relations',
645
-            $this->_model_relations
646
-        );
647
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
648
-            /** @var $relation_obj EE_Model_Relation_Base */
649
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
650
-        }
651
-        foreach ($this->_indexes as $index_name => $index_obj) {
652
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
653
-        }
654
-        $this->set_timezone($timezone);
655
-        // finalize default where condition strategy, or set default
656
-        if (! $this->_default_where_conditions_strategy) {
657
-            // nothing was set during child constructor, so set default
658
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
659
-        }
660
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
661
-        if (! $this->_minimum_where_conditions_strategy) {
662
-            // nothing was set during child constructor, so set default
663
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
664
-        }
665
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
666
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
667
-        // to indicate to NOT set it, set it to the logical default
668
-        if ($this->_caps_slug === null) {
669
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
670
-        }
671
-        // initialize the standard cap restriction generators if none were specified by the child constructor
672
-        if (is_array($this->_cap_restriction_generators)) {
673
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
674
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
675
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
676
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
677
-                        new EE_Restriction_Generator_Protected(),
678
-                        $cap_context,
679
-                        $this
680
-                    );
681
-                }
682
-            }
683
-        }
684
-        // if there are cap restriction generators, use them to make the default cap restrictions
685
-        if (is_array($this->_cap_restriction_generators)) {
686
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
687
-                if (! $generator_object) {
688
-                    continue;
689
-                }
690
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
691
-                    throw new EE_Error(
692
-                        sprintf(
693
-                            esc_html__(
694
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
695
-                                'event_espresso'
696
-                            ),
697
-                            $context,
698
-                            $this->get_this_model_name()
699
-                        )
700
-                    );
701
-                }
702
-                $action = $this->cap_action_for_context($context);
703
-                if (! $generator_object->construction_finalized()) {
704
-                    $generator_object->_construct_finalize($this, $action);
705
-                }
706
-            }
707
-        }
708
-        do_action('AHEE__' . get_class($this) . '__construct__end');
709
-    }
710
-
711
-
712
-    /**
713
-     * @return LoaderInterface
714
-     * @throws InvalidArgumentException
715
-     * @throws InvalidDataTypeException
716
-     * @throws InvalidInterfaceException
717
-     */
718
-    protected static function getLoader(): LoaderInterface
719
-    {
720
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
721
-            EEM_Base::$loader = LoaderFactory::getLoader();
722
-        }
723
-        return EEM_Base::$loader;
724
-    }
725
-
726
-
727
-    /**
728
-     * @return Mirror
729
-     * @since   5.0.0.p
730
-     */
731
-    private static function getMirror(): Mirror
732
-    {
733
-        if (! EEM_Base::$mirror instanceof Mirror) {
734
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
735
-        }
736
-        return EEM_Base::$mirror;
737
-    }
738
-
739
-
740
-    /**
741
-     * @param string $model_class_Name
742
-     * @param string $timezone
743
-     * @return array
744
-     * @throws ReflectionException
745
-     * @since   5.0.0.p
746
-     */
747
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
748
-    {
749
-        $arguments = [$timezone];
750
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
751
-        if (count($params) > 1) {
752
-            if ($params[1]->getName() === 'model_field_factory') {
753
-                $arguments = [
754
-                    $timezone,
755
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
756
-                ];
757
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
758
-                $arguments = [
759
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
760
-                    $timezone,
761
-                ];
762
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
763
-                $arguments = [
764
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
765
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
766
-                    $timezone,
767
-                ];
768
-            }
769
-        }
770
-        return $arguments;
771
-    }
772
-
773
-
774
-    /**
775
-     * This function is a singleton method used to instantiate the Espresso_model object
776
-     *
777
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
778
-     *                                (and any incoming timezone data that gets saved).
779
-     *                                Note this just sends the timezone info to the date time model field objects.
780
-     *                                Default is NULL
781
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
782
-     * @return static (as in the concrete child class)
783
-     * @throws EE_Error
784
-     * @throws ReflectionException
785
-     */
786
-    public static function instance($timezone = null)
787
-    {
788
-        // check if instance of Espresso_model already exists
789
-        if (! static::$_instance instanceof static) {
790
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
791
-            $model     = new static(...$arguments);
792
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
793
-            static::$_instance = $model;
794
-        }
795
-        // we might have a timezone set, let set_timezone decide what to do with it
796
-        if ($timezone) {
797
-            static::$_instance->set_timezone($timezone);
798
-        }
799
-        // Espresso_model object
800
-        return static::$_instance;
801
-    }
802
-
803
-
804
-    /**
805
-     * resets the model and returns it
806
-     *
807
-     * @param string|null $timezone
808
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
809
-     * all its properties reset; if it wasn't instantiated, returns null)
810
-     * @throws EE_Error
811
-     * @throws ReflectionException
812
-     * @throws InvalidArgumentException
813
-     * @throws InvalidDataTypeException
814
-     * @throws InvalidInterfaceException
815
-     */
816
-    public static function reset($timezone = null)
817
-    {
818
-        if (! static::$_instance instanceof EEM_Base) {
819
-            return null;
820
-        }
821
-        // Let's NOT swap out the current instance for a new one
822
-        // because if someone has a reference to it, we can't remove their reference.
823
-        // It's best to keep using the same reference but change the original object instead,
824
-        // so reset all its properties to their original values as defined in the class.
825
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
826
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
827
-            // don't set instance to null like it was originally,
828
-            // but it's static anyways, and we're ignoring static properties (for now at least)
829
-            if (! isset($static_properties[ $property ])) {
830
-                static::$_instance->{$property} = $value;
831
-            }
832
-        }
833
-        // and then directly call its constructor again, like we would if we were creating a new one
834
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
835
-        static::$_instance->__construct(...$arguments);
836
-        return self::instance();
837
-    }
838
-
839
-
840
-    /**
841
-     * Used to set the $_model_query_blog_id static property.
842
-     *
843
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
844
-     *                      value for get_current_blog_id() will be used.
845
-     */
846
-    public static function set_model_query_blog_id($blog_id = 0)
847
-    {
848
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
849
-            ? (int) $blog_id
850
-            : get_current_blog_id();
851
-    }
852
-
853
-
854
-    /**
855
-     * Returns whatever is set as the internal $model_query_blog_id.
856
-     *
857
-     * @return int
858
-     */
859
-    public static function get_model_query_blog_id()
860
-    {
861
-        return EEM_Base::$_model_query_blog_id;
862
-    }
863
-
864
-
865
-    /**
866
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
867
-     *
868
-     * @param boolean $translated return localized strings or JUST the array.
869
-     * @return array
870
-     * @throws EE_Error
871
-     * @throws InvalidArgumentException
872
-     * @throws InvalidDataTypeException
873
-     * @throws InvalidInterfaceException
874
-     * @throws ReflectionException
875
-     */
876
-    public function status_array($translated = false)
877
-    {
878
-        if (! array_key_exists('Status', $this->_model_relations)) {
879
-            return [];
880
-        }
881
-        $model_name   = $this->get_this_model_name();
882
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
883
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884
-        $status_array = [];
885
-        foreach ($stati as $status) {
886
-            $status_array[ $status->ID() ] = $status->get('STS_code');
887
-        }
888
-        return $translated
889
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
890
-            : $status_array;
891
-    }
892
-
893
-
894
-    /**
895
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
896
-     *
897
-     * @param array $query_params             @see
898
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
899
-     *                                        or if you have the development copy of EE you can view this at the path:
900
-     *                                        /docs/G--Model-System/model-query-params.md
901
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
902
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
903
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
904
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
905
-     *                                        EEM_Transaction::instance()->get_all( array( array(
906
-     *                                        'OR'=>array(
907
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
908
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
909
-     *                                        )
910
-     *                                        ),
911
-     *                                        'limit'=>10,
912
-     *                                        'group_by'=>'TXN_ID'
913
-     *                                        ));
914
-     *                                        get all the answers to the question titled "shirt size" for event with id
915
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
916
-     *                                        'Question.QST_display_text'=>'shirt size',
917
-     *                                        'Registration.Event.EVT_ID'=>12
918
-     *                                        ),
919
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
920
-     *                                        ));
921
-     * @throws EE_Error
922
-     * @throws ReflectionException
923
-     */
924
-    public function get_all($query_params = [])
925
-    {
926
-        if (
927
-            isset($query_params['limit'])
928
-            && ! isset($query_params['group_by'])
929
-        ) {
930
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
931
-        }
932
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
933
-    }
934
-
935
-
936
-    /**
937
-     * Modifies the query parameters so we only get back model objects
938
-     * that "belong" to the current user
939
-     *
940
-     * @param array $query_params @see
941
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
942
-     * @return array @see
943
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
944
-     * @throws ReflectionException
945
-     * @throws ReflectionException
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = [])
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-    /**
958
-     * Returns the name of the field's name that points to the WP_User table
959
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
960
-     * foreign key to the WP_User table)
961
-     *
962
-     * @return string|boolean string on success, boolean false when there is no
963
-     * foreign key to the WP_User table
964
-     * @throws ReflectionException
965
-     * @throws ReflectionException
966
-     */
967
-    public function wp_user_field_name()
968
-    {
969
-        try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
971
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
-                $last_model_name              = end($models_to_follow_to_wp_users);
973
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
975
-            } else {
976
-                $model_with_fk_to_wp_users = $this;
977
-                $model_chain_to_wp_user    = '';
978
-            }
979
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
981
-        } catch (EE_Error $e) {
982
-            return false;
983
-        }
984
-    }
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1005
-     * like how registrations don't have a foreign key to wp_users, but the
1006
-     * events they are for are), or is unrelated to wp users.
1007
-     * generally available
1008
-     *
1009
-     * @return boolean
1010
-     */
1011
-    public function is_owned()
1012
-    {
1013
-        if ($this->model_chain_to_wp_user()) {
1014
-            return true;
1015
-        }
1016
-        try {
1017
-            $this->get_foreign_key_to('WP_User');
1018
-            return true;
1019
-        } catch (EE_Error $e) {
1020
-            return false;
1021
-        }
1022
-    }
1023
-
1024
-
1025
-    /**
1026
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1027
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1028
-     * the model)
1029
-     *
1030
-     * @param array  $query_params      @see
1031
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1032
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1033
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1034
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1035
-     *                                  override this and set the select to "*", or a specific column name, like
1036
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1037
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1038
-     *                                  the aliases used to refer to this selection, and values are to be
1039
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1040
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1041
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1042
-     * @throws EE_Error
1043
-     * @throws InvalidArgumentException
1044
-     */
1045
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1046
-    {
1047
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1048
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1049
-        $select_expressions       = $columns_to_select === null
1050
-            ? $this->_construct_default_select_sql($model_query_info)
1051
-            : '';
1052
-        if ($this->_custom_selections instanceof CustomSelects) {
1053
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1054
-            $select_expressions .= $select_expressions
1055
-                ? ', ' . $custom_expressions
1056
-                : $custom_expressions;
1057
-        }
1058
-
1059
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1060
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1066
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1067
-     * method of including extra select information.
1068
-     *
1069
-     * @param array             $query_params
1070
-     * @param null|array|string $columns_to_select
1071
-     * @return null|CustomSelects
1072
-     * @throws InvalidArgumentException
1073
-     */
1074
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1075
-    {
1076
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1077
-            return null;
1078
-        }
1079
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1080
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1081
-        return new CustomSelects($selects);
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1087
-     * but you can use the model query params to more easily
1088
-     * take care of joins, field preparation etc.
1089
-     *
1090
-     * @param array  $query_params      @see
1091
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1092
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1093
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1094
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1095
-     *                                  override this and set the select to "*", or a specific column name, like
1096
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1097
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1098
-     *                                  the aliases used to refer to this selection, and values are to be
1099
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1100
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1101
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1105
-    {
1106
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * For creating a custom select statement
1112
-     *
1113
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1114
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1115
-     *                                 SQL, and 1=>is the datatype
1116
-     * @return string
1117
-     * @throws EE_Error
1118
-     */
1119
-    private function _construct_select_from_input($columns_to_select)
1120
-    {
1121
-        if (is_array($columns_to_select)) {
1122
-            $select_sql_array = [];
1123
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1124
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1125
-                    throw new EE_Error(
1126
-                        sprintf(
1127
-                            esc_html__(
1128
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1129
-                                'event_espresso'
1130
-                            ),
1131
-                            $selection_and_datatype,
1132
-                            $alias
1133
-                        )
1134
-                    );
1135
-                }
1136
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            esc_html__(
1140
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype[1],
1144
-                            $selection_and_datatype[0],
1145
-                            $alias,
1146
-                            implode(', ', $this->_valid_wpdb_data_types)
1147
-                        )
1148
-                    );
1149
-                }
1150
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1151
-            }
1152
-            $columns_to_select_string = implode(', ', $select_sql_array);
1153
-        } else {
1154
-            $columns_to_select_string = $columns_to_select;
1155
-        }
1156
-        return $columns_to_select_string;
1157
-    }
1158
-
1159
-
1160
-    /**
1161
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1162
-     *
1163
-     * @return string
1164
-     * @throws EE_Error
1165
-     */
1166
-    public function primary_key_name()
1167
-    {
1168
-        return $this->get_primary_key_field()->get_name();
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1174
-     * If there is no primary key on this model, $id is treated as primary key string
1175
-     *
1176
-     * @param mixed $id int or string, depending on the type of the model's primary key
1177
-     * @return EE_Base_Class|mixed|null
1178
-     * @throws EE_Error
1179
-     * @throws ReflectionException
1180
-     */
1181
-    public function get_one_by_ID($id)
1182
-    {
1183
-        if ($this->get_from_entity_map($id)) {
1184
-            return $this->get_from_entity_map($id);
1185
-        }
1186
-        $model_object = $this->get_one(
1187
-            $this->alter_query_params_to_restrict_by_ID(
1188
-                $id,
1189
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1190
-            )
1191
-        );
1192
-        $className    = $this->_get_class_name();
1193
-        if ($model_object instanceof $className) {
1194
-            // make sure valid objects get added to the entity map
1195
-            // so that the next call to this method doesn't trigger another trip to the db
1196
-            $this->add_to_entity_map($model_object);
1197
-        }
1198
-        return $model_object;
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * Alters query parameters to only get items with this ID are returned.
1204
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1205
-     * or could just be a simple primary key ID
1206
-     *
1207
-     * @param int   $id
1208
-     * @param array $query_params
1209
-     * @return array of normal query params, @see
1210
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1211
-     * @throws EE_Error
1212
-     */
1213
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1214
-    {
1215
-        if (! isset($query_params[0])) {
1216
-            $query_params[0] = [];
1217
-        }
1218
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1219
-        if ($conditions_from_id === null) {
1220
-            $query_params[0][ $this->primary_key_name() ] = $id;
1221
-        } else {
1222
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1223
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1224
-        }
1225
-        return $query_params;
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1231
-     * array. If no item is found, null is returned.
1232
-     *
1233
-     * @param array $query_params like EEM_Base's $query_params variable.
1234
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1235
-     * @throws EE_Error
1236
-     */
1237
-    public function get_one($query_params = [])
1238
-    {
1239
-        if (! is_array($query_params)) {
1240
-            EE_Error::doing_it_wrong(
1241
-                'EEM_Base::get_one',
1242
-                sprintf(
1243
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
-                    gettype($query_params)
1245
-                ),
1246
-                '4.6.0'
1247
-            );
1248
-            $query_params = [];
1249
-        }
1250
-        $query_params['limit'] = 1;
1251
-        $items                 = $this->get_all($query_params);
1252
-        if (empty($items)) {
1253
-            return null;
1254
-        }
1255
-        return array_shift($items);
1256
-    }
1257
-
1258
-
1259
-    /**
1260
-     * Returns the next x number of items in sequence from the given value as
1261
-     * found in the database matching the given query conditions.
1262
-     *
1263
-     * @param mixed $current_field_value    Value used for the reference point.
1264
-     * @param null  $field_to_order_by      What field is used for the
1265
-     *                                      reference point.
1266
-     * @param int   $limit                  How many to return.
1267
-     * @param array $query_params           Extra conditions on the query.
1268
-     * @param null  $columns_to_select      If left null, then an array of
1269
-     *                                      EE_Base_Class objects is returned,
1270
-     *                                      otherwise you can indicate just the
1271
-     *                                      columns you want returned.
1272
-     * @return EE_Base_Class[]|array
1273
-     * @throws EE_Error
1274
-     */
1275
-    public function next_x(
1276
-        $current_field_value,
1277
-        $field_to_order_by = null,
1278
-        $limit = 1,
1279
-        $query_params = [],
1280
-        $columns_to_select = null
1281
-    ) {
1282
-        return $this->_get_consecutive(
1283
-            $current_field_value,
1284
-            '>',
1285
-            $field_to_order_by,
1286
-            $limit,
1287
-            $query_params,
1288
-            $columns_to_select
1289
-        );
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * Returns the previous x number of items in sequence from the given value
1295
-     * as found in the database matching the given query conditions.
1296
-     *
1297
-     * @param mixed $current_field_value    Value used for the reference point.
1298
-     * @param null  $field_to_order_by      What field is used for the
1299
-     *                                      reference point.
1300
-     * @param int   $limit                  How many to return.
1301
-     * @param array $query_params           Extra conditions on the query.
1302
-     * @param null  $columns_to_select      If left null, then an array of
1303
-     *                                      EE_Base_Class objects is returned,
1304
-     *                                      otherwise you can indicate just the
1305
-     *                                      columns you want returned.
1306
-     * @return EE_Base_Class[]|array
1307
-     * @throws EE_Error
1308
-     */
1309
-    public function previous_x(
1310
-        $current_field_value,
1311
-        $field_to_order_by = null,
1312
-        $limit = 1,
1313
-        $query_params = [],
1314
-        $columns_to_select = null
1315
-    ) {
1316
-        return $this->_get_consecutive(
1317
-            $current_field_value,
1318
-            '<',
1319
-            $field_to_order_by,
1320
-            $limit,
1321
-            $query_params,
1322
-            $columns_to_select
1323
-        );
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * Returns the next item in sequence from the given value as found in the
1329
-     * database matching the given query conditions.
1330
-     *
1331
-     * @param mixed $current_field_value    Value used for the reference point.
1332
-     * @param null  $field_to_order_by      What field is used for the
1333
-     *                                      reference point.
1334
-     * @param array $query_params           Extra conditions on the query.
1335
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
-     *                                      object is returned, otherwise you
1337
-     *                                      can indicate just the columns you
1338
-     *                                      want and a single array indexed by
1339
-     *                                      the columns will be returned.
1340
-     * @return EE_Base_Class|null|array()
1341
-     * @throws EE_Error
1342
-     */
1343
-    public function next(
1344
-        $current_field_value,
1345
-        $field_to_order_by = null,
1346
-        $query_params = [],
1347
-        $columns_to_select = null
1348
-    ) {
1349
-        $results = $this->_get_consecutive(
1350
-            $current_field_value,
1351
-            '>',
1352
-            $field_to_order_by,
1353
-            1,
1354
-            $query_params,
1355
-            $columns_to_select
1356
-        );
1357
-        return empty($results) ? null : reset($results);
1358
-    }
1359
-
1360
-
1361
-    /**
1362
-     * Returns the previous item in sequence from the given value as found in
1363
-     * the database matching the given query conditions.
1364
-     *
1365
-     * @param mixed $current_field_value    Value used for the reference point.
1366
-     * @param null  $field_to_order_by      What field is used for the
1367
-     *                                      reference point.
1368
-     * @param array $query_params           Extra conditions on the query.
1369
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
-     *                                      object is returned, otherwise you
1371
-     *                                      can indicate just the columns you
1372
-     *                                      want and a single array indexed by
1373
-     *                                      the columns will be returned.
1374
-     * @return EE_Base_Class|null|array()
1375
-     * @throws EE_Error
1376
-     */
1377
-    public function previous(
1378
-        $current_field_value,
1379
-        $field_to_order_by = null,
1380
-        $query_params = [],
1381
-        $columns_to_select = null
1382
-    ) {
1383
-        $results = $this->_get_consecutive(
1384
-            $current_field_value,
1385
-            '<',
1386
-            $field_to_order_by,
1387
-            1,
1388
-            $query_params,
1389
-            $columns_to_select
1390
-        );
1391
-        return empty($results) ? null : reset($results);
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * Returns the a consecutive number of items in sequence from the given
1397
-     * value as found in the database matching the given query conditions.
1398
-     *
1399
-     * @param mixed  $current_field_value   Value used for the reference point.
1400
-     * @param string $operand               What operand is used for the sequence.
1401
-     * @param string $field_to_order_by     What field is used for the reference point.
1402
-     * @param int    $limit                 How many to return.
1403
-     * @param array  $query_params          Extra conditions on the query.
1404
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1405
-     *                                      otherwise you can indicate just the columns you want returned.
1406
-     * @return EE_Base_Class[]|array
1407
-     * @throws EE_Error
1408
-     */
1409
-    protected function _get_consecutive(
1410
-        $current_field_value,
1411
-        $operand = '>',
1412
-        $field_to_order_by = null,
1413
-        $limit = 1,
1414
-        $query_params = [],
1415
-        $columns_to_select = null
1416
-    ) {
1417
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1418
-        if (empty($field_to_order_by)) {
1419
-            if ($this->has_primary_key_field()) {
1420
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1421
-            } else {
1422
-                if (WP_DEBUG) {
1423
-                    throw new EE_Error(
1424
-                        esc_html__(
1425
-                            'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1426
-                            'event_espresso'
1427
-                        )
1428
-                    );
1429
-                }
1430
-                EE_Error::add_error(
1431
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1432
-                    __FILE__,
1433
-                    __FUNCTION__,
1434
-                    __LINE__
1435
-                );
1436
-                return [];
1437
-            }
1438
-        }
1439
-        if (! is_array($query_params)) {
1440
-            EE_Error::doing_it_wrong(
1441
-                'EEM_Base::_get_consecutive',
1442
-                sprintf(
1443
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1444
-                    gettype($query_params)
1445
-                ),
1446
-                '4.6.0'
1447
-            );
1448
-            $query_params = [];
1449
-        }
1450
-        // let's add the where query param for consecutive look up.
1451
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1452
-        $query_params['limit']                 = $limit;
1453
-        // set direction
1454
-        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1455
-        $query_params['order_by'] = $operand === '>'
1456
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1457
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1458
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1459
-        if (empty($columns_to_select)) {
1460
-            return $this->get_all($query_params);
1461
-        }
1462
-        // getting just the fields
1463
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This sets the _timezone property after model object has been instantiated.
1469
-     *
1470
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1471
-     */
1472
-    public function set_timezone($timezone)
1473
-    {
1474
-        if ($timezone !== null) {
1475
-            $this->_timezone = $timezone;
1476
-        }
1477
-        // note we need to loop through relations and set the timezone on those objects as well.
1478
-        foreach ($this->_model_relations as $relation) {
1479
-            $relation->set_timezone($timezone);
1480
-        }
1481
-        // and finally we do the same for any datetime fields
1482
-        foreach ($this->_fields as $field) {
1483
-            if ($field instanceof EE_Datetime_Field) {
1484
-                $field->set_timezone($timezone);
1485
-            }
1486
-        }
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * This just returns whatever is set for the current timezone.
1492
-     *
1493
-     * @access public
1494
-     * @return string
1495
-     */
1496
-    public function get_timezone()
1497
-    {
1498
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1499
-        if (empty($this->_timezone)) {
1500
-            foreach ($this->_fields as $field) {
1501
-                if ($field instanceof EE_Datetime_Field) {
1502
-                    $this->set_timezone($field->get_timezone());
1503
-                    break;
1504
-                }
1505
-            }
1506
-        }
1507
-        // if timezone STILL empty then return the default timezone for the site.
1508
-        if (empty($this->_timezone)) {
1509
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1510
-        }
1511
-        return $this->_timezone;
1512
-    }
1513
-
1514
-
1515
-    /**
1516
-     * This returns the date formats set for the given field name and also ensures that
1517
-     * $this->_timezone property is set correctly.
1518
-     *
1519
-     * @param string $field_name The name of the field the formats are being retrieved for.
1520
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1521
-     * @return array formats in an array with the date format first, and the time format last.
1522
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1523
-     * @since 4.6.x
1524
-     */
1525
-    public function get_formats_for($field_name, $pretty = false)
1526
-    {
1527
-        $field_settings = $this->field_settings_for($field_name);
1528
-        // if not a valid EE_Datetime_Field then throw error
1529
-        if (! $field_settings instanceof EE_Datetime_Field) {
1530
-            throw new EE_Error(
1531
-                sprintf(
1532
-                    esc_html__(
1533
-                        'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1534
-                        'event_espresso'
1535
-                    ),
1536
-                    $field_name
1537
-                )
1538
-            );
1539
-        }
1540
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1541
-        // the field.
1542
-        $this->_timezone = $field_settings->get_timezone();
1543
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1544
-    }
1545
-
1546
-
1547
-    /**
1548
-     * This returns the current time in a format setup for a query on this model.
1549
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1550
-     * it will return:
1551
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1552
-     *  NOW
1553
-     *  - or a unix timestamp (equivalent to time())
1554
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1555
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1556
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1557
-     *
1558
-     * @param string $field_name       The field the current time is needed for.
1559
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1560
-     *                                 formatted string matching the set format for the field in the set timezone will
1561
-     *                                 be returned.
1562
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1563
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1564
-     *                                 exception is triggered.
1565
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1566
-     * @throws Exception
1567
-     * @since 4.6.x
1568
-     */
1569
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1570
-    {
1571
-        $formats  = $this->get_formats_for($field_name);
1572
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1573
-        if ($timestamp) {
1574
-            return $DateTime->format('U');
1575
-        }
1576
-        // not returning timestamp, so return formatted string in timezone.
1577
-        switch ($what) {
1578
-            case 'time':
1579
-                return $DateTime->format($formats[1]);
1580
-            case 'date':
1581
-                return $DateTime->format($formats[0]);
1582
-            default:
1583
-                return $DateTime->format(implode(' ', $formats));
1584
-        }
1585
-    }
1586
-
1587
-
1588
-    /**
1589
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1590
-     * for the model are.  Returns a DateTime object.
1591
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1592
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1593
-     * ignored.
1594
-     *
1595
-     * @param string $field_name      The field being setup.
1596
-     * @param string $timestring      The date time string being used.
1597
-     * @param string $incoming_format The format for the time string.
1598
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1599
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1600
-     *                                format is
1601
-     *                                'U', this is ignored.
1602
-     * @return DateTime
1603
-     * @throws EE_Error
1604
-     */
1605
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1606
-    {
1607
-        // just using this to ensure the timezone is set correctly internally
1608
-        $this->get_formats_for($field_name);
1609
-        // load EEH_DTT_Helper
1610
-        $set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1611
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1612
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1613
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1614
-    }
1615
-
1616
-
1617
-    /**
1618
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1619
-     *
1620
-     * @return EE_Table_Base[]
1621
-     */
1622
-    public function get_tables()
1623
-    {
1624
-        return $this->_tables;
1625
-    }
1626
-
1627
-
1628
-    /**
1629
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1630
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1631
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1632
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1633
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1634
-     * model object with EVT_ID = 1
1635
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1636
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1637
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1638
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1639
-     * are not specified)
1640
-     *
1641
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1642
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1643
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1644
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1645
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1646
-     *                                         ID=34, we'd use this method as follows:
1647
-     *                                         EEM_Transaction::instance()->update(
1648
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1649
-     *                                         array(array('TXN_ID'=>34)));
1650
-     * @param array   $query_params            @see
1651
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1652
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1653
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1654
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1655
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1656
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1657
-     *                                         TRUE, it is assumed that you've already called
1658
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1659
-     *                                         malicious javascript. However, if
1660
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1661
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1662
-     *                                         and every other field, before insertion. We provide this parameter
1663
-     *                                         because model objects perform their prepare_for_set function on all
1664
-     *                                         their values, and so don't need to be called again (and in many cases,
1665
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1666
-     *                                         prepare_for_set method...)
1667
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1668
-     *                                         in this model's entity map according to $fields_n_values that match
1669
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1670
-     *                                         by setting this to FALSE, but be aware that model objects being used
1671
-     *                                         could get out-of-sync with the database
1672
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1673
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1674
-     *                                         bad)
1675
-     * @throws EE_Error
1676
-     * @throws ReflectionException
1677
-     */
1678
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1679
-    {
1680
-        if (! is_array($query_params)) {
1681
-            EE_Error::doing_it_wrong(
1682
-                'EEM_Base::update',
1683
-                sprintf(
1684
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1685
-                    gettype($query_params)
1686
-                ),
1687
-                '4.6.0'
1688
-            );
1689
-            $query_params = [];
1690
-        }
1691
-        /**
1692
-         * Action called before a model update call has been made.
1693
-         *
1694
-         * @param EEM_Base $model
1695
-         * @param array    $fields_n_values the updated fields and their new values
1696
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1697
-         */
1698
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1699
-        /**
1700
-         * Filters the fields about to be updated given the query parameters. You can provide the
1701
-         * $query_params to $this->get_all() to find exactly which records will be updated
1702
-         *
1703
-         * @param array    $fields_n_values fields and their new values
1704
-         * @param EEM_Base $model           the model being queried
1705
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1706
-         */
1707
-        $fields_n_values = (array) apply_filters(
1708
-            'FHEE__EEM_Base__update__fields_n_values',
1709
-            $fields_n_values,
1710
-            $this,
1711
-            $query_params
1712
-        );
1713
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1714
-        // to do that, for each table, verify that it's PK isn't null.
1715
-        $tables = $this->get_tables();
1716
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1717
-        // NOTE: we should make this code more efficient by NOT querying twice
1718
-        // before the real update, but that needs to first go through ALPHA testing
1719
-        // as it's dangerous. says Mike August 8 2014
1720
-        // we want to make sure the default_where strategy is ignored
1721
-        $this->_ignore_where_strategy = true;
1722
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1723
-        foreach ($wpdb_select_results as $wpdb_result) {
1724
-            // type cast stdClass as array
1725
-            $wpdb_result = (array) $wpdb_result;
1726
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1727
-            if ($this->has_primary_key_field()) {
1728
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1729
-            } else {
1730
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1731
-                $main_table_pk_value = null;
1732
-            }
1733
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1734
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1735
-            if (count($tables) > 1) {
1736
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1737
-                // in that table, and so we'll want to insert one
1738
-                foreach ($tables as $table_obj) {
1739
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1740
-                    // if there is no private key for this table on the results, it means there's no entry
1741
-                    // in this table, right? so insert a row in the current table, using any fields available
1742
-                    if (
1743
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1744
-                           && $wpdb_result[ $this_table_pk_column ])
1745
-                    ) {
1746
-                        $success = $this->_insert_into_specific_table(
1747
-                            $table_obj,
1748
-                            $fields_n_values,
1749
-                            $main_table_pk_value
1750
-                        );
1751
-                        // if we died here, report the error
1752
-                        if (! $success) {
1753
-                            return false;
1754
-                        }
1755
-                    }
1756
-                }
1757
-            }
1758
-            //              //and now check that if we have cached any models by that ID on the model, that
1759
-            //              //they also get updated properly
1760
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1761
-            //              if( $model_object ){
1762
-            //                  foreach( $fields_n_values as $field => $value ){
1763
-            //                      $model_object->set($field, $value);
1764
-            // let's make sure default_where strategy is followed now
1765
-            $this->_ignore_where_strategy = false;
1766
-        }
1767
-        // if we want to keep model objects in sync, AND
1768
-        // if this wasn't called from a model object (to update itself)
1769
-        // then we want to make sure we keep all the existing
1770
-        // model objects in sync with the db
1771
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1772
-            if ($this->has_primary_key_field()) {
1773
-                $model_objs_affected_ids = $this->get_col($query_params);
1774
-            } else {
1775
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1776
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1777
-                $model_objs_affected_ids     = [];
1778
-                foreach ($models_affected_key_columns as $row) {
1779
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1780
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1781
-                }
1782
-            }
1783
-            if (! $model_objs_affected_ids) {
1784
-                // wait wait wait- if nothing was affected let's stop here
1785
-                return 0;
1786
-            }
1787
-            foreach ($model_objs_affected_ids as $id) {
1788
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1789
-                if ($model_obj_in_entity_map) {
1790
-                    foreach ($fields_n_values as $field => $new_value) {
1791
-                        $model_obj_in_entity_map->set($field, $new_value);
1792
-                    }
1793
-                }
1794
-            }
1795
-            // if there is a primary key on this model, we can now do a slight optimization
1796
-            if ($this->has_primary_key_field()) {
1797
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1798
-                $query_params = [
1799
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1800
-                    'limit'                    => count($model_objs_affected_ids),
1801
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1802
-                ];
1803
-            }
1804
-        }
1805
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1806
-        $SQL              = "UPDATE "
1807
-                            . $model_query_info->get_full_join_sql()
1808
-                            . " SET "
1809
-                            . $this->_construct_update_sql($fields_n_values)
1810
-                            . $model_query_info->get_where_sql(
1811
-                            );// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1812
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1813
-        /**
1814
-         * Action called after a model update call has been made.
1815
-         *
1816
-         * @param EEM_Base $model
1817
-         * @param array    $fields_n_values the updated fields and their new values
1818
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1819
-         * @param int      $rows_affected
1820
-         */
1821
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1822
-        return $rows_affected;// how many supposedly got updated
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1828
-     * are teh values of the field specified (or by default the primary key field)
1829
-     * that matched the query params. Note that you should pass the name of the
1830
-     * model FIELD, not the database table's column name.
1831
-     *
1832
-     * @param array  $query_params @see
1833
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1834
-     * @param string $field_to_select
1835
-     * @return array just like $wpdb->get_col()
1836
-     * @throws EE_Error
1837
-     */
1838
-    public function get_col($query_params = [], $field_to_select = null)
1839
-    {
1840
-        if ($field_to_select) {
1841
-            $field = $this->field_settings_for($field_to_select);
1842
-        } elseif ($this->has_primary_key_field()) {
1843
-            $field = $this->get_primary_key_field();
1844
-        } else {
1845
-            $field_settings = $this->field_settings();
1846
-            // no primary key, just grab the first column
1847
-            $field = reset($field_settings);
1848
-            // don't need this array now
1849
-            unset($field_settings);
1850
-        }
1851
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1852
-        $select_expressions = $field->get_qualified_column();
1853
-        $SQL                =
1854
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1855
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1856
-    }
1857
-
1858
-
1859
-    /**
1860
-     * Returns a single column value for a single row from the database
1861
-     *
1862
-     * @param array  $query_params    @see
1863
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1864
-     * @param string $field_to_select @see EEM_Base::get_col()
1865
-     * @return string
1866
-     * @throws EE_Error
1867
-     */
1868
-    public function get_var($query_params = [], $field_to_select = null)
1869
-    {
1870
-        $query_params['limit'] = 1;
1871
-        $col                   = $this->get_col($query_params, $field_to_select);
1872
-        if (! empty($col)) {
1873
-            return reset($col);
1874
-        }
1875
-        return null;
1876
-    }
1877
-
1878
-
1879
-    /**
1880
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1881
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1882
-     * injection, but currently no further filtering is done
1883
-     *
1884
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1885
-     *                               be updated to in the DB
1886
-     * @return string of SQL
1887
-     * @throws EE_Error
1888
-     * @global      $wpdb
1889
-     */
1890
-    public function _construct_update_sql($fields_n_values)
1891
-    {
1892
-        /** @type WPDB $wpdb */
1893
-        global $wpdb;
1894
-        $cols_n_values = [];
1895
-        foreach ($fields_n_values as $field_name => $value) {
1896
-            $field_obj = $this->field_settings_for($field_name);
1897
-            // if the value is NULL, we want to assign the value to that.
1898
-            // wpdb->prepare doesn't really handle that properly
1899
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1900
-            $value_sql       = $prepared_value === null ? 'NULL'
1901
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1902
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1903
-        }
1904
-        return implode(",", $cols_n_values);
1905
-    }
1906
-
1907
-
1908
-    /**
1909
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
-     * Performs a HARD delete, meaning the database row should always be removed,
1911
-     * not just have a flag field on it switched
1912
-     * Wrapper for EEM_Base::delete_permanently()
1913
-     *
1914
-     * @param mixed   $id
1915
-     * @param boolean $allow_blocking
1916
-     * @return int the number of rows deleted
1917
-     * @throws EE_Error
1918
-     * @throws ReflectionException
1919
-     */
1920
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1921
-    {
1922
-        return $this->delete_permanently(
1923
-            [
1924
-                [$this->get_primary_key_field()->get_name() => $id],
1925
-                'limit' => 1,
1926
-            ],
1927
-            $allow_blocking
1928
-        );
1929
-    }
1930
-
1931
-
1932
-    /**
1933
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1934
-     * Wrapper for EEM_Base::delete()
1935
-     *
1936
-     * @param mixed   $id
1937
-     * @param boolean $allow_blocking
1938
-     * @return int the number of rows deleted
1939
-     * @throws EE_Error
1940
-     */
1941
-    public function delete_by_ID($id, $allow_blocking = true)
1942
-    {
1943
-        return $this->delete(
1944
-            [
1945
-                [$this->get_primary_key_field()->get_name() => $id],
1946
-                'limit' => 1,
1947
-            ],
1948
-            $allow_blocking
1949
-        );
1950
-    }
1951
-
1952
-
1953
-    /**
1954
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1955
-     * meaning if the model has a field that indicates its been "trashed" or
1956
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1957
-     *
1958
-     * @param array   $query_params
1959
-     * @param boolean $allow_blocking
1960
-     * @return int how many rows got deleted
1961
-     * @throws EE_Error
1962
-     * @throws ReflectionException
1963
-     * @see EEM_Base::delete_permanently
1964
-     */
1965
-    public function delete($query_params, $allow_blocking = true)
1966
-    {
1967
-        return $this->delete_permanently($query_params, $allow_blocking);
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1973
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1974
-     * as archived, not actually deleted
1975
-     *
1976
-     * @param array   $query_params   @see
1977
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1978
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1979
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1980
-     *                                deletes regardless of other objects which may depend on it. Its generally
1981
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1982
-     *                                DB
1983
-     * @return int how many rows got deleted
1984
-     * @throws EE_Error
1985
-     * @throws ReflectionException
1986
-     */
1987
-    public function delete_permanently($query_params, $allow_blocking = true)
1988
-    {
1989
-        /**
1990
-         * Action called just before performing a real deletion query. You can use the
1991
-         * model and its $query_params to find exactly which items will be deleted
1992
-         *
1993
-         * @param EEM_Base $model
1994
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1995
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1996
-         *                                 to block (prevent) this deletion
1997
-         */
1998
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1999
-        // some MySQL databases may be running safe mode, which may restrict
2000
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2001
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2002
-        // to delete them
2003
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2004
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2005
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2006
-            $columns_and_ids_for_deleting
2007
-        );
2008
-        /**
2009
-         * Allows client code to act on the items being deleted before the query is actually executed.
2010
-         *
2011
-         * @param EEM_Base $this                            The model instance being acted on.
2012
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2013
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2014
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2015
-         *                                                  derived from the incoming query parameters.
2016
-         * @see details on the structure of this array in the phpdocs
2017
-         *                                                  for the `_get_ids_for_delete_method`
2018
-         *
2019
-         */
2020
-        do_action(
2021
-            'AHEE__EEM_Base__delete__before_query',
2022
-            $this,
2023
-            $query_params,
2024
-            $allow_blocking,
2025
-            $columns_and_ids_for_deleting
2026
-        );
2027
-        if ($deletion_where_query_part) {
2028
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2029
-            $table_aliases    = array_keys($this->_tables);
2030
-            $SQL              = "DELETE "
2031
-                                . implode(", ", $table_aliases)
2032
-                                . " FROM "
2033
-                                . $model_query_info->get_full_join_sql()
2034
-                                . " WHERE "
2035
-                                . $deletion_where_query_part;
2036
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2037
-        } else {
2038
-            $rows_deleted = 0;
2039
-        }
2040
-
2041
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2042
-        // there was no error with the delete query.
2043
-        if (
2044
-            $this->has_primary_key_field()
2045
-            && $rows_deleted !== false
2046
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2047
-        ) {
2048
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2049
-            foreach ($ids_for_removal as $id) {
2050
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2051
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2052
-                }
2053
-            }
2054
-
2055
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2056
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2057
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2058
-            // (although it is possible).
2059
-            // Note this can be skipped by using the provided filter and returning false.
2060
-            if (
2061
-                apply_filters(
2062
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2063
-                    ! $this instanceof EEM_Extra_Meta,
2064
-                    $this
2065
-                )
2066
-            ) {
2067
-                EEM_Extra_Meta::instance()->delete_permanently([
2068
-                                                                   0 => [
2069
-                                                                       'EXM_type' => $this->get_this_model_name(),
2070
-                                                                       'OBJ_ID'   => [
2071
-                                                                           'IN',
2072
-                                                                           $ids_for_removal,
2073
-                                                                       ],
2074
-                                                                   ],
2075
-                                                               ]);
2076
-            }
2077
-        }
2078
-
2079
-        /**
2080
-         * Action called just after performing a real deletion query. Although at this point the
2081
-         * items should have been deleted
2082
-         *
2083
-         * @param EEM_Base $model
2084
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2085
-         * @param int      $rows_deleted
2086
-         */
2087
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2088
-        return $rows_deleted;// how many supposedly got deleted
2089
-    }
2090
-
2091
-
2092
-    /**
2093
-     * Checks all the relations that throw error messages when there are blocking related objects
2094
-     * for related model objects. If there are any related model objects on those relations,
2095
-     * adds an EE_Error, and return true
2096
-     *
2097
-     * @param EE_Base_Class|int $this_model_obj_or_id
2098
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2099
-     *                                                 should be ignored when determining whether there are related
2100
-     *                                                 model objects which block this model object's deletion. Useful
2101
-     *                                                 if you know A is related to B and are considering deleting A,
2102
-     *                                                 but want to see if A has any other objects blocking its deletion
2103
-     *                                                 before removing the relation between A and B
2104
-     * @return boolean
2105
-     * @throws EE_Error
2106
-     * @throws ReflectionException
2107
-     */
2108
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2109
-    {
2110
-        // first, if $ignore_this_model_obj was supplied, get its model
2111
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2112
-            $ignored_model = $ignore_this_model_obj->get_model();
2113
-        } else {
2114
-            $ignored_model = null;
2115
-        }
2116
-        // now check all the relations of $this_model_obj_or_id and see if there
2117
-        // are any related model objects blocking it?
2118
-        $is_blocked = false;
2119
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2120
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2121
-                // if $ignore_this_model_obj was supplied, then for the query
2122
-                // on that model needs to be told to ignore $ignore_this_model_obj
2123
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2124
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2125
-                        [
2126
-                            $ignored_model->get_primary_key_field()->get_name() => [
2127
-                                '!=',
2128
-                                $ignore_this_model_obj->ID(),
2129
-                            ],
2130
-                        ],
2131
-                    ]);
2132
-                } else {
2133
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2134
-                }
2135
-                if ($related_model_objects) {
2136
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2137
-                    $is_blocked = true;
2138
-                }
2139
-            }
2140
-        }
2141
-        return $is_blocked;
2142
-    }
2143
-
2144
-
2145
-    /**
2146
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2147
-     *
2148
-     * @param array $row_results_for_deleting
2149
-     * @param bool  $allow_blocking
2150
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2151
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2152
-     *                              dimension array where the key is the fully qualified primary key column and the
2153
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2154
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2155
-     *                              be a two dimensional array where each element is a group of columns and values that
2156
-     *                              get deleted. Example: array(
2157
-     *                              0 => array(
2158
-     *                              'Term_Relationship.object_id' => 1
2159
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2160
-     *                              ),
2161
-     *                              1 => array(
2162
-     *                              'Term_Relationship.object_id' => 1
2163
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2164
-     *                              )
2165
-     *                              )
2166
-     * @throws EE_Error
2167
-     * @throws ReflectionException
2168
-     */
2169
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2170
-    {
2171
-        $ids_to_delete_indexed_by_column = [];
2172
-        if ($this->has_primary_key_field()) {
2173
-            $primary_table                   = $this->_get_main_table();
2174
-            $primary_table_pk_field          =
2175
-                $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2176
-            $other_tables                    = $this->_get_other_tables();
2177
-            $ids_to_delete_indexed_by_column = $query = [];
2178
-            foreach ($row_results_for_deleting as $item_to_delete) {
2179
-                // before we mark this item for deletion,
2180
-                // make sure there's no related entities blocking its deletion (if we're checking)
2181
-                if (
2182
-                    $allow_blocking
2183
-                    && $this->delete_is_blocked_by_related_models(
2184
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2185
-                    )
2186
-                ) {
2187
-                    continue;
2188
-                }
2189
-                // primary table deletes
2190
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2191
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2192
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2193
-                }
2194
-            }
2195
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2196
-            $fields = $this->get_combined_primary_key_fields();
2197
-            foreach ($row_results_for_deleting as $item_to_delete) {
2198
-                $ids_to_delete_indexed_by_column_for_row = [];
2199
-                foreach ($fields as $cpk_field) {
2200
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2201
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2202
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2203
-                    }
2204
-                }
2205
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2206
-            }
2207
-        } else {
2208
-            // so there's no primary key and no combined key...
2209
-            // sorry, can't help you
2210
-            throw new EE_Error(
2211
-                sprintf(
2212
-                    esc_html__(
2213
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2214
-                        "event_espresso"
2215
-                    ),
2216
-                    get_class($this)
2217
-                )
2218
-            );
2219
-        }
2220
-        return $ids_to_delete_indexed_by_column;
2221
-    }
2222
-
2223
-
2224
-    /**
2225
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2226
-     * the corresponding query_part for the query performing the delete.
2227
-     *
2228
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2229
-     * @return string
2230
-     * @throws EE_Error
2231
-     */
2232
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2233
-    {
2234
-        $query_part = '';
2235
-        if (empty($ids_to_delete_indexed_by_column)) {
2236
-            return $query_part;
2237
-        } elseif ($this->has_primary_key_field()) {
2238
-            $query = [];
2239
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2240
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2241
-            }
2242
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2243
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2244
-            $ways_to_identify_a_row = [];
2245
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2246
-                $values_for_each_combined_primary_key_for_a_row = [];
2247
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2248
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2249
-                }
2250
-                $ways_to_identify_a_row[] = '('
2251
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2252
-                                            . ')';
2253
-            }
2254
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2255
-        }
2256
-        return $query_part;
2257
-    }
2258
-
2259
-
2260
-    /**
2261
-     * Gets the model field by the fully qualified name
2262
-     *
2263
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2264
-     * @return EE_Model_Field_Base
2265
-     * @throws EE_Error
2266
-     * @throws EE_Error
2267
-     */
2268
-    public function get_field_by_column($qualified_column_name)
2269
-    {
2270
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2271
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2272
-                return $field_obj;
2273
-            }
2274
-        }
2275
-        throw new EE_Error(
2276
-            sprintf(
2277
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2278
-                $this->get_this_model_name(),
2279
-                $qualified_column_name
2280
-            )
2281
-        );
2282
-    }
2283
-
2284
-
2285
-    /**
2286
-     * Count all the rows that match criteria the model query params.
2287
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2288
-     * column
2289
-     *
2290
-     * @param array  $query_params   @see
2291
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2292
-     * @param string $field_to_count field on model to count by (not column name)
2293
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2294
-     *                               that by the setting $distinct to TRUE;
2295
-     * @return int
2296
-     * @throws EE_Error
2297
-     */
2298
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2299
-    {
2300
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2301
-        if ($field_to_count) {
2302
-            $field_obj       = $this->field_settings_for($field_to_count);
2303
-            $column_to_count = $field_obj->get_qualified_column();
2304
-        } elseif ($this->has_primary_key_field()) {
2305
-            $pk_field_obj    = $this->get_primary_key_field();
2306
-            $column_to_count = $pk_field_obj->get_qualified_column();
2307
-        } else {
2308
-            // there's no primary key
2309
-            // if we're counting distinct items, and there's no primary key,
2310
-            // we need to list out the columns for distinction;
2311
-            // otherwise we can just use star
2312
-            if ($distinct) {
2313
-                $columns_to_use = [];
2314
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2315
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2316
-                }
2317
-                $column_to_count = implode(',', $columns_to_use);
2318
-            } else {
2319
-                $column_to_count = '*';
2320
-            }
2321
-        }
2322
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2323
-        $SQL             =
2324
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2325
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2326
-    }
2327
-
2328
-
2329
-    /**
2330
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2331
-     *
2332
-     * @param array  $query_params @see
2333
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2334
-     * @param string $field_to_sum name of field (array key in $_fields array)
2335
-     * @return float
2336
-     * @throws EE_Error
2337
-     */
2338
-    public function sum($query_params, $field_to_sum = null)
2339
-    {
2340
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2341
-        if ($field_to_sum) {
2342
-            $field_obj = $this->field_settings_for($field_to_sum);
2343
-        } else {
2344
-            $field_obj = $this->get_primary_key_field();
2345
-        }
2346
-        $column_to_count = $field_obj->get_qualified_column();
2347
-        $SQL             =
2348
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2349
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2350
-        $data_type       = $field_obj->get_wpdb_data_type();
2351
-        if ($data_type === '%d' || $data_type === '%s') {
2352
-            return (float) $return_value;
2353
-        }
2354
-        // must be %f
2355
-        return (float) $return_value;
2356
-    }
2357
-
2358
-
2359
-    /**
2360
-     * Just calls the specified method on $wpdb with the given arguments
2361
-     * Consolidates a little extra error handling code
2362
-     *
2363
-     * @param string $wpdb_method
2364
-     * @param array  $arguments_to_provide
2365
-     * @return mixed
2366
-     * @throws EE_Error
2367
-     * @global wpdb  $wpdb
2368
-     */
2369
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2370
-    {
2371
-        // if we're in maintenance mode level 2, DON'T run any queries
2372
-        // because level 2 indicates the database needs updating and
2373
-        // is probably out of sync with the code
2374
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2375
-            throw new EE_Error(
2376
-                sprintf(
2377
-                    esc_html__(
2378
-                        "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2379
-                        "event_espresso"
2380
-                    )
2381
-                )
2382
-            );
2383
-        }
2384
-        /** @type WPDB $wpdb */
2385
-        global $wpdb;
2386
-        if (! method_exists($wpdb, $wpdb_method)) {
2387
-            throw new EE_Error(
2388
-                sprintf(
2389
-                    esc_html__(
2390
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2391
-                        'event_espresso'
2392
-                    ),
2393
-                    $wpdb_method
2394
-                )
2395
-            );
2396
-        }
2397
-        if (WP_DEBUG) {
2398
-            $old_show_errors_value = $wpdb->show_errors;
2399
-            $wpdb->show_errors(false);
2400
-        }
2401
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2402
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2403
-        if (WP_DEBUG) {
2404
-            $wpdb->show_errors($old_show_errors_value);
2405
-            if (! empty($wpdb->last_error)) {
2406
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2407
-            }
2408
-            if ($result === false) {
2409
-                throw new EE_Error(
2410
-                    sprintf(
2411
-                        esc_html__(
2412
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2413
-                            'event_espresso'
2414
-                        ),
2415
-                        $wpdb_method,
2416
-                        var_export($arguments_to_provide, true)
2417
-                    )
2418
-                );
2419
-            }
2420
-        } elseif ($result === false) {
2421
-            EE_Error::add_error(
2422
-                sprintf(
2423
-                    esc_html__(
2424
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2425
-                        'event_espresso'
2426
-                    ),
2427
-                    $wpdb_method,
2428
-                    var_export($arguments_to_provide, true),
2429
-                    $wpdb->last_error
2430
-                ),
2431
-                __FILE__,
2432
-                __FUNCTION__,
2433
-                __LINE__
2434
-            );
2435
-        }
2436
-        return $result;
2437
-    }
2438
-
2439
-
2440
-    /**
2441
-     * Attempts to run the indicated WPDB method with the provided arguments,
2442
-     * and if there's an error tries to verify the DB is correct. Uses
2443
-     * the static property EEM_Base::$_db_verification_level to determine whether
2444
-     * we should try to fix the EE core db, the addons, or just give up
2445
-     *
2446
-     * @param string $wpdb_method
2447
-     * @param array  $arguments_to_provide
2448
-     * @return mixed
2449
-     */
2450
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2451
-    {
2452
-        /** @type WPDB $wpdb */
2453
-        global $wpdb;
2454
-        $wpdb->last_error = null;
2455
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2456
-        // was there an error running the query? but we don't care on new activations
2457
-        // (we're going to setup the DB anyway on new activations)
2458
-        if (
2459
-            ($result === false || ! empty($wpdb->last_error))
2460
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2461
-        ) {
2462
-            switch (EEM_Base::$_db_verification_level) {
2463
-                case EEM_Base::db_verified_none:
2464
-                    // let's double-check core's DB
2465
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2466
-                    break;
2467
-                case EEM_Base::db_verified_core:
2468
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2469
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2470
-                    break;
2471
-                case EEM_Base::db_verified_addons:
2472
-                    // ummmm... you in trouble
2473
-                    return $result;
2474
-            }
2475
-            if (! empty($error_message)) {
2476
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2477
-                trigger_error($error_message);
2478
-            }
2479
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2480
-        }
2481
-        return $result;
2482
-    }
2483
-
2484
-
2485
-    /**
2486
-     * Verifies the EE core database is up-to-date and records that we've done it on
2487
-     * EEM_Base::$_db_verification_level
2488
-     *
2489
-     * @param string $wpdb_method
2490
-     * @param array  $arguments_to_provide
2491
-     * @return string
2492
-     */
2493
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2494
-    {
2495
-        /** @type WPDB $wpdb */
2496
-        global $wpdb;
2497
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2498
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2499
-        $error_message                    = sprintf(
2500
-            esc_html__(
2501
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2502
-                'event_espresso'
2503
-            ),
2504
-            $wpdb->last_error,
2505
-            $wpdb_method,
2506
-            wp_json_encode($arguments_to_provide)
2507
-        );
2508
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2509
-        return $error_message;
2510
-    }
2511
-
2512
-
2513
-    /**
2514
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2515
-     * EEM_Base::$_db_verification_level
2516
-     *
2517
-     * @param $wpdb_method
2518
-     * @param $arguments_to_provide
2519
-     * @return string
2520
-     */
2521
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2522
-    {
2523
-        /** @type WPDB $wpdb */
2524
-        global $wpdb;
2525
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2526
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2527
-        $error_message                    = sprintf(
2528
-            esc_html__(
2529
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2530
-                'event_espresso'
2531
-            ),
2532
-            $wpdb->last_error,
2533
-            $wpdb_method,
2534
-            wp_json_encode($arguments_to_provide)
2535
-        );
2536
-        EE_System::instance()->initialize_addons();
2537
-        return $error_message;
2538
-    }
2539
-
2540
-
2541
-    /**
2542
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2543
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2544
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2545
-     * ..."
2546
-     *
2547
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2548
-     * @return string
2549
-     */
2550
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2551
-    {
2552
-        return " FROM " . $model_query_info->get_full_join_sql() .
2553
-               $model_query_info->get_where_sql() .
2554
-               $model_query_info->get_group_by_sql() .
2555
-               $model_query_info->get_having_sql() .
2556
-               $model_query_info->get_order_by_sql() .
2557
-               $model_query_info->get_limit_sql();
2558
-    }
2559
-
2560
-
2561
-    /**
2562
-     * Set to easily debug the next X queries ran from this model.
2563
-     *
2564
-     * @param int $count
2565
-     */
2566
-    public function show_next_x_db_queries($count = 1)
2567
-    {
2568
-        $this->_show_next_x_db_queries = $count;
2569
-    }
2570
-
2571
-
2572
-    /**
2573
-     * @param $sql_query
2574
-     */
2575
-    public function show_db_query_if_previously_requested($sql_query)
2576
-    {
2577
-        if ($this->_show_next_x_db_queries > 0) {
2578
-            echo esc_html($sql_query);
2579
-            $this->_show_next_x_db_queries--;
2580
-        }
2581
-    }
2582
-
2583
-
2584
-    /**
2585
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2586
-     * There are the 3 cases:
2587
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2588
-     * $otherModelObject has no ID, it is first saved.
2589
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2590
-     * has no ID, it is first saved.
2591
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2592
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2593
-     * join table
2594
-     *
2595
-     * @param EE_Base_Class                     /int $thisModelObject
2596
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2597
-     * @param string $relationName                     , key in EEM_Base::_relations
2598
-     *                                                 an attendee to a group, you also want to specify which role they
2599
-     *                                                 will have in that group. So you would use this parameter to
2600
-     *                                                 specify array('role-column-name'=>'role-id')
2601
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2602
-     *                                                 to for relation to methods that allow you to further specify
2603
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2604
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2605
-     *                                                 because these will be inserted in any new rows created as well.
2606
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2607
-     * @throws EE_Error
2608
-     */
2609
-    public function add_relationship_to(
2610
-        $id_or_obj,
2611
-        $other_model_id_or_obj,
2612
-        $relationName,
2613
-        $extra_join_model_fields_n_values = []
2614
-    ) {
2615
-        $relation_obj = $this->related_settings_for($relationName);
2616
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2617
-    }
2618
-
2619
-
2620
-    /**
2621
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2622
-     * There are the 3 cases:
2623
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2624
-     * error
2625
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2626
-     * an error
2627
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2628
-     *
2629
-     * @param EE_Base_Class /int $id_or_obj
2630
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2631
-     * @param string $relationName key in EEM_Base::_relations
2632
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2633
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2634
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2635
-     *                             because these will be inserted in any new rows created as well.
2636
-     * @return boolean of success
2637
-     * @throws EE_Error
2638
-     */
2639
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2640
-    {
2641
-        $relation_obj = $this->related_settings_for($relationName);
2642
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2643
-    }
2644
-
2645
-
2646
-    /**
2647
-     * @param mixed  $id_or_obj
2648
-     * @param string $relationName
2649
-     * @param array  $where_query_params
2650
-     * @param EE_Base_Class[] objects to which relations were removed
2651
-     * @return EE_Base_Class[]
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2655
-    {
2656
-        $relation_obj = $this->related_settings_for($relationName);
2657
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2658
-    }
2659
-
2660
-
2661
-    /**
2662
-     * Gets all the related items of the specified $model_name, using $query_params.
2663
-     * Note: by default, we remove the "default query params"
2664
-     * because we want to get even deleted items etc.
2665
-     *
2666
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2667
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2668
-     * @param array  $query_params @see
2669
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
-     * @return EE_Base_Class[]
2671
-     * @throws EE_Error
2672
-     * @throws ReflectionException
2673
-     */
2674
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2675
-    {
2676
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2677
-        $relation_settings = $this->related_settings_for($model_name);
2678
-        return $relation_settings->get_all_related($model_obj, $query_params);
2679
-    }
2680
-
2681
-
2682
-    /**
2683
-     * Deletes all the model objects across the relation indicated by $model_name
2684
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2685
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2686
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2687
-     *
2688
-     * @param EE_Base_Class|int|string $id_or_obj
2689
-     * @param string                   $model_name
2690
-     * @param array                    $query_params
2691
-     * @return int how many deleted
2692
-     * @throws EE_Error
2693
-     * @throws ReflectionException
2694
-     */
2695
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2696
-    {
2697
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2698
-        $relation_settings = $this->related_settings_for($model_name);
2699
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2700
-    }
2701
-
2702
-
2703
-    /**
2704
-     * Hard deletes all the model objects across the relation indicated by $model_name
2705
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2706
-     * the model objects can't be hard deleted because of blocking related model objects,
2707
-     * just does a soft-delete on them instead.
2708
-     *
2709
-     * @param EE_Base_Class|int|string $id_or_obj
2710
-     * @param string                   $model_name
2711
-     * @param array                    $query_params
2712
-     * @return int how many deleted
2713
-     * @throws EE_Error
2714
-     * @throws ReflectionException
2715
-     */
2716
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2717
-    {
2718
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2719
-        $relation_settings = $this->related_settings_for($model_name);
2720
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2721
-    }
2722
-
2723
-
2724
-    /**
2725
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2726
-     * unless otherwise specified in the $query_params
2727
-     *
2728
-     * @param int             /EE_Base_Class $id_or_obj
2729
-     * @param string $model_name     like 'Event', or 'Registration'
2730
-     * @param array  $query_params   @see
2731
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2733
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2734
-     *                               that by the setting $distinct to TRUE;
2735
-     * @return int
2736
-     * @throws EE_Error
2737
-     */
2738
-    public function count_related(
2739
-        $id_or_obj,
2740
-        $model_name,
2741
-        $query_params = [],
2742
-        $field_to_count = null,
2743
-        $distinct = false
2744
-    ) {
2745
-        $related_model = $this->get_related_model_obj($model_name);
2746
-        // we're just going to use the query params on the related model's normal get_all query,
2747
-        // except add a condition to say to match the current mod
2748
-        if (! isset($query_params['default_where_conditions'])) {
2749
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2750
-        }
2751
-        $this_model_name                                                 = $this->get_this_model_name();
2752
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2753
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2754
-        return $related_model->count($query_params, $field_to_count, $distinct);
2755
-    }
2756
-
2757
-
2758
-    /**
2759
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2760
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2761
-     *
2762
-     * @param int           /EE_Base_Class $id_or_obj
2763
-     * @param string $model_name   like 'Event', or 'Registration'
2764
-     * @param array  $query_params @see
2765
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2766
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2767
-     * @return float
2768
-     * @throws EE_Error
2769
-     */
2770
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2771
-    {
2772
-        $related_model = $this->get_related_model_obj($model_name);
2773
-        if (! is_array($query_params)) {
2774
-            EE_Error::doing_it_wrong(
2775
-                'EEM_Base::sum_related',
2776
-                sprintf(
2777
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2778
-                    gettype($query_params)
2779
-                ),
2780
-                '4.6.0'
2781
-            );
2782
-            $query_params = [];
2783
-        }
2784
-        // we're just going to use the query params on the related model's normal get_all query,
2785
-        // except add a condition to say to match the current mod
2786
-        if (! isset($query_params['default_where_conditions'])) {
2787
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2788
-        }
2789
-        $this_model_name                                                 = $this->get_this_model_name();
2790
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2791
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2792
-        return $related_model->sum($query_params, $field_to_sum);
2793
-    }
2794
-
2795
-
2796
-    /**
2797
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2798
-     * $modelObject
2799
-     *
2800
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2801
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2802
-     * @param array               $query_params     @see
2803
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2804
-     * @return EE_Base_Class
2805
-     * @throws EE_Error
2806
-     */
2807
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2808
-    {
2809
-        $query_params['limit'] = 1;
2810
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2811
-        if ($results) {
2812
-            return array_shift($results);
2813
-        }
2814
-        return null;
2815
-    }
2816
-
2817
-
2818
-    /**
2819
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2820
-     *
2821
-     * @return string
2822
-     */
2823
-    public function get_this_model_name()
2824
-    {
2825
-        return str_replace("EEM_", "", get_class($this));
2826
-    }
2827
-
2828
-
2829
-    /**
2830
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2831
-     *
2832
-     * @return EE_Any_Foreign_Model_Name_Field
2833
-     * @throws EE_Error
2834
-     */
2835
-    public function get_field_containing_related_model_name()
2836
-    {
2837
-        foreach ($this->field_settings(true) as $field) {
2838
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2839
-                $field_with_model_name = $field;
2840
-            }
2841
-        }
2842
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2843
-            throw new EE_Error(
2844
-                sprintf(
2845
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2846
-                    $this->get_this_model_name()
2847
-                )
2848
-            );
2849
-        }
2850
-        return $field_with_model_name;
2851
-    }
2852
-
2853
-
2854
-    /**
2855
-     * Inserts a new entry into the database, for each table.
2856
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2857
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2858
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2859
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2860
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2861
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2862
-     *
2863
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2864
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2865
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2866
-     *                              of EEM_Base)
2867
-     * @return int|string new primary key on main table that got inserted
2868
-     * @throws EE_Error
2869
-     */
2870
-    public function insert($field_n_values)
2871
-    {
2872
-        /**
2873
-         * Filters the fields and their values before inserting an item using the models
2874
-         *
2875
-         * @param array    $fields_n_values keys are the fields and values are their new values
2876
-         * @param EEM_Base $model           the model used
2877
-         */
2878
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2879
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2880
-            $main_table = $this->_get_main_table();
2881
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2882
-            if ($new_id !== false) {
2883
-                foreach ($this->_get_other_tables() as $other_table) {
2884
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2885
-                }
2886
-            }
2887
-            /**
2888
-             * Done just after attempting to insert a new model object
2889
-             *
2890
-             * @param EEM_Base $model           used
2891
-             * @param array    $fields_n_values fields and their values
2892
-             * @param int|string the              ID of the newly-inserted model object
2893
-             */
2894
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2895
-            return $new_id;
2896
-        }
2897
-        return false;
2898
-    }
2899
-
2900
-
2901
-    /**
2902
-     * Checks that the result would satisfy the unique indexes on this model
2903
-     *
2904
-     * @param array  $field_n_values
2905
-     * @param string $action
2906
-     * @return boolean
2907
-     * @throws EE_Error
2908
-     */
2909
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2910
-    {
2911
-        foreach ($this->unique_indexes() as $index_name => $index) {
2912
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2913
-            if ($this->exists([$uniqueness_where_params])) {
2914
-                EE_Error::add_error(
2915
-                    sprintf(
2916
-                        esc_html__(
2917
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2918
-                            "event_espresso"
2919
-                        ),
2920
-                        $action,
2921
-                        $this->_get_class_name(),
2922
-                        $index_name,
2923
-                        implode(",", $index->field_names()),
2924
-                        http_build_query($uniqueness_where_params)
2925
-                    ),
2926
-                    __FILE__,
2927
-                    __FUNCTION__,
2928
-                    __LINE__
2929
-                );
2930
-                return false;
2931
-            }
2932
-        }
2933
-        return true;
2934
-    }
2935
-
2936
-
2937
-    /**
2938
-     * Checks the database for an item that conflicts (ie, if this item were
2939
-     * saved to the DB would break some uniqueness requirement, like a primary key
2940
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2941
-     * can be either an EE_Base_Class or an array of fields n values
2942
-     *
2943
-     * @param EE_Base_Class|array $obj_or_fields_array
2944
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2945
-     *                                                 when looking for conflicts
2946
-     *                                                 (ie, if false, we ignore the model object's primary key
2947
-     *                                                 when finding "conflicts". If true, it's also considered).
2948
-     *                                                 Only works for INT primary key,
2949
-     *                                                 STRING primary keys cannot be ignored
2950
-     * @return EE_Base_Class|array
2951
-     * @throws EE_Error
2952
-     * @throws ReflectionException
2953
-     */
2954
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2955
-    {
2956
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2957
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2958
-        } elseif (is_array($obj_or_fields_array)) {
2959
-            $fields_n_values = $obj_or_fields_array;
2960
-        } else {
2961
-            throw new EE_Error(
2962
-                sprintf(
2963
-                    esc_html__(
2964
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2965
-                        "event_espresso"
2966
-                    ),
2967
-                    get_class($this),
2968
-                    $obj_or_fields_array
2969
-                )
2970
-            );
2971
-        }
2972
-        $query_params = [];
2973
-        if (
2974
-            $this->has_primary_key_field()
2975
-            && ($include_primary_key
2976
-                || $this->get_primary_key_field()
2977
-                   instanceof
2978
-                   EE_Primary_Key_String_Field)
2979
-            && isset($fields_n_values[ $this->primary_key_name() ])
2980
-        ) {
2981
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2982
-        }
2983
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2984
-            $uniqueness_where_params                              =
2985
-                array_intersect_key($fields_n_values, $unique_index->fields());
2986
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2987
-        }
2988
-        // if there is nothing to base this search on, then we shouldn't find anything
2989
-        if (empty($query_params)) {
2990
-            return [];
2991
-        }
2992
-        return $this->get_one($query_params);
2993
-    }
2994
-
2995
-
2996
-    /**
2997
-     * Like count, but is optimized and returns a boolean instead of an int
2998
-     *
2999
-     * @param array $query_params
3000
-     * @return boolean
3001
-     * @throws EE_Error
3002
-     */
3003
-    public function exists($query_params)
3004
-    {
3005
-        $query_params['limit'] = 1;
3006
-        return $this->count($query_params) > 0;
3007
-    }
3008
-
3009
-
3010
-    /**
3011
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3012
-     *
3013
-     * @param int|string $id
3014
-     * @return boolean
3015
-     * @throws EE_Error
3016
-     */
3017
-    public function exists_by_ID($id)
3018
-    {
3019
-        return $this->exists(
3020
-            [
3021
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3022
-                [
3023
-                    $this->primary_key_name() => $id,
3024
-                ],
3025
-            ]
3026
-        );
3027
-    }
3028
-
3029
-
3030
-    /**
3031
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3032
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3033
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3034
-     * on the main table)
3035
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3036
-     * cases where we want to call it directly rather than via insert().
3037
-     *
3038
-     * @access   protected
3039
-     * @param EE_Table_Base $table
3040
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3041
-     *                                       float
3042
-     * @param int           $new_id          for now we assume only int keys
3043
-     * @return int ID of new row inserted, or FALSE on failure
3044
-     * @throws EE_Error
3045
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3046
-     */
3047
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3048
-    {
3049
-        global $wpdb;
3050
-        $insertion_col_n_values = [];
3051
-        $format_for_insertion   = [];
3052
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3053
-        foreach ($fields_on_table as $field_name => $field_obj) {
3054
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3055
-            if ($field_obj->is_auto_increment()) {
3056
-                continue;
3057
-            }
3058
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3059
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3060
-            if ($prepared_value !== null) {
3061
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3062
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3063
-            }
3064
-        }
3065
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3066
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3067
-            // so add the fk to the main table as a column
3068
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3069
-            $format_for_insertion[]                              =
3070
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3071
-        }
3072
-
3073
-        // insert the new entry
3074
-        $result = $this->_do_wpdb_query(
3075
-            'insert',
3076
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3077
-        );
3078
-        if ($result === false) {
3079
-            return false;
3080
-        }
3081
-        // ok, now what do we return for the ID of the newly-inserted thing?
3082
-        if ($this->has_primary_key_field()) {
3083
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3084
-                return $wpdb->insert_id;
3085
-            }
3086
-            // it's not an auto-increment primary key, so
3087
-            // it must have been supplied
3088
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3089
-        }
3090
-        // we can't return a  primary key because there is none. instead return
3091
-        // a unique string indicating this model
3092
-        return $this->get_index_primary_key_string($fields_n_values);
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3098
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3099
-     * and there is no default, we pass it along. WPDB will take care of it)
3100
-     *
3101
-     * @param EE_Model_Field_Base $field_obj
3102
-     * @param array               $fields_n_values
3103
-     * @return mixed string|int|float depending on what the table column will be expecting
3104
-     * @throws EE_Error
3105
-     */
3106
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3107
-    {
3108
-        $field_name = $field_obj->get_name();
3109
-        // if this field doesn't allow nullable, don't allow it
3110
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3111
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3112
-        }
3113
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3114
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3115
-    }
3116
-
3117
-
3118
-    /**
3119
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3120
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3121
-     * the field's prepare_for_set() method.
3122
-     *
3123
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3124
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3125
-     *                                   top of file)
3126
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3127
-     *                                   $value is a custom selection
3128
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3129
-     */
3130
-    private function _prepare_value_for_use_in_db($value, $field)
3131
-    {
3132
-        if ($field instanceof EE_Model_Field_Base) {
3133
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3134
-            switch ($this->_values_already_prepared_by_model_object) {
3135
-                /** @noinspection PhpMissingBreakStatementInspection */
3136
-                case self::not_prepared_by_model_object:
3137
-                    $value = $field->prepare_for_set($value);
3138
-                // purposefully left out "return"
3139
-                // no break
3140
-                case self::prepared_by_model_object:
3141
-                    /** @noinspection SuspiciousAssignmentsInspection */
3142
-                    $value = $field->prepare_for_use_in_db($value);
3143
-                // no break
3144
-                case self::prepared_for_use_in_db:
3145
-                    // leave the value alone
3146
-            }
3147
-            // phpcs:enable
3148
-        }
3149
-        return $value;
3150
-    }
3151
-
3152
-
3153
-    /**
3154
-     * Returns the main table on this model
3155
-     *
3156
-     * @return EE_Primary_Table
3157
-     * @throws EE_Error
3158
-     */
3159
-    protected function _get_main_table()
3160
-    {
3161
-        foreach ($this->_tables as $table) {
3162
-            if ($table instanceof EE_Primary_Table) {
3163
-                return $table;
3164
-            }
3165
-        }
3166
-        throw new EE_Error(
3167
-            sprintf(
3168
-                esc_html__(
3169
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3170
-                    'event_espresso'
3171
-                ),
3172
-                get_class($this)
3173
-            )
3174
-        );
3175
-    }
3176
-
3177
-
3178
-    /**
3179
-     * table
3180
-     * returns EE_Primary_Table table name
3181
-     *
3182
-     * @return string
3183
-     * @throws EE_Error
3184
-     */
3185
-    public function table()
3186
-    {
3187
-        return $this->_get_main_table()->get_table_name();
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * table
3193
-     * returns first EE_Secondary_Table table name
3194
-     *
3195
-     * @return string
3196
-     */
3197
-    public function second_table()
3198
-    {
3199
-        // grab second table from tables array
3200
-        $second_table = end($this->_tables);
3201
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3202
-    }
3203
-
3204
-
3205
-    /**
3206
-     * get_table_obj_by_alias
3207
-     * returns table name given it's alias
3208
-     *
3209
-     * @param string $table_alias
3210
-     * @return EE_Primary_Table | EE_Secondary_Table
3211
-     */
3212
-    public function get_table_obj_by_alias($table_alias = '')
3213
-    {
3214
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3215
-    }
3216
-
3217
-
3218
-    /**
3219
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3220
-     *
3221
-     * @return EE_Secondary_Table[]
3222
-     */
3223
-    protected function _get_other_tables()
3224
-    {
3225
-        $other_tables = [];
3226
-        foreach ($this->_tables as $table_alias => $table) {
3227
-            if ($table instanceof EE_Secondary_Table) {
3228
-                $other_tables[ $table_alias ] = $table;
3229
-            }
3230
-        }
3231
-        return $other_tables;
3232
-    }
3233
-
3234
-
3235
-    /**
3236
-     * Finds all the fields that correspond to the given table
3237
-     *
3238
-     * @param string $table_alias , array key in EEM_Base::_tables
3239
-     * @return EE_Model_Field_Base[]
3240
-     */
3241
-    public function _get_fields_for_table($table_alias)
3242
-    {
3243
-        return $this->_fields[ $table_alias ];
3244
-    }
3245
-
3246
-
3247
-    /**
3248
-     * Recurses through all the where parameters, and finds all the related models we'll need
3249
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3250
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3251
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3252
-     * related Registration, Transaction, and Payment models.
3253
-     *
3254
-     * @param array $query_params @see
3255
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3256
-     * @return EE_Model_Query_Info_Carrier
3257
-     * @throws EE_Error
3258
-     */
3259
-    public function _extract_related_models_from_query($query_params)
3260
-    {
3261
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3262
-        if (array_key_exists(0, $query_params)) {
3263
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3264
-        }
3265
-        if (array_key_exists('group_by', $query_params)) {
3266
-            if (is_array($query_params['group_by'])) {
3267
-                $this->_extract_related_models_from_sub_params_array_values(
3268
-                    $query_params['group_by'],
3269
-                    $query_info_carrier,
3270
-                    'group_by'
3271
-                );
3272
-            } elseif (! empty($query_params['group_by'])) {
3273
-                $this->_extract_related_model_info_from_query_param(
3274
-                    $query_params['group_by'],
3275
-                    $query_info_carrier,
3276
-                    'group_by'
3277
-                );
3278
-            }
3279
-        }
3280
-        if (array_key_exists('having', $query_params)) {
3281
-            $this->_extract_related_models_from_sub_params_array_keys(
3282
-                $query_params[0],
3283
-                $query_info_carrier,
3284
-                'having'
3285
-            );
3286
-        }
3287
-        if (array_key_exists('order_by', $query_params)) {
3288
-            if (is_array($query_params['order_by'])) {
3289
-                $this->_extract_related_models_from_sub_params_array_keys(
3290
-                    $query_params['order_by'],
3291
-                    $query_info_carrier,
3292
-                    'order_by'
3293
-                );
3294
-            } elseif (! empty($query_params['order_by'])) {
3295
-                $this->_extract_related_model_info_from_query_param(
3296
-                    $query_params['order_by'],
3297
-                    $query_info_carrier,
3298
-                    'order_by'
3299
-                );
3300
-            }
3301
-        }
3302
-        if (array_key_exists('force_join', $query_params)) {
3303
-            $this->_extract_related_models_from_sub_params_array_values(
3304
-                $query_params['force_join'],
3305
-                $query_info_carrier,
3306
-                'force_join'
3307
-            );
3308
-        }
3309
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3310
-        return $query_info_carrier;
3311
-    }
3312
-
3313
-
3314
-    /**
3315
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3316
-     *
3317
-     * @param array                       $sub_query_params @see
3318
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3319
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3320
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3321
-     * @return EE_Model_Query_Info_Carrier
3322
-     * @throws EE_Error
3323
-     */
3324
-    private function _extract_related_models_from_sub_params_array_keys(
3325
-        $sub_query_params,
3326
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3327
-        $query_param_type
3328
-    ) {
3329
-        if (! empty($sub_query_params)) {
3330
-            $sub_query_params = (array) $sub_query_params;
3331
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3332
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3333
-                $this->_extract_related_model_info_from_query_param(
3334
-                    $param,
3335
-                    $model_query_info_carrier,
3336
-                    $query_param_type
3337
-                );
3338
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3339
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3340
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3341
-                // of array('Registration.TXN_ID'=>23)
3342
-                $query_param_sans_stars =
3343
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3344
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3345
-                    if (! is_array($possibly_array_of_params)) {
3346
-                        throw new EE_Error(
3347
-                            sprintf(
3348
-                                esc_html__(
3349
-                                    "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3350
-                                    "event_espresso"
3351
-                                ),
3352
-                                $param,
3353
-                                $possibly_array_of_params
3354
-                            )
3355
-                        );
3356
-                    }
3357
-                    $this->_extract_related_models_from_sub_params_array_keys(
3358
-                        $possibly_array_of_params,
3359
-                        $model_query_info_carrier,
3360
-                        $query_param_type
3361
-                    );
3362
-                } elseif (
3363
-                    $query_param_type === 0 // ie WHERE
3364
-                    && is_array($possibly_array_of_params)
3365
-                    && isset($possibly_array_of_params[2])
3366
-                    && $possibly_array_of_params[2] == true
3367
-                ) {
3368
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3369
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3370
-                    // from which we should extract query parameters!
3371
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3372
-                        throw new EE_Error(
3373
-                            sprintf(
3374
-                                esc_html__(
3375
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
-                                    "event_espresso"
3377
-                                ),
3378
-                                $query_param_type,
3379
-                                implode(",", $possibly_array_of_params)
3380
-                            )
3381
-                        );
3382
-                    }
3383
-                    $this->_extract_related_model_info_from_query_param(
3384
-                        $possibly_array_of_params[1],
3385
-                        $model_query_info_carrier,
3386
-                        $query_param_type
3387
-                    );
3388
-                }
3389
-            }
3390
-        }
3391
-        return $model_query_info_carrier;
3392
-    }
3393
-
3394
-
3395
-    /**
3396
-     * For extracting related models from forced_joins, where the array values contain the info about what
3397
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3398
-     *
3399
-     * @param array                       $sub_query_params @see
3400
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3401
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3402
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3403
-     * @return EE_Model_Query_Info_Carrier
3404
-     * @throws EE_Error
3405
-     */
3406
-    private function _extract_related_models_from_sub_params_array_values(
3407
-        $sub_query_params,
3408
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3409
-        $query_param_type
3410
-    ) {
3411
-        if (! empty($sub_query_params)) {
3412
-            if (! is_array($sub_query_params)) {
3413
-                throw new EE_Error(
3414
-                    sprintf(
3415
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3416
-                        $sub_query_params
3417
-                    )
3418
-                );
3419
-            }
3420
-            foreach ($sub_query_params as $param) {
3421
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3422
-                $this->_extract_related_model_info_from_query_param(
3423
-                    $param,
3424
-                    $model_query_info_carrier,
3425
-                    $query_param_type
3426
-                );
3427
-            }
3428
-        }
3429
-        return $model_query_info_carrier;
3430
-    }
3431
-
3432
-
3433
-    /**
3434
-     * Extract all the query parts from  model query params
3435
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3436
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3437
-     * but use them in a different order. Eg, we need to know what models we are querying
3438
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3439
-     * other models before we can finalize the where clause SQL.
3440
-     *
3441
-     * @param array $query_params @see
3442
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3443
-     * @return EE_Model_Query_Info_Carrier
3444
-     * @throws EE_Error
3445
-     * @throws ModelConfigurationException*@throws ReflectionException
3446
-     * @throws ReflectionException
3447
-     */
3448
-    public function _create_model_query_info_carrier($query_params)
3449
-    {
3450
-        if (! is_array($query_params)) {
3451
-            EE_Error::doing_it_wrong(
3452
-                'EEM_Base::_create_model_query_info_carrier',
3453
-                sprintf(
3454
-                    esc_html__(
3455
-                        '$query_params should be an array, you passed a variable of type %s',
3456
-                        'event_espresso'
3457
-                    ),
3458
-                    gettype($query_params)
3459
-                ),
3460
-                '4.6.0'
3461
-            );
3462
-            $query_params = [];
3463
-        }
3464
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3465
-        // first check if we should alter the query to account for caps or not
3466
-        // because the caps might require us to do extra joins
3467
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3468
-            $query_params[0] = array_replace_recursive(
3469
-                $query_params[0],
3470
-                $this->caps_where_conditions($query_params['caps'])
3471
-            );
3472
-        }
3473
-
3474
-        // check if we should alter the query to remove data related to protected
3475
-        // custom post types
3476
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3477
-            $where_param_key_for_password = $this->modelChainAndPassword();
3478
-            // only include if related to a cpt where no password has been set
3479
-            $query_params[0]['OR*nopassword'] = [
3480
-                $where_param_key_for_password       => '',
3481
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3482
-            ];
3483
-        }
3484
-        $query_object = $this->_extract_related_models_from_query($query_params);
3485
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3486
-        foreach ($query_params[0] as $key => $value) {
3487
-            if (is_int($key)) {
3488
-                throw new EE_Error(
3489
-                    sprintf(
3490
-                        esc_html__(
3491
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3492
-                            "event_espresso"
3493
-                        ),
3494
-                        $key,
3495
-                        var_export($value, true),
3496
-                        var_export($query_params, true),
3497
-                        get_class($this)
3498
-                    )
3499
-                );
3500
-            }
3501
-        }
3502
-        if (
3503
-            array_key_exists('default_where_conditions', $query_params)
3504
-            && ! empty($query_params['default_where_conditions'])
3505
-        ) {
3506
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3507
-        } else {
3508
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3509
-        }
3510
-        $query_params[0] = array_merge(
3511
-            $this->_get_default_where_conditions_for_models_in_query(
3512
-                $query_object,
3513
-                $use_default_where_conditions,
3514
-                $query_params[0]
3515
-            ),
3516
-            $query_params[0]
3517
-        );
3518
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3519
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3520
-        // So we need to setup a subquery and use that for the main join.
3521
-        // Note for now this only works on the primary table for the model.
3522
-        // So for instance, you could set the limit array like this:
3523
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3524
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3525
-            $query_object->set_main_model_join_sql(
3526
-                $this->_construct_limit_join_select(
3527
-                    $query_params['on_join_limit'][0],
3528
-                    $query_params['on_join_limit'][1]
3529
-                )
3530
-            );
3531
-        }
3532
-        // set limit
3533
-        if (array_key_exists('limit', $query_params)) {
3534
-            if (is_array($query_params['limit'])) {
3535
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3536
-                    $e = sprintf(
3537
-                        esc_html__(
3538
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3539
-                            "event_espresso"
3540
-                        ),
3541
-                        http_build_query($query_params['limit'])
3542
-                    );
3543
-                    throw new EE_Error($e . "|" . $e);
3544
-                }
3545
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3546
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3547
-            } elseif (! empty($query_params['limit'])) {
3548
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3549
-            }
3550
-        }
3551
-        // set order by
3552
-        if (array_key_exists('order_by', $query_params)) {
3553
-            if (is_array($query_params['order_by'])) {
3554
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3555
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3556
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3557
-                if (array_key_exists('order', $query_params)) {
3558
-                    throw new EE_Error(
3559
-                        sprintf(
3560
-                            esc_html__(
3561
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3562
-                                "event_espresso"
3563
-                            ),
3564
-                            get_class($this),
3565
-                            implode(", ", array_keys($query_params['order_by'])),
3566
-                            implode(", ", $query_params['order_by']),
3567
-                            $query_params['order']
3568
-                        )
3569
-                    );
3570
-                }
3571
-                $this->_extract_related_models_from_sub_params_array_keys(
3572
-                    $query_params['order_by'],
3573
-                    $query_object,
3574
-                    'order_by'
3575
-                );
3576
-                // assume it's an array of fields to order by
3577
-                $order_array = [];
3578
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3579
-                    $order         = $this->_extract_order($order);
3580
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3581
-                }
3582
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3583
-            } elseif (! empty($query_params['order_by'])) {
3584
-                $this->_extract_related_model_info_from_query_param(
3585
-                    $query_params['order_by'],
3586
-                    $query_object,
3587
-                    'order',
3588
-                    $query_params['order_by']
3589
-                );
3590
-                $order = isset($query_params['order'])
3591
-                    ? $this->_extract_order($query_params['order'])
3592
-                    : 'DESC';
3593
-                $query_object->set_order_by_sql(
3594
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3595
-                );
3596
-            }
3597
-        }
3598
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3599
-        if (
3600
-            ! array_key_exists('order_by', $query_params)
3601
-            && array_key_exists('order', $query_params)
3602
-            && ! empty($query_params['order'])
3603
-        ) {
3604
-            $pk_field = $this->get_primary_key_field();
3605
-            $order    = $this->_extract_order($query_params['order']);
3606
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3607
-        }
3608
-        // set group by
3609
-        if (array_key_exists('group_by', $query_params)) {
3610
-            if (is_array($query_params['group_by'])) {
3611
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3612
-                $group_by_array = [];
3613
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3614
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3615
-                }
3616
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3617
-            } elseif (! empty($query_params['group_by'])) {
3618
-                $query_object->set_group_by_sql(
3619
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3620
-                );
3621
-            }
3622
-        }
3623
-        // set having
3624
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3625
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3626
-        }
3627
-        // now, just verify they didn't pass anything wack
3628
-        foreach ($query_params as $query_key => $query_value) {
3629
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3630
-                throw new EE_Error(
3631
-                    sprintf(
3632
-                        esc_html__(
3633
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3634
-                            'event_espresso'
3635
-                        ),
3636
-                        $query_key,
3637
-                        get_class($this),
3638
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3639
-                        implode(',', $this->_allowed_query_params)
3640
-                    )
3641
-                );
3642
-            }
3643
-        }
3644
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3645
-        if (empty($main_model_join_sql)) {
3646
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3647
-        }
3648
-        return $query_object;
3649
-    }
3650
-
3651
-
3652
-    /**
3653
-     * Gets the where conditions that should be imposed on the query based on the
3654
-     * context (eg reading frontend, backend, edit or delete).
3655
-     *
3656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3657
-     * @return array @see
3658
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
-     * @throws EE_Error
3660
-     */
3661
-    public function caps_where_conditions($context = self::caps_read)
3662
-    {
3663
-        EEM_Base::verify_is_valid_cap_context($context);
3664
-        $cap_where_conditions = [];
3665
-        $cap_restrictions     = $this->caps_missing($context);
3666
-        /**
3667
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3668
-         */
3669
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3670
-            $cap_where_conditions = array_replace_recursive(
3671
-                $cap_where_conditions,
3672
-                $restriction_if_no_cap->get_default_where_conditions()
3673
-            );
3674
-        }
3675
-        return apply_filters(
3676
-            'FHEE__EEM_Base__caps_where_conditions__return',
3677
-            $cap_where_conditions,
3678
-            $this,
3679
-            $context,
3680
-            $cap_restrictions
3681
-        );
3682
-    }
3683
-
3684
-
3685
-    /**
3686
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3687
-     * otherwise throws an exception
3688
-     *
3689
-     * @param string $should_be_order_string
3690
-     * @return string either ASC, asc, DESC or desc
3691
-     * @throws EE_Error
3692
-     */
3693
-    private function _extract_order($should_be_order_string)
3694
-    {
3695
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3696
-            return $should_be_order_string;
3697
-        }
3698
-        throw new EE_Error(
3699
-            sprintf(
3700
-                esc_html__(
3701
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3702
-                    "event_espresso"
3703
-                ),
3704
-                get_class($this),
3705
-                $should_be_order_string
3706
-            )
3707
-        );
3708
-    }
3709
-
3710
-
3711
-    /**
3712
-     * Looks at all the models which are included in this query, and asks each
3713
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3714
-     * so they can be merged
3715
-     *
3716
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3717
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3718
-     *                                                                  'none' means NO default where conditions will
3719
-     *                                                                  be used AT ALL during this query.
3720
-     *                                                                  'other_models_only' means default where
3721
-     *                                                                  conditions from other models will be used, but
3722
-     *                                                                  not for this primary model. 'all', the default,
3723
-     *                                                                  means default where conditions will apply as
3724
-     *                                                                  normal
3725
-     * @param array                       $where_query_params           @see
3726
-     *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3727
-     * @throws EE_Error
3728
-     */
3729
-    private function _get_default_where_conditions_for_models_in_query(
3730
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3731
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3732
-        $where_query_params = []
3733
-    ) {
3734
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3735
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3736
-            throw new EE_Error(
3737
-                sprintf(
3738
-                    esc_html__(
3739
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3740
-                        "event_espresso"
3741
-                    ),
3742
-                    $use_default_where_conditions,
3743
-                    implode(", ", $allowed_used_default_where_conditions_values)
3744
-                )
3745
-            );
3746
-        }
3747
-        $universal_query_params = [];
3748
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3749
-            $universal_query_params = $this->_get_default_where_conditions();
3750
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3751
-            $universal_query_params = $this->_get_minimum_where_conditions();
3752
-        }
3753
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3754
-            $related_model = $this->get_related_model_obj($model_name);
3755
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3756
-                $related_model_universal_where_params =
3757
-                    $related_model->_get_default_where_conditions($model_relation_path);
3758
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3759
-                $related_model_universal_where_params =
3760
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3761
-            } else {
3762
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3763
-                continue;
3764
-            }
3765
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3766
-                $related_model_universal_where_params,
3767
-                $where_query_params,
3768
-                $related_model,
3769
-                $model_relation_path
3770
-            );
3771
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3772
-                $universal_query_params,
3773
-                $overrides
3774
-            );
3775
-        }
3776
-        return $universal_query_params;
3777
-    }
3778
-
3779
-
3780
-    /**
3781
-     * Determines whether or not we should use default where conditions for the model in question
3782
-     * (this model, or other related models).
3783
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3784
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3785
-     * We should use default where conditions on related models when they requested to use default where conditions
3786
-     * on all models, or specifically just on other related models
3787
-     *
3788
-     * @param      $default_where_conditions_value
3789
-     * @param bool $for_this_model false means this is for OTHER related models
3790
-     * @return bool
3791
-     */
3792
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3793
-    {
3794
-        return (
3795
-                   $for_this_model
3796
-                   && in_array(
3797
-                       $default_where_conditions_value,
3798
-                       [
3799
-                           EEM_Base::default_where_conditions_all,
3800
-                           EEM_Base::default_where_conditions_this_only,
3801
-                           EEM_Base::default_where_conditions_minimum_others,
3802
-                       ],
3803
-                       true
3804
-                   )
3805
-               )
3806
-               || (
3807
-                   ! $for_this_model
3808
-                   && in_array(
3809
-                       $default_where_conditions_value,
3810
-                       [
3811
-                           EEM_Base::default_where_conditions_all,
3812
-                           EEM_Base::default_where_conditions_others_only,
3813
-                       ],
3814
-                       true
3815
-                   )
3816
-               );
3817
-    }
3818
-
3819
-
3820
-    /**
3821
-     * Determines whether or not we should use default minimum conditions for the model in question
3822
-     * (this model, or other related models).
3823
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3824
-     * where conditions.
3825
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3826
-     * on this model or others
3827
-     *
3828
-     * @param      $default_where_conditions_value
3829
-     * @param bool $for_this_model false means this is for OTHER related models
3830
-     * @return bool
3831
-     */
3832
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3833
-    {
3834
-        return (
3835
-                   $for_this_model
3836
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3837
-               )
3838
-               || (
3839
-                   ! $for_this_model
3840
-                   && in_array(
3841
-                       $default_where_conditions_value,
3842
-                       [
3843
-                           EEM_Base::default_where_conditions_minimum_others,
3844
-                           EEM_Base::default_where_conditions_minimum_all,
3845
-                       ],
3846
-                       true
3847
-                   )
3848
-               );
3849
-    }
3850
-
3851
-
3852
-    /**
3853
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3854
-     * then we also add a special where condition which allows for that model's primary key
3855
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3856
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3857
-     *
3858
-     * @param array    $default_where_conditions
3859
-     * @param array    $provided_where_conditions
3860
-     * @param EEM_Base $model
3861
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3862
-     * @return array @see
3863
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3864
-     * @throws EE_Error
3865
-     */
3866
-    private function _override_defaults_or_make_null_friendly(
3867
-        $default_where_conditions,
3868
-        $provided_where_conditions,
3869
-        $model,
3870
-        $model_relation_path
3871
-    ) {
3872
-        $null_friendly_where_conditions = [];
3873
-        $none_overridden                = true;
3874
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3875
-        foreach ($default_where_conditions as $key => $val) {
3876
-            if (isset($provided_where_conditions[ $key ])) {
3877
-                $none_overridden = false;
3878
-            } else {
3879
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3880
-            }
3881
-        }
3882
-        if ($none_overridden && $default_where_conditions) {
3883
-            if ($model->has_primary_key_field()) {
3884
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3885
-                                                                                   . "."
3886
-                                                                                   . $model->primary_key_name() ] =
3887
-                    ['IS NULL'];
3888
-            }/*else{
40
+	/**
41
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
44
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
+	 *
46
+	 * @var boolean
47
+	 */
48
+	private $_values_already_prepared_by_model_object = 0;
49
+
50
+	/**
51
+	 * when $_values_already_prepared_by_model_object equals this, we assume
52
+	 * the data is just like form input that needs to have the model fields'
53
+	 * prepare_for_set and prepare_for_use_in_db called on it
54
+	 */
55
+	const not_prepared_by_model_object = 0;
56
+
57
+	/**
58
+	 * when $_values_already_prepared_by_model_object equals this, we
59
+	 * assume this value is coming from a model object and doesn't need to have
60
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
61
+	 */
62
+	const prepared_by_model_object = 1;
63
+
64
+	/**
65
+	 * when $_values_already_prepared_by_model_object equals this, we assume
66
+	 * the values are already to be used in the database (ie no processing is done
67
+	 * on them by the model's fields)
68
+	 */
69
+	const prepared_for_use_in_db = 2;
70
+
71
+
72
+	protected $singular_item = 'Item';
73
+
74
+	protected $plural_item   = 'Items';
75
+
76
+	/**
77
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
+	 */
79
+	protected $_tables;
80
+
81
+	/**
82
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
+	 *
86
+	 * @var EE_Model_Field_Base[][] $_fields
87
+	 */
88
+	protected $_fields;
89
+
90
+	/**
91
+	 * array of different kinds of relations
92
+	 *
93
+	 * @var EE_Model_Relation_Base[] $_model_relations
94
+	 */
95
+	protected $_model_relations = [];
96
+
97
+	/**
98
+	 * @var EE_Index[] $_indexes
99
+	 */
100
+	protected $_indexes = [];
101
+
102
+	/**
103
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
104
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
+	 * by setting the same columns as used in these queries in the query yourself.
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_default_where_conditions_strategy;
110
+
111
+	/**
112
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
+	 * This is particularly useful when you want something between 'none' and 'default'
114
+	 *
115
+	 * @var EE_Default_Where_Conditions
116
+	 */
117
+	protected $_minimum_where_conditions_strategy;
118
+
119
+	/**
120
+	 * String describing how to find the "owner" of this model's objects.
121
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
+	 * But when there isn't, this indicates which related model, or transiently-related model,
123
+	 * has the foreign key to the wp_users table.
124
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
+	 * related to events, and events have a foreign key to wp_users.
126
+	 * On EEM_Transaction, this would be 'Transaction.Event'
127
+	 *
128
+	 * @var string
129
+	 */
130
+	protected $_model_chain_to_wp_user = '';
131
+
132
+	/**
133
+	 * String describing how to find the model with a password controlling access to this model. This property has the
134
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
+	 * This value is the path of models to follow to arrive at the model with the password field.
136
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
+	 * model with a password that should affect reading this on the front-end.
138
+	 * Eg this is an empty string for the Event model because it has a password.
139
+	 * This is null for the Registration model, because its event's password has no bearing on whether
140
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
+	 * should hide tickets for datetimes for events that have a password set.
143
+	 *
144
+	 * @var string |null
145
+	 */
146
+	protected $model_chain_to_password = null;
147
+
148
+	/**
149
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
+	 * don't need it (particularly CPT models)
151
+	 *
152
+	 * @var bool
153
+	 */
154
+	protected $_ignore_where_strategy = false;
155
+
156
+	/**
157
+	 * String used in caps relating to this model. Eg, if the caps relating to this
158
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
+	 *
160
+	 * @var string. If null it hasn't been initialized yet. If false then we
161
+	 * have indicated capabilities don't apply to this
162
+	 */
163
+	protected $_caps_slug = null;
164
+
165
+	/**
166
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
+	 * and next-level keys are capability names, and each's value is a
168
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
170
+	 * and then each capability in the corresponding sub-array that they're missing
171
+	 * adds the where conditions onto the query.
172
+	 *
173
+	 * @var array
174
+	 */
175
+	protected $_cap_restrictions = [
176
+		self::caps_read       => [],
177
+		self::caps_read_admin => [],
178
+		self::caps_edit       => [],
179
+		self::caps_delete     => [],
180
+	];
181
+
182
+	/**
183
+	 * Array defining which cap restriction generators to use to create default
184
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
185
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
+	 * automatically set this to false (not just null).
188
+	 *
189
+	 * @var EE_Restriction_Generator_Base[]
190
+	 */
191
+	protected $_cap_restriction_generators = [];
192
+
193
+	/**
194
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
+	 */
196
+	const caps_read       = 'read';
197
+
198
+	const caps_read_admin = 'read_admin';
199
+
200
+	const caps_edit       = 'edit';
201
+
202
+	const caps_delete     = 'delete';
203
+
204
+	/**
205
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
+	 * maps to 'read' because when looking for relevant permissions we're going to use
208
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
209
+	 *
210
+	 * @var array
211
+	 */
212
+	protected $_cap_contexts_to_cap_action_map = [
213
+		self::caps_read       => 'read',
214
+		self::caps_read_admin => 'read',
215
+		self::caps_edit       => 'edit',
216
+		self::caps_delete     => 'delete',
217
+	];
218
+
219
+	/**
220
+	 * Timezone
221
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
+	 * EE_Datetime_Field data type will have access to it.
225
+	 *
226
+	 * @var string
227
+	 */
228
+	protected $_timezone;
229
+
230
+
231
+	/**
232
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
+	 * multisite.
234
+	 *
235
+	 * @var int
236
+	 */
237
+	protected static $_model_query_blog_id;
238
+
239
+	/**
240
+	 * A copy of _fields, except the array keys are the model names pointed to by
241
+	 * the field
242
+	 *
243
+	 * @var EE_Model_Field_Base[]
244
+	 */
245
+	private $_cache_foreign_key_to_fields = [];
246
+
247
+	/**
248
+	 * Cached list of all the fields on the model, indexed by their name
249
+	 *
250
+	 * @var EE_Model_Field_Base[]
251
+	 */
252
+	private $_cached_fields = null;
253
+
254
+	/**
255
+	 * Cached list of all the fields on the model, except those that are
256
+	 * marked as only pertinent to the database
257
+	 *
258
+	 * @var EE_Model_Field_Base[]
259
+	 */
260
+	private $_cached_fields_non_db_only = null;
261
+
262
+	/**
263
+	 * A cached reference to the primary key for quick lookup
264
+	 *
265
+	 * @var EE_Model_Field_Base
266
+	 */
267
+	private $_primary_key_field = null;
268
+
269
+	/**
270
+	 * Flag indicating whether this model has a primary key or not
271
+	 *
272
+	 * @var boolean
273
+	 */
274
+	protected $_has_primary_key_field = null;
275
+
276
+	/**
277
+	 * array in the format:  [ FK alias => full PK ]
278
+	 * where keys are local column name aliases for foreign keys
279
+	 * and values are the fully qualified column name for the primary key they represent
280
+	 *  ex:
281
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
+	 *
283
+	 * @var array $foreign_key_aliases
284
+	 */
285
+	protected $foreign_key_aliases = [];
286
+
287
+	/**
288
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
289
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
+	 * This should be true for models that deal with data that should exist independent of EE.
291
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
293
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
295
+	 *
296
+	 * @var boolean
297
+	 */
298
+	protected $_wp_core_model = false;
299
+
300
+	/**
301
+	 * @var bool stores whether this model has a password field or not.
302
+	 * null until initialized by hasPasswordField()
303
+	 */
304
+	protected $has_password_field;
305
+
306
+	/**
307
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
+	 */
309
+	protected $password_field;
310
+
311
+	/**
312
+	 *    List of valid operators that can be used for querying.
313
+	 * The keys are all operators we'll accept, the values are the real SQL
314
+	 * operators used
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_valid_operators = [
319
+		'='           => '=',
320
+		'<='          => '<=',
321
+		'<'           => '<',
322
+		'>='          => '>=',
323
+		'>'           => '>',
324
+		'!='          => '!=',
325
+		'LIKE'        => 'LIKE',
326
+		'like'        => 'LIKE',
327
+		'NOT_LIKE'    => 'NOT LIKE',
328
+		'not_like'    => 'NOT LIKE',
329
+		'NOT LIKE'    => 'NOT LIKE',
330
+		'not like'    => 'NOT LIKE',
331
+		'IN'          => 'IN',
332
+		'in'          => 'IN',
333
+		'NOT_IN'      => 'NOT IN',
334
+		'not_in'      => 'NOT IN',
335
+		'NOT IN'      => 'NOT IN',
336
+		'not in'      => 'NOT IN',
337
+		'between'     => 'BETWEEN',
338
+		'BETWEEN'     => 'BETWEEN',
339
+		'IS_NOT_NULL' => 'IS NOT NULL',
340
+		'is_not_null' => 'IS NOT NULL',
341
+		'IS NOT NULL' => 'IS NOT NULL',
342
+		'is not null' => 'IS NOT NULL',
343
+		'IS_NULL'     => 'IS NULL',
344
+		'is_null'     => 'IS NULL',
345
+		'IS NULL'     => 'IS NULL',
346
+		'is null'     => 'IS NULL',
347
+		'REGEXP'      => 'REGEXP',
348
+		'regexp'      => 'REGEXP',
349
+		'NOT_REGEXP'  => 'NOT REGEXP',
350
+		'not_regexp'  => 'NOT REGEXP',
351
+		'NOT REGEXP'  => 'NOT REGEXP',
352
+		'not regexp'  => 'NOT REGEXP',
353
+	];
354
+
355
+	/**
356
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
+	 *
358
+	 * @var array
359
+	 */
360
+	protected $_in_style_operators = ['IN', 'NOT IN'];
361
+
362
+	/**
363
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
+	 * '12-31-2012'"
365
+	 *
366
+	 * @var array
367
+	 */
368
+	protected $_between_style_operators = ['BETWEEN'];
369
+
370
+	/**
371
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
+	 *
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
+
377
+	/**
378
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
+	 * on a join table.
380
+	 *
381
+	 * @var array
382
+	 */
383
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
+
385
+	/**
386
+	 * Allowed values for $query_params['order'] for ordering in queries
387
+	 *
388
+	 * @var array
389
+	 */
390
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
+
392
+	/**
393
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
395
+	 *
396
+	 * @var array
397
+	 */
398
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
+
400
+	/**
401
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
403
+	 *
404
+	 * @var array
405
+	 */
406
+	private $_allowed_query_params = [
407
+		0,
408
+		'limit',
409
+		'order_by',
410
+		'group_by',
411
+		'having',
412
+		'force_join',
413
+		'order',
414
+		'on_join_limit',
415
+		'default_where_conditions',
416
+		'caps',
417
+		'extra_selects',
418
+		'exclude_protected',
419
+	];
420
+
421
+	/**
422
+	 * All the data types that can be used in $wpdb->prepare statements.
423
+	 *
424
+	 * @var array
425
+	 */
426
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
+
428
+	/**
429
+	 * @var EE_Registry $EE
430
+	 */
431
+	protected $EE = null;
432
+
433
+
434
+	/**
435
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
+	 *
437
+	 * @var int
438
+	 */
439
+	protected $_show_next_x_db_queries = 0;
440
+
441
+	/**
442
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
+	 * WHERE, GROUP_BY, etc.
445
+	 *
446
+	 * @var CustomSelects
447
+	 */
448
+	protected $_custom_selections = [];
449
+
450
+	/**
451
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
+	 * caches every model object we've fetched from the DB on this request
453
+	 *
454
+	 * @var array
455
+	 */
456
+	protected $_entity_map;
457
+
458
+	/**
459
+	 * @var LoaderInterface
460
+	 */
461
+	protected static $loader;
462
+
463
+	/**
464
+	 * @var Mirror
465
+	 */
466
+	private static $mirror;
467
+
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has not yet verified the db on this http request
471
+	 */
472
+	const db_verified_none = 0;
473
+
474
+	/**
475
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
476
+	 * but not the addons' dbs
477
+	 */
478
+	const db_verified_core = 1;
479
+
480
+	/**
481
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
+	 * the EE core db too)
483
+	 */
484
+	const db_verified_addons = 2;
485
+
486
+	/**
487
+	 * indicates whether an EEM_Base child has already re-verified the DB
488
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
489
+	 * looking like EEM_Base::db_verified_*
490
+	 *
491
+	 * @var int - 0 = none, 1 = core, 2 = addons
492
+	 */
493
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
494
+
495
+	/**
496
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
499
+	 */
500
+	const default_where_conditions_all = 'all';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
+	 *        models which share tables with other models, this can return data for the wrong model.
508
+	 */
509
+	const default_where_conditions_this_only = 'this_model_only';
510
+
511
+	/**
512
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
+	 */
516
+	const default_where_conditions_others_only = 'other_models_only';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
522
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
+	 *        (regardless of whether those events and venues are trashed)
524
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
+	 *        events.
526
+	 */
527
+	const default_where_conditions_minimum_all = 'minimum';
528
+
529
+	/**
530
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
+	 *        not)
534
+	 */
535
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
+
537
+	/**
538
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
+	 *        it's possible it will return table entries for other models. You should use
541
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
542
+	 */
543
+	const default_where_conditions_none = 'none';
544
+
545
+
546
+	/**
547
+	 * About all child constructors:
548
+	 * they should define the _tables, _fields and _model_relations arrays.
549
+	 * Should ALWAYS be called after child constructor.
550
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
551
+	 * finalizes constructing all the object's attributes.
552
+	 * Generally, rather than requiring a child to code
553
+	 * $this->_tables = array(
554
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
+	 *        ...);
556
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
+	 * each EE_Table has a function to set the table's alias after the constructor, using
558
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
+	 * do something similar.
560
+	 *
561
+	 * @param null $timezone
562
+	 * @throws EE_Error
563
+	 */
564
+	protected function __construct($timezone = null)
565
+	{
566
+		// check that the model has not been loaded too soon
567
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
+			throw new EE_Error(
569
+				sprintf(
570
+					esc_html__(
571
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
572
+						'event_espresso'
573
+					),
574
+					get_class($this)
575
+				)
576
+			);
577
+		}
578
+		/**
579
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
580
+		 */
581
+		if (empty(EEM_Base::$_model_query_blog_id)) {
582
+			EEM_Base::set_model_query_blog_id();
583
+		}
584
+		/**
585
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
586
+		 * just use EE_Register_Model_Extension
587
+		 *
588
+		 * @var EE_Table_Base[] $_tables
589
+		 */
590
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
+		foreach ($this->_tables as $table_alias => $table_obj) {
592
+			/** @var $table_obj EE_Table_Base */
593
+			$table_obj->_construct_finalize_with_alias($table_alias);
594
+			if ($table_obj instanceof EE_Secondary_Table) {
595
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
596
+			}
597
+		}
598
+		/**
599
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
600
+		 * EE_Register_Model_Extension
601
+		 *
602
+		 * @param EE_Model_Field_Base[] $_fields
603
+		 */
604
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
605
+		$this->_invalidate_field_caches();
606
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
607
+			if (! array_key_exists($table_alias, $this->_tables)) {
608
+				throw new EE_Error(
609
+					sprintf(
610
+						esc_html__(
611
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
+							'event_espresso'
613
+						),
614
+						$table_alias,
615
+						implode(",", $this->_fields)
616
+					)
617
+				);
618
+			}
619
+			foreach ($fields_for_table as $field_name => $field_obj) {
620
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
621
+				// primary key field base has a slightly different _construct_finalize
622
+				/** @var $field_obj EE_Model_Field_Base */
623
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
624
+			}
625
+		}
626
+		// everything is related to Extra_Meta
627
+		if (get_class($this) !== 'EEM_Extra_Meta') {
628
+			// make extra meta related to everything, but don't block deleting things just
629
+			// because they have related extra meta info. For now just orphan those extra meta
630
+			// in the future we should automatically delete them
631
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
632
+		}
633
+		// and change logs
634
+		if (get_class($this) !== 'EEM_Change_Log') {
635
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
636
+		}
637
+		/**
638
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
639
+		 * EE_Register_Model_Extension
640
+		 *
641
+		 * @param EE_Model_Relation_Base[] $_model_relations
642
+		 */
643
+		$this->_model_relations = (array) apply_filters(
644
+			'FHEE__' . get_class($this) . '__construct__model_relations',
645
+			$this->_model_relations
646
+		);
647
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
648
+			/** @var $relation_obj EE_Model_Relation_Base */
649
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
650
+		}
651
+		foreach ($this->_indexes as $index_name => $index_obj) {
652
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
653
+		}
654
+		$this->set_timezone($timezone);
655
+		// finalize default where condition strategy, or set default
656
+		if (! $this->_default_where_conditions_strategy) {
657
+			// nothing was set during child constructor, so set default
658
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
659
+		}
660
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
661
+		if (! $this->_minimum_where_conditions_strategy) {
662
+			// nothing was set during child constructor, so set default
663
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
664
+		}
665
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
666
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
667
+		// to indicate to NOT set it, set it to the logical default
668
+		if ($this->_caps_slug === null) {
669
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
670
+		}
671
+		// initialize the standard cap restriction generators if none were specified by the child constructor
672
+		if (is_array($this->_cap_restriction_generators)) {
673
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
674
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
675
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
676
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
677
+						new EE_Restriction_Generator_Protected(),
678
+						$cap_context,
679
+						$this
680
+					);
681
+				}
682
+			}
683
+		}
684
+		// if there are cap restriction generators, use them to make the default cap restrictions
685
+		if (is_array($this->_cap_restriction_generators)) {
686
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
687
+				if (! $generator_object) {
688
+					continue;
689
+				}
690
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
691
+					throw new EE_Error(
692
+						sprintf(
693
+							esc_html__(
694
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
695
+								'event_espresso'
696
+							),
697
+							$context,
698
+							$this->get_this_model_name()
699
+						)
700
+					);
701
+				}
702
+				$action = $this->cap_action_for_context($context);
703
+				if (! $generator_object->construction_finalized()) {
704
+					$generator_object->_construct_finalize($this, $action);
705
+				}
706
+			}
707
+		}
708
+		do_action('AHEE__' . get_class($this) . '__construct__end');
709
+	}
710
+
711
+
712
+	/**
713
+	 * @return LoaderInterface
714
+	 * @throws InvalidArgumentException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws InvalidInterfaceException
717
+	 */
718
+	protected static function getLoader(): LoaderInterface
719
+	{
720
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
721
+			EEM_Base::$loader = LoaderFactory::getLoader();
722
+		}
723
+		return EEM_Base::$loader;
724
+	}
725
+
726
+
727
+	/**
728
+	 * @return Mirror
729
+	 * @since   5.0.0.p
730
+	 */
731
+	private static function getMirror(): Mirror
732
+	{
733
+		if (! EEM_Base::$mirror instanceof Mirror) {
734
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
735
+		}
736
+		return EEM_Base::$mirror;
737
+	}
738
+
739
+
740
+	/**
741
+	 * @param string $model_class_Name
742
+	 * @param string $timezone
743
+	 * @return array
744
+	 * @throws ReflectionException
745
+	 * @since   5.0.0.p
746
+	 */
747
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
748
+	{
749
+		$arguments = [$timezone];
750
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
751
+		if (count($params) > 1) {
752
+			if ($params[1]->getName() === 'model_field_factory') {
753
+				$arguments = [
754
+					$timezone,
755
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
756
+				];
757
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
758
+				$arguments = [
759
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
760
+					$timezone,
761
+				];
762
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
763
+				$arguments = [
764
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
765
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
766
+					$timezone,
767
+				];
768
+			}
769
+		}
770
+		return $arguments;
771
+	}
772
+
773
+
774
+	/**
775
+	 * This function is a singleton method used to instantiate the Espresso_model object
776
+	 *
777
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
778
+	 *                                (and any incoming timezone data that gets saved).
779
+	 *                                Note this just sends the timezone info to the date time model field objects.
780
+	 *                                Default is NULL
781
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
782
+	 * @return static (as in the concrete child class)
783
+	 * @throws EE_Error
784
+	 * @throws ReflectionException
785
+	 */
786
+	public static function instance($timezone = null)
787
+	{
788
+		// check if instance of Espresso_model already exists
789
+		if (! static::$_instance instanceof static) {
790
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
791
+			$model     = new static(...$arguments);
792
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
793
+			static::$_instance = $model;
794
+		}
795
+		// we might have a timezone set, let set_timezone decide what to do with it
796
+		if ($timezone) {
797
+			static::$_instance->set_timezone($timezone);
798
+		}
799
+		// Espresso_model object
800
+		return static::$_instance;
801
+	}
802
+
803
+
804
+	/**
805
+	 * resets the model and returns it
806
+	 *
807
+	 * @param string|null $timezone
808
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
809
+	 * all its properties reset; if it wasn't instantiated, returns null)
810
+	 * @throws EE_Error
811
+	 * @throws ReflectionException
812
+	 * @throws InvalidArgumentException
813
+	 * @throws InvalidDataTypeException
814
+	 * @throws InvalidInterfaceException
815
+	 */
816
+	public static function reset($timezone = null)
817
+	{
818
+		if (! static::$_instance instanceof EEM_Base) {
819
+			return null;
820
+		}
821
+		// Let's NOT swap out the current instance for a new one
822
+		// because if someone has a reference to it, we can't remove their reference.
823
+		// It's best to keep using the same reference but change the original object instead,
824
+		// so reset all its properties to their original values as defined in the class.
825
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
826
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
827
+			// don't set instance to null like it was originally,
828
+			// but it's static anyways, and we're ignoring static properties (for now at least)
829
+			if (! isset($static_properties[ $property ])) {
830
+				static::$_instance->{$property} = $value;
831
+			}
832
+		}
833
+		// and then directly call its constructor again, like we would if we were creating a new one
834
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
835
+		static::$_instance->__construct(...$arguments);
836
+		return self::instance();
837
+	}
838
+
839
+
840
+	/**
841
+	 * Used to set the $_model_query_blog_id static property.
842
+	 *
843
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
844
+	 *                      value for get_current_blog_id() will be used.
845
+	 */
846
+	public static function set_model_query_blog_id($blog_id = 0)
847
+	{
848
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
849
+			? (int) $blog_id
850
+			: get_current_blog_id();
851
+	}
852
+
853
+
854
+	/**
855
+	 * Returns whatever is set as the internal $model_query_blog_id.
856
+	 *
857
+	 * @return int
858
+	 */
859
+	public static function get_model_query_blog_id()
860
+	{
861
+		return EEM_Base::$_model_query_blog_id;
862
+	}
863
+
864
+
865
+	/**
866
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
867
+	 *
868
+	 * @param boolean $translated return localized strings or JUST the array.
869
+	 * @return array
870
+	 * @throws EE_Error
871
+	 * @throws InvalidArgumentException
872
+	 * @throws InvalidDataTypeException
873
+	 * @throws InvalidInterfaceException
874
+	 * @throws ReflectionException
875
+	 */
876
+	public function status_array($translated = false)
877
+	{
878
+		if (! array_key_exists('Status', $this->_model_relations)) {
879
+			return [];
880
+		}
881
+		$model_name   = $this->get_this_model_name();
882
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
883
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884
+		$status_array = [];
885
+		foreach ($stati as $status) {
886
+			$status_array[ $status->ID() ] = $status->get('STS_code');
887
+		}
888
+		return $translated
889
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
890
+			: $status_array;
891
+	}
892
+
893
+
894
+	/**
895
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
896
+	 *
897
+	 * @param array $query_params             @see
898
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
899
+	 *                                        or if you have the development copy of EE you can view this at the path:
900
+	 *                                        /docs/G--Model-System/model-query-params.md
901
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
902
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
903
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
904
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
905
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
906
+	 *                                        'OR'=>array(
907
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
908
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
909
+	 *                                        )
910
+	 *                                        ),
911
+	 *                                        'limit'=>10,
912
+	 *                                        'group_by'=>'TXN_ID'
913
+	 *                                        ));
914
+	 *                                        get all the answers to the question titled "shirt size" for event with id
915
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
916
+	 *                                        'Question.QST_display_text'=>'shirt size',
917
+	 *                                        'Registration.Event.EVT_ID'=>12
918
+	 *                                        ),
919
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
920
+	 *                                        ));
921
+	 * @throws EE_Error
922
+	 * @throws ReflectionException
923
+	 */
924
+	public function get_all($query_params = [])
925
+	{
926
+		if (
927
+			isset($query_params['limit'])
928
+			&& ! isset($query_params['group_by'])
929
+		) {
930
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
931
+		}
932
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
933
+	}
934
+
935
+
936
+	/**
937
+	 * Modifies the query parameters so we only get back model objects
938
+	 * that "belong" to the current user
939
+	 *
940
+	 * @param array $query_params @see
941
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
942
+	 * @return array @see
943
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
944
+	 * @throws ReflectionException
945
+	 * @throws ReflectionException
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = [])
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Returns the name of the field's name that points to the WP_User table
959
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
960
+	 * foreign key to the WP_User table)
961
+	 *
962
+	 * @return string|boolean string on success, boolean false when there is no
963
+	 * foreign key to the WP_User table
964
+	 * @throws ReflectionException
965
+	 * @throws ReflectionException
966
+	 */
967
+	public function wp_user_field_name()
968
+	{
969
+		try {
970
+			if (! empty($this->_model_chain_to_wp_user)) {
971
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
+				$last_model_name              = end($models_to_follow_to_wp_users);
973
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
974
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
975
+			} else {
976
+				$model_with_fk_to_wp_users = $this;
977
+				$model_chain_to_wp_user    = '';
978
+			}
979
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
981
+		} catch (EE_Error $e) {
982
+			return false;
983
+		}
984
+	}
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1005
+	 * like how registrations don't have a foreign key to wp_users, but the
1006
+	 * events they are for are), or is unrelated to wp users.
1007
+	 * generally available
1008
+	 *
1009
+	 * @return boolean
1010
+	 */
1011
+	public function is_owned()
1012
+	{
1013
+		if ($this->model_chain_to_wp_user()) {
1014
+			return true;
1015
+		}
1016
+		try {
1017
+			$this->get_foreign_key_to('WP_User');
1018
+			return true;
1019
+		} catch (EE_Error $e) {
1020
+			return false;
1021
+		}
1022
+	}
1023
+
1024
+
1025
+	/**
1026
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1027
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1028
+	 * the model)
1029
+	 *
1030
+	 * @param array  $query_params      @see
1031
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1032
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1033
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1034
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1035
+	 *                                  override this and set the select to "*", or a specific column name, like
1036
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1037
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1038
+	 *                                  the aliases used to refer to this selection, and values are to be
1039
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1040
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1041
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1042
+	 * @throws EE_Error
1043
+	 * @throws InvalidArgumentException
1044
+	 */
1045
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1046
+	{
1047
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1048
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1049
+		$select_expressions       = $columns_to_select === null
1050
+			? $this->_construct_default_select_sql($model_query_info)
1051
+			: '';
1052
+		if ($this->_custom_selections instanceof CustomSelects) {
1053
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1054
+			$select_expressions .= $select_expressions
1055
+				? ', ' . $custom_expressions
1056
+				: $custom_expressions;
1057
+		}
1058
+
1059
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1060
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1066
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1067
+	 * method of including extra select information.
1068
+	 *
1069
+	 * @param array             $query_params
1070
+	 * @param null|array|string $columns_to_select
1071
+	 * @return null|CustomSelects
1072
+	 * @throws InvalidArgumentException
1073
+	 */
1074
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1075
+	{
1076
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1077
+			return null;
1078
+		}
1079
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1080
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1081
+		return new CustomSelects($selects);
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1087
+	 * but you can use the model query params to more easily
1088
+	 * take care of joins, field preparation etc.
1089
+	 *
1090
+	 * @param array  $query_params      @see
1091
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1092
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1093
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1094
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1095
+	 *                                  override this and set the select to "*", or a specific column name, like
1096
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1097
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1098
+	 *                                  the aliases used to refer to this selection, and values are to be
1099
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1100
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1101
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1105
+	{
1106
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * For creating a custom select statement
1112
+	 *
1113
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1114
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1115
+	 *                                 SQL, and 1=>is the datatype
1116
+	 * @return string
1117
+	 * @throws EE_Error
1118
+	 */
1119
+	private function _construct_select_from_input($columns_to_select)
1120
+	{
1121
+		if (is_array($columns_to_select)) {
1122
+			$select_sql_array = [];
1123
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1124
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1125
+					throw new EE_Error(
1126
+						sprintf(
1127
+							esc_html__(
1128
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1129
+								'event_espresso'
1130
+							),
1131
+							$selection_and_datatype,
1132
+							$alias
1133
+						)
1134
+					);
1135
+				}
1136
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							esc_html__(
1140
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype[1],
1144
+							$selection_and_datatype[0],
1145
+							$alias,
1146
+							implode(', ', $this->_valid_wpdb_data_types)
1147
+						)
1148
+					);
1149
+				}
1150
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1151
+			}
1152
+			$columns_to_select_string = implode(', ', $select_sql_array);
1153
+		} else {
1154
+			$columns_to_select_string = $columns_to_select;
1155
+		}
1156
+		return $columns_to_select_string;
1157
+	}
1158
+
1159
+
1160
+	/**
1161
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1162
+	 *
1163
+	 * @return string
1164
+	 * @throws EE_Error
1165
+	 */
1166
+	public function primary_key_name()
1167
+	{
1168
+		return $this->get_primary_key_field()->get_name();
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1174
+	 * If there is no primary key on this model, $id is treated as primary key string
1175
+	 *
1176
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1177
+	 * @return EE_Base_Class|mixed|null
1178
+	 * @throws EE_Error
1179
+	 * @throws ReflectionException
1180
+	 */
1181
+	public function get_one_by_ID($id)
1182
+	{
1183
+		if ($this->get_from_entity_map($id)) {
1184
+			return $this->get_from_entity_map($id);
1185
+		}
1186
+		$model_object = $this->get_one(
1187
+			$this->alter_query_params_to_restrict_by_ID(
1188
+				$id,
1189
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1190
+			)
1191
+		);
1192
+		$className    = $this->_get_class_name();
1193
+		if ($model_object instanceof $className) {
1194
+			// make sure valid objects get added to the entity map
1195
+			// so that the next call to this method doesn't trigger another trip to the db
1196
+			$this->add_to_entity_map($model_object);
1197
+		}
1198
+		return $model_object;
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * Alters query parameters to only get items with this ID are returned.
1204
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1205
+	 * or could just be a simple primary key ID
1206
+	 *
1207
+	 * @param int   $id
1208
+	 * @param array $query_params
1209
+	 * @return array of normal query params, @see
1210
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1211
+	 * @throws EE_Error
1212
+	 */
1213
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1214
+	{
1215
+		if (! isset($query_params[0])) {
1216
+			$query_params[0] = [];
1217
+		}
1218
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1219
+		if ($conditions_from_id === null) {
1220
+			$query_params[0][ $this->primary_key_name() ] = $id;
1221
+		} else {
1222
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1223
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1224
+		}
1225
+		return $query_params;
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1231
+	 * array. If no item is found, null is returned.
1232
+	 *
1233
+	 * @param array $query_params like EEM_Base's $query_params variable.
1234
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1235
+	 * @throws EE_Error
1236
+	 */
1237
+	public function get_one($query_params = [])
1238
+	{
1239
+		if (! is_array($query_params)) {
1240
+			EE_Error::doing_it_wrong(
1241
+				'EEM_Base::get_one',
1242
+				sprintf(
1243
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
+					gettype($query_params)
1245
+				),
1246
+				'4.6.0'
1247
+			);
1248
+			$query_params = [];
1249
+		}
1250
+		$query_params['limit'] = 1;
1251
+		$items                 = $this->get_all($query_params);
1252
+		if (empty($items)) {
1253
+			return null;
1254
+		}
1255
+		return array_shift($items);
1256
+	}
1257
+
1258
+
1259
+	/**
1260
+	 * Returns the next x number of items in sequence from the given value as
1261
+	 * found in the database matching the given query conditions.
1262
+	 *
1263
+	 * @param mixed $current_field_value    Value used for the reference point.
1264
+	 * @param null  $field_to_order_by      What field is used for the
1265
+	 *                                      reference point.
1266
+	 * @param int   $limit                  How many to return.
1267
+	 * @param array $query_params           Extra conditions on the query.
1268
+	 * @param null  $columns_to_select      If left null, then an array of
1269
+	 *                                      EE_Base_Class objects is returned,
1270
+	 *                                      otherwise you can indicate just the
1271
+	 *                                      columns you want returned.
1272
+	 * @return EE_Base_Class[]|array
1273
+	 * @throws EE_Error
1274
+	 */
1275
+	public function next_x(
1276
+		$current_field_value,
1277
+		$field_to_order_by = null,
1278
+		$limit = 1,
1279
+		$query_params = [],
1280
+		$columns_to_select = null
1281
+	) {
1282
+		return $this->_get_consecutive(
1283
+			$current_field_value,
1284
+			'>',
1285
+			$field_to_order_by,
1286
+			$limit,
1287
+			$query_params,
1288
+			$columns_to_select
1289
+		);
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * Returns the previous x number of items in sequence from the given value
1295
+	 * as found in the database matching the given query conditions.
1296
+	 *
1297
+	 * @param mixed $current_field_value    Value used for the reference point.
1298
+	 * @param null  $field_to_order_by      What field is used for the
1299
+	 *                                      reference point.
1300
+	 * @param int   $limit                  How many to return.
1301
+	 * @param array $query_params           Extra conditions on the query.
1302
+	 * @param null  $columns_to_select      If left null, then an array of
1303
+	 *                                      EE_Base_Class objects is returned,
1304
+	 *                                      otherwise you can indicate just the
1305
+	 *                                      columns you want returned.
1306
+	 * @return EE_Base_Class[]|array
1307
+	 * @throws EE_Error
1308
+	 */
1309
+	public function previous_x(
1310
+		$current_field_value,
1311
+		$field_to_order_by = null,
1312
+		$limit = 1,
1313
+		$query_params = [],
1314
+		$columns_to_select = null
1315
+	) {
1316
+		return $this->_get_consecutive(
1317
+			$current_field_value,
1318
+			'<',
1319
+			$field_to_order_by,
1320
+			$limit,
1321
+			$query_params,
1322
+			$columns_to_select
1323
+		);
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * Returns the next item in sequence from the given value as found in the
1329
+	 * database matching the given query conditions.
1330
+	 *
1331
+	 * @param mixed $current_field_value    Value used for the reference point.
1332
+	 * @param null  $field_to_order_by      What field is used for the
1333
+	 *                                      reference point.
1334
+	 * @param array $query_params           Extra conditions on the query.
1335
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
+	 *                                      object is returned, otherwise you
1337
+	 *                                      can indicate just the columns you
1338
+	 *                                      want and a single array indexed by
1339
+	 *                                      the columns will be returned.
1340
+	 * @return EE_Base_Class|null|array()
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	public function next(
1344
+		$current_field_value,
1345
+		$field_to_order_by = null,
1346
+		$query_params = [],
1347
+		$columns_to_select = null
1348
+	) {
1349
+		$results = $this->_get_consecutive(
1350
+			$current_field_value,
1351
+			'>',
1352
+			$field_to_order_by,
1353
+			1,
1354
+			$query_params,
1355
+			$columns_to_select
1356
+		);
1357
+		return empty($results) ? null : reset($results);
1358
+	}
1359
+
1360
+
1361
+	/**
1362
+	 * Returns the previous item in sequence from the given value as found in
1363
+	 * the database matching the given query conditions.
1364
+	 *
1365
+	 * @param mixed $current_field_value    Value used for the reference point.
1366
+	 * @param null  $field_to_order_by      What field is used for the
1367
+	 *                                      reference point.
1368
+	 * @param array $query_params           Extra conditions on the query.
1369
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
+	 *                                      object is returned, otherwise you
1371
+	 *                                      can indicate just the columns you
1372
+	 *                                      want and a single array indexed by
1373
+	 *                                      the columns will be returned.
1374
+	 * @return EE_Base_Class|null|array()
1375
+	 * @throws EE_Error
1376
+	 */
1377
+	public function previous(
1378
+		$current_field_value,
1379
+		$field_to_order_by = null,
1380
+		$query_params = [],
1381
+		$columns_to_select = null
1382
+	) {
1383
+		$results = $this->_get_consecutive(
1384
+			$current_field_value,
1385
+			'<',
1386
+			$field_to_order_by,
1387
+			1,
1388
+			$query_params,
1389
+			$columns_to_select
1390
+		);
1391
+		return empty($results) ? null : reset($results);
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * Returns the a consecutive number of items in sequence from the given
1397
+	 * value as found in the database matching the given query conditions.
1398
+	 *
1399
+	 * @param mixed  $current_field_value   Value used for the reference point.
1400
+	 * @param string $operand               What operand is used for the sequence.
1401
+	 * @param string $field_to_order_by     What field is used for the reference point.
1402
+	 * @param int    $limit                 How many to return.
1403
+	 * @param array  $query_params          Extra conditions on the query.
1404
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1405
+	 *                                      otherwise you can indicate just the columns you want returned.
1406
+	 * @return EE_Base_Class[]|array
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	protected function _get_consecutive(
1410
+		$current_field_value,
1411
+		$operand = '>',
1412
+		$field_to_order_by = null,
1413
+		$limit = 1,
1414
+		$query_params = [],
1415
+		$columns_to_select = null
1416
+	) {
1417
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1418
+		if (empty($field_to_order_by)) {
1419
+			if ($this->has_primary_key_field()) {
1420
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1421
+			} else {
1422
+				if (WP_DEBUG) {
1423
+					throw new EE_Error(
1424
+						esc_html__(
1425
+							'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1426
+							'event_espresso'
1427
+						)
1428
+					);
1429
+				}
1430
+				EE_Error::add_error(
1431
+					esc_html__('There was an error with the query.', 'event_espresso'),
1432
+					__FILE__,
1433
+					__FUNCTION__,
1434
+					__LINE__
1435
+				);
1436
+				return [];
1437
+			}
1438
+		}
1439
+		if (! is_array($query_params)) {
1440
+			EE_Error::doing_it_wrong(
1441
+				'EEM_Base::_get_consecutive',
1442
+				sprintf(
1443
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1444
+					gettype($query_params)
1445
+				),
1446
+				'4.6.0'
1447
+			);
1448
+			$query_params = [];
1449
+		}
1450
+		// let's add the where query param for consecutive look up.
1451
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1452
+		$query_params['limit']                 = $limit;
1453
+		// set direction
1454
+		$incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1455
+		$query_params['order_by'] = $operand === '>'
1456
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1457
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1458
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1459
+		if (empty($columns_to_select)) {
1460
+			return $this->get_all($query_params);
1461
+		}
1462
+		// getting just the fields
1463
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This sets the _timezone property after model object has been instantiated.
1469
+	 *
1470
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1471
+	 */
1472
+	public function set_timezone($timezone)
1473
+	{
1474
+		if ($timezone !== null) {
1475
+			$this->_timezone = $timezone;
1476
+		}
1477
+		// note we need to loop through relations and set the timezone on those objects as well.
1478
+		foreach ($this->_model_relations as $relation) {
1479
+			$relation->set_timezone($timezone);
1480
+		}
1481
+		// and finally we do the same for any datetime fields
1482
+		foreach ($this->_fields as $field) {
1483
+			if ($field instanceof EE_Datetime_Field) {
1484
+				$field->set_timezone($timezone);
1485
+			}
1486
+		}
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * This just returns whatever is set for the current timezone.
1492
+	 *
1493
+	 * @access public
1494
+	 * @return string
1495
+	 */
1496
+	public function get_timezone()
1497
+	{
1498
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1499
+		if (empty($this->_timezone)) {
1500
+			foreach ($this->_fields as $field) {
1501
+				if ($field instanceof EE_Datetime_Field) {
1502
+					$this->set_timezone($field->get_timezone());
1503
+					break;
1504
+				}
1505
+			}
1506
+		}
1507
+		// if timezone STILL empty then return the default timezone for the site.
1508
+		if (empty($this->_timezone)) {
1509
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1510
+		}
1511
+		return $this->_timezone;
1512
+	}
1513
+
1514
+
1515
+	/**
1516
+	 * This returns the date formats set for the given field name and also ensures that
1517
+	 * $this->_timezone property is set correctly.
1518
+	 *
1519
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1520
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1521
+	 * @return array formats in an array with the date format first, and the time format last.
1522
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1523
+	 * @since 4.6.x
1524
+	 */
1525
+	public function get_formats_for($field_name, $pretty = false)
1526
+	{
1527
+		$field_settings = $this->field_settings_for($field_name);
1528
+		// if not a valid EE_Datetime_Field then throw error
1529
+		if (! $field_settings instanceof EE_Datetime_Field) {
1530
+			throw new EE_Error(
1531
+				sprintf(
1532
+					esc_html__(
1533
+						'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1534
+						'event_espresso'
1535
+					),
1536
+					$field_name
1537
+				)
1538
+			);
1539
+		}
1540
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1541
+		// the field.
1542
+		$this->_timezone = $field_settings->get_timezone();
1543
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1544
+	}
1545
+
1546
+
1547
+	/**
1548
+	 * This returns the current time in a format setup for a query on this model.
1549
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1550
+	 * it will return:
1551
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1552
+	 *  NOW
1553
+	 *  - or a unix timestamp (equivalent to time())
1554
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1555
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1556
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1557
+	 *
1558
+	 * @param string $field_name       The field the current time is needed for.
1559
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1560
+	 *                                 formatted string matching the set format for the field in the set timezone will
1561
+	 *                                 be returned.
1562
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1563
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1564
+	 *                                 exception is triggered.
1565
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1566
+	 * @throws Exception
1567
+	 * @since 4.6.x
1568
+	 */
1569
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1570
+	{
1571
+		$formats  = $this->get_formats_for($field_name);
1572
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1573
+		if ($timestamp) {
1574
+			return $DateTime->format('U');
1575
+		}
1576
+		// not returning timestamp, so return formatted string in timezone.
1577
+		switch ($what) {
1578
+			case 'time':
1579
+				return $DateTime->format($formats[1]);
1580
+			case 'date':
1581
+				return $DateTime->format($formats[0]);
1582
+			default:
1583
+				return $DateTime->format(implode(' ', $formats));
1584
+		}
1585
+	}
1586
+
1587
+
1588
+	/**
1589
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1590
+	 * for the model are.  Returns a DateTime object.
1591
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1592
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1593
+	 * ignored.
1594
+	 *
1595
+	 * @param string $field_name      The field being setup.
1596
+	 * @param string $timestring      The date time string being used.
1597
+	 * @param string $incoming_format The format for the time string.
1598
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1599
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1600
+	 *                                format is
1601
+	 *                                'U', this is ignored.
1602
+	 * @return DateTime
1603
+	 * @throws EE_Error
1604
+	 */
1605
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1606
+	{
1607
+		// just using this to ensure the timezone is set correctly internally
1608
+		$this->get_formats_for($field_name);
1609
+		// load EEH_DTT_Helper
1610
+		$set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1611
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1612
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1613
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1614
+	}
1615
+
1616
+
1617
+	/**
1618
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1619
+	 *
1620
+	 * @return EE_Table_Base[]
1621
+	 */
1622
+	public function get_tables()
1623
+	{
1624
+		return $this->_tables;
1625
+	}
1626
+
1627
+
1628
+	/**
1629
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1630
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1631
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1632
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1633
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1634
+	 * model object with EVT_ID = 1
1635
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1636
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1637
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1638
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1639
+	 * are not specified)
1640
+	 *
1641
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1642
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1643
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1644
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1645
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1646
+	 *                                         ID=34, we'd use this method as follows:
1647
+	 *                                         EEM_Transaction::instance()->update(
1648
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1649
+	 *                                         array(array('TXN_ID'=>34)));
1650
+	 * @param array   $query_params            @see
1651
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1652
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1653
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1654
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1655
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1656
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1657
+	 *                                         TRUE, it is assumed that you've already called
1658
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1659
+	 *                                         malicious javascript. However, if
1660
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1661
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1662
+	 *                                         and every other field, before insertion. We provide this parameter
1663
+	 *                                         because model objects perform their prepare_for_set function on all
1664
+	 *                                         their values, and so don't need to be called again (and in many cases,
1665
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1666
+	 *                                         prepare_for_set method...)
1667
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1668
+	 *                                         in this model's entity map according to $fields_n_values that match
1669
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1670
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1671
+	 *                                         could get out-of-sync with the database
1672
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1673
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1674
+	 *                                         bad)
1675
+	 * @throws EE_Error
1676
+	 * @throws ReflectionException
1677
+	 */
1678
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1679
+	{
1680
+		if (! is_array($query_params)) {
1681
+			EE_Error::doing_it_wrong(
1682
+				'EEM_Base::update',
1683
+				sprintf(
1684
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1685
+					gettype($query_params)
1686
+				),
1687
+				'4.6.0'
1688
+			);
1689
+			$query_params = [];
1690
+		}
1691
+		/**
1692
+		 * Action called before a model update call has been made.
1693
+		 *
1694
+		 * @param EEM_Base $model
1695
+		 * @param array    $fields_n_values the updated fields and their new values
1696
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1697
+		 */
1698
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1699
+		/**
1700
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1701
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1702
+		 *
1703
+		 * @param array    $fields_n_values fields and their new values
1704
+		 * @param EEM_Base $model           the model being queried
1705
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1706
+		 */
1707
+		$fields_n_values = (array) apply_filters(
1708
+			'FHEE__EEM_Base__update__fields_n_values',
1709
+			$fields_n_values,
1710
+			$this,
1711
+			$query_params
1712
+		);
1713
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1714
+		// to do that, for each table, verify that it's PK isn't null.
1715
+		$tables = $this->get_tables();
1716
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1717
+		// NOTE: we should make this code more efficient by NOT querying twice
1718
+		// before the real update, but that needs to first go through ALPHA testing
1719
+		// as it's dangerous. says Mike August 8 2014
1720
+		// we want to make sure the default_where strategy is ignored
1721
+		$this->_ignore_where_strategy = true;
1722
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1723
+		foreach ($wpdb_select_results as $wpdb_result) {
1724
+			// type cast stdClass as array
1725
+			$wpdb_result = (array) $wpdb_result;
1726
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1727
+			if ($this->has_primary_key_field()) {
1728
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1729
+			} else {
1730
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1731
+				$main_table_pk_value = null;
1732
+			}
1733
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1734
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1735
+			if (count($tables) > 1) {
1736
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1737
+				// in that table, and so we'll want to insert one
1738
+				foreach ($tables as $table_obj) {
1739
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1740
+					// if there is no private key for this table on the results, it means there's no entry
1741
+					// in this table, right? so insert a row in the current table, using any fields available
1742
+					if (
1743
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1744
+						   && $wpdb_result[ $this_table_pk_column ])
1745
+					) {
1746
+						$success = $this->_insert_into_specific_table(
1747
+							$table_obj,
1748
+							$fields_n_values,
1749
+							$main_table_pk_value
1750
+						);
1751
+						// if we died here, report the error
1752
+						if (! $success) {
1753
+							return false;
1754
+						}
1755
+					}
1756
+				}
1757
+			}
1758
+			//              //and now check that if we have cached any models by that ID on the model, that
1759
+			//              //they also get updated properly
1760
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1761
+			//              if( $model_object ){
1762
+			//                  foreach( $fields_n_values as $field => $value ){
1763
+			//                      $model_object->set($field, $value);
1764
+			// let's make sure default_where strategy is followed now
1765
+			$this->_ignore_where_strategy = false;
1766
+		}
1767
+		// if we want to keep model objects in sync, AND
1768
+		// if this wasn't called from a model object (to update itself)
1769
+		// then we want to make sure we keep all the existing
1770
+		// model objects in sync with the db
1771
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1772
+			if ($this->has_primary_key_field()) {
1773
+				$model_objs_affected_ids = $this->get_col($query_params);
1774
+			} else {
1775
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1776
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1777
+				$model_objs_affected_ids     = [];
1778
+				foreach ($models_affected_key_columns as $row) {
1779
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1780
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1781
+				}
1782
+			}
1783
+			if (! $model_objs_affected_ids) {
1784
+				// wait wait wait- if nothing was affected let's stop here
1785
+				return 0;
1786
+			}
1787
+			foreach ($model_objs_affected_ids as $id) {
1788
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1789
+				if ($model_obj_in_entity_map) {
1790
+					foreach ($fields_n_values as $field => $new_value) {
1791
+						$model_obj_in_entity_map->set($field, $new_value);
1792
+					}
1793
+				}
1794
+			}
1795
+			// if there is a primary key on this model, we can now do a slight optimization
1796
+			if ($this->has_primary_key_field()) {
1797
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1798
+				$query_params = [
1799
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1800
+					'limit'                    => count($model_objs_affected_ids),
1801
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1802
+				];
1803
+			}
1804
+		}
1805
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1806
+		$SQL              = "UPDATE "
1807
+							. $model_query_info->get_full_join_sql()
1808
+							. " SET "
1809
+							. $this->_construct_update_sql($fields_n_values)
1810
+							. $model_query_info->get_where_sql(
1811
+							);// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1812
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1813
+		/**
1814
+		 * Action called after a model update call has been made.
1815
+		 *
1816
+		 * @param EEM_Base $model
1817
+		 * @param array    $fields_n_values the updated fields and their new values
1818
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1819
+		 * @param int      $rows_affected
1820
+		 */
1821
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1822
+		return $rows_affected;// how many supposedly got updated
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1828
+	 * are teh values of the field specified (or by default the primary key field)
1829
+	 * that matched the query params. Note that you should pass the name of the
1830
+	 * model FIELD, not the database table's column name.
1831
+	 *
1832
+	 * @param array  $query_params @see
1833
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1834
+	 * @param string $field_to_select
1835
+	 * @return array just like $wpdb->get_col()
1836
+	 * @throws EE_Error
1837
+	 */
1838
+	public function get_col($query_params = [], $field_to_select = null)
1839
+	{
1840
+		if ($field_to_select) {
1841
+			$field = $this->field_settings_for($field_to_select);
1842
+		} elseif ($this->has_primary_key_field()) {
1843
+			$field = $this->get_primary_key_field();
1844
+		} else {
1845
+			$field_settings = $this->field_settings();
1846
+			// no primary key, just grab the first column
1847
+			$field = reset($field_settings);
1848
+			// don't need this array now
1849
+			unset($field_settings);
1850
+		}
1851
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1852
+		$select_expressions = $field->get_qualified_column();
1853
+		$SQL                =
1854
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1855
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1856
+	}
1857
+
1858
+
1859
+	/**
1860
+	 * Returns a single column value for a single row from the database
1861
+	 *
1862
+	 * @param array  $query_params    @see
1863
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1864
+	 * @param string $field_to_select @see EEM_Base::get_col()
1865
+	 * @return string
1866
+	 * @throws EE_Error
1867
+	 */
1868
+	public function get_var($query_params = [], $field_to_select = null)
1869
+	{
1870
+		$query_params['limit'] = 1;
1871
+		$col                   = $this->get_col($query_params, $field_to_select);
1872
+		if (! empty($col)) {
1873
+			return reset($col);
1874
+		}
1875
+		return null;
1876
+	}
1877
+
1878
+
1879
+	/**
1880
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1881
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1882
+	 * injection, but currently no further filtering is done
1883
+	 *
1884
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1885
+	 *                               be updated to in the DB
1886
+	 * @return string of SQL
1887
+	 * @throws EE_Error
1888
+	 * @global      $wpdb
1889
+	 */
1890
+	public function _construct_update_sql($fields_n_values)
1891
+	{
1892
+		/** @type WPDB $wpdb */
1893
+		global $wpdb;
1894
+		$cols_n_values = [];
1895
+		foreach ($fields_n_values as $field_name => $value) {
1896
+			$field_obj = $this->field_settings_for($field_name);
1897
+			// if the value is NULL, we want to assign the value to that.
1898
+			// wpdb->prepare doesn't really handle that properly
1899
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1900
+			$value_sql       = $prepared_value === null ? 'NULL'
1901
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1902
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1903
+		}
1904
+		return implode(",", $cols_n_values);
1905
+	}
1906
+
1907
+
1908
+	/**
1909
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
+	 * Performs a HARD delete, meaning the database row should always be removed,
1911
+	 * not just have a flag field on it switched
1912
+	 * Wrapper for EEM_Base::delete_permanently()
1913
+	 *
1914
+	 * @param mixed   $id
1915
+	 * @param boolean $allow_blocking
1916
+	 * @return int the number of rows deleted
1917
+	 * @throws EE_Error
1918
+	 * @throws ReflectionException
1919
+	 */
1920
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1921
+	{
1922
+		return $this->delete_permanently(
1923
+			[
1924
+				[$this->get_primary_key_field()->get_name() => $id],
1925
+				'limit' => 1,
1926
+			],
1927
+			$allow_blocking
1928
+		);
1929
+	}
1930
+
1931
+
1932
+	/**
1933
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1934
+	 * Wrapper for EEM_Base::delete()
1935
+	 *
1936
+	 * @param mixed   $id
1937
+	 * @param boolean $allow_blocking
1938
+	 * @return int the number of rows deleted
1939
+	 * @throws EE_Error
1940
+	 */
1941
+	public function delete_by_ID($id, $allow_blocking = true)
1942
+	{
1943
+		return $this->delete(
1944
+			[
1945
+				[$this->get_primary_key_field()->get_name() => $id],
1946
+				'limit' => 1,
1947
+			],
1948
+			$allow_blocking
1949
+		);
1950
+	}
1951
+
1952
+
1953
+	/**
1954
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1955
+	 * meaning if the model has a field that indicates its been "trashed" or
1956
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1957
+	 *
1958
+	 * @param array   $query_params
1959
+	 * @param boolean $allow_blocking
1960
+	 * @return int how many rows got deleted
1961
+	 * @throws EE_Error
1962
+	 * @throws ReflectionException
1963
+	 * @see EEM_Base::delete_permanently
1964
+	 */
1965
+	public function delete($query_params, $allow_blocking = true)
1966
+	{
1967
+		return $this->delete_permanently($query_params, $allow_blocking);
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1973
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1974
+	 * as archived, not actually deleted
1975
+	 *
1976
+	 * @param array   $query_params   @see
1977
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1978
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1979
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1980
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1981
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1982
+	 *                                DB
1983
+	 * @return int how many rows got deleted
1984
+	 * @throws EE_Error
1985
+	 * @throws ReflectionException
1986
+	 */
1987
+	public function delete_permanently($query_params, $allow_blocking = true)
1988
+	{
1989
+		/**
1990
+		 * Action called just before performing a real deletion query. You can use the
1991
+		 * model and its $query_params to find exactly which items will be deleted
1992
+		 *
1993
+		 * @param EEM_Base $model
1994
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1995
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1996
+		 *                                 to block (prevent) this deletion
1997
+		 */
1998
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1999
+		// some MySQL databases may be running safe mode, which may restrict
2000
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2001
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2002
+		// to delete them
2003
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2004
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
2005
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2006
+			$columns_and_ids_for_deleting
2007
+		);
2008
+		/**
2009
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2010
+		 *
2011
+		 * @param EEM_Base $this                            The model instance being acted on.
2012
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2013
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2014
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2015
+		 *                                                  derived from the incoming query parameters.
2016
+		 * @see details on the structure of this array in the phpdocs
2017
+		 *                                                  for the `_get_ids_for_delete_method`
2018
+		 *
2019
+		 */
2020
+		do_action(
2021
+			'AHEE__EEM_Base__delete__before_query',
2022
+			$this,
2023
+			$query_params,
2024
+			$allow_blocking,
2025
+			$columns_and_ids_for_deleting
2026
+		);
2027
+		if ($deletion_where_query_part) {
2028
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2029
+			$table_aliases    = array_keys($this->_tables);
2030
+			$SQL              = "DELETE "
2031
+								. implode(", ", $table_aliases)
2032
+								. " FROM "
2033
+								. $model_query_info->get_full_join_sql()
2034
+								. " WHERE "
2035
+								. $deletion_where_query_part;
2036
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2037
+		} else {
2038
+			$rows_deleted = 0;
2039
+		}
2040
+
2041
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2042
+		// there was no error with the delete query.
2043
+		if (
2044
+			$this->has_primary_key_field()
2045
+			&& $rows_deleted !== false
2046
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2047
+		) {
2048
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2049
+			foreach ($ids_for_removal as $id) {
2050
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2051
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2052
+				}
2053
+			}
2054
+
2055
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2056
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2057
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2058
+			// (although it is possible).
2059
+			// Note this can be skipped by using the provided filter and returning false.
2060
+			if (
2061
+				apply_filters(
2062
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2063
+					! $this instanceof EEM_Extra_Meta,
2064
+					$this
2065
+				)
2066
+			) {
2067
+				EEM_Extra_Meta::instance()->delete_permanently([
2068
+																   0 => [
2069
+																	   'EXM_type' => $this->get_this_model_name(),
2070
+																	   'OBJ_ID'   => [
2071
+																		   'IN',
2072
+																		   $ids_for_removal,
2073
+																	   ],
2074
+																   ],
2075
+															   ]);
2076
+			}
2077
+		}
2078
+
2079
+		/**
2080
+		 * Action called just after performing a real deletion query. Although at this point the
2081
+		 * items should have been deleted
2082
+		 *
2083
+		 * @param EEM_Base $model
2084
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2085
+		 * @param int      $rows_deleted
2086
+		 */
2087
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2088
+		return $rows_deleted;// how many supposedly got deleted
2089
+	}
2090
+
2091
+
2092
+	/**
2093
+	 * Checks all the relations that throw error messages when there are blocking related objects
2094
+	 * for related model objects. If there are any related model objects on those relations,
2095
+	 * adds an EE_Error, and return true
2096
+	 *
2097
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2098
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2099
+	 *                                                 should be ignored when determining whether there are related
2100
+	 *                                                 model objects which block this model object's deletion. Useful
2101
+	 *                                                 if you know A is related to B and are considering deleting A,
2102
+	 *                                                 but want to see if A has any other objects blocking its deletion
2103
+	 *                                                 before removing the relation between A and B
2104
+	 * @return boolean
2105
+	 * @throws EE_Error
2106
+	 * @throws ReflectionException
2107
+	 */
2108
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2109
+	{
2110
+		// first, if $ignore_this_model_obj was supplied, get its model
2111
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2112
+			$ignored_model = $ignore_this_model_obj->get_model();
2113
+		} else {
2114
+			$ignored_model = null;
2115
+		}
2116
+		// now check all the relations of $this_model_obj_or_id and see if there
2117
+		// are any related model objects blocking it?
2118
+		$is_blocked = false;
2119
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2120
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2121
+				// if $ignore_this_model_obj was supplied, then for the query
2122
+				// on that model needs to be told to ignore $ignore_this_model_obj
2123
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2124
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2125
+						[
2126
+							$ignored_model->get_primary_key_field()->get_name() => [
2127
+								'!=',
2128
+								$ignore_this_model_obj->ID(),
2129
+							],
2130
+						],
2131
+					]);
2132
+				} else {
2133
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2134
+				}
2135
+				if ($related_model_objects) {
2136
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2137
+					$is_blocked = true;
2138
+				}
2139
+			}
2140
+		}
2141
+		return $is_blocked;
2142
+	}
2143
+
2144
+
2145
+	/**
2146
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2147
+	 *
2148
+	 * @param array $row_results_for_deleting
2149
+	 * @param bool  $allow_blocking
2150
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2151
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2152
+	 *                              dimension array where the key is the fully qualified primary key column and the
2153
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2154
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2155
+	 *                              be a two dimensional array where each element is a group of columns and values that
2156
+	 *                              get deleted. Example: array(
2157
+	 *                              0 => array(
2158
+	 *                              'Term_Relationship.object_id' => 1
2159
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2160
+	 *                              ),
2161
+	 *                              1 => array(
2162
+	 *                              'Term_Relationship.object_id' => 1
2163
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2164
+	 *                              )
2165
+	 *                              )
2166
+	 * @throws EE_Error
2167
+	 * @throws ReflectionException
2168
+	 */
2169
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2170
+	{
2171
+		$ids_to_delete_indexed_by_column = [];
2172
+		if ($this->has_primary_key_field()) {
2173
+			$primary_table                   = $this->_get_main_table();
2174
+			$primary_table_pk_field          =
2175
+				$this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2176
+			$other_tables                    = $this->_get_other_tables();
2177
+			$ids_to_delete_indexed_by_column = $query = [];
2178
+			foreach ($row_results_for_deleting as $item_to_delete) {
2179
+				// before we mark this item for deletion,
2180
+				// make sure there's no related entities blocking its deletion (if we're checking)
2181
+				if (
2182
+					$allow_blocking
2183
+					&& $this->delete_is_blocked_by_related_models(
2184
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2185
+					)
2186
+				) {
2187
+					continue;
2188
+				}
2189
+				// primary table deletes
2190
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2191
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2192
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2193
+				}
2194
+			}
2195
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2196
+			$fields = $this->get_combined_primary_key_fields();
2197
+			foreach ($row_results_for_deleting as $item_to_delete) {
2198
+				$ids_to_delete_indexed_by_column_for_row = [];
2199
+				foreach ($fields as $cpk_field) {
2200
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2201
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2202
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2203
+					}
2204
+				}
2205
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2206
+			}
2207
+		} else {
2208
+			// so there's no primary key and no combined key...
2209
+			// sorry, can't help you
2210
+			throw new EE_Error(
2211
+				sprintf(
2212
+					esc_html__(
2213
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2214
+						"event_espresso"
2215
+					),
2216
+					get_class($this)
2217
+				)
2218
+			);
2219
+		}
2220
+		return $ids_to_delete_indexed_by_column;
2221
+	}
2222
+
2223
+
2224
+	/**
2225
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2226
+	 * the corresponding query_part for the query performing the delete.
2227
+	 *
2228
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2229
+	 * @return string
2230
+	 * @throws EE_Error
2231
+	 */
2232
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2233
+	{
2234
+		$query_part = '';
2235
+		if (empty($ids_to_delete_indexed_by_column)) {
2236
+			return $query_part;
2237
+		} elseif ($this->has_primary_key_field()) {
2238
+			$query = [];
2239
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2240
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2241
+			}
2242
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2243
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2244
+			$ways_to_identify_a_row = [];
2245
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2246
+				$values_for_each_combined_primary_key_for_a_row = [];
2247
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2248
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2249
+				}
2250
+				$ways_to_identify_a_row[] = '('
2251
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2252
+											. ')';
2253
+			}
2254
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2255
+		}
2256
+		return $query_part;
2257
+	}
2258
+
2259
+
2260
+	/**
2261
+	 * Gets the model field by the fully qualified name
2262
+	 *
2263
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2264
+	 * @return EE_Model_Field_Base
2265
+	 * @throws EE_Error
2266
+	 * @throws EE_Error
2267
+	 */
2268
+	public function get_field_by_column($qualified_column_name)
2269
+	{
2270
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2271
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2272
+				return $field_obj;
2273
+			}
2274
+		}
2275
+		throw new EE_Error(
2276
+			sprintf(
2277
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2278
+				$this->get_this_model_name(),
2279
+				$qualified_column_name
2280
+			)
2281
+		);
2282
+	}
2283
+
2284
+
2285
+	/**
2286
+	 * Count all the rows that match criteria the model query params.
2287
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2288
+	 * column
2289
+	 *
2290
+	 * @param array  $query_params   @see
2291
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2292
+	 * @param string $field_to_count field on model to count by (not column name)
2293
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2294
+	 *                               that by the setting $distinct to TRUE;
2295
+	 * @return int
2296
+	 * @throws EE_Error
2297
+	 */
2298
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2299
+	{
2300
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2301
+		if ($field_to_count) {
2302
+			$field_obj       = $this->field_settings_for($field_to_count);
2303
+			$column_to_count = $field_obj->get_qualified_column();
2304
+		} elseif ($this->has_primary_key_field()) {
2305
+			$pk_field_obj    = $this->get_primary_key_field();
2306
+			$column_to_count = $pk_field_obj->get_qualified_column();
2307
+		} else {
2308
+			// there's no primary key
2309
+			// if we're counting distinct items, and there's no primary key,
2310
+			// we need to list out the columns for distinction;
2311
+			// otherwise we can just use star
2312
+			if ($distinct) {
2313
+				$columns_to_use = [];
2314
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2315
+					$columns_to_use[] = $field_obj->get_qualified_column();
2316
+				}
2317
+				$column_to_count = implode(',', $columns_to_use);
2318
+			} else {
2319
+				$column_to_count = '*';
2320
+			}
2321
+		}
2322
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2323
+		$SQL             =
2324
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2325
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2326
+	}
2327
+
2328
+
2329
+	/**
2330
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2331
+	 *
2332
+	 * @param array  $query_params @see
2333
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2334
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2335
+	 * @return float
2336
+	 * @throws EE_Error
2337
+	 */
2338
+	public function sum($query_params, $field_to_sum = null)
2339
+	{
2340
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2341
+		if ($field_to_sum) {
2342
+			$field_obj = $this->field_settings_for($field_to_sum);
2343
+		} else {
2344
+			$field_obj = $this->get_primary_key_field();
2345
+		}
2346
+		$column_to_count = $field_obj->get_qualified_column();
2347
+		$SQL             =
2348
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2349
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2350
+		$data_type       = $field_obj->get_wpdb_data_type();
2351
+		if ($data_type === '%d' || $data_type === '%s') {
2352
+			return (float) $return_value;
2353
+		}
2354
+		// must be %f
2355
+		return (float) $return_value;
2356
+	}
2357
+
2358
+
2359
+	/**
2360
+	 * Just calls the specified method on $wpdb with the given arguments
2361
+	 * Consolidates a little extra error handling code
2362
+	 *
2363
+	 * @param string $wpdb_method
2364
+	 * @param array  $arguments_to_provide
2365
+	 * @return mixed
2366
+	 * @throws EE_Error
2367
+	 * @global wpdb  $wpdb
2368
+	 */
2369
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2370
+	{
2371
+		// if we're in maintenance mode level 2, DON'T run any queries
2372
+		// because level 2 indicates the database needs updating and
2373
+		// is probably out of sync with the code
2374
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2375
+			throw new EE_Error(
2376
+				sprintf(
2377
+					esc_html__(
2378
+						"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2379
+						"event_espresso"
2380
+					)
2381
+				)
2382
+			);
2383
+		}
2384
+		/** @type WPDB $wpdb */
2385
+		global $wpdb;
2386
+		if (! method_exists($wpdb, $wpdb_method)) {
2387
+			throw new EE_Error(
2388
+				sprintf(
2389
+					esc_html__(
2390
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2391
+						'event_espresso'
2392
+					),
2393
+					$wpdb_method
2394
+				)
2395
+			);
2396
+		}
2397
+		if (WP_DEBUG) {
2398
+			$old_show_errors_value = $wpdb->show_errors;
2399
+			$wpdb->show_errors(false);
2400
+		}
2401
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2402
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2403
+		if (WP_DEBUG) {
2404
+			$wpdb->show_errors($old_show_errors_value);
2405
+			if (! empty($wpdb->last_error)) {
2406
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2407
+			}
2408
+			if ($result === false) {
2409
+				throw new EE_Error(
2410
+					sprintf(
2411
+						esc_html__(
2412
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2413
+							'event_espresso'
2414
+						),
2415
+						$wpdb_method,
2416
+						var_export($arguments_to_provide, true)
2417
+					)
2418
+				);
2419
+			}
2420
+		} elseif ($result === false) {
2421
+			EE_Error::add_error(
2422
+				sprintf(
2423
+					esc_html__(
2424
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2425
+						'event_espresso'
2426
+					),
2427
+					$wpdb_method,
2428
+					var_export($arguments_to_provide, true),
2429
+					$wpdb->last_error
2430
+				),
2431
+				__FILE__,
2432
+				__FUNCTION__,
2433
+				__LINE__
2434
+			);
2435
+		}
2436
+		return $result;
2437
+	}
2438
+
2439
+
2440
+	/**
2441
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2442
+	 * and if there's an error tries to verify the DB is correct. Uses
2443
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2444
+	 * we should try to fix the EE core db, the addons, or just give up
2445
+	 *
2446
+	 * @param string $wpdb_method
2447
+	 * @param array  $arguments_to_provide
2448
+	 * @return mixed
2449
+	 */
2450
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2451
+	{
2452
+		/** @type WPDB $wpdb */
2453
+		global $wpdb;
2454
+		$wpdb->last_error = null;
2455
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2456
+		// was there an error running the query? but we don't care on new activations
2457
+		// (we're going to setup the DB anyway on new activations)
2458
+		if (
2459
+			($result === false || ! empty($wpdb->last_error))
2460
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2461
+		) {
2462
+			switch (EEM_Base::$_db_verification_level) {
2463
+				case EEM_Base::db_verified_none:
2464
+					// let's double-check core's DB
2465
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2466
+					break;
2467
+				case EEM_Base::db_verified_core:
2468
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2469
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2470
+					break;
2471
+				case EEM_Base::db_verified_addons:
2472
+					// ummmm... you in trouble
2473
+					return $result;
2474
+			}
2475
+			if (! empty($error_message)) {
2476
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2477
+				trigger_error($error_message);
2478
+			}
2479
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2480
+		}
2481
+		return $result;
2482
+	}
2483
+
2484
+
2485
+	/**
2486
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2487
+	 * EEM_Base::$_db_verification_level
2488
+	 *
2489
+	 * @param string $wpdb_method
2490
+	 * @param array  $arguments_to_provide
2491
+	 * @return string
2492
+	 */
2493
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2494
+	{
2495
+		/** @type WPDB $wpdb */
2496
+		global $wpdb;
2497
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2498
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2499
+		$error_message                    = sprintf(
2500
+			esc_html__(
2501
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2502
+				'event_espresso'
2503
+			),
2504
+			$wpdb->last_error,
2505
+			$wpdb_method,
2506
+			wp_json_encode($arguments_to_provide)
2507
+		);
2508
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2509
+		return $error_message;
2510
+	}
2511
+
2512
+
2513
+	/**
2514
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2515
+	 * EEM_Base::$_db_verification_level
2516
+	 *
2517
+	 * @param $wpdb_method
2518
+	 * @param $arguments_to_provide
2519
+	 * @return string
2520
+	 */
2521
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2522
+	{
2523
+		/** @type WPDB $wpdb */
2524
+		global $wpdb;
2525
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2526
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2527
+		$error_message                    = sprintf(
2528
+			esc_html__(
2529
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2530
+				'event_espresso'
2531
+			),
2532
+			$wpdb->last_error,
2533
+			$wpdb_method,
2534
+			wp_json_encode($arguments_to_provide)
2535
+		);
2536
+		EE_System::instance()->initialize_addons();
2537
+		return $error_message;
2538
+	}
2539
+
2540
+
2541
+	/**
2542
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2543
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2544
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2545
+	 * ..."
2546
+	 *
2547
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2548
+	 * @return string
2549
+	 */
2550
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2551
+	{
2552
+		return " FROM " . $model_query_info->get_full_join_sql() .
2553
+			   $model_query_info->get_where_sql() .
2554
+			   $model_query_info->get_group_by_sql() .
2555
+			   $model_query_info->get_having_sql() .
2556
+			   $model_query_info->get_order_by_sql() .
2557
+			   $model_query_info->get_limit_sql();
2558
+	}
2559
+
2560
+
2561
+	/**
2562
+	 * Set to easily debug the next X queries ran from this model.
2563
+	 *
2564
+	 * @param int $count
2565
+	 */
2566
+	public function show_next_x_db_queries($count = 1)
2567
+	{
2568
+		$this->_show_next_x_db_queries = $count;
2569
+	}
2570
+
2571
+
2572
+	/**
2573
+	 * @param $sql_query
2574
+	 */
2575
+	public function show_db_query_if_previously_requested($sql_query)
2576
+	{
2577
+		if ($this->_show_next_x_db_queries > 0) {
2578
+			echo esc_html($sql_query);
2579
+			$this->_show_next_x_db_queries--;
2580
+		}
2581
+	}
2582
+
2583
+
2584
+	/**
2585
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2586
+	 * There are the 3 cases:
2587
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2588
+	 * $otherModelObject has no ID, it is first saved.
2589
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2590
+	 * has no ID, it is first saved.
2591
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2592
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2593
+	 * join table
2594
+	 *
2595
+	 * @param EE_Base_Class                     /int $thisModelObject
2596
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2597
+	 * @param string $relationName                     , key in EEM_Base::_relations
2598
+	 *                                                 an attendee to a group, you also want to specify which role they
2599
+	 *                                                 will have in that group. So you would use this parameter to
2600
+	 *                                                 specify array('role-column-name'=>'role-id')
2601
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2602
+	 *                                                 to for relation to methods that allow you to further specify
2603
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2604
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2605
+	 *                                                 because these will be inserted in any new rows created as well.
2606
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2607
+	 * @throws EE_Error
2608
+	 */
2609
+	public function add_relationship_to(
2610
+		$id_or_obj,
2611
+		$other_model_id_or_obj,
2612
+		$relationName,
2613
+		$extra_join_model_fields_n_values = []
2614
+	) {
2615
+		$relation_obj = $this->related_settings_for($relationName);
2616
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2617
+	}
2618
+
2619
+
2620
+	/**
2621
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2622
+	 * There are the 3 cases:
2623
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2624
+	 * error
2625
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2626
+	 * an error
2627
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2628
+	 *
2629
+	 * @param EE_Base_Class /int $id_or_obj
2630
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2631
+	 * @param string $relationName key in EEM_Base::_relations
2632
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2633
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2634
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2635
+	 *                             because these will be inserted in any new rows created as well.
2636
+	 * @return boolean of success
2637
+	 * @throws EE_Error
2638
+	 */
2639
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2640
+	{
2641
+		$relation_obj = $this->related_settings_for($relationName);
2642
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2643
+	}
2644
+
2645
+
2646
+	/**
2647
+	 * @param mixed  $id_or_obj
2648
+	 * @param string $relationName
2649
+	 * @param array  $where_query_params
2650
+	 * @param EE_Base_Class[] objects to which relations were removed
2651
+	 * @return EE_Base_Class[]
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2655
+	{
2656
+		$relation_obj = $this->related_settings_for($relationName);
2657
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2658
+	}
2659
+
2660
+
2661
+	/**
2662
+	 * Gets all the related items of the specified $model_name, using $query_params.
2663
+	 * Note: by default, we remove the "default query params"
2664
+	 * because we want to get even deleted items etc.
2665
+	 *
2666
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2667
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2668
+	 * @param array  $query_params @see
2669
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
+	 * @return EE_Base_Class[]
2671
+	 * @throws EE_Error
2672
+	 * @throws ReflectionException
2673
+	 */
2674
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2675
+	{
2676
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2677
+		$relation_settings = $this->related_settings_for($model_name);
2678
+		return $relation_settings->get_all_related($model_obj, $query_params);
2679
+	}
2680
+
2681
+
2682
+	/**
2683
+	 * Deletes all the model objects across the relation indicated by $model_name
2684
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2685
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2686
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2687
+	 *
2688
+	 * @param EE_Base_Class|int|string $id_or_obj
2689
+	 * @param string                   $model_name
2690
+	 * @param array                    $query_params
2691
+	 * @return int how many deleted
2692
+	 * @throws EE_Error
2693
+	 * @throws ReflectionException
2694
+	 */
2695
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2696
+	{
2697
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2698
+		$relation_settings = $this->related_settings_for($model_name);
2699
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2700
+	}
2701
+
2702
+
2703
+	/**
2704
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2705
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2706
+	 * the model objects can't be hard deleted because of blocking related model objects,
2707
+	 * just does a soft-delete on them instead.
2708
+	 *
2709
+	 * @param EE_Base_Class|int|string $id_or_obj
2710
+	 * @param string                   $model_name
2711
+	 * @param array                    $query_params
2712
+	 * @return int how many deleted
2713
+	 * @throws EE_Error
2714
+	 * @throws ReflectionException
2715
+	 */
2716
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2717
+	{
2718
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2719
+		$relation_settings = $this->related_settings_for($model_name);
2720
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2721
+	}
2722
+
2723
+
2724
+	/**
2725
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2726
+	 * unless otherwise specified in the $query_params
2727
+	 *
2728
+	 * @param int             /EE_Base_Class $id_or_obj
2729
+	 * @param string $model_name     like 'Event', or 'Registration'
2730
+	 * @param array  $query_params   @see
2731
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2732
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2733
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2734
+	 *                               that by the setting $distinct to TRUE;
2735
+	 * @return int
2736
+	 * @throws EE_Error
2737
+	 */
2738
+	public function count_related(
2739
+		$id_or_obj,
2740
+		$model_name,
2741
+		$query_params = [],
2742
+		$field_to_count = null,
2743
+		$distinct = false
2744
+	) {
2745
+		$related_model = $this->get_related_model_obj($model_name);
2746
+		// we're just going to use the query params on the related model's normal get_all query,
2747
+		// except add a condition to say to match the current mod
2748
+		if (! isset($query_params['default_where_conditions'])) {
2749
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2750
+		}
2751
+		$this_model_name                                                 = $this->get_this_model_name();
2752
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2753
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2754
+		return $related_model->count($query_params, $field_to_count, $distinct);
2755
+	}
2756
+
2757
+
2758
+	/**
2759
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2760
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2761
+	 *
2762
+	 * @param int           /EE_Base_Class $id_or_obj
2763
+	 * @param string $model_name   like 'Event', or 'Registration'
2764
+	 * @param array  $query_params @see
2765
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2766
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2767
+	 * @return float
2768
+	 * @throws EE_Error
2769
+	 */
2770
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2771
+	{
2772
+		$related_model = $this->get_related_model_obj($model_name);
2773
+		if (! is_array($query_params)) {
2774
+			EE_Error::doing_it_wrong(
2775
+				'EEM_Base::sum_related',
2776
+				sprintf(
2777
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2778
+					gettype($query_params)
2779
+				),
2780
+				'4.6.0'
2781
+			);
2782
+			$query_params = [];
2783
+		}
2784
+		// we're just going to use the query params on the related model's normal get_all query,
2785
+		// except add a condition to say to match the current mod
2786
+		if (! isset($query_params['default_where_conditions'])) {
2787
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2788
+		}
2789
+		$this_model_name                                                 = $this->get_this_model_name();
2790
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2791
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2792
+		return $related_model->sum($query_params, $field_to_sum);
2793
+	}
2794
+
2795
+
2796
+	/**
2797
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2798
+	 * $modelObject
2799
+	 *
2800
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2801
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2802
+	 * @param array               $query_params     @see
2803
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2804
+	 * @return EE_Base_Class
2805
+	 * @throws EE_Error
2806
+	 */
2807
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2808
+	{
2809
+		$query_params['limit'] = 1;
2810
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2811
+		if ($results) {
2812
+			return array_shift($results);
2813
+		}
2814
+		return null;
2815
+	}
2816
+
2817
+
2818
+	/**
2819
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2820
+	 *
2821
+	 * @return string
2822
+	 */
2823
+	public function get_this_model_name()
2824
+	{
2825
+		return str_replace("EEM_", "", get_class($this));
2826
+	}
2827
+
2828
+
2829
+	/**
2830
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2831
+	 *
2832
+	 * @return EE_Any_Foreign_Model_Name_Field
2833
+	 * @throws EE_Error
2834
+	 */
2835
+	public function get_field_containing_related_model_name()
2836
+	{
2837
+		foreach ($this->field_settings(true) as $field) {
2838
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2839
+				$field_with_model_name = $field;
2840
+			}
2841
+		}
2842
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2843
+			throw new EE_Error(
2844
+				sprintf(
2845
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2846
+					$this->get_this_model_name()
2847
+				)
2848
+			);
2849
+		}
2850
+		return $field_with_model_name;
2851
+	}
2852
+
2853
+
2854
+	/**
2855
+	 * Inserts a new entry into the database, for each table.
2856
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2857
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2858
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2859
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2860
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2861
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2862
+	 *
2863
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2864
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2865
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2866
+	 *                              of EEM_Base)
2867
+	 * @return int|string new primary key on main table that got inserted
2868
+	 * @throws EE_Error
2869
+	 */
2870
+	public function insert($field_n_values)
2871
+	{
2872
+		/**
2873
+		 * Filters the fields and their values before inserting an item using the models
2874
+		 *
2875
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2876
+		 * @param EEM_Base $model           the model used
2877
+		 */
2878
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2879
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2880
+			$main_table = $this->_get_main_table();
2881
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2882
+			if ($new_id !== false) {
2883
+				foreach ($this->_get_other_tables() as $other_table) {
2884
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2885
+				}
2886
+			}
2887
+			/**
2888
+			 * Done just after attempting to insert a new model object
2889
+			 *
2890
+			 * @param EEM_Base $model           used
2891
+			 * @param array    $fields_n_values fields and their values
2892
+			 * @param int|string the              ID of the newly-inserted model object
2893
+			 */
2894
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2895
+			return $new_id;
2896
+		}
2897
+		return false;
2898
+	}
2899
+
2900
+
2901
+	/**
2902
+	 * Checks that the result would satisfy the unique indexes on this model
2903
+	 *
2904
+	 * @param array  $field_n_values
2905
+	 * @param string $action
2906
+	 * @return boolean
2907
+	 * @throws EE_Error
2908
+	 */
2909
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2910
+	{
2911
+		foreach ($this->unique_indexes() as $index_name => $index) {
2912
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2913
+			if ($this->exists([$uniqueness_where_params])) {
2914
+				EE_Error::add_error(
2915
+					sprintf(
2916
+						esc_html__(
2917
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2918
+							"event_espresso"
2919
+						),
2920
+						$action,
2921
+						$this->_get_class_name(),
2922
+						$index_name,
2923
+						implode(",", $index->field_names()),
2924
+						http_build_query($uniqueness_where_params)
2925
+					),
2926
+					__FILE__,
2927
+					__FUNCTION__,
2928
+					__LINE__
2929
+				);
2930
+				return false;
2931
+			}
2932
+		}
2933
+		return true;
2934
+	}
2935
+
2936
+
2937
+	/**
2938
+	 * Checks the database for an item that conflicts (ie, if this item were
2939
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2940
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2941
+	 * can be either an EE_Base_Class or an array of fields n values
2942
+	 *
2943
+	 * @param EE_Base_Class|array $obj_or_fields_array
2944
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2945
+	 *                                                 when looking for conflicts
2946
+	 *                                                 (ie, if false, we ignore the model object's primary key
2947
+	 *                                                 when finding "conflicts". If true, it's also considered).
2948
+	 *                                                 Only works for INT primary key,
2949
+	 *                                                 STRING primary keys cannot be ignored
2950
+	 * @return EE_Base_Class|array
2951
+	 * @throws EE_Error
2952
+	 * @throws ReflectionException
2953
+	 */
2954
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2955
+	{
2956
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2957
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2958
+		} elseif (is_array($obj_or_fields_array)) {
2959
+			$fields_n_values = $obj_or_fields_array;
2960
+		} else {
2961
+			throw new EE_Error(
2962
+				sprintf(
2963
+					esc_html__(
2964
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2965
+						"event_espresso"
2966
+					),
2967
+					get_class($this),
2968
+					$obj_or_fields_array
2969
+				)
2970
+			);
2971
+		}
2972
+		$query_params = [];
2973
+		if (
2974
+			$this->has_primary_key_field()
2975
+			&& ($include_primary_key
2976
+				|| $this->get_primary_key_field()
2977
+				   instanceof
2978
+				   EE_Primary_Key_String_Field)
2979
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2980
+		) {
2981
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2982
+		}
2983
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2984
+			$uniqueness_where_params                              =
2985
+				array_intersect_key($fields_n_values, $unique_index->fields());
2986
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2987
+		}
2988
+		// if there is nothing to base this search on, then we shouldn't find anything
2989
+		if (empty($query_params)) {
2990
+			return [];
2991
+		}
2992
+		return $this->get_one($query_params);
2993
+	}
2994
+
2995
+
2996
+	/**
2997
+	 * Like count, but is optimized and returns a boolean instead of an int
2998
+	 *
2999
+	 * @param array $query_params
3000
+	 * @return boolean
3001
+	 * @throws EE_Error
3002
+	 */
3003
+	public function exists($query_params)
3004
+	{
3005
+		$query_params['limit'] = 1;
3006
+		return $this->count($query_params) > 0;
3007
+	}
3008
+
3009
+
3010
+	/**
3011
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3012
+	 *
3013
+	 * @param int|string $id
3014
+	 * @return boolean
3015
+	 * @throws EE_Error
3016
+	 */
3017
+	public function exists_by_ID($id)
3018
+	{
3019
+		return $this->exists(
3020
+			[
3021
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3022
+				[
3023
+					$this->primary_key_name() => $id,
3024
+				],
3025
+			]
3026
+		);
3027
+	}
3028
+
3029
+
3030
+	/**
3031
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3032
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3033
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3034
+	 * on the main table)
3035
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3036
+	 * cases where we want to call it directly rather than via insert().
3037
+	 *
3038
+	 * @access   protected
3039
+	 * @param EE_Table_Base $table
3040
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3041
+	 *                                       float
3042
+	 * @param int           $new_id          for now we assume only int keys
3043
+	 * @return int ID of new row inserted, or FALSE on failure
3044
+	 * @throws EE_Error
3045
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3046
+	 */
3047
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3048
+	{
3049
+		global $wpdb;
3050
+		$insertion_col_n_values = [];
3051
+		$format_for_insertion   = [];
3052
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3053
+		foreach ($fields_on_table as $field_name => $field_obj) {
3054
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3055
+			if ($field_obj->is_auto_increment()) {
3056
+				continue;
3057
+			}
3058
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3059
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3060
+			if ($prepared_value !== null) {
3061
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3062
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3063
+			}
3064
+		}
3065
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3066
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3067
+			// so add the fk to the main table as a column
3068
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3069
+			$format_for_insertion[]                              =
3070
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3071
+		}
3072
+
3073
+		// insert the new entry
3074
+		$result = $this->_do_wpdb_query(
3075
+			'insert',
3076
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3077
+		);
3078
+		if ($result === false) {
3079
+			return false;
3080
+		}
3081
+		// ok, now what do we return for the ID of the newly-inserted thing?
3082
+		if ($this->has_primary_key_field()) {
3083
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3084
+				return $wpdb->insert_id;
3085
+			}
3086
+			// it's not an auto-increment primary key, so
3087
+			// it must have been supplied
3088
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3089
+		}
3090
+		// we can't return a  primary key because there is none. instead return
3091
+		// a unique string indicating this model
3092
+		return $this->get_index_primary_key_string($fields_n_values);
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3098
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3099
+	 * and there is no default, we pass it along. WPDB will take care of it)
3100
+	 *
3101
+	 * @param EE_Model_Field_Base $field_obj
3102
+	 * @param array               $fields_n_values
3103
+	 * @return mixed string|int|float depending on what the table column will be expecting
3104
+	 * @throws EE_Error
3105
+	 */
3106
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3107
+	{
3108
+		$field_name = $field_obj->get_name();
3109
+		// if this field doesn't allow nullable, don't allow it
3110
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3111
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3112
+		}
3113
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3114
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3115
+	}
3116
+
3117
+
3118
+	/**
3119
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3120
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3121
+	 * the field's prepare_for_set() method.
3122
+	 *
3123
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3124
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3125
+	 *                                   top of file)
3126
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3127
+	 *                                   $value is a custom selection
3128
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3129
+	 */
3130
+	private function _prepare_value_for_use_in_db($value, $field)
3131
+	{
3132
+		if ($field instanceof EE_Model_Field_Base) {
3133
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3134
+			switch ($this->_values_already_prepared_by_model_object) {
3135
+				/** @noinspection PhpMissingBreakStatementInspection */
3136
+				case self::not_prepared_by_model_object:
3137
+					$value = $field->prepare_for_set($value);
3138
+				// purposefully left out "return"
3139
+				// no break
3140
+				case self::prepared_by_model_object:
3141
+					/** @noinspection SuspiciousAssignmentsInspection */
3142
+					$value = $field->prepare_for_use_in_db($value);
3143
+				// no break
3144
+				case self::prepared_for_use_in_db:
3145
+					// leave the value alone
3146
+			}
3147
+			// phpcs:enable
3148
+		}
3149
+		return $value;
3150
+	}
3151
+
3152
+
3153
+	/**
3154
+	 * Returns the main table on this model
3155
+	 *
3156
+	 * @return EE_Primary_Table
3157
+	 * @throws EE_Error
3158
+	 */
3159
+	protected function _get_main_table()
3160
+	{
3161
+		foreach ($this->_tables as $table) {
3162
+			if ($table instanceof EE_Primary_Table) {
3163
+				return $table;
3164
+			}
3165
+		}
3166
+		throw new EE_Error(
3167
+			sprintf(
3168
+				esc_html__(
3169
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3170
+					'event_espresso'
3171
+				),
3172
+				get_class($this)
3173
+			)
3174
+		);
3175
+	}
3176
+
3177
+
3178
+	/**
3179
+	 * table
3180
+	 * returns EE_Primary_Table table name
3181
+	 *
3182
+	 * @return string
3183
+	 * @throws EE_Error
3184
+	 */
3185
+	public function table()
3186
+	{
3187
+		return $this->_get_main_table()->get_table_name();
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * table
3193
+	 * returns first EE_Secondary_Table table name
3194
+	 *
3195
+	 * @return string
3196
+	 */
3197
+	public function second_table()
3198
+	{
3199
+		// grab second table from tables array
3200
+		$second_table = end($this->_tables);
3201
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3202
+	}
3203
+
3204
+
3205
+	/**
3206
+	 * get_table_obj_by_alias
3207
+	 * returns table name given it's alias
3208
+	 *
3209
+	 * @param string $table_alias
3210
+	 * @return EE_Primary_Table | EE_Secondary_Table
3211
+	 */
3212
+	public function get_table_obj_by_alias($table_alias = '')
3213
+	{
3214
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3215
+	}
3216
+
3217
+
3218
+	/**
3219
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3220
+	 *
3221
+	 * @return EE_Secondary_Table[]
3222
+	 */
3223
+	protected function _get_other_tables()
3224
+	{
3225
+		$other_tables = [];
3226
+		foreach ($this->_tables as $table_alias => $table) {
3227
+			if ($table instanceof EE_Secondary_Table) {
3228
+				$other_tables[ $table_alias ] = $table;
3229
+			}
3230
+		}
3231
+		return $other_tables;
3232
+	}
3233
+
3234
+
3235
+	/**
3236
+	 * Finds all the fields that correspond to the given table
3237
+	 *
3238
+	 * @param string $table_alias , array key in EEM_Base::_tables
3239
+	 * @return EE_Model_Field_Base[]
3240
+	 */
3241
+	public function _get_fields_for_table($table_alias)
3242
+	{
3243
+		return $this->_fields[ $table_alias ];
3244
+	}
3245
+
3246
+
3247
+	/**
3248
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3249
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3250
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3251
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3252
+	 * related Registration, Transaction, and Payment models.
3253
+	 *
3254
+	 * @param array $query_params @see
3255
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3256
+	 * @return EE_Model_Query_Info_Carrier
3257
+	 * @throws EE_Error
3258
+	 */
3259
+	public function _extract_related_models_from_query($query_params)
3260
+	{
3261
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3262
+		if (array_key_exists(0, $query_params)) {
3263
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3264
+		}
3265
+		if (array_key_exists('group_by', $query_params)) {
3266
+			if (is_array($query_params['group_by'])) {
3267
+				$this->_extract_related_models_from_sub_params_array_values(
3268
+					$query_params['group_by'],
3269
+					$query_info_carrier,
3270
+					'group_by'
3271
+				);
3272
+			} elseif (! empty($query_params['group_by'])) {
3273
+				$this->_extract_related_model_info_from_query_param(
3274
+					$query_params['group_by'],
3275
+					$query_info_carrier,
3276
+					'group_by'
3277
+				);
3278
+			}
3279
+		}
3280
+		if (array_key_exists('having', $query_params)) {
3281
+			$this->_extract_related_models_from_sub_params_array_keys(
3282
+				$query_params[0],
3283
+				$query_info_carrier,
3284
+				'having'
3285
+			);
3286
+		}
3287
+		if (array_key_exists('order_by', $query_params)) {
3288
+			if (is_array($query_params['order_by'])) {
3289
+				$this->_extract_related_models_from_sub_params_array_keys(
3290
+					$query_params['order_by'],
3291
+					$query_info_carrier,
3292
+					'order_by'
3293
+				);
3294
+			} elseif (! empty($query_params['order_by'])) {
3295
+				$this->_extract_related_model_info_from_query_param(
3296
+					$query_params['order_by'],
3297
+					$query_info_carrier,
3298
+					'order_by'
3299
+				);
3300
+			}
3301
+		}
3302
+		if (array_key_exists('force_join', $query_params)) {
3303
+			$this->_extract_related_models_from_sub_params_array_values(
3304
+				$query_params['force_join'],
3305
+				$query_info_carrier,
3306
+				'force_join'
3307
+			);
3308
+		}
3309
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3310
+		return $query_info_carrier;
3311
+	}
3312
+
3313
+
3314
+	/**
3315
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3316
+	 *
3317
+	 * @param array                       $sub_query_params @see
3318
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3319
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3320
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3321
+	 * @return EE_Model_Query_Info_Carrier
3322
+	 * @throws EE_Error
3323
+	 */
3324
+	private function _extract_related_models_from_sub_params_array_keys(
3325
+		$sub_query_params,
3326
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3327
+		$query_param_type
3328
+	) {
3329
+		if (! empty($sub_query_params)) {
3330
+			$sub_query_params = (array) $sub_query_params;
3331
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3332
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3333
+				$this->_extract_related_model_info_from_query_param(
3334
+					$param,
3335
+					$model_query_info_carrier,
3336
+					$query_param_type
3337
+				);
3338
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3339
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3340
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3341
+				// of array('Registration.TXN_ID'=>23)
3342
+				$query_param_sans_stars =
3343
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3344
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3345
+					if (! is_array($possibly_array_of_params)) {
3346
+						throw new EE_Error(
3347
+							sprintf(
3348
+								esc_html__(
3349
+									"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3350
+									"event_espresso"
3351
+								),
3352
+								$param,
3353
+								$possibly_array_of_params
3354
+							)
3355
+						);
3356
+					}
3357
+					$this->_extract_related_models_from_sub_params_array_keys(
3358
+						$possibly_array_of_params,
3359
+						$model_query_info_carrier,
3360
+						$query_param_type
3361
+					);
3362
+				} elseif (
3363
+					$query_param_type === 0 // ie WHERE
3364
+					&& is_array($possibly_array_of_params)
3365
+					&& isset($possibly_array_of_params[2])
3366
+					&& $possibly_array_of_params[2] == true
3367
+				) {
3368
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3369
+					// indicating that $possible_array_of_params[1] is actually a field name,
3370
+					// from which we should extract query parameters!
3371
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3372
+						throw new EE_Error(
3373
+							sprintf(
3374
+								esc_html__(
3375
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3376
+									"event_espresso"
3377
+								),
3378
+								$query_param_type,
3379
+								implode(",", $possibly_array_of_params)
3380
+							)
3381
+						);
3382
+					}
3383
+					$this->_extract_related_model_info_from_query_param(
3384
+						$possibly_array_of_params[1],
3385
+						$model_query_info_carrier,
3386
+						$query_param_type
3387
+					);
3388
+				}
3389
+			}
3390
+		}
3391
+		return $model_query_info_carrier;
3392
+	}
3393
+
3394
+
3395
+	/**
3396
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3397
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3398
+	 *
3399
+	 * @param array                       $sub_query_params @see
3400
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3401
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3402
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3403
+	 * @return EE_Model_Query_Info_Carrier
3404
+	 * @throws EE_Error
3405
+	 */
3406
+	private function _extract_related_models_from_sub_params_array_values(
3407
+		$sub_query_params,
3408
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3409
+		$query_param_type
3410
+	) {
3411
+		if (! empty($sub_query_params)) {
3412
+			if (! is_array($sub_query_params)) {
3413
+				throw new EE_Error(
3414
+					sprintf(
3415
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3416
+						$sub_query_params
3417
+					)
3418
+				);
3419
+			}
3420
+			foreach ($sub_query_params as $param) {
3421
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3422
+				$this->_extract_related_model_info_from_query_param(
3423
+					$param,
3424
+					$model_query_info_carrier,
3425
+					$query_param_type
3426
+				);
3427
+			}
3428
+		}
3429
+		return $model_query_info_carrier;
3430
+	}
3431
+
3432
+
3433
+	/**
3434
+	 * Extract all the query parts from  model query params
3435
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3436
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3437
+	 * but use them in a different order. Eg, we need to know what models we are querying
3438
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3439
+	 * other models before we can finalize the where clause SQL.
3440
+	 *
3441
+	 * @param array $query_params @see
3442
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3443
+	 * @return EE_Model_Query_Info_Carrier
3444
+	 * @throws EE_Error
3445
+	 * @throws ModelConfigurationException*@throws ReflectionException
3446
+	 * @throws ReflectionException
3447
+	 */
3448
+	public function _create_model_query_info_carrier($query_params)
3449
+	{
3450
+		if (! is_array($query_params)) {
3451
+			EE_Error::doing_it_wrong(
3452
+				'EEM_Base::_create_model_query_info_carrier',
3453
+				sprintf(
3454
+					esc_html__(
3455
+						'$query_params should be an array, you passed a variable of type %s',
3456
+						'event_espresso'
3457
+					),
3458
+					gettype($query_params)
3459
+				),
3460
+				'4.6.0'
3461
+			);
3462
+			$query_params = [];
3463
+		}
3464
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3465
+		// first check if we should alter the query to account for caps or not
3466
+		// because the caps might require us to do extra joins
3467
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3468
+			$query_params[0] = array_replace_recursive(
3469
+				$query_params[0],
3470
+				$this->caps_where_conditions($query_params['caps'])
3471
+			);
3472
+		}
3473
+
3474
+		// check if we should alter the query to remove data related to protected
3475
+		// custom post types
3476
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3477
+			$where_param_key_for_password = $this->modelChainAndPassword();
3478
+			// only include if related to a cpt where no password has been set
3479
+			$query_params[0]['OR*nopassword'] = [
3480
+				$where_param_key_for_password       => '',
3481
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3482
+			];
3483
+		}
3484
+		$query_object = $this->_extract_related_models_from_query($query_params);
3485
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3486
+		foreach ($query_params[0] as $key => $value) {
3487
+			if (is_int($key)) {
3488
+				throw new EE_Error(
3489
+					sprintf(
3490
+						esc_html__(
3491
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3492
+							"event_espresso"
3493
+						),
3494
+						$key,
3495
+						var_export($value, true),
3496
+						var_export($query_params, true),
3497
+						get_class($this)
3498
+					)
3499
+				);
3500
+			}
3501
+		}
3502
+		if (
3503
+			array_key_exists('default_where_conditions', $query_params)
3504
+			&& ! empty($query_params['default_where_conditions'])
3505
+		) {
3506
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3507
+		} else {
3508
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3509
+		}
3510
+		$query_params[0] = array_merge(
3511
+			$this->_get_default_where_conditions_for_models_in_query(
3512
+				$query_object,
3513
+				$use_default_where_conditions,
3514
+				$query_params[0]
3515
+			),
3516
+			$query_params[0]
3517
+		);
3518
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3519
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3520
+		// So we need to setup a subquery and use that for the main join.
3521
+		// Note for now this only works on the primary table for the model.
3522
+		// So for instance, you could set the limit array like this:
3523
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3524
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3525
+			$query_object->set_main_model_join_sql(
3526
+				$this->_construct_limit_join_select(
3527
+					$query_params['on_join_limit'][0],
3528
+					$query_params['on_join_limit'][1]
3529
+				)
3530
+			);
3531
+		}
3532
+		// set limit
3533
+		if (array_key_exists('limit', $query_params)) {
3534
+			if (is_array($query_params['limit'])) {
3535
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3536
+					$e = sprintf(
3537
+						esc_html__(
3538
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3539
+							"event_espresso"
3540
+						),
3541
+						http_build_query($query_params['limit'])
3542
+					);
3543
+					throw new EE_Error($e . "|" . $e);
3544
+				}
3545
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3546
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3547
+			} elseif (! empty($query_params['limit'])) {
3548
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3549
+			}
3550
+		}
3551
+		// set order by
3552
+		if (array_key_exists('order_by', $query_params)) {
3553
+			if (is_array($query_params['order_by'])) {
3554
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3555
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3556
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3557
+				if (array_key_exists('order', $query_params)) {
3558
+					throw new EE_Error(
3559
+						sprintf(
3560
+							esc_html__(
3561
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3562
+								"event_espresso"
3563
+							),
3564
+							get_class($this),
3565
+							implode(", ", array_keys($query_params['order_by'])),
3566
+							implode(", ", $query_params['order_by']),
3567
+							$query_params['order']
3568
+						)
3569
+					);
3570
+				}
3571
+				$this->_extract_related_models_from_sub_params_array_keys(
3572
+					$query_params['order_by'],
3573
+					$query_object,
3574
+					'order_by'
3575
+				);
3576
+				// assume it's an array of fields to order by
3577
+				$order_array = [];
3578
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3579
+					$order         = $this->_extract_order($order);
3580
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3581
+				}
3582
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3583
+			} elseif (! empty($query_params['order_by'])) {
3584
+				$this->_extract_related_model_info_from_query_param(
3585
+					$query_params['order_by'],
3586
+					$query_object,
3587
+					'order',
3588
+					$query_params['order_by']
3589
+				);
3590
+				$order = isset($query_params['order'])
3591
+					? $this->_extract_order($query_params['order'])
3592
+					: 'DESC';
3593
+				$query_object->set_order_by_sql(
3594
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3595
+				);
3596
+			}
3597
+		}
3598
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3599
+		if (
3600
+			! array_key_exists('order_by', $query_params)
3601
+			&& array_key_exists('order', $query_params)
3602
+			&& ! empty($query_params['order'])
3603
+		) {
3604
+			$pk_field = $this->get_primary_key_field();
3605
+			$order    = $this->_extract_order($query_params['order']);
3606
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3607
+		}
3608
+		// set group by
3609
+		if (array_key_exists('group_by', $query_params)) {
3610
+			if (is_array($query_params['group_by'])) {
3611
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3612
+				$group_by_array = [];
3613
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3614
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3615
+				}
3616
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3617
+			} elseif (! empty($query_params['group_by'])) {
3618
+				$query_object->set_group_by_sql(
3619
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3620
+				);
3621
+			}
3622
+		}
3623
+		// set having
3624
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3625
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3626
+		}
3627
+		// now, just verify they didn't pass anything wack
3628
+		foreach ($query_params as $query_key => $query_value) {
3629
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3630
+				throw new EE_Error(
3631
+					sprintf(
3632
+						esc_html__(
3633
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3634
+							'event_espresso'
3635
+						),
3636
+						$query_key,
3637
+						get_class($this),
3638
+						//                      print_r( $this->_allowed_query_params, TRUE )
3639
+						implode(',', $this->_allowed_query_params)
3640
+					)
3641
+				);
3642
+			}
3643
+		}
3644
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3645
+		if (empty($main_model_join_sql)) {
3646
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3647
+		}
3648
+		return $query_object;
3649
+	}
3650
+
3651
+
3652
+	/**
3653
+	 * Gets the where conditions that should be imposed on the query based on the
3654
+	 * context (eg reading frontend, backend, edit or delete).
3655
+	 *
3656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3657
+	 * @return array @see
3658
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
+	 * @throws EE_Error
3660
+	 */
3661
+	public function caps_where_conditions($context = self::caps_read)
3662
+	{
3663
+		EEM_Base::verify_is_valid_cap_context($context);
3664
+		$cap_where_conditions = [];
3665
+		$cap_restrictions     = $this->caps_missing($context);
3666
+		/**
3667
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3668
+		 */
3669
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3670
+			$cap_where_conditions = array_replace_recursive(
3671
+				$cap_where_conditions,
3672
+				$restriction_if_no_cap->get_default_where_conditions()
3673
+			);
3674
+		}
3675
+		return apply_filters(
3676
+			'FHEE__EEM_Base__caps_where_conditions__return',
3677
+			$cap_where_conditions,
3678
+			$this,
3679
+			$context,
3680
+			$cap_restrictions
3681
+		);
3682
+	}
3683
+
3684
+
3685
+	/**
3686
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3687
+	 * otherwise throws an exception
3688
+	 *
3689
+	 * @param string $should_be_order_string
3690
+	 * @return string either ASC, asc, DESC or desc
3691
+	 * @throws EE_Error
3692
+	 */
3693
+	private function _extract_order($should_be_order_string)
3694
+	{
3695
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3696
+			return $should_be_order_string;
3697
+		}
3698
+		throw new EE_Error(
3699
+			sprintf(
3700
+				esc_html__(
3701
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3702
+					"event_espresso"
3703
+				),
3704
+				get_class($this),
3705
+				$should_be_order_string
3706
+			)
3707
+		);
3708
+	}
3709
+
3710
+
3711
+	/**
3712
+	 * Looks at all the models which are included in this query, and asks each
3713
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3714
+	 * so they can be merged
3715
+	 *
3716
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3717
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3718
+	 *                                                                  'none' means NO default where conditions will
3719
+	 *                                                                  be used AT ALL during this query.
3720
+	 *                                                                  'other_models_only' means default where
3721
+	 *                                                                  conditions from other models will be used, but
3722
+	 *                                                                  not for this primary model. 'all', the default,
3723
+	 *                                                                  means default where conditions will apply as
3724
+	 *                                                                  normal
3725
+	 * @param array                       $where_query_params           @see
3726
+	 *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3727
+	 * @throws EE_Error
3728
+	 */
3729
+	private function _get_default_where_conditions_for_models_in_query(
3730
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3731
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3732
+		$where_query_params = []
3733
+	) {
3734
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3735
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3736
+			throw new EE_Error(
3737
+				sprintf(
3738
+					esc_html__(
3739
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3740
+						"event_espresso"
3741
+					),
3742
+					$use_default_where_conditions,
3743
+					implode(", ", $allowed_used_default_where_conditions_values)
3744
+				)
3745
+			);
3746
+		}
3747
+		$universal_query_params = [];
3748
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3749
+			$universal_query_params = $this->_get_default_where_conditions();
3750
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3751
+			$universal_query_params = $this->_get_minimum_where_conditions();
3752
+		}
3753
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3754
+			$related_model = $this->get_related_model_obj($model_name);
3755
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3756
+				$related_model_universal_where_params =
3757
+					$related_model->_get_default_where_conditions($model_relation_path);
3758
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3759
+				$related_model_universal_where_params =
3760
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3761
+			} else {
3762
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3763
+				continue;
3764
+			}
3765
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3766
+				$related_model_universal_where_params,
3767
+				$where_query_params,
3768
+				$related_model,
3769
+				$model_relation_path
3770
+			);
3771
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3772
+				$universal_query_params,
3773
+				$overrides
3774
+			);
3775
+		}
3776
+		return $universal_query_params;
3777
+	}
3778
+
3779
+
3780
+	/**
3781
+	 * Determines whether or not we should use default where conditions for the model in question
3782
+	 * (this model, or other related models).
3783
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3784
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3785
+	 * We should use default where conditions on related models when they requested to use default where conditions
3786
+	 * on all models, or specifically just on other related models
3787
+	 *
3788
+	 * @param      $default_where_conditions_value
3789
+	 * @param bool $for_this_model false means this is for OTHER related models
3790
+	 * @return bool
3791
+	 */
3792
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3793
+	{
3794
+		return (
3795
+				   $for_this_model
3796
+				   && in_array(
3797
+					   $default_where_conditions_value,
3798
+					   [
3799
+						   EEM_Base::default_where_conditions_all,
3800
+						   EEM_Base::default_where_conditions_this_only,
3801
+						   EEM_Base::default_where_conditions_minimum_others,
3802
+					   ],
3803
+					   true
3804
+				   )
3805
+			   )
3806
+			   || (
3807
+				   ! $for_this_model
3808
+				   && in_array(
3809
+					   $default_where_conditions_value,
3810
+					   [
3811
+						   EEM_Base::default_where_conditions_all,
3812
+						   EEM_Base::default_where_conditions_others_only,
3813
+					   ],
3814
+					   true
3815
+				   )
3816
+			   );
3817
+	}
3818
+
3819
+
3820
+	/**
3821
+	 * Determines whether or not we should use default minimum conditions for the model in question
3822
+	 * (this model, or other related models).
3823
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3824
+	 * where conditions.
3825
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3826
+	 * on this model or others
3827
+	 *
3828
+	 * @param      $default_where_conditions_value
3829
+	 * @param bool $for_this_model false means this is for OTHER related models
3830
+	 * @return bool
3831
+	 */
3832
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3833
+	{
3834
+		return (
3835
+				   $for_this_model
3836
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3837
+			   )
3838
+			   || (
3839
+				   ! $for_this_model
3840
+				   && in_array(
3841
+					   $default_where_conditions_value,
3842
+					   [
3843
+						   EEM_Base::default_where_conditions_minimum_others,
3844
+						   EEM_Base::default_where_conditions_minimum_all,
3845
+					   ],
3846
+					   true
3847
+				   )
3848
+			   );
3849
+	}
3850
+
3851
+
3852
+	/**
3853
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3854
+	 * then we also add a special where condition which allows for that model's primary key
3855
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3856
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3857
+	 *
3858
+	 * @param array    $default_where_conditions
3859
+	 * @param array    $provided_where_conditions
3860
+	 * @param EEM_Base $model
3861
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3862
+	 * @return array @see
3863
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3864
+	 * @throws EE_Error
3865
+	 */
3866
+	private function _override_defaults_or_make_null_friendly(
3867
+		$default_where_conditions,
3868
+		$provided_where_conditions,
3869
+		$model,
3870
+		$model_relation_path
3871
+	) {
3872
+		$null_friendly_where_conditions = [];
3873
+		$none_overridden                = true;
3874
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3875
+		foreach ($default_where_conditions as $key => $val) {
3876
+			if (isset($provided_where_conditions[ $key ])) {
3877
+				$none_overridden = false;
3878
+			} else {
3879
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3880
+			}
3881
+		}
3882
+		if ($none_overridden && $default_where_conditions) {
3883
+			if ($model->has_primary_key_field()) {
3884
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3885
+																				   . "."
3886
+																				   . $model->primary_key_name() ] =
3887
+					['IS NULL'];
3888
+			}/*else{
3889 3889
                 //@todo NO PK, use other defaults
3890 3890
             }*/
3891
-        }
3892
-        return $null_friendly_where_conditions;
3893
-    }
3894
-
3895
-
3896
-    /**
3897
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3898
-     * default where conditions on all get_all, update, and delete queries done by this model.
3899
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3900
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3901
-     *
3902
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3903
-     * @return array @see
3904
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3905
-     * @throws EE_Error
3906
-     * @throws EE_Error
3907
-     */
3908
-    private function _get_default_where_conditions($model_relation_path = '')
3909
-    {
3910
-        if ($this->_ignore_where_strategy) {
3911
-            return [];
3912
-        }
3913
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3914
-    }
3915
-
3916
-
3917
-    /**
3918
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3919
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3920
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3921
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3922
-     * Similar to _get_default_where_conditions
3923
-     *
3924
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3925
-     * @return array @see
3926
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3927
-     * @throws EE_Error
3928
-     * @throws EE_Error
3929
-     */
3930
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3931
-    {
3932
-        if ($this->_ignore_where_strategy) {
3933
-            return [];
3934
-        }
3935
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3936
-    }
3937
-
3938
-
3939
-    /**
3940
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3941
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3942
-     *
3943
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3944
-     * @return string
3945
-     * @throws EE_Error
3946
-     */
3947
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3948
-    {
3949
-        $selects = $this->_get_columns_to_select_for_this_model();
3950
-        foreach (
3951
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3952
-        ) {
3953
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3954
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3955
-            foreach ($other_model_selects as $key => $value) {
3956
-                $selects[] = $value;
3957
-            }
3958
-        }
3959
-        return implode(", ", $selects);
3960
-    }
3961
-
3962
-
3963
-    /**
3964
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3965
-     * So that's going to be the columns for all the fields on the model
3966
-     *
3967
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3968
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3969
-     */
3970
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3971
-    {
3972
-        $fields                                       = $this->field_settings();
3973
-        $selects                                      = [];
3974
-        $table_alias_with_model_relation_chain_prefix =
3975
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3976
-                $model_relation_chain,
3977
-                $this->get_this_model_name()
3978
-            );
3979
-        foreach ($fields as $field_obj) {
3980
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3981
-                         . $field_obj->get_table_alias()
3982
-                         . "."
3983
-                         . $field_obj->get_table_column()
3984
-                         . " AS '"
3985
-                         . $table_alias_with_model_relation_chain_prefix
3986
-                         . $field_obj->get_table_alias()
3987
-                         . "."
3988
-                         . $field_obj->get_table_column()
3989
-                         . "'";
3990
-        }
3991
-        // make sure we are also getting the PKs of each table
3992
-        $tables = $this->get_tables();
3993
-        if (count($tables) > 1) {
3994
-            foreach ($tables as $table_obj) {
3995
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3996
-                                       . $table_obj->get_fully_qualified_pk_column();
3997
-                if (! in_array($qualified_pk_column, $selects)) {
3998
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3999
-                }
4000
-            }
4001
-        }
4002
-        return $selects;
4003
-    }
4004
-
4005
-
4006
-    /**
4007
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4008
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4009
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4010
-     * SQL for joining, and the data types
4011
-     *
4012
-     * @param null|string                 $original_query_param
4013
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4014
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4015
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4016
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4017
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4018
-     *                                                          or 'Registration's
4019
-     * @param string                      $original_query_param what it originally was (eg
4020
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4021
-     *                                                          matches $query_param
4022
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4023
-     * @throws EE_Error
4024
-     */
4025
-    private function _extract_related_model_info_from_query_param(
4026
-        $query_param,
4027
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4028
-        $query_param_type,
4029
-        $original_query_param = null
4030
-    ) {
4031
-        if ($original_query_param === null) {
4032
-            $original_query_param = $query_param;
4033
-        }
4034
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4035
-        // check to see if we have a field on this model
4036
-        $this_model_fields = $this->field_settings(true);
4037
-        if (array_key_exists($query_param, $this_model_fields)) {
4038
-            $field_is_allowed = in_array(
4039
-                $query_param_type,
4040
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4041
-                true
4042
-            );
4043
-            if ($field_is_allowed) {
4044
-                return;
4045
-            }
4046
-            throw new EE_Error(
4047
-                sprintf(
4048
-                    esc_html__(
4049
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4050
-                        "event_espresso"
4051
-                    ),
4052
-                    $query_param,
4053
-                    get_class($this),
4054
-                    $query_param_type,
4055
-                    $original_query_param
4056
-                )
4057
-            );
4058
-        }
4059
-        // check if this is a special logic query param
4060
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4061
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4062
-            if ($operator_is_allowed) {
4063
-                return;
4064
-            }
4065
-            throw new EE_Error(
4066
-                sprintf(
4067
-                    esc_html__(
4068
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4069
-                        'event_espresso'
4070
-                    ),
4071
-                    implode('", "', $this->_logic_query_param_keys),
4072
-                    $query_param,
4073
-                    get_class($this),
4074
-                    '<br />',
4075
-                    "\t"
4076
-                    . ' $passed_in_query_info = <pre>'
4077
-                    . print_r($passed_in_query_info, true)
4078
-                    . '</pre>'
4079
-                    . "\n\t"
4080
-                    . ' $query_param_type = '
4081
-                    . $query_param_type
4082
-                    . "\n\t"
4083
-                    . ' $original_query_param = '
4084
-                    . $original_query_param
4085
-                )
4086
-            );
4087
-        }
4088
-        // check if it's a custom selection
4089
-        if (
4090
-            $this->_custom_selections instanceof CustomSelects
4091
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4092
-        ) {
4093
-            return;
4094
-        }
4095
-        // check if has a model name at the beginning
4096
-        // and
4097
-        // check if it's a field on a related model
4098
-        if (
4099
-            $this->extractJoinModelFromQueryParams(
4100
-                $passed_in_query_info,
4101
-                $query_param,
4102
-                $original_query_param,
4103
-                $query_param_type
4104
-            )
4105
-        ) {
4106
-            return;
4107
-        }
4108
-
4109
-        // ok so $query_param didn't start with a model name
4110
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4111
-        // it's wack, that's what it is
4112
-        throw new EE_Error(
4113
-            sprintf(
4114
-                esc_html__(
4115
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4116
-                    "event_espresso"
4117
-                ),
4118
-                $query_param,
4119
-                get_class($this),
4120
-                $query_param_type,
4121
-                $original_query_param
4122
-            )
4123
-        );
4124
-    }
4125
-
4126
-
4127
-    /**
4128
-     * Extracts any possible join model information from the provided possible_join_string.
4129
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4130
-     * join
4131
-     * parts that should be added to the query.
4132
-     *
4133
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4134
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4135
-     * @param null|string                 $original_query_param
4136
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4137
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4138
-     *                                                           etc.)
4139
-     * @return bool  returns true if a join was added and false if not.
4140
-     * @throws EE_Error
4141
-     */
4142
-    private function extractJoinModelFromQueryParams(
4143
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4144
-        $possible_join_string,
4145
-        $original_query_param,
4146
-        $query_parameter_type
4147
-    ) {
4148
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4149
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4150
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4151
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4152
-                if ($possible_join_string === '') {
4153
-                    // nothing left to $query_param
4154
-                    // we should actually end in a field name, not a model like this!
4155
-                    throw new EE_Error(
4156
-                        sprintf(
4157
-                            esc_html__(
4158
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4159
-                                "event_espresso"
4160
-                            ),
4161
-                            $possible_join_string,
4162
-                            $query_parameter_type,
4163
-                            get_class($this),
4164
-                            $valid_related_model_name
4165
-                        )
4166
-                    );
4167
-                }
4168
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4169
-                $related_model_obj->_extract_related_model_info_from_query_param(
4170
-                    $possible_join_string,
4171
-                    $query_info_carrier,
4172
-                    $query_parameter_type,
4173
-                    $original_query_param
4174
-                );
4175
-                return true;
4176
-            }
4177
-            if ($possible_join_string === $valid_related_model_name) {
4178
-                $this->_add_join_to_model(
4179
-                    $valid_related_model_name,
4180
-                    $query_info_carrier,
4181
-                    $original_query_param
4182
-                );
4183
-                return true;
4184
-            }
4185
-        }
4186
-        return false;
4187
-    }
4188
-
4189
-
4190
-    /**
4191
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4192
-     *
4193
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4194
-     * @throws EE_Error
4195
-     */
4196
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4197
-    {
4198
-        if (
4199
-            $this->_custom_selections instanceof CustomSelects
4200
-            && (
4201
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4202
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4203
-            )
4204
-        ) {
4205
-            $original_selects = $this->_custom_selections->originalSelects();
4206
-            foreach ($original_selects as $alias => $select_configuration) {
4207
-                $this->extractJoinModelFromQueryParams(
4208
-                    $query_info_carrier,
4209
-                    $select_configuration[0],
4210
-                    $select_configuration[0],
4211
-                    'custom_selects'
4212
-                );
4213
-            }
4214
-        }
4215
-    }
4216
-
4217
-
4218
-    /**
4219
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4220
-     * and store it on $passed_in_query_info
4221
-     *
4222
-     * @param string                      $model_name
4223
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4224
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4225
-     *                                                          model and $model_name. Eg, if we are querying Event,
4226
-     *                                                          and are adding a join to 'Payment' with the original
4227
-     *                                                          query param key
4228
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4229
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4230
-     *                                                          Payment wants to add default query params so that it
4231
-     *                                                          will know what models to prepend onto its default query
4232
-     *                                                          params or in case it wants to rename tables (in case
4233
-     *                                                          there are multiple joins to the same table)
4234
-     * @return void
4235
-     * @throws EE_Error
4236
-     */
4237
-    private function _add_join_to_model(
4238
-        $model_name,
4239
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4240
-        $original_query_param
4241
-    ) {
4242
-        $relation_obj         = $this->related_settings_for($model_name);
4243
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4244
-        // check if the relation is HABTM, because then we're essentially doing two joins
4245
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4246
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4247
-            $join_model_obj = $relation_obj->get_join_model();
4248
-            // replace the model specified with the join model for this relation chain, whi
4249
-            $relation_chain_to_join_model =
4250
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4251
-                    $model_name,
4252
-                    $join_model_obj->get_this_model_name(),
4253
-                    $model_relation_chain
4254
-                );
4255
-            $passed_in_query_info->merge(
4256
-                new EE_Model_Query_Info_Carrier(
4257
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4258
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4259
-                )
4260
-            );
4261
-        }
4262
-        // now just join to the other table pointed to by the relation object, and add its data types
4263
-        $passed_in_query_info->merge(
4264
-            new EE_Model_Query_Info_Carrier(
4265
-                [$model_relation_chain => $model_name],
4266
-                $relation_obj->get_join_statement($model_relation_chain)
4267
-            )
4268
-        );
4269
-    }
4270
-
4271
-
4272
-    /**
4273
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4274
-     *
4275
-     * @param array $where_params @see
4276
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4277
-     * @return string of SQL
4278
-     * @throws EE_Error
4279
-     */
4280
-    private function _construct_where_clause($where_params)
4281
-    {
4282
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4283
-        if ($SQL) {
4284
-            return " WHERE " . $SQL;
4285
-        }
4286
-        return '';
4287
-    }
4288
-
4289
-
4290
-    /**
4291
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4292
-     * and should be passed HAVING parameters, not WHERE parameters
4293
-     *
4294
-     * @param array $having_params
4295
-     * @return string
4296
-     * @throws EE_Error
4297
-     */
4298
-    private function _construct_having_clause($having_params)
4299
-    {
4300
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4301
-        if ($SQL) {
4302
-            return " HAVING " . $SQL;
4303
-        }
4304
-        return '';
4305
-    }
4306
-
4307
-
4308
-    /**
4309
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4310
-     * Event_Meta.meta_value = 'foo'))"
4311
-     *
4312
-     * @param array  $where_params @see
4313
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4314
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4315
-     * @return string of SQL
4316
-     * @throws EE_Error
4317
-     */
4318
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4319
-    {
4320
-        $where_clauses = [];
4321
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4322
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4323
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4324
-                switch ($query_param) {
4325
-                    case 'not':
4326
-                    case 'NOT':
4327
-                        $where_clauses[] = "! ("
4328
-                                           . $this->_construct_condition_clause_recursive(
4329
-                                               $op_and_value_or_sub_condition,
4330
-                                               $glue
4331
-                                           )
4332
-                                           . ")";
4333
-                        break;
4334
-                    case 'and':
4335
-                    case 'AND':
4336
-                        $where_clauses[] = " ("
4337
-                                           . $this->_construct_condition_clause_recursive(
4338
-                                               $op_and_value_or_sub_condition,
4339
-                                               ' AND '
4340
-                                           )
4341
-                                           . ")";
4342
-                        break;
4343
-                    case 'or':
4344
-                    case 'OR':
4345
-                        $where_clauses[] = " ("
4346
-                                           . $this->_construct_condition_clause_recursive(
4347
-                                               $op_and_value_or_sub_condition,
4348
-                                               ' OR '
4349
-                                           )
4350
-                                           . ")";
4351
-                        break;
4352
-                }
4353
-            } else {
4354
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4355
-                // if it's not a normal field, maybe it's a custom selection?
4356
-                if (! $field_obj) {
4357
-                    if ($this->_custom_selections instanceof CustomSelects) {
4358
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4359
-                    } else {
4360
-                        throw new EE_Error(
4361
-                            sprintf(
4362
-                                esc_html__(
4363
-                                    "%s is neither a valid model field name, nor a custom selection",
4364
-                                    "event_espresso"
4365
-                                ),
4366
-                                $query_param
4367
-                            )
4368
-                        );
4369
-                    }
4370
-                }
4371
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4372
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4373
-            }
4374
-        }
4375
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4376
-    }
4377
-
4378
-
4379
-    /**
4380
-     * Takes the input parameter and extract the table name (alias) and column name
4381
-     *
4382
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4383
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4384
-     * @throws EE_Error
4385
-     */
4386
-    private function _deduce_column_name_from_query_param($query_param)
4387
-    {
4388
-        $field = $this->_deduce_field_from_query_param($query_param);
4389
-        if ($field) {
4390
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4391
-                $field->get_model_name(),
4392
-                $query_param
4393
-            );
4394
-            return $table_alias_prefix . $field->get_qualified_column();
4395
-        }
4396
-        if (
4397
-            $this->_custom_selections instanceof CustomSelects
4398
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4399
-        ) {
4400
-            // maybe it's custom selection item?
4401
-            // if so, just use it as the "column name"
4402
-            return $query_param;
4403
-        }
4404
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4405
-            ? implode(',', $this->_custom_selections->columnAliases())
4406
-            : '';
4407
-        throw new EE_Error(
4408
-            sprintf(
4409
-                esc_html__(
4410
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4411
-                    "event_espresso"
4412
-                ),
4413
-                $query_param,
4414
-                $custom_select_aliases
4415
-            )
4416
-        );
4417
-    }
4418
-
4419
-
4420
-    /**
4421
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4422
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4423
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4424
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4425
-     *
4426
-     * @param string $condition_query_param_key
4427
-     * @return string
4428
-     */
4429
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4430
-    {
4431
-        $pos_of_star = strpos($condition_query_param_key, '*');
4432
-        if ($pos_of_star === false) {
4433
-            return $condition_query_param_key;
4434
-        }
4435
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4436
-        return $condition_query_param_sans_star;
4437
-    }
4438
-
4439
-
4440
-    /**
4441
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4442
-     *
4443
-     * @param mixed      array | string    $op_and_value
4444
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4445
-     * @return string
4446
-     * @throws EE_Error
4447
-     */
4448
-    private function _construct_op_and_value($op_and_value, $field_obj)
4449
-    {
4450
-        if (is_array($op_and_value)) {
4451
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4452
-            if (! $operator) {
4453
-                $php_array_like_string = [];
4454
-                foreach ($op_and_value as $key => $value) {
4455
-                    $php_array_like_string[] = "$key=>$value";
4456
-                }
4457
-                throw new EE_Error(
4458
-                    sprintf(
4459
-                        esc_html__(
4460
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4461
-                            "event_espresso"
4462
-                        ),
4463
-                        implode(",", $php_array_like_string)
4464
-                    )
4465
-                );
4466
-            }
4467
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4468
-        } else {
4469
-            $operator = '=';
4470
-            $value    = $op_and_value;
4471
-        }
4472
-        // check to see if the value is actually another field
4473
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4474
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4475
-        }
4476
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4477
-            // in this case, the value should be an array, or at least a comma-separated list
4478
-            // it will need to handle a little differently
4479
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4480
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4481
-            return $operator . SP . $cleaned_value;
4482
-        }
4483
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4484
-            // the value should be an array with count of two.
4485
-            if (count($value) !== 2) {
4486
-                throw new EE_Error(
4487
-                    sprintf(
4488
-                        esc_html__(
4489
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4490
-                            'event_espresso'
4491
-                        ),
4492
-                        "BETWEEN"
4493
-                    )
4494
-                );
4495
-            }
4496
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4497
-            return $operator . SP . $cleaned_value;
4498
-        }
4499
-        if (in_array($operator, $this->valid_null_style_operators())) {
4500
-            if ($value !== null) {
4501
-                throw new EE_Error(
4502
-                    sprintf(
4503
-                        esc_html__(
4504
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4505
-                            "event_espresso"
4506
-                        ),
4507
-                        $value,
4508
-                        $operator
4509
-                    )
4510
-                );
4511
-            }
4512
-            return $operator;
4513
-        }
4514
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4515
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4516
-            // remove other junk. So just treat it as a string.
4517
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4518
-        }
4519
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4520
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4521
-        }
4522
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4523
-            throw new EE_Error(
4524
-                sprintf(
4525
-                    esc_html__(
4526
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4527
-                        'event_espresso'
4528
-                    ),
4529
-                    $operator,
4530
-                    $operator
4531
-                )
4532
-            );
4533
-        }
4534
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4535
-            throw new EE_Error(
4536
-                sprintf(
4537
-                    esc_html__(
4538
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4539
-                        'event_espresso'
4540
-                    ),
4541
-                    $operator,
4542
-                    $operator
4543
-                )
4544
-            );
4545
-        }
4546
-        throw new EE_Error(
4547
-            sprintf(
4548
-                esc_html__(
4549
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4550
-                    "event_espresso"
4551
-                ),
4552
-                http_build_query($op_and_value)
4553
-            )
4554
-        );
4555
-    }
4556
-
4557
-
4558
-    /**
4559
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4560
-     *
4561
-     * @param array                      $values
4562
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4563
-     *                                              '%s'
4564
-     * @return string
4565
-     * @throws EE_Error
4566
-     */
4567
-    public function _construct_between_value($values, $field_obj)
4568
-    {
4569
-        $cleaned_values = [];
4570
-        foreach ($values as $value) {
4571
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4572
-        }
4573
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4574
-    }
4575
-
4576
-
4577
-    /**
4578
-     * Takes an array or a comma-separated list of $values and cleans them
4579
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4580
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4581
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4582
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4583
-     *
4584
-     * @param mixed                      $values    array or comma-separated string
4585
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4586
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4587
-     * @throws EE_Error
4588
-     */
4589
-    public function _construct_in_value($values, $field_obj)
4590
-    {
4591
-        $prepped = [];
4592
-        // check if the value is a CSV list
4593
-        if (is_string($values)) {
4594
-            // in which case, turn it into an array
4595
-            $values = explode(',', $values);
4596
-        }
4597
-        // make sure we only have one of each value in the list
4598
-        $values = array_unique($values);
4599
-        foreach ($values as $value) {
4600
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4601
-        }
4602
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4603
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4604
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4605
-        if (empty($prepped)) {
4606
-            $all_fields  = $this->field_settings();
4607
-            $first_field = reset($all_fields);
4608
-            $main_table  = $this->_get_main_table();
4609
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4610
-        }
4611
-        return '(' . implode(',', $prepped) . ')';
4612
-    }
4613
-
4614
-
4615
-    /**
4616
-     * @param mixed                      $value
4617
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4618
-     * @return false|null|string
4619
-     * @throws EE_Error
4620
-     */
4621
-    private function _wpdb_prepare_using_field($value, $field_obj)
4622
-    {
4623
-        /** @type WPDB $wpdb */
4624
-        global $wpdb;
4625
-        if ($field_obj instanceof EE_Model_Field_Base) {
4626
-            return $wpdb->prepare(
4627
-                $field_obj->get_wpdb_data_type(),
4628
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4629
-            );
4630
-        } //$field_obj should really just be a data type
4631
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4632
-            throw new EE_Error(
4633
-                sprintf(
4634
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4635
-                    $field_obj,
4636
-                    implode(",", $this->_valid_wpdb_data_types)
4637
-                )
4638
-            );
4639
-        }
4640
-        return $wpdb->prepare($field_obj, $value);
4641
-    }
4642
-
4643
-
4644
-    /**
4645
-     * Takes the input parameter and finds the model field that it indicates.
4646
-     *
4647
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4648
-     * @return EE_Model_Field_Base
4649
-     * @throws EE_Error
4650
-     */
4651
-    protected function _deduce_field_from_query_param($query_param_name)
4652
-    {
4653
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4654
-        // which will help us find the database table and column
4655
-        $query_param_parts = explode(".", $query_param_name);
4656
-        if (empty($query_param_parts)) {
4657
-            throw new EE_Error(
4658
-                sprintf(
4659
-                    esc_html__(
4660
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4661
-                        'event_espresso'
4662
-                    ),
4663
-                    $query_param_name
4664
-                )
4665
-            );
4666
-        }
4667
-        $number_of_parts       = count($query_param_parts);
4668
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4669
-        if ($number_of_parts === 1) {
4670
-            $field_name = $last_query_param_part;
4671
-            $model_obj  = $this;
4672
-        } else {// $number_of_parts >= 2
4673
-            // the last part is the column name, and there are only 2parts. therefore...
4674
-            $field_name = $last_query_param_part;
4675
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4676
-        }
4677
-        try {
4678
-            return $model_obj->field_settings_for($field_name);
4679
-        } catch (EE_Error $e) {
4680
-            return null;
4681
-        }
4682
-    }
4683
-
4684
-
4685
-    /**
4686
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4687
-     * alias and column which corresponds to it
4688
-     *
4689
-     * @param string $field_name
4690
-     * @return string
4691
-     * @throws EE_Error
4692
-     */
4693
-    public function _get_qualified_column_for_field($field_name)
4694
-    {
4695
-        $all_fields = $this->field_settings();
4696
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4697
-        if ($field) {
4698
-            return $field->get_qualified_column();
4699
-        }
4700
-        throw new EE_Error(
4701
-            sprintf(
4702
-                esc_html__(
4703
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4704
-                    'event_espresso'
4705
-                ),
4706
-                $field_name,
4707
-                get_class($this)
4708
-            )
4709
-        );
4710
-    }
4711
-
4712
-
4713
-    /**
4714
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4715
-     * Example usage:
4716
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4717
-     *      array(),
4718
-     *      ARRAY_A,
4719
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4720
-     *  );
4721
-     * is equivalent to
4722
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4723
-     * and
4724
-     *  EEM_Event::instance()->get_all_wpdb_results(
4725
-     *      array(
4726
-     *          array(
4727
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4728
-     *          ),
4729
-     *          ARRAY_A,
4730
-     *          implode(
4731
-     *              ', ',
4732
-     *              array_merge(
4733
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4734
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4735
-     *              )
4736
-     *          )
4737
-     *      )
4738
-     *  );
4739
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4740
-     *
4741
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4742
-     *                                            and the one whose fields you are selecting for example: when querying
4743
-     *                                            tickets model and selecting fields from the tickets model you would
4744
-     *                                            leave this parameter empty, because no models are needed to join
4745
-     *                                            between the queried model and the selected one. Likewise when
4746
-     *                                            querying the datetime model and selecting fields from the tickets
4747
-     *                                            model, it would also be left empty, because there is a direct
4748
-     *                                            relation from datetimes to tickets, so no model is needed to join
4749
-     *                                            them together. However, when querying from the event model and
4750
-     *                                            selecting fields from the ticket model, you should provide the string
4751
-     *                                            'Datetime', indicating that the event model must first join to the
4752
-     *                                            datetime model in order to find its relation to ticket model.
4753
-     *                                            Also, when querying from the venue model and selecting fields from
4754
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4755
-     *                                            indicating you need to join the venue model to the event model,
4756
-     *                                            to the datetime model, in order to find its relation to the ticket
4757
-     *                                            model. This string is used to deduce the prefix that gets added onto
4758
-     *                                            the models' tables qualified columns
4759
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4760
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4761
-     *                                            qualified column names
4762
-     * @return array|string
4763
-     */
4764
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4765
-    {
4766
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4767
-        $qualified_columns = [];
4768
-        foreach ($this->field_settings() as $field_name => $field) {
4769
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4770
-        }
4771
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4772
-    }
4773
-
4774
-
4775
-    /**
4776
-     * constructs the select use on special limit joins
4777
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4778
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4779
-     * (as that is typically where the limits would be set).
4780
-     *
4781
-     * @param string       $table_alias The table the select is being built for
4782
-     * @param mixed|string $limit       The limit for this select
4783
-     * @return string                The final select join element for the query.
4784
-     * @throws EE_Error
4785
-     * @throws EE_Error
4786
-     */
4787
-    public function _construct_limit_join_select($table_alias, $limit)
4788
-    {
4789
-        $SQL = '';
4790
-        foreach ($this->_tables as $table_obj) {
4791
-            if ($table_obj instanceof EE_Primary_Table) {
4792
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4793
-                    ? $table_obj->get_select_join_limit($limit)
4794
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4795
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4796
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4797
-                    ? $table_obj->get_select_join_limit_join($limit)
4798
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4799
-            }
4800
-        }
4801
-        return $SQL;
4802
-    }
4803
-
4804
-
4805
-    /**
4806
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4807
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4808
-     *
4809
-     * @return string SQL
4810
-     * @throws EE_Error
4811
-     */
4812
-    public function _construct_internal_join()
4813
-    {
4814
-        $SQL = $this->_get_main_table()->get_table_sql();
4815
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4816
-        return $SQL;
4817
-    }
4818
-
4819
-
4820
-    /**
4821
-     * Constructs the SQL for joining all the tables on this model.
4822
-     * Normally $alias should be the primary table's alias, but in cases where
4823
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4824
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4825
-     * alias, this will construct SQL like:
4826
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4827
-     * With $alias being a secondary table's alias, this will construct SQL like:
4828
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4829
-     *
4830
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4831
-     * @return string
4832
-     * @throws EE_Error
4833
-     * @throws EE_Error
4834
-     */
4835
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4836
-    {
4837
-        $SQL               = '';
4838
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4839
-        foreach ($this->_tables as $table_obj) {
4840
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4841
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4842
-                    // so we're joining to this table, meaning the table is already in
4843
-                    // the FROM statement, BUT the primary table isn't. So we want
4844
-                    // to add the inverse join sql
4845
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4846
-                } else {
4847
-                    // just add a regular JOIN to this table from the primary table
4848
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4849
-                }
4850
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4851
-        }
4852
-        return $SQL;
4853
-    }
4854
-
4855
-
4856
-    /**
4857
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4858
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4859
-     * their data type (eg, '%s', '%d', etc)
4860
-     *
4861
-     * @return array
4862
-     */
4863
-    public function _get_data_types()
4864
-    {
4865
-        $data_types = [];
4866
-        foreach ($this->field_settings() as $field_obj) {
4867
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4868
-            /** @var $field_obj EE_Model_Field_Base */
4869
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4870
-        }
4871
-        return $data_types;
4872
-    }
4873
-
4874
-
4875
-    /**
4876
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4877
-     *
4878
-     * @param string $model_name
4879
-     * @return EEM_Base
4880
-     * @throws EE_Error
4881
-     */
4882
-    public function get_related_model_obj($model_name)
4883
-    {
4884
-        $model_classname = "EEM_" . $model_name;
4885
-        if (! class_exists($model_classname)) {
4886
-            throw new EE_Error(
4887
-                sprintf(
4888
-                    esc_html__(
4889
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4890
-                        'event_espresso'
4891
-                    ),
4892
-                    $model_name,
4893
-                    $model_classname
4894
-                )
4895
-            );
4896
-        }
4897
-        return call_user_func($model_classname . "::instance");
4898
-    }
4899
-
4900
-
4901
-    /**
4902
-     * Returns the array of EE_ModelRelations for this model.
4903
-     *
4904
-     * @return EE_Model_Relation_Base[]
4905
-     */
4906
-    public function relation_settings()
4907
-    {
4908
-        return $this->_model_relations;
4909
-    }
4910
-
4911
-
4912
-    /**
4913
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4914
-     * because without THOSE models, this model probably doesn't have much purpose.
4915
-     * (Eg, without an event, datetimes have little purpose.)
4916
-     *
4917
-     * @return EE_Belongs_To_Relation[]
4918
-     */
4919
-    public function belongs_to_relations()
4920
-    {
4921
-        $belongs_to_relations = [];
4922
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4923
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4924
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4925
-            }
4926
-        }
4927
-        return $belongs_to_relations;
4928
-    }
4929
-
4930
-
4931
-    /**
4932
-     * Returns the specified EE_Model_Relation, or throws an exception
4933
-     *
4934
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4935
-     * @return EE_Model_Relation_Base
4936
-     * @throws EE_Error
4937
-     */
4938
-    public function related_settings_for($relation_name)
4939
-    {
4940
-        $relatedModels = $this->relation_settings();
4941
-        if (! array_key_exists($relation_name, $relatedModels)) {
4942
-            throw new EE_Error(
4943
-                sprintf(
4944
-                    esc_html__(
4945
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4946
-                        'event_espresso'
4947
-                    ),
4948
-                    $relation_name,
4949
-                    $this->_get_class_name(),
4950
-                    implode(', ', array_keys($relatedModels))
4951
-                )
4952
-            );
4953
-        }
4954
-        return $relatedModels[ $relation_name ];
4955
-    }
4956
-
4957
-
4958
-    /**
4959
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4960
-     * fields
4961
-     *
4962
-     * @param string  $fieldName
4963
-     * @param boolean $include_db_only_fields
4964
-     * @return EE_Model_Field_Base
4965
-     * @throws EE_Error
4966
-     */
4967
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4968
-    {
4969
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4970
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4971
-            throw new EE_Error(
4972
-                sprintf(
4973
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4974
-                    $fieldName,
4975
-                    get_class($this)
4976
-                )
4977
-            );
4978
-        }
4979
-        return $fieldSettings[ $fieldName ];
4980
-    }
4981
-
4982
-
4983
-    /**
4984
-     * Checks if this field exists on this model
4985
-     *
4986
-     * @param string $fieldName a key in the model's _field_settings array
4987
-     * @return boolean
4988
-     */
4989
-    public function has_field($fieldName)
4990
-    {
4991
-        $fieldSettings = $this->field_settings(true);
4992
-        if (isset($fieldSettings[ $fieldName ])) {
4993
-            return true;
4994
-        }
4995
-        return false;
4996
-    }
4997
-
4998
-
4999
-    /**
5000
-     * Returns whether or not this model has a relation to the specified model
5001
-     *
5002
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5003
-     * @return boolean
5004
-     */
5005
-    public function has_relation($relation_name)
5006
-    {
5007
-        $relations = $this->relation_settings();
5008
-        if (isset($relations[ $relation_name ])) {
5009
-            return true;
5010
-        }
5011
-        return false;
5012
-    }
5013
-
5014
-
5015
-    /**
5016
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5017
-     * Eg, on EE_Answer that would be ANS_ID field object
5018
-     *
5019
-     * @param $field_obj
5020
-     * @return boolean
5021
-     */
5022
-    public function is_primary_key_field($field_obj)
5023
-    {
5024
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
5025
-    }
5026
-
5027
-
5028
-    /**
5029
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5030
-     * Eg, on EE_Answer that would be ANS_ID field object
5031
-     *
5032
-     * @return EE_Primary_Key_Field_Base
5033
-     * @throws EE_Error
5034
-     */
5035
-    public function get_primary_key_field()
5036
-    {
5037
-        if ($this->_primary_key_field === null) {
5038
-            foreach ($this->field_settings(true) as $field_obj) {
5039
-                if ($this->is_primary_key_field($field_obj)) {
5040
-                    $this->_primary_key_field = $field_obj;
5041
-                    break;
5042
-                }
5043
-            }
5044
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5045
-                throw new EE_Error(
5046
-                    sprintf(
5047
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5048
-                        get_class($this)
5049
-                    )
5050
-                );
5051
-            }
5052
-        }
5053
-        return $this->_primary_key_field;
5054
-    }
5055
-
5056
-
5057
-    /**
5058
-     * Returns whether or not not there is a primary key on this model.
5059
-     * Internally does some caching.
5060
-     *
5061
-     * @return boolean
5062
-     */
5063
-    public function has_primary_key_field()
5064
-    {
5065
-        if ($this->_has_primary_key_field === null) {
5066
-            try {
5067
-                $this->get_primary_key_field();
5068
-                $this->_has_primary_key_field = true;
5069
-            } catch (EE_Error $e) {
5070
-                $this->_has_primary_key_field = false;
5071
-            }
5072
-        }
5073
-        return $this->_has_primary_key_field;
5074
-    }
5075
-
5076
-
5077
-    /**
5078
-     * Finds the first field of type $field_class_name.
5079
-     *
5080
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5081
-     *                                 EE_Foreign_Key_Field, etc
5082
-     * @return EE_Model_Field_Base or null if none is found
5083
-     */
5084
-    public function get_a_field_of_type($field_class_name)
5085
-    {
5086
-        foreach ($this->field_settings() as $field) {
5087
-            if ($field instanceof $field_class_name) {
5088
-                return $field;
5089
-            }
5090
-        }
5091
-        return null;
5092
-    }
5093
-
5094
-
5095
-    /**
5096
-     * Gets a foreign key field pointing to model.
5097
-     *
5098
-     * @param string $model_name eg Event, Registration, not EEM_Event
5099
-     * @return EE_Foreign_Key_Field_Base
5100
-     * @throws EE_Error
5101
-     */
5102
-    public function get_foreign_key_to($model_name)
5103
-    {
5104
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5105
-            foreach ($this->field_settings() as $field) {
5106
-                if (
5107
-                    $field instanceof EE_Foreign_Key_Field_Base
5108
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5109
-                ) {
5110
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5111
-                    break;
5112
-                }
5113
-            }
5114
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5115
-                throw new EE_Error(
5116
-                    sprintf(
5117
-                        esc_html__(
5118
-                            "There is no foreign key field pointing to model %s on model %s",
5119
-                            'event_espresso'
5120
-                        ),
5121
-                        $model_name,
5122
-                        get_class($this)
5123
-                    )
5124
-                );
5125
-            }
5126
-        }
5127
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5128
-    }
5129
-
5130
-
5131
-    /**
5132
-     * Gets the table name (including $wpdb->prefix) for the table alias
5133
-     *
5134
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5135
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5136
-     *                            Either one works
5137
-     * @return string
5138
-     */
5139
-    public function get_table_for_alias($table_alias)
5140
-    {
5141
-        $table_alias_sans_model_relation_chain_prefix =
5142
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5143
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5144
-    }
5145
-
5146
-
5147
-    /**
5148
-     * Returns a flat array of all field son this model, instead of organizing them
5149
-     * by table_alias as they are in the constructor.
5150
-     *
5151
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5152
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5153
-     */
5154
-    public function field_settings($include_db_only_fields = false)
5155
-    {
5156
-        if ($include_db_only_fields) {
5157
-            if ($this->_cached_fields === null) {
5158
-                $this->_cached_fields = [];
5159
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5160
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5161
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5162
-                    }
5163
-                }
5164
-            }
5165
-            return $this->_cached_fields;
5166
-        }
5167
-        if ($this->_cached_fields_non_db_only === null) {
5168
-            $this->_cached_fields_non_db_only = [];
5169
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5170
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5171
-                    /** @var $field_obj EE_Model_Field_Base */
5172
-                    if (! $field_obj->is_db_only_field()) {
5173
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5174
-                    }
5175
-                }
5176
-            }
5177
-        }
5178
-        return $this->_cached_fields_non_db_only;
5179
-    }
5180
-
5181
-
5182
-    /**
5183
-     *        cycle though array of attendees and create objects out of each item
5184
-     *
5185
-     * @access        private
5186
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5187
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5188
-     *                           numerically indexed)
5189
-     * @throws EE_Error
5190
-     * @throws ReflectionException
5191
-     */
5192
-    protected function _create_objects($rows = [])
5193
-    {
5194
-        $array_of_objects = [];
5195
-        if (empty($rows)) {
5196
-            return [];
5197
-        }
5198
-        $count_if_model_has_no_primary_key = 0;
5199
-        $has_primary_key                   = $this->has_primary_key_field();
5200
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5201
-        foreach ((array) $rows as $row) {
5202
-            if (empty($row)) {
5203
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5204
-                return [];
5205
-            }
5206
-            // check if we've already set this object in the results array,
5207
-            // in which case there's no need to process it further (again)
5208
-            if ($has_primary_key) {
5209
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5210
-                    $row,
5211
-                    $primary_key_field->get_qualified_column(),
5212
-                    $primary_key_field->get_table_column()
5213
-                );
5214
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5215
-                    continue;
5216
-                }
5217
-            }
5218
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5219
-            if (! $classInstance) {
5220
-                throw new EE_Error(
5221
-                    sprintf(
5222
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5223
-                        $this->get_this_model_name(),
5224
-                        http_build_query($row)
5225
-                    )
5226
-                );
5227
-            }
5228
-            // set the timezone on the instantiated objects
5229
-            $classInstance->set_timezone($this->_timezone);
5230
-            // make sure if there is any timezone setting present that we set the timezone for the object
5231
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5232
-            $array_of_objects[ $key ] = $classInstance;
5233
-            // also, for all the relations of type BelongsTo, see if we can cache
5234
-            // those related models
5235
-            // (we could do this for other relations too, but if there are conditions
5236
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5237
-            // so it requires a little more thought than just caching them immediately...)
5238
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5239
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5240
-                    // check if this model's INFO is present. If so, cache it on the model
5241
-                    $other_model           = $relation_obj->get_other_model();
5242
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5243
-                    // if we managed to make a model object from the results, cache it on the main model object
5244
-                    if ($other_model_obj_maybe) {
5245
-                        // set timezone on these other model objects if they are present
5246
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5247
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5248
-                    }
5249
-                }
5250
-            }
5251
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5252
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5253
-            // the field in the CustomSelects object
5254
-            if ($this->_custom_selections instanceof CustomSelects) {
5255
-                $classInstance->setCustomSelectsValues(
5256
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5257
-                );
5258
-            }
5259
-        }
5260
-        return $array_of_objects;
5261
-    }
5262
-
5263
-
5264
-    /**
5265
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5266
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5267
-     *
5268
-     * @param array $db_results_row
5269
-     * @return array
5270
-     */
5271
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5272
-    {
5273
-        $results = [];
5274
-        if ($this->_custom_selections instanceof CustomSelects) {
5275
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5276
-                if (isset($db_results_row[ $alias ])) {
5277
-                    $results[ $alias ] = $this->convertValueToDataType(
5278
-                        $db_results_row[ $alias ],
5279
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5280
-                    );
5281
-                }
5282
-            }
5283
-        }
5284
-        return $results;
5285
-    }
5286
-
5287
-
5288
-    /**
5289
-     * This will set the value for the given alias
5290
-     *
5291
-     * @param string $value
5292
-     * @param string $datatype (one of %d, %s, %f)
5293
-     * @return int|string|float (int for %d, string for %s, float for %f)
5294
-     */
5295
-    protected function convertValueToDataType($value, $datatype)
5296
-    {
5297
-        switch ($datatype) {
5298
-            case '%f':
5299
-                return (float) $value;
5300
-            case '%d':
5301
-                return (int) $value;
5302
-            default:
5303
-                return (string) $value;
5304
-        }
5305
-    }
5306
-
5307
-
5308
-    /**
5309
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5310
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5311
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5312
-     * object (as set in the model_field!).
5313
-     *
5314
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5315
-     * @throws EE_Error
5316
-     * @throws ReflectionException
5317
-     */
5318
-    public function create_default_object()
5319
-    {
5320
-        $this_model_fields_and_values = [];
5321
-        // setup the row using default values;
5322
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5323
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5324
-        }
5325
-        $className     = $this->_get_class_name();
5326
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5327
-    }
5328
-
5329
-
5330
-    /**
5331
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5332
-     *                             or an stdClass where each property is the name of a column,
5333
-     * @return EE_Base_Class
5334
-     * @throws EE_Error
5335
-     * @throws ReflectionException
5336
-     */
5337
-    public function instantiate_class_from_array_or_object($cols_n_values)
5338
-    {
5339
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5340
-            $cols_n_values = get_object_vars($cols_n_values);
5341
-        }
5342
-        $primary_key = null;
5343
-        // make sure the array only has keys that are fields/columns on this model
5344
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5345
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5346
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5347
-        }
5348
-        $className = $this->_get_class_name();
5349
-        // check we actually found results that we can use to build our model object
5350
-        // if not, return null
5351
-        if ($this->has_primary_key_field()) {
5352
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5353
-                return null;
5354
-            }
5355
-        } elseif ($this->unique_indexes()) {
5356
-            $first_column = reset($this_model_fields_n_values);
5357
-            if (empty($first_column)) {
5358
-                return null;
5359
-            }
5360
-        }
5361
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5362
-        if ($primary_key) {
5363
-            $classInstance = $this->get_from_entity_map($primary_key);
5364
-            if (! $classInstance) {
5365
-                $classInstance = EE_Registry::instance()
5366
-                                            ->load_class(
5367
-                                                $className,
5368
-                                                [$this_model_fields_n_values, $this->_timezone],
5369
-                                                true,
5370
-                                                false
5371
-                                            );
5372
-                // add this new object to the entity map
5373
-                $classInstance = $this->add_to_entity_map($classInstance);
5374
-            }
5375
-        } else {
5376
-            $classInstance = EE_Registry::instance()
5377
-                                        ->load_class(
5378
-                                            $className,
5379
-                                            [$this_model_fields_n_values, $this->_timezone],
5380
-                                            true,
5381
-                                            false
5382
-                                        );
5383
-        }
5384
-        return $classInstance;
5385
-    }
5386
-
5387
-
5388
-    /**
5389
-     * Gets the model object from the  entity map if it exists
5390
-     *
5391
-     * @param int|string $id the ID of the model object
5392
-     * @return EE_Base_Class
5393
-     */
5394
-    public function get_from_entity_map($id)
5395
-    {
5396
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5397
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5398
-    }
5399
-
5400
-
5401
-    /**
5402
-     * add_to_entity_map
5403
-     * Adds the object to the model's entity mappings
5404
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5405
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5406
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5407
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5408
-     *        then this method should be called immediately after the update query
5409
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5410
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5411
-     *
5412
-     * @param EE_Base_Class $object
5413
-     * @return EE_Base_Class
5414
-     * @throws EE_Error
5415
-     * @throws ReflectionException
5416
-     */
5417
-    public function add_to_entity_map(EE_Base_Class $object)
5418
-    {
5419
-        $className = $this->_get_class_name();
5420
-        if (! $object instanceof $className) {
5421
-            throw new EE_Error(
5422
-                sprintf(
5423
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5424
-                    is_object($object) ? get_class($object) : $object,
5425
-                    $className
5426
-                )
5427
-            );
5428
-        }
5429
-        /** @var $object EE_Base_Class */
5430
-        if (! $object->ID()) {
5431
-            throw new EE_Error(
5432
-                sprintf(
5433
-                    esc_html__(
5434
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5435
-                        "event_espresso"
5436
-                    ),
5437
-                    get_class($this)
5438
-                )
5439
-            );
5440
-        }
5441
-        // double check it's not already there
5442
-        $classInstance = $this->get_from_entity_map($object->ID());
5443
-        if ($classInstance) {
5444
-            return $classInstance;
5445
-        }
5446
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5447
-        return $object;
5448
-    }
5449
-
5450
-
5451
-    /**
5452
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5453
-     * if no identifier is provided, then the entire entity map is emptied
5454
-     *
5455
-     * @param int|string $id the ID of the model object
5456
-     * @return boolean
5457
-     */
5458
-    public function clear_entity_map($id = null)
5459
-    {
5460
-        if (empty($id)) {
5461
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5462
-            return true;
5463
-        }
5464
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5465
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5466
-            return true;
5467
-        }
5468
-        return false;
5469
-    }
5470
-
5471
-
5472
-    /**
5473
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5474
-     * Given an array where keys are column (or column alias) names and values,
5475
-     * returns an array of their corresponding field names and database values
5476
-     *
5477
-     * @param array $cols_n_values
5478
-     * @return array
5479
-     * @throws EE_Error
5480
-     * @throws ReflectionException
5481
-     */
5482
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5483
-    {
5484
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5485
-    }
5486
-
5487
-
5488
-    /**
5489
-     * _deduce_fields_n_values_from_cols_n_values
5490
-     * Given an array where keys are column (or column alias) names and values,
5491
-     * returns an array of their corresponding field names and database values
5492
-     *
5493
-     * @param array|stdClass $cols_n_values
5494
-     * @return array
5495
-     * @throws EE_Error
5496
-     * @throws ReflectionException
5497
-     */
5498
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5499
-    {
5500
-        if ($cols_n_values instanceof stdClass) {
5501
-            $cols_n_values = get_object_vars($cols_n_values);
5502
-        }
5503
-        $this_model_fields_n_values = [];
5504
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5505
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5506
-                $cols_n_values,
5507
-                $table_obj->get_fully_qualified_pk_column(),
5508
-                $table_obj->get_pk_column()
5509
-            );
5510
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5511
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5512
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5513
-                    if (! $field_obj->is_db_only_field()) {
5514
-                        // prepare field as if its coming from db
5515
-                        $prepared_value                            =
5516
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5517
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5518
-                    }
5519
-                }
5520
-            } else {
5521
-                // the table's rows existed. Use their values
5522
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5523
-                    if (! $field_obj->is_db_only_field()) {
5524
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5525
-                            $cols_n_values,
5526
-                            $field_obj->get_qualified_column(),
5527
-                            $field_obj->get_table_column()
5528
-                        );
5529
-                    }
5530
-                }
5531
-            }
5532
-        }
5533
-        return $this_model_fields_n_values;
5534
-    }
5535
-
5536
-
5537
-    /**
5538
-     * @param $cols_n_values
5539
-     * @param $qualified_column
5540
-     * @param $regular_column
5541
-     * @return null
5542
-     * @throws EE_Error
5543
-     * @throws ReflectionException
5544
-     */
5545
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5546
-    {
5547
-        $value = null;
5548
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5549
-        // does the field on the model relate to this column retrieved from the db?
5550
-        // or is it a db-only field? (not relating to the model)
5551
-        if (isset($cols_n_values[ $qualified_column ])) {
5552
-            $value = $cols_n_values[ $qualified_column ];
5553
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5554
-            $value = $cols_n_values[ $regular_column ];
5555
-        } elseif (! empty($this->foreign_key_aliases)) {
5556
-            // no PK?  ok check if there is a foreign key alias set for this table
5557
-            // then check if that alias exists in the incoming data
5558
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5559
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5560
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5561
-                    $value = $cols_n_values[ $FK_alias ];
5562
-                    [$pk_class] = explode('.', $PK_column);
5563
-                    $pk_model_name = "EEM_{$pk_class}";
5564
-                    /** @var EEM_Base $pk_model */
5565
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5566
-                    if ($pk_model instanceof EEM_Base) {
5567
-                        // make sure object is pulled from db and added to entity map
5568
-                        $pk_model->get_one_by_ID($value);
5569
-                    }
5570
-                    break;
5571
-                }
5572
-            }
5573
-        }
5574
-        return $value;
5575
-    }
5576
-
5577
-
5578
-    /**
5579
-     * refresh_entity_map_from_db
5580
-     * Makes sure the model object in the entity map at $id assumes the values
5581
-     * of the database (opposite of EE_base_Class::save())
5582
-     *
5583
-     * @param int|string $id
5584
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5585
-     * @throws EE_Error
5586
-     * @throws ReflectionException
5587
-     */
5588
-    public function refresh_entity_map_from_db($id)
5589
-    {
5590
-        $obj_in_map = $this->get_from_entity_map($id);
5591
-        if ($obj_in_map) {
5592
-            $wpdb_results = $this->_get_all_wpdb_results(
5593
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5594
-            );
5595
-            if ($wpdb_results && is_array($wpdb_results)) {
5596
-                $one_row = reset($wpdb_results);
5597
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5598
-                    $obj_in_map->set_from_db($field_name, $db_value);
5599
-                }
5600
-                // clear the cache of related model objects
5601
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5602
-                    $obj_in_map->clear_cache($relation_name, null, true);
5603
-                }
5604
-            }
5605
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5606
-            return $obj_in_map;
5607
-        }
5608
-        return $this->get_one_by_ID($id);
5609
-    }
5610
-
5611
-
5612
-    /**
5613
-     * refresh_entity_map_with
5614
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5615
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5616
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5617
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5618
-     *
5619
-     * @param int|string    $id
5620
-     * @param EE_Base_Class $replacing_model_obj
5621
-     * @return EE_Base_Class
5622
-     * @throws EE_Error
5623
-     * @throws ReflectionException
5624
-     */
5625
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5626
-    {
5627
-        $obj_in_map = $this->get_from_entity_map($id);
5628
-        if ($obj_in_map) {
5629
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5630
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5631
-                    $obj_in_map->set($field_name, $value);
5632
-                }
5633
-                // make the model object in the entity map's cache match the $replacing_model_obj
5634
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5635
-                    $obj_in_map->clear_cache($relation_name, null, true);
5636
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5637
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5638
-                    }
5639
-                }
5640
-            }
5641
-            return $obj_in_map;
5642
-        }
5643
-        $this->add_to_entity_map($replacing_model_obj);
5644
-        return $replacing_model_obj;
5645
-    }
5646
-
5647
-
5648
-    /**
5649
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5650
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5651
-     * require_once($this->_getClassName().".class.php");
5652
-     *
5653
-     * @return string
5654
-     */
5655
-    private function _get_class_name()
5656
-    {
5657
-        return "EE_" . $this->get_this_model_name();
5658
-    }
5659
-
5660
-
5661
-    /**
5662
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5663
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5664
-     * it would be 'Events'.
5665
-     *
5666
-     * @param int|float|null $quantity
5667
-     * @return string
5668
-     */
5669
-    public function item_name($quantity = 1): string
5670
-    {
5671
-        $quantity = floor($quantity);
5672
-        return apply_filters(
5673
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5674
-            $quantity > 1 ? $this->plural_item : $this->singular_item,
5675
-            $quantity,
5676
-            $this->plural_item,
5677
-            $this->singular_item
5678
-        );
5679
-    }
5680
-
5681
-
5682
-    /**
5683
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5684
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5685
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5686
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5687
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5688
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5689
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5690
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5691
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5692
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5693
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5694
-     *        return $previousReturnValue.$returnString;
5695
-     * }
5696
-     * require('EEM_Answer.model.php');
5697
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5698
-     * // will output "you called my_callback! and passed args:monkeys,100"
5699
-     *
5700
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5701
-     * @param array  $args       array of original arguments passed to the function
5702
-     * @return mixed whatever the plugin which calls add_filter decides
5703
-     * @throws EE_Error
5704
-     */
5705
-    public function __call($methodName, $args)
5706
-    {
5707
-        $className = get_class($this);
5708
-        $tagName   = "FHEE__{$className}__{$methodName}";
5709
-        if (! has_filter($tagName)) {
5710
-            throw new EE_Error(
5711
-                sprintf(
5712
-                    esc_html__(
5713
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5714
-                        'event_espresso'
5715
-                    ),
5716
-                    $methodName,
5717
-                    $className,
5718
-                    $tagName,
5719
-                    '<br />'
5720
-                )
5721
-            );
5722
-        }
5723
-        return apply_filters($tagName, null, $this, $args);
5724
-    }
5725
-
5726
-
5727
-    /**
5728
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5729
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5730
-     *
5731
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5732
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5733
-     *                                                       the object's class name
5734
-     *                                                       or object's ID
5735
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5736
-     *                                                       exists in the database. If it does not, we add it
5737
-     * @return EE_Base_Class
5738
-     * @throws EE_Error
5739
-     * @throws ReflectionException
5740
-     */
5741
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5742
-    {
5743
-        $className = $this->_get_class_name();
5744
-        if ($base_class_obj_or_id instanceof $className) {
5745
-            $model_object = $base_class_obj_or_id;
5746
-        } else {
5747
-            $primary_key_field = $this->get_primary_key_field();
5748
-            if (
5749
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5750
-                && (
5751
-                    is_int($base_class_obj_or_id)
5752
-                    || is_string($base_class_obj_or_id)
5753
-                )
5754
-            ) {
5755
-                // assume it's an ID.
5756
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5757
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5758
-            } elseif (
5759
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5760
-                && is_string($base_class_obj_or_id)
5761
-            ) {
5762
-                // assume its a string representation of the object
5763
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5764
-            } else {
5765
-                throw new EE_Error(
5766
-                    sprintf(
5767
-                        esc_html__(
5768
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5769
-                            'event_espresso'
5770
-                        ),
5771
-                        $base_class_obj_or_id,
5772
-                        $this->_get_class_name(),
5773
-                        print_r($base_class_obj_or_id, true)
5774
-                    )
5775
-                );
5776
-            }
5777
-        }
5778
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5779
-            $model_object->save();
5780
-        }
5781
-        return $model_object;
5782
-    }
5783
-
5784
-
5785
-    /**
5786
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5787
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5788
-     * returns it ID.
5789
-     *
5790
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5791
-     * @return int|string depending on the type of this model object's ID
5792
-     * @throws EE_Error
5793
-     * @throws ReflectionException
5794
-     */
5795
-    public function ensure_is_ID($base_class_obj_or_id)
5796
-    {
5797
-        $className = $this->_get_class_name();
5798
-        if ($base_class_obj_or_id instanceof $className) {
5799
-            /** @var $base_class_obj_or_id EE_Base_Class */
5800
-            $id = $base_class_obj_or_id->ID();
5801
-        } elseif (is_int($base_class_obj_or_id)) {
5802
-            // assume it's an ID
5803
-            $id = $base_class_obj_or_id;
5804
-        } elseif (is_string($base_class_obj_or_id)) {
5805
-            // assume its a string representation of the object
5806
-            $id = $base_class_obj_or_id;
5807
-        } else {
5808
-            throw new EE_Error(
5809
-                sprintf(
5810
-                    esc_html__(
5811
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5812
-                        'event_espresso'
5813
-                    ),
5814
-                    $base_class_obj_or_id,
5815
-                    $this->_get_class_name(),
5816
-                    print_r($base_class_obj_or_id, true)
5817
-                )
5818
-            );
5819
-        }
5820
-        return $id;
5821
-    }
5822
-
5823
-
5824
-    /**
5825
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5826
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5827
-     * been sanitized and converted into the appropriate domain.
5828
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5829
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5830
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5831
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5832
-     * $EVT = EEM_Event::instance(); $old_setting =
5833
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5834
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5835
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5836
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5837
-     *
5838
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5839
-     * @return void
5840
-     */
5841
-    public function assume_values_already_prepared_by_model_object(
5842
-        $values_already_prepared = self::not_prepared_by_model_object
5843
-    ) {
5844
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5845
-    }
5846
-
5847
-
5848
-    /**
5849
-     * Read comments for assume_values_already_prepared_by_model_object()
5850
-     *
5851
-     * @return int
5852
-     */
5853
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5854
-    {
5855
-        return $this->_values_already_prepared_by_model_object;
5856
-    }
5857
-
5858
-
5859
-    /**
5860
-     * Gets all the indexes on this model
5861
-     *
5862
-     * @return EE_Index[]
5863
-     */
5864
-    public function indexes()
5865
-    {
5866
-        return $this->_indexes;
5867
-    }
5868
-
5869
-
5870
-    /**
5871
-     * Gets all the Unique Indexes on this model
5872
-     *
5873
-     * @return EE_Unique_Index[]
5874
-     */
5875
-    public function unique_indexes()
5876
-    {
5877
-        $unique_indexes = [];
5878
-        foreach ($this->_indexes as $name => $index) {
5879
-            if ($index instanceof EE_Unique_Index) {
5880
-                $unique_indexes [ $name ] = $index;
5881
-            }
5882
-        }
5883
-        return $unique_indexes;
5884
-    }
5885
-
5886
-
5887
-    /**
5888
-     * Gets all the fields which, when combined, make the primary key.
5889
-     * This is usually just an array with 1 element (the primary key), but in cases
5890
-     * where there is no primary key, it's a combination of fields as defined
5891
-     * on a primary index
5892
-     *
5893
-     * @return EE_Model_Field_Base[] indexed by the field's name
5894
-     * @throws EE_Error
5895
-     */
5896
-    public function get_combined_primary_key_fields()
5897
-    {
5898
-        foreach ($this->indexes() as $index) {
5899
-            if ($index instanceof EE_Primary_Key_Index) {
5900
-                return $index->fields();
5901
-            }
5902
-        }
5903
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5904
-    }
5905
-
5906
-
5907
-    /**
5908
-     * Used to build a primary key string (when the model has no primary key),
5909
-     * which can be used a unique string to identify this model object.
5910
-     *
5911
-     * @param array $fields_n_values keys are field names, values are their values.
5912
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5913
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5914
-     *                               before passing it to this function (that will convert it from columns-n-values
5915
-     *                               to field-names-n-values).
5916
-     * @return string
5917
-     * @throws EE_Error
5918
-     */
5919
-    public function get_index_primary_key_string($fields_n_values)
5920
-    {
5921
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5922
-            $fields_n_values,
5923
-            $this->get_combined_primary_key_fields()
5924
-        );
5925
-        return http_build_query($cols_n_values_for_primary_key_index);
5926
-    }
5927
-
5928
-
5929
-    /**
5930
-     * Gets the field values from the primary key string
5931
-     *
5932
-     * @param string $index_primary_key_string
5933
-     * @return null|array
5934
-     * @throws EE_Error
5935
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5936
-     */
5937
-    public function parse_index_primary_key_string($index_primary_key_string)
5938
-    {
5939
-        $key_fields = $this->get_combined_primary_key_fields();
5940
-        // check all of them are in the $id
5941
-        $key_vals_in_combined_pk = [];
5942
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5943
-        foreach ($key_fields as $key_field_name => $field_obj) {
5944
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5945
-                return null;
5946
-            }
5947
-        }
5948
-        return $key_vals_in_combined_pk;
5949
-    }
5950
-
5951
-
5952
-    /**
5953
-     * verifies that an array of key-value pairs for model fields has a key
5954
-     * for each field comprising the primary key index
5955
-     *
5956
-     * @param array $key_vals
5957
-     * @return boolean
5958
-     * @throws EE_Error
5959
-     */
5960
-    public function has_all_combined_primary_key_fields($key_vals)
5961
-    {
5962
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5963
-        foreach ($keys_it_should_have as $key) {
5964
-            if (! isset($key_vals[ $key ])) {
5965
-                return false;
5966
-            }
5967
-        }
5968
-        return true;
5969
-    }
5970
-
5971
-
5972
-    /**
5973
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5974
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5975
-     *
5976
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5977
-     * @param array               $query_params                     @see
5978
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5979
-     * @throws EE_Error
5980
-     * @throws ReflectionException
5981
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5982
-     *                                                              indexed)
5983
-     */
5984
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5985
-    {
5986
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5987
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5988
-        } elseif (is_array($model_object_or_attributes_array)) {
5989
-            $attributes_array = $model_object_or_attributes_array;
5990
-        } else {
5991
-            throw new EE_Error(
5992
-                sprintf(
5993
-                    esc_html__(
5994
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5995
-                        "event_espresso"
5996
-                    ),
5997
-                    $model_object_or_attributes_array
5998
-                )
5999
-            );
6000
-        }
6001
-        // even copies obviously won't have the same ID, so remove the primary key
6002
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6003
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6004
-            unset($attributes_array[ $this->primary_key_name() ]);
6005
-        }
6006
-        if (isset($query_params[0])) {
6007
-            $query_params[0] = array_merge($attributes_array, $query_params);
6008
-        } else {
6009
-            $query_params[0] = $attributes_array;
6010
-        }
6011
-        return $this->get_all($query_params);
6012
-    }
6013
-
6014
-
6015
-    /**
6016
-     * Gets the first copy we find. See get_all_copies for more details
6017
-     *
6018
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6019
-     * @param array $query_params
6020
-     * @return EE_Base_Class
6021
-     * @throws EE_Error
6022
-     * @throws ReflectionException
6023
-     */
6024
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6025
-    {
6026
-        if (! is_array($query_params)) {
6027
-            EE_Error::doing_it_wrong(
6028
-                'EEM_Base::get_one_copy',
6029
-                sprintf(
6030
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6031
-                    gettype($query_params)
6032
-                ),
6033
-                '4.6.0'
6034
-            );
6035
-            $query_params = [];
6036
-        }
6037
-        $query_params['limit'] = 1;
6038
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6039
-        if (is_array($copies)) {
6040
-            return array_shift($copies);
6041
-        }
6042
-        return null;
6043
-    }
6044
-
6045
-
6046
-    /**
6047
-     * Updates the item with the specified id. Ignores default query parameters because
6048
-     * we have specified the ID, and its assumed we KNOW what we're doing
6049
-     *
6050
-     * @param array      $fields_n_values keys are field names, values are their new values
6051
-     * @param int|string $id              the value of the primary key to update
6052
-     * @return int number of rows updated
6053
-     * @throws EE_Error
6054
-     * @throws ReflectionException
6055
-     */
6056
-    public function update_by_ID($fields_n_values, $id)
6057
-    {
6058
-        $query_params = [
6059
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6060
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6061
-        ];
6062
-        return $this->update($fields_n_values, $query_params);
6063
-    }
6064
-
6065
-
6066
-    /**
6067
-     * Changes an operator which was supplied to the models into one usable in SQL
6068
-     *
6069
-     * @param string $operator_supplied
6070
-     * @return string an operator which can be used in SQL
6071
-     * @throws EE_Error
6072
-     */
6073
-    private function _prepare_operator_for_sql($operator_supplied)
6074
-    {
6075
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6076
-        if ($sql_operator) {
6077
-            return $sql_operator;
6078
-        }
6079
-        throw new EE_Error(
6080
-            sprintf(
6081
-                esc_html__(
6082
-                    "The operator '%s' is not in the list of valid operators: %s",
6083
-                    "event_espresso"
6084
-                ),
6085
-                $operator_supplied,
6086
-                implode(",", array_keys($this->_valid_operators))
6087
-            )
6088
-        );
6089
-    }
6090
-
6091
-
6092
-    /**
6093
-     * Gets the valid operators
6094
-     *
6095
-     * @return array keys are accepted strings, values are the SQL they are converted to
6096
-     */
6097
-    public function valid_operators()
6098
-    {
6099
-        return $this->_valid_operators;
6100
-    }
6101
-
6102
-
6103
-    /**
6104
-     * Gets the between-style operators (take 2 arguments).
6105
-     *
6106
-     * @return array keys are accepted strings, values are the SQL they are converted to
6107
-     */
6108
-    public function valid_between_style_operators()
6109
-    {
6110
-        return array_intersect(
6111
-            $this->valid_operators(),
6112
-            $this->_between_style_operators
6113
-        );
6114
-    }
6115
-
6116
-
6117
-    /**
6118
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6119
-     *
6120
-     * @return array keys are accepted strings, values are the SQL they are converted to
6121
-     */
6122
-    public function valid_like_style_operators()
6123
-    {
6124
-        return array_intersect(
6125
-            $this->valid_operators(),
6126
-            $this->_like_style_operators
6127
-        );
6128
-    }
6129
-
6130
-
6131
-    /**
6132
-     * Gets the "in"-style operators
6133
-     *
6134
-     * @return array keys are accepted strings, values are the SQL they are converted to
6135
-     */
6136
-    public function valid_in_style_operators()
6137
-    {
6138
-        return array_intersect(
6139
-            $this->valid_operators(),
6140
-            $this->_in_style_operators
6141
-        );
6142
-    }
6143
-
6144
-
6145
-    /**
6146
-     * Gets the "null"-style operators (accept no arguments)
6147
-     *
6148
-     * @return array keys are accepted strings, values are the SQL they are converted to
6149
-     */
6150
-    public function valid_null_style_operators()
6151
-    {
6152
-        return array_intersect(
6153
-            $this->valid_operators(),
6154
-            $this->_null_style_operators
6155
-        );
6156
-    }
6157
-
6158
-
6159
-    /**
6160
-     * Gets an array where keys are the primary keys and values are their 'names'
6161
-     * (as determined by the model object's name() function, which is often overridden)
6162
-     *
6163
-     * @param array $query_params like get_all's
6164
-     * @return string[]
6165
-     * @throws EE_Error
6166
-     * @throws ReflectionException
6167
-     */
6168
-    public function get_all_names($query_params = [])
6169
-    {
6170
-        $objs  = $this->get_all($query_params);
6171
-        $names = [];
6172
-        foreach ($objs as $obj) {
6173
-            $names[ $obj->ID() ] = $obj->name();
6174
-        }
6175
-        return $names;
6176
-    }
6177
-
6178
-
6179
-    /**
6180
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6181
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6182
-     * this is duplicated effort and reduces efficiency) you would be better to use
6183
-     * array_keys() on $model_objects.
6184
-     *
6185
-     * @param \EE_Base_Class[] $model_objects
6186
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6187
-     *                                               in the returned array
6188
-     * @return array
6189
-     * @throws EE_Error
6190
-     * @throws ReflectionException
6191
-     */
6192
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6193
-    {
6194
-        if (! $this->has_primary_key_field()) {
6195
-            if (WP_DEBUG) {
6196
-                EE_Error::add_error(
6197
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6198
-                    __FILE__,
6199
-                    __FUNCTION__,
6200
-                    __LINE__
6201
-                );
6202
-            }
6203
-        }
6204
-        $IDs = [];
6205
-        foreach ($model_objects as $model_object) {
6206
-            $id = $model_object->ID();
6207
-            if (! $id) {
6208
-                if ($filter_out_empty_ids) {
6209
-                    continue;
6210
-                }
6211
-                if (WP_DEBUG) {
6212
-                    EE_Error::add_error(
6213
-                        esc_html__(
6214
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6215
-                            'event_espresso'
6216
-                        ),
6217
-                        __FILE__,
6218
-                        __FUNCTION__,
6219
-                        __LINE__
6220
-                    );
6221
-                }
6222
-            }
6223
-            $IDs[] = $id;
6224
-        }
6225
-        return $IDs;
6226
-    }
6227
-
6228
-
6229
-    /**
6230
-     * Returns the string used in capabilities relating to this model. If there
6231
-     * are no capabilities that relate to this model returns false
6232
-     *
6233
-     * @return string|false
6234
-     */
6235
-    public function cap_slug()
6236
-    {
6237
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6238
-    }
6239
-
6240
-
6241
-    /**
6242
-     * Returns the capability-restrictions array (@param string $context
6243
-     *
6244
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6245
-     * @throws EE_Error
6246
-     * @see EEM_Base::_cap_restrictions).
6247
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6248
-     *      only returns the cap restrictions array in that context (ie, the array
6249
-     *      at that key)
6250
-     *
6251
-     */
6252
-    public function cap_restrictions($context = EEM_Base::caps_read)
6253
-    {
6254
-        EEM_Base::verify_is_valid_cap_context($context);
6255
-        // check if we ought to run the restriction generator first
6256
-        if (
6257
-            isset($this->_cap_restriction_generators[ $context ])
6258
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6259
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6260
-        ) {
6261
-            $this->_cap_restrictions[ $context ] = array_merge(
6262
-                $this->_cap_restrictions[ $context ],
6263
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6264
-            );
6265
-        }
6266
-        // and make sure we've finalized the construction of each restriction
6267
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6268
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6269
-                $where_conditions_obj->_finalize_construct($this);
6270
-            }
6271
-        }
6272
-        return $this->_cap_restrictions[ $context ];
6273
-    }
6274
-
6275
-
6276
-    /**
6277
-     * Indicating whether or not this model thinks its a wp core model
6278
-     *
6279
-     * @return boolean
6280
-     */
6281
-    public function is_wp_core_model()
6282
-    {
6283
-        return $this->_wp_core_model;
6284
-    }
6285
-
6286
-
6287
-    /**
6288
-     * Gets all the caps that are missing which impose a restriction on
6289
-     * queries made in this context
6290
-     *
6291
-     * @param string $context one of EEM_Base::caps_ constants
6292
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6293
-     * @throws EE_Error
6294
-     */
6295
-    public function caps_missing($context = EEM_Base::caps_read)
6296
-    {
6297
-        $missing_caps     = [];
6298
-        $cap_restrictions = $this->cap_restrictions($context);
6299
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6300
-            if (
6301
-                ! EE_Capabilities::instance()
6302
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6303
-            ) {
6304
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6305
-            }
6306
-        }
6307
-        return $missing_caps;
6308
-    }
6309
-
6310
-
6311
-    /**
6312
-     * Gets the mapping from capability contexts to action strings used in capability names
6313
-     *
6314
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6315
-     * one of 'read', 'edit', or 'delete'
6316
-     */
6317
-    public function cap_contexts_to_cap_action_map()
6318
-    {
6319
-        return apply_filters(
6320
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6321
-            $this->_cap_contexts_to_cap_action_map,
6322
-            $this
6323
-        );
6324
-    }
6325
-
6326
-
6327
-    /**
6328
-     * Gets the action string for the specified capability context
6329
-     *
6330
-     * @param string $context
6331
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6332
-     * @throws EE_Error
6333
-     */
6334
-    public function cap_action_for_context($context)
6335
-    {
6336
-        $mapping = $this->cap_contexts_to_cap_action_map();
6337
-        if (isset($mapping[ $context ])) {
6338
-            return $mapping[ $context ];
6339
-        }
6340
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6341
-            return $action;
6342
-        }
6343
-        throw new EE_Error(
6344
-            sprintf(
6345
-                esc_html__(
6346
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6347
-                    'event_espresso'
6348
-                ),
6349
-                $context,
6350
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6351
-            )
6352
-        );
6353
-    }
6354
-
6355
-
6356
-    /**
6357
-     * Returns all the capability contexts which are valid when querying models
6358
-     *
6359
-     * @return array
6360
-     */
6361
-    public static function valid_cap_contexts()
6362
-    {
6363
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6364
-            self::caps_read,
6365
-            self::caps_read_admin,
6366
-            self::caps_edit,
6367
-            self::caps_delete,
6368
-        ]);
6369
-    }
6370
-
6371
-
6372
-    /**
6373
-     * Returns all valid options for 'default_where_conditions'
6374
-     *
6375
-     * @return array
6376
-     */
6377
-    public static function valid_default_where_conditions()
6378
-    {
6379
-        return [
6380
-            EEM_Base::default_where_conditions_all,
6381
-            EEM_Base::default_where_conditions_this_only,
6382
-            EEM_Base::default_where_conditions_others_only,
6383
-            EEM_Base::default_where_conditions_minimum_all,
6384
-            EEM_Base::default_where_conditions_minimum_others,
6385
-            EEM_Base::default_where_conditions_none,
6386
-        ];
6387
-    }
6388
-
6389
-    // public static function default_where_conditions_full
6390
-
6391
-
6392
-    /**
6393
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6394
-     *
6395
-     * @param string $context
6396
-     * @return bool
6397
-     * @throws EE_Error
6398
-     */
6399
-    public static function verify_is_valid_cap_context($context)
6400
-    {
6401
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6402
-        if (in_array($context, $valid_cap_contexts)) {
6403
-            return true;
6404
-        }
6405
-        throw new EE_Error(
6406
-            sprintf(
6407
-                esc_html__(
6408
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6409
-                    'event_espresso'
6410
-                ),
6411
-                $context,
6412
-                'EEM_Base',
6413
-                implode(',', $valid_cap_contexts)
6414
-            )
6415
-        );
6416
-    }
6417
-
6418
-
6419
-    /**
6420
-     * Clears all the models field caches. This is only useful when a sub-class
6421
-     * might have added a field or something and these caches might be invalidated
6422
-     */
6423
-    protected function _invalidate_field_caches()
6424
-    {
6425
-        $this->_cache_foreign_key_to_fields = [];
6426
-        $this->_cached_fields               = null;
6427
-        $this->_cached_fields_non_db_only   = null;
6428
-    }
6429
-
6430
-
6431
-    /**
6432
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6433
-     * (eg "and", "or", "not").
6434
-     *
6435
-     * @return array
6436
-     */
6437
-    public function logic_query_param_keys()
6438
-    {
6439
-        return $this->_logic_query_param_keys;
6440
-    }
6441
-
6442
-
6443
-    /**
6444
-     * Determines whether or not the where query param array key is for a logic query param.
6445
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6446
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6447
-     *
6448
-     * @param $query_param_key
6449
-     * @return bool
6450
-     */
6451
-    public function is_logic_query_param_key($query_param_key)
6452
-    {
6453
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6454
-            if (
6455
-                $query_param_key === $logic_query_param_key
6456
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6457
-            ) {
6458
-                return true;
6459
-            }
6460
-        }
6461
-        return false;
6462
-    }
6463
-
6464
-
6465
-    /**
6466
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6467
-     *
6468
-     * @return boolean
6469
-     * @since 4.9.74.p
6470
-     */
6471
-    public function hasPassword()
6472
-    {
6473
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6474
-        if ($this->has_password_field === null) {
6475
-            $password_field           = $this->getPasswordField();
6476
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6477
-        }
6478
-        return $this->has_password_field;
6479
-    }
6480
-
6481
-
6482
-    /**
6483
-     * Returns the password field on this model, if there is one
6484
-     *
6485
-     * @return EE_Password_Field|null
6486
-     * @since 4.9.74.p
6487
-     */
6488
-    public function getPasswordField()
6489
-    {
6490
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6491
-        // there's no need to search for it. If we don't know yet, then find out
6492
-        if ($this->has_password_field === null && $this->password_field === null) {
6493
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6494
-        }
6495
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6496
-        return $this->password_field;
6497
-    }
6498
-
6499
-
6500
-    /**
6501
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6502
-     *
6503
-     * @return EE_Model_Field_Base[]
6504
-     * @throws EE_Error
6505
-     * @since 4.9.74.p
6506
-     */
6507
-    public function getPasswordProtectedFields()
6508
-    {
6509
-        $password_field = $this->getPasswordField();
6510
-        $fields         = [];
6511
-        if ($password_field instanceof EE_Password_Field) {
6512
-            $field_names = $password_field->protectedFields();
6513
-            foreach ($field_names as $field_name) {
6514
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6515
-            }
6516
-        }
6517
-        return $fields;
6518
-    }
6519
-
6520
-
6521
-    /**
6522
-     * Checks if the current user can perform the requested action on this model
6523
-     *
6524
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6525
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6526
-     * @return bool
6527
-     * @throws EE_Error
6528
-     * @throws InvalidArgumentException
6529
-     * @throws InvalidDataTypeException
6530
-     * @throws InvalidInterfaceException
6531
-     * @throws ReflectionException
6532
-     * @throws UnexpectedEntityException
6533
-     * @since 4.9.74.p
6534
-     */
6535
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6536
-    {
6537
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6538
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6539
-        }
6540
-        if (! is_array($model_obj_or_fields_n_values)) {
6541
-            throw new UnexpectedEntityException(
6542
-                $model_obj_or_fields_n_values,
6543
-                'EE_Base_Class',
6544
-                sprintf(
6545
-                    esc_html__(
6546
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6547
-                        'event_espresso'
6548
-                    ),
6549
-                    __FUNCTION__
6550
-                )
6551
-            );
6552
-        }
6553
-        return $this->exists(
6554
-            $this->alter_query_params_to_restrict_by_ID(
6555
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6556
-                [
6557
-                    'default_where_conditions' => 'none',
6558
-                    'caps'                     => $cap_to_check,
6559
-                ]
6560
-            )
6561
-        );
6562
-    }
6563
-
6564
-
6565
-    /**
6566
-     * Returns the query param where conditions key to the password affecting this model.
6567
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6568
-     *
6569
-     * @return null|string
6570
-     * @throws EE_Error
6571
-     * @throws InvalidArgumentException
6572
-     * @throws InvalidDataTypeException
6573
-     * @throws InvalidInterfaceException
6574
-     * @throws ModelConfigurationException
6575
-     * @throws ReflectionException
6576
-     * @since 4.9.74.p
6577
-     */
6578
-    public function modelChainAndPassword()
6579
-    {
6580
-        if ($this->model_chain_to_password === null) {
6581
-            throw new ModelConfigurationException(
6582
-                $this,
6583
-                esc_html_x(
6584
-                // @codingStandardsIgnoreStart
6585
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6586
-                    // @codingStandardsIgnoreEnd
6587
-                    '1: model name',
6588
-                    'event_espresso'
6589
-                )
6590
-            );
6591
-        }
6592
-        if ($this->model_chain_to_password === '') {
6593
-            $model_with_password = $this;
6594
-        } else {
6595
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6596
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6597
-            } else {
6598
-                $last_model_in_chain = $this->model_chain_to_password;
6599
-            }
6600
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6601
-        }
6602
-
6603
-        $password_field = $model_with_password->getPasswordField();
6604
-        if ($password_field instanceof EE_Password_Field) {
6605
-            $password_field_name = $password_field->get_name();
6606
-        } else {
6607
-            throw new ModelConfigurationException(
6608
-                $this,
6609
-                sprintf(
6610
-                    esc_html_x(
6611
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6612
-                        '1: model name, 2: special string',
6613
-                        'event_espresso'
6614
-                    ),
6615
-                    $model_with_password->get_this_model_name(),
6616
-                    $this->model_chain_to_password
6617
-                )
6618
-            );
6619
-        }
6620
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6621
-    }
6622
-
6623
-
6624
-    /**
6625
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6626
-     * or if this model itself has a password affecting access to some of its other fields.
6627
-     *
6628
-     * @return boolean
6629
-     * @since 4.9.74.p
6630
-     */
6631
-    public function restrictedByRelatedModelPassword()
6632
-    {
6633
-        return $this->model_chain_to_password !== null;
6634
-    }
3891
+		}
3892
+		return $null_friendly_where_conditions;
3893
+	}
3894
+
3895
+
3896
+	/**
3897
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3898
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3899
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3900
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3901
+	 *
3902
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3903
+	 * @return array @see
3904
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3905
+	 * @throws EE_Error
3906
+	 * @throws EE_Error
3907
+	 */
3908
+	private function _get_default_where_conditions($model_relation_path = '')
3909
+	{
3910
+		if ($this->_ignore_where_strategy) {
3911
+			return [];
3912
+		}
3913
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3914
+	}
3915
+
3916
+
3917
+	/**
3918
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3919
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3920
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3921
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3922
+	 * Similar to _get_default_where_conditions
3923
+	 *
3924
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3925
+	 * @return array @see
3926
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3927
+	 * @throws EE_Error
3928
+	 * @throws EE_Error
3929
+	 */
3930
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3931
+	{
3932
+		if ($this->_ignore_where_strategy) {
3933
+			return [];
3934
+		}
3935
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3936
+	}
3937
+
3938
+
3939
+	/**
3940
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3941
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3942
+	 *
3943
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3944
+	 * @return string
3945
+	 * @throws EE_Error
3946
+	 */
3947
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3948
+	{
3949
+		$selects = $this->_get_columns_to_select_for_this_model();
3950
+		foreach (
3951
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3952
+		) {
3953
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3954
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3955
+			foreach ($other_model_selects as $key => $value) {
3956
+				$selects[] = $value;
3957
+			}
3958
+		}
3959
+		return implode(", ", $selects);
3960
+	}
3961
+
3962
+
3963
+	/**
3964
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3965
+	 * So that's going to be the columns for all the fields on the model
3966
+	 *
3967
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3968
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3969
+	 */
3970
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3971
+	{
3972
+		$fields                                       = $this->field_settings();
3973
+		$selects                                      = [];
3974
+		$table_alias_with_model_relation_chain_prefix =
3975
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3976
+				$model_relation_chain,
3977
+				$this->get_this_model_name()
3978
+			);
3979
+		foreach ($fields as $field_obj) {
3980
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3981
+						 . $field_obj->get_table_alias()
3982
+						 . "."
3983
+						 . $field_obj->get_table_column()
3984
+						 . " AS '"
3985
+						 . $table_alias_with_model_relation_chain_prefix
3986
+						 . $field_obj->get_table_alias()
3987
+						 . "."
3988
+						 . $field_obj->get_table_column()
3989
+						 . "'";
3990
+		}
3991
+		// make sure we are also getting the PKs of each table
3992
+		$tables = $this->get_tables();
3993
+		if (count($tables) > 1) {
3994
+			foreach ($tables as $table_obj) {
3995
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3996
+									   . $table_obj->get_fully_qualified_pk_column();
3997
+				if (! in_array($qualified_pk_column, $selects)) {
3998
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3999
+				}
4000
+			}
4001
+		}
4002
+		return $selects;
4003
+	}
4004
+
4005
+
4006
+	/**
4007
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4008
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4009
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4010
+	 * SQL for joining, and the data types
4011
+	 *
4012
+	 * @param null|string                 $original_query_param
4013
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4014
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4015
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4016
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4017
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4018
+	 *                                                          or 'Registration's
4019
+	 * @param string                      $original_query_param what it originally was (eg
4020
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4021
+	 *                                                          matches $query_param
4022
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4023
+	 * @throws EE_Error
4024
+	 */
4025
+	private function _extract_related_model_info_from_query_param(
4026
+		$query_param,
4027
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4028
+		$query_param_type,
4029
+		$original_query_param = null
4030
+	) {
4031
+		if ($original_query_param === null) {
4032
+			$original_query_param = $query_param;
4033
+		}
4034
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4035
+		// check to see if we have a field on this model
4036
+		$this_model_fields = $this->field_settings(true);
4037
+		if (array_key_exists($query_param, $this_model_fields)) {
4038
+			$field_is_allowed = in_array(
4039
+				$query_param_type,
4040
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4041
+				true
4042
+			);
4043
+			if ($field_is_allowed) {
4044
+				return;
4045
+			}
4046
+			throw new EE_Error(
4047
+				sprintf(
4048
+					esc_html__(
4049
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4050
+						"event_espresso"
4051
+					),
4052
+					$query_param,
4053
+					get_class($this),
4054
+					$query_param_type,
4055
+					$original_query_param
4056
+				)
4057
+			);
4058
+		}
4059
+		// check if this is a special logic query param
4060
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4061
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4062
+			if ($operator_is_allowed) {
4063
+				return;
4064
+			}
4065
+			throw new EE_Error(
4066
+				sprintf(
4067
+					esc_html__(
4068
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4069
+						'event_espresso'
4070
+					),
4071
+					implode('", "', $this->_logic_query_param_keys),
4072
+					$query_param,
4073
+					get_class($this),
4074
+					'<br />',
4075
+					"\t"
4076
+					. ' $passed_in_query_info = <pre>'
4077
+					. print_r($passed_in_query_info, true)
4078
+					. '</pre>'
4079
+					. "\n\t"
4080
+					. ' $query_param_type = '
4081
+					. $query_param_type
4082
+					. "\n\t"
4083
+					. ' $original_query_param = '
4084
+					. $original_query_param
4085
+				)
4086
+			);
4087
+		}
4088
+		// check if it's a custom selection
4089
+		if (
4090
+			$this->_custom_selections instanceof CustomSelects
4091
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4092
+		) {
4093
+			return;
4094
+		}
4095
+		// check if has a model name at the beginning
4096
+		// and
4097
+		// check if it's a field on a related model
4098
+		if (
4099
+			$this->extractJoinModelFromQueryParams(
4100
+				$passed_in_query_info,
4101
+				$query_param,
4102
+				$original_query_param,
4103
+				$query_param_type
4104
+			)
4105
+		) {
4106
+			return;
4107
+		}
4108
+
4109
+		// ok so $query_param didn't start with a model name
4110
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4111
+		// it's wack, that's what it is
4112
+		throw new EE_Error(
4113
+			sprintf(
4114
+				esc_html__(
4115
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4116
+					"event_espresso"
4117
+				),
4118
+				$query_param,
4119
+				get_class($this),
4120
+				$query_param_type,
4121
+				$original_query_param
4122
+			)
4123
+		);
4124
+	}
4125
+
4126
+
4127
+	/**
4128
+	 * Extracts any possible join model information from the provided possible_join_string.
4129
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4130
+	 * join
4131
+	 * parts that should be added to the query.
4132
+	 *
4133
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4134
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4135
+	 * @param null|string                 $original_query_param
4136
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4137
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4138
+	 *                                                           etc.)
4139
+	 * @return bool  returns true if a join was added and false if not.
4140
+	 * @throws EE_Error
4141
+	 */
4142
+	private function extractJoinModelFromQueryParams(
4143
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4144
+		$possible_join_string,
4145
+		$original_query_param,
4146
+		$query_parameter_type
4147
+	) {
4148
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4149
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4150
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4151
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4152
+				if ($possible_join_string === '') {
4153
+					// nothing left to $query_param
4154
+					// we should actually end in a field name, not a model like this!
4155
+					throw new EE_Error(
4156
+						sprintf(
4157
+							esc_html__(
4158
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4159
+								"event_espresso"
4160
+							),
4161
+							$possible_join_string,
4162
+							$query_parameter_type,
4163
+							get_class($this),
4164
+							$valid_related_model_name
4165
+						)
4166
+					);
4167
+				}
4168
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4169
+				$related_model_obj->_extract_related_model_info_from_query_param(
4170
+					$possible_join_string,
4171
+					$query_info_carrier,
4172
+					$query_parameter_type,
4173
+					$original_query_param
4174
+				);
4175
+				return true;
4176
+			}
4177
+			if ($possible_join_string === $valid_related_model_name) {
4178
+				$this->_add_join_to_model(
4179
+					$valid_related_model_name,
4180
+					$query_info_carrier,
4181
+					$original_query_param
4182
+				);
4183
+				return true;
4184
+			}
4185
+		}
4186
+		return false;
4187
+	}
4188
+
4189
+
4190
+	/**
4191
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4192
+	 *
4193
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4194
+	 * @throws EE_Error
4195
+	 */
4196
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4197
+	{
4198
+		if (
4199
+			$this->_custom_selections instanceof CustomSelects
4200
+			&& (
4201
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4202
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4203
+			)
4204
+		) {
4205
+			$original_selects = $this->_custom_selections->originalSelects();
4206
+			foreach ($original_selects as $alias => $select_configuration) {
4207
+				$this->extractJoinModelFromQueryParams(
4208
+					$query_info_carrier,
4209
+					$select_configuration[0],
4210
+					$select_configuration[0],
4211
+					'custom_selects'
4212
+				);
4213
+			}
4214
+		}
4215
+	}
4216
+
4217
+
4218
+	/**
4219
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4220
+	 * and store it on $passed_in_query_info
4221
+	 *
4222
+	 * @param string                      $model_name
4223
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4224
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4225
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4226
+	 *                                                          and are adding a join to 'Payment' with the original
4227
+	 *                                                          query param key
4228
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4229
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4230
+	 *                                                          Payment wants to add default query params so that it
4231
+	 *                                                          will know what models to prepend onto its default query
4232
+	 *                                                          params or in case it wants to rename tables (in case
4233
+	 *                                                          there are multiple joins to the same table)
4234
+	 * @return void
4235
+	 * @throws EE_Error
4236
+	 */
4237
+	private function _add_join_to_model(
4238
+		$model_name,
4239
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4240
+		$original_query_param
4241
+	) {
4242
+		$relation_obj         = $this->related_settings_for($model_name);
4243
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4244
+		// check if the relation is HABTM, because then we're essentially doing two joins
4245
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4246
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4247
+			$join_model_obj = $relation_obj->get_join_model();
4248
+			// replace the model specified with the join model for this relation chain, whi
4249
+			$relation_chain_to_join_model =
4250
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4251
+					$model_name,
4252
+					$join_model_obj->get_this_model_name(),
4253
+					$model_relation_chain
4254
+				);
4255
+			$passed_in_query_info->merge(
4256
+				new EE_Model_Query_Info_Carrier(
4257
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4258
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4259
+				)
4260
+			);
4261
+		}
4262
+		// now just join to the other table pointed to by the relation object, and add its data types
4263
+		$passed_in_query_info->merge(
4264
+			new EE_Model_Query_Info_Carrier(
4265
+				[$model_relation_chain => $model_name],
4266
+				$relation_obj->get_join_statement($model_relation_chain)
4267
+			)
4268
+		);
4269
+	}
4270
+
4271
+
4272
+	/**
4273
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4274
+	 *
4275
+	 * @param array $where_params @see
4276
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4277
+	 * @return string of SQL
4278
+	 * @throws EE_Error
4279
+	 */
4280
+	private function _construct_where_clause($where_params)
4281
+	{
4282
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4283
+		if ($SQL) {
4284
+			return " WHERE " . $SQL;
4285
+		}
4286
+		return '';
4287
+	}
4288
+
4289
+
4290
+	/**
4291
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4292
+	 * and should be passed HAVING parameters, not WHERE parameters
4293
+	 *
4294
+	 * @param array $having_params
4295
+	 * @return string
4296
+	 * @throws EE_Error
4297
+	 */
4298
+	private function _construct_having_clause($having_params)
4299
+	{
4300
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4301
+		if ($SQL) {
4302
+			return " HAVING " . $SQL;
4303
+		}
4304
+		return '';
4305
+	}
4306
+
4307
+
4308
+	/**
4309
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4310
+	 * Event_Meta.meta_value = 'foo'))"
4311
+	 *
4312
+	 * @param array  $where_params @see
4313
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4314
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4315
+	 * @return string of SQL
4316
+	 * @throws EE_Error
4317
+	 */
4318
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4319
+	{
4320
+		$where_clauses = [];
4321
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4322
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4323
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4324
+				switch ($query_param) {
4325
+					case 'not':
4326
+					case 'NOT':
4327
+						$where_clauses[] = "! ("
4328
+										   . $this->_construct_condition_clause_recursive(
4329
+											   $op_and_value_or_sub_condition,
4330
+											   $glue
4331
+										   )
4332
+										   . ")";
4333
+						break;
4334
+					case 'and':
4335
+					case 'AND':
4336
+						$where_clauses[] = " ("
4337
+										   . $this->_construct_condition_clause_recursive(
4338
+											   $op_and_value_or_sub_condition,
4339
+											   ' AND '
4340
+										   )
4341
+										   . ")";
4342
+						break;
4343
+					case 'or':
4344
+					case 'OR':
4345
+						$where_clauses[] = " ("
4346
+										   . $this->_construct_condition_clause_recursive(
4347
+											   $op_and_value_or_sub_condition,
4348
+											   ' OR '
4349
+										   )
4350
+										   . ")";
4351
+						break;
4352
+				}
4353
+			} else {
4354
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4355
+				// if it's not a normal field, maybe it's a custom selection?
4356
+				if (! $field_obj) {
4357
+					if ($this->_custom_selections instanceof CustomSelects) {
4358
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4359
+					} else {
4360
+						throw new EE_Error(
4361
+							sprintf(
4362
+								esc_html__(
4363
+									"%s is neither a valid model field name, nor a custom selection",
4364
+									"event_espresso"
4365
+								),
4366
+								$query_param
4367
+							)
4368
+						);
4369
+					}
4370
+				}
4371
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4372
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4373
+			}
4374
+		}
4375
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4376
+	}
4377
+
4378
+
4379
+	/**
4380
+	 * Takes the input parameter and extract the table name (alias) and column name
4381
+	 *
4382
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4383
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4384
+	 * @throws EE_Error
4385
+	 */
4386
+	private function _deduce_column_name_from_query_param($query_param)
4387
+	{
4388
+		$field = $this->_deduce_field_from_query_param($query_param);
4389
+		if ($field) {
4390
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4391
+				$field->get_model_name(),
4392
+				$query_param
4393
+			);
4394
+			return $table_alias_prefix . $field->get_qualified_column();
4395
+		}
4396
+		if (
4397
+			$this->_custom_selections instanceof CustomSelects
4398
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4399
+		) {
4400
+			// maybe it's custom selection item?
4401
+			// if so, just use it as the "column name"
4402
+			return $query_param;
4403
+		}
4404
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4405
+			? implode(',', $this->_custom_selections->columnAliases())
4406
+			: '';
4407
+		throw new EE_Error(
4408
+			sprintf(
4409
+				esc_html__(
4410
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4411
+					"event_espresso"
4412
+				),
4413
+				$query_param,
4414
+				$custom_select_aliases
4415
+			)
4416
+		);
4417
+	}
4418
+
4419
+
4420
+	/**
4421
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4422
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4423
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4424
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4425
+	 *
4426
+	 * @param string $condition_query_param_key
4427
+	 * @return string
4428
+	 */
4429
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4430
+	{
4431
+		$pos_of_star = strpos($condition_query_param_key, '*');
4432
+		if ($pos_of_star === false) {
4433
+			return $condition_query_param_key;
4434
+		}
4435
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4436
+		return $condition_query_param_sans_star;
4437
+	}
4438
+
4439
+
4440
+	/**
4441
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4442
+	 *
4443
+	 * @param mixed      array | string    $op_and_value
4444
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4445
+	 * @return string
4446
+	 * @throws EE_Error
4447
+	 */
4448
+	private function _construct_op_and_value($op_and_value, $field_obj)
4449
+	{
4450
+		if (is_array($op_and_value)) {
4451
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4452
+			if (! $operator) {
4453
+				$php_array_like_string = [];
4454
+				foreach ($op_and_value as $key => $value) {
4455
+					$php_array_like_string[] = "$key=>$value";
4456
+				}
4457
+				throw new EE_Error(
4458
+					sprintf(
4459
+						esc_html__(
4460
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4461
+							"event_espresso"
4462
+						),
4463
+						implode(",", $php_array_like_string)
4464
+					)
4465
+				);
4466
+			}
4467
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4468
+		} else {
4469
+			$operator = '=';
4470
+			$value    = $op_and_value;
4471
+		}
4472
+		// check to see if the value is actually another field
4473
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4474
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4475
+		}
4476
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4477
+			// in this case, the value should be an array, or at least a comma-separated list
4478
+			// it will need to handle a little differently
4479
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4480
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4481
+			return $operator . SP . $cleaned_value;
4482
+		}
4483
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4484
+			// the value should be an array with count of two.
4485
+			if (count($value) !== 2) {
4486
+				throw new EE_Error(
4487
+					sprintf(
4488
+						esc_html__(
4489
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4490
+							'event_espresso'
4491
+						),
4492
+						"BETWEEN"
4493
+					)
4494
+				);
4495
+			}
4496
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4497
+			return $operator . SP . $cleaned_value;
4498
+		}
4499
+		if (in_array($operator, $this->valid_null_style_operators())) {
4500
+			if ($value !== null) {
4501
+				throw new EE_Error(
4502
+					sprintf(
4503
+						esc_html__(
4504
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4505
+							"event_espresso"
4506
+						),
4507
+						$value,
4508
+						$operator
4509
+					)
4510
+				);
4511
+			}
4512
+			return $operator;
4513
+		}
4514
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4515
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4516
+			// remove other junk. So just treat it as a string.
4517
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4518
+		}
4519
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4520
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4521
+		}
4522
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4523
+			throw new EE_Error(
4524
+				sprintf(
4525
+					esc_html__(
4526
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4527
+						'event_espresso'
4528
+					),
4529
+					$operator,
4530
+					$operator
4531
+				)
4532
+			);
4533
+		}
4534
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4535
+			throw new EE_Error(
4536
+				sprintf(
4537
+					esc_html__(
4538
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4539
+						'event_espresso'
4540
+					),
4541
+					$operator,
4542
+					$operator
4543
+				)
4544
+			);
4545
+		}
4546
+		throw new EE_Error(
4547
+			sprintf(
4548
+				esc_html__(
4549
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4550
+					"event_espresso"
4551
+				),
4552
+				http_build_query($op_and_value)
4553
+			)
4554
+		);
4555
+	}
4556
+
4557
+
4558
+	/**
4559
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4560
+	 *
4561
+	 * @param array                      $values
4562
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4563
+	 *                                              '%s'
4564
+	 * @return string
4565
+	 * @throws EE_Error
4566
+	 */
4567
+	public function _construct_between_value($values, $field_obj)
4568
+	{
4569
+		$cleaned_values = [];
4570
+		foreach ($values as $value) {
4571
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4572
+		}
4573
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4574
+	}
4575
+
4576
+
4577
+	/**
4578
+	 * Takes an array or a comma-separated list of $values and cleans them
4579
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4580
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4581
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4582
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4583
+	 *
4584
+	 * @param mixed                      $values    array or comma-separated string
4585
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4586
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4587
+	 * @throws EE_Error
4588
+	 */
4589
+	public function _construct_in_value($values, $field_obj)
4590
+	{
4591
+		$prepped = [];
4592
+		// check if the value is a CSV list
4593
+		if (is_string($values)) {
4594
+			// in which case, turn it into an array
4595
+			$values = explode(',', $values);
4596
+		}
4597
+		// make sure we only have one of each value in the list
4598
+		$values = array_unique($values);
4599
+		foreach ($values as $value) {
4600
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4601
+		}
4602
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4603
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4604
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4605
+		if (empty($prepped)) {
4606
+			$all_fields  = $this->field_settings();
4607
+			$first_field = reset($all_fields);
4608
+			$main_table  = $this->_get_main_table();
4609
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4610
+		}
4611
+		return '(' . implode(',', $prepped) . ')';
4612
+	}
4613
+
4614
+
4615
+	/**
4616
+	 * @param mixed                      $value
4617
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4618
+	 * @return false|null|string
4619
+	 * @throws EE_Error
4620
+	 */
4621
+	private function _wpdb_prepare_using_field($value, $field_obj)
4622
+	{
4623
+		/** @type WPDB $wpdb */
4624
+		global $wpdb;
4625
+		if ($field_obj instanceof EE_Model_Field_Base) {
4626
+			return $wpdb->prepare(
4627
+				$field_obj->get_wpdb_data_type(),
4628
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4629
+			);
4630
+		} //$field_obj should really just be a data type
4631
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4632
+			throw new EE_Error(
4633
+				sprintf(
4634
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4635
+					$field_obj,
4636
+					implode(",", $this->_valid_wpdb_data_types)
4637
+				)
4638
+			);
4639
+		}
4640
+		return $wpdb->prepare($field_obj, $value);
4641
+	}
4642
+
4643
+
4644
+	/**
4645
+	 * Takes the input parameter and finds the model field that it indicates.
4646
+	 *
4647
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4648
+	 * @return EE_Model_Field_Base
4649
+	 * @throws EE_Error
4650
+	 */
4651
+	protected function _deduce_field_from_query_param($query_param_name)
4652
+	{
4653
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4654
+		// which will help us find the database table and column
4655
+		$query_param_parts = explode(".", $query_param_name);
4656
+		if (empty($query_param_parts)) {
4657
+			throw new EE_Error(
4658
+				sprintf(
4659
+					esc_html__(
4660
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4661
+						'event_espresso'
4662
+					),
4663
+					$query_param_name
4664
+				)
4665
+			);
4666
+		}
4667
+		$number_of_parts       = count($query_param_parts);
4668
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4669
+		if ($number_of_parts === 1) {
4670
+			$field_name = $last_query_param_part;
4671
+			$model_obj  = $this;
4672
+		} else {// $number_of_parts >= 2
4673
+			// the last part is the column name, and there are only 2parts. therefore...
4674
+			$field_name = $last_query_param_part;
4675
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4676
+		}
4677
+		try {
4678
+			return $model_obj->field_settings_for($field_name);
4679
+		} catch (EE_Error $e) {
4680
+			return null;
4681
+		}
4682
+	}
4683
+
4684
+
4685
+	/**
4686
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4687
+	 * alias and column which corresponds to it
4688
+	 *
4689
+	 * @param string $field_name
4690
+	 * @return string
4691
+	 * @throws EE_Error
4692
+	 */
4693
+	public function _get_qualified_column_for_field($field_name)
4694
+	{
4695
+		$all_fields = $this->field_settings();
4696
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4697
+		if ($field) {
4698
+			return $field->get_qualified_column();
4699
+		}
4700
+		throw new EE_Error(
4701
+			sprintf(
4702
+				esc_html__(
4703
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4704
+					'event_espresso'
4705
+				),
4706
+				$field_name,
4707
+				get_class($this)
4708
+			)
4709
+		);
4710
+	}
4711
+
4712
+
4713
+	/**
4714
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4715
+	 * Example usage:
4716
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4717
+	 *      array(),
4718
+	 *      ARRAY_A,
4719
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4720
+	 *  );
4721
+	 * is equivalent to
4722
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4723
+	 * and
4724
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4725
+	 *      array(
4726
+	 *          array(
4727
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4728
+	 *          ),
4729
+	 *          ARRAY_A,
4730
+	 *          implode(
4731
+	 *              ', ',
4732
+	 *              array_merge(
4733
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4734
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4735
+	 *              )
4736
+	 *          )
4737
+	 *      )
4738
+	 *  );
4739
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4740
+	 *
4741
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4742
+	 *                                            and the one whose fields you are selecting for example: when querying
4743
+	 *                                            tickets model and selecting fields from the tickets model you would
4744
+	 *                                            leave this parameter empty, because no models are needed to join
4745
+	 *                                            between the queried model and the selected one. Likewise when
4746
+	 *                                            querying the datetime model and selecting fields from the tickets
4747
+	 *                                            model, it would also be left empty, because there is a direct
4748
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4749
+	 *                                            them together. However, when querying from the event model and
4750
+	 *                                            selecting fields from the ticket model, you should provide the string
4751
+	 *                                            'Datetime', indicating that the event model must first join to the
4752
+	 *                                            datetime model in order to find its relation to ticket model.
4753
+	 *                                            Also, when querying from the venue model and selecting fields from
4754
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4755
+	 *                                            indicating you need to join the venue model to the event model,
4756
+	 *                                            to the datetime model, in order to find its relation to the ticket
4757
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4758
+	 *                                            the models' tables qualified columns
4759
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4760
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4761
+	 *                                            qualified column names
4762
+	 * @return array|string
4763
+	 */
4764
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4765
+	{
4766
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4767
+		$qualified_columns = [];
4768
+		foreach ($this->field_settings() as $field_name => $field) {
4769
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4770
+		}
4771
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4772
+	}
4773
+
4774
+
4775
+	/**
4776
+	 * constructs the select use on special limit joins
4777
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4778
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4779
+	 * (as that is typically where the limits would be set).
4780
+	 *
4781
+	 * @param string       $table_alias The table the select is being built for
4782
+	 * @param mixed|string $limit       The limit for this select
4783
+	 * @return string                The final select join element for the query.
4784
+	 * @throws EE_Error
4785
+	 * @throws EE_Error
4786
+	 */
4787
+	public function _construct_limit_join_select($table_alias, $limit)
4788
+	{
4789
+		$SQL = '';
4790
+		foreach ($this->_tables as $table_obj) {
4791
+			if ($table_obj instanceof EE_Primary_Table) {
4792
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4793
+					? $table_obj->get_select_join_limit($limit)
4794
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4795
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4796
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4797
+					? $table_obj->get_select_join_limit_join($limit)
4798
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4799
+			}
4800
+		}
4801
+		return $SQL;
4802
+	}
4803
+
4804
+
4805
+	/**
4806
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4807
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4808
+	 *
4809
+	 * @return string SQL
4810
+	 * @throws EE_Error
4811
+	 */
4812
+	public function _construct_internal_join()
4813
+	{
4814
+		$SQL = $this->_get_main_table()->get_table_sql();
4815
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4816
+		return $SQL;
4817
+	}
4818
+
4819
+
4820
+	/**
4821
+	 * Constructs the SQL for joining all the tables on this model.
4822
+	 * Normally $alias should be the primary table's alias, but in cases where
4823
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4824
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4825
+	 * alias, this will construct SQL like:
4826
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4827
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4828
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4829
+	 *
4830
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4831
+	 * @return string
4832
+	 * @throws EE_Error
4833
+	 * @throws EE_Error
4834
+	 */
4835
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4836
+	{
4837
+		$SQL               = '';
4838
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4839
+		foreach ($this->_tables as $table_obj) {
4840
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4841
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4842
+					// so we're joining to this table, meaning the table is already in
4843
+					// the FROM statement, BUT the primary table isn't. So we want
4844
+					// to add the inverse join sql
4845
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4846
+				} else {
4847
+					// just add a regular JOIN to this table from the primary table
4848
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4849
+				}
4850
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4851
+		}
4852
+		return $SQL;
4853
+	}
4854
+
4855
+
4856
+	/**
4857
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4858
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4859
+	 * their data type (eg, '%s', '%d', etc)
4860
+	 *
4861
+	 * @return array
4862
+	 */
4863
+	public function _get_data_types()
4864
+	{
4865
+		$data_types = [];
4866
+		foreach ($this->field_settings() as $field_obj) {
4867
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4868
+			/** @var $field_obj EE_Model_Field_Base */
4869
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4870
+		}
4871
+		return $data_types;
4872
+	}
4873
+
4874
+
4875
+	/**
4876
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4877
+	 *
4878
+	 * @param string $model_name
4879
+	 * @return EEM_Base
4880
+	 * @throws EE_Error
4881
+	 */
4882
+	public function get_related_model_obj($model_name)
4883
+	{
4884
+		$model_classname = "EEM_" . $model_name;
4885
+		if (! class_exists($model_classname)) {
4886
+			throw new EE_Error(
4887
+				sprintf(
4888
+					esc_html__(
4889
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4890
+						'event_espresso'
4891
+					),
4892
+					$model_name,
4893
+					$model_classname
4894
+				)
4895
+			);
4896
+		}
4897
+		return call_user_func($model_classname . "::instance");
4898
+	}
4899
+
4900
+
4901
+	/**
4902
+	 * Returns the array of EE_ModelRelations for this model.
4903
+	 *
4904
+	 * @return EE_Model_Relation_Base[]
4905
+	 */
4906
+	public function relation_settings()
4907
+	{
4908
+		return $this->_model_relations;
4909
+	}
4910
+
4911
+
4912
+	/**
4913
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4914
+	 * because without THOSE models, this model probably doesn't have much purpose.
4915
+	 * (Eg, without an event, datetimes have little purpose.)
4916
+	 *
4917
+	 * @return EE_Belongs_To_Relation[]
4918
+	 */
4919
+	public function belongs_to_relations()
4920
+	{
4921
+		$belongs_to_relations = [];
4922
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4923
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4924
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4925
+			}
4926
+		}
4927
+		return $belongs_to_relations;
4928
+	}
4929
+
4930
+
4931
+	/**
4932
+	 * Returns the specified EE_Model_Relation, or throws an exception
4933
+	 *
4934
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4935
+	 * @return EE_Model_Relation_Base
4936
+	 * @throws EE_Error
4937
+	 */
4938
+	public function related_settings_for($relation_name)
4939
+	{
4940
+		$relatedModels = $this->relation_settings();
4941
+		if (! array_key_exists($relation_name, $relatedModels)) {
4942
+			throw new EE_Error(
4943
+				sprintf(
4944
+					esc_html__(
4945
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4946
+						'event_espresso'
4947
+					),
4948
+					$relation_name,
4949
+					$this->_get_class_name(),
4950
+					implode(', ', array_keys($relatedModels))
4951
+				)
4952
+			);
4953
+		}
4954
+		return $relatedModels[ $relation_name ];
4955
+	}
4956
+
4957
+
4958
+	/**
4959
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4960
+	 * fields
4961
+	 *
4962
+	 * @param string  $fieldName
4963
+	 * @param boolean $include_db_only_fields
4964
+	 * @return EE_Model_Field_Base
4965
+	 * @throws EE_Error
4966
+	 */
4967
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4968
+	{
4969
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4970
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4971
+			throw new EE_Error(
4972
+				sprintf(
4973
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4974
+					$fieldName,
4975
+					get_class($this)
4976
+				)
4977
+			);
4978
+		}
4979
+		return $fieldSettings[ $fieldName ];
4980
+	}
4981
+
4982
+
4983
+	/**
4984
+	 * Checks if this field exists on this model
4985
+	 *
4986
+	 * @param string $fieldName a key in the model's _field_settings array
4987
+	 * @return boolean
4988
+	 */
4989
+	public function has_field($fieldName)
4990
+	{
4991
+		$fieldSettings = $this->field_settings(true);
4992
+		if (isset($fieldSettings[ $fieldName ])) {
4993
+			return true;
4994
+		}
4995
+		return false;
4996
+	}
4997
+
4998
+
4999
+	/**
5000
+	 * Returns whether or not this model has a relation to the specified model
5001
+	 *
5002
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5003
+	 * @return boolean
5004
+	 */
5005
+	public function has_relation($relation_name)
5006
+	{
5007
+		$relations = $this->relation_settings();
5008
+		if (isset($relations[ $relation_name ])) {
5009
+			return true;
5010
+		}
5011
+		return false;
5012
+	}
5013
+
5014
+
5015
+	/**
5016
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5017
+	 * Eg, on EE_Answer that would be ANS_ID field object
5018
+	 *
5019
+	 * @param $field_obj
5020
+	 * @return boolean
5021
+	 */
5022
+	public function is_primary_key_field($field_obj)
5023
+	{
5024
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
5025
+	}
5026
+
5027
+
5028
+	/**
5029
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5030
+	 * Eg, on EE_Answer that would be ANS_ID field object
5031
+	 *
5032
+	 * @return EE_Primary_Key_Field_Base
5033
+	 * @throws EE_Error
5034
+	 */
5035
+	public function get_primary_key_field()
5036
+	{
5037
+		if ($this->_primary_key_field === null) {
5038
+			foreach ($this->field_settings(true) as $field_obj) {
5039
+				if ($this->is_primary_key_field($field_obj)) {
5040
+					$this->_primary_key_field = $field_obj;
5041
+					break;
5042
+				}
5043
+			}
5044
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5045
+				throw new EE_Error(
5046
+					sprintf(
5047
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5048
+						get_class($this)
5049
+					)
5050
+				);
5051
+			}
5052
+		}
5053
+		return $this->_primary_key_field;
5054
+	}
5055
+
5056
+
5057
+	/**
5058
+	 * Returns whether or not not there is a primary key on this model.
5059
+	 * Internally does some caching.
5060
+	 *
5061
+	 * @return boolean
5062
+	 */
5063
+	public function has_primary_key_field()
5064
+	{
5065
+		if ($this->_has_primary_key_field === null) {
5066
+			try {
5067
+				$this->get_primary_key_field();
5068
+				$this->_has_primary_key_field = true;
5069
+			} catch (EE_Error $e) {
5070
+				$this->_has_primary_key_field = false;
5071
+			}
5072
+		}
5073
+		return $this->_has_primary_key_field;
5074
+	}
5075
+
5076
+
5077
+	/**
5078
+	 * Finds the first field of type $field_class_name.
5079
+	 *
5080
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5081
+	 *                                 EE_Foreign_Key_Field, etc
5082
+	 * @return EE_Model_Field_Base or null if none is found
5083
+	 */
5084
+	public function get_a_field_of_type($field_class_name)
5085
+	{
5086
+		foreach ($this->field_settings() as $field) {
5087
+			if ($field instanceof $field_class_name) {
5088
+				return $field;
5089
+			}
5090
+		}
5091
+		return null;
5092
+	}
5093
+
5094
+
5095
+	/**
5096
+	 * Gets a foreign key field pointing to model.
5097
+	 *
5098
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5099
+	 * @return EE_Foreign_Key_Field_Base
5100
+	 * @throws EE_Error
5101
+	 */
5102
+	public function get_foreign_key_to($model_name)
5103
+	{
5104
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5105
+			foreach ($this->field_settings() as $field) {
5106
+				if (
5107
+					$field instanceof EE_Foreign_Key_Field_Base
5108
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5109
+				) {
5110
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5111
+					break;
5112
+				}
5113
+			}
5114
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5115
+				throw new EE_Error(
5116
+					sprintf(
5117
+						esc_html__(
5118
+							"There is no foreign key field pointing to model %s on model %s",
5119
+							'event_espresso'
5120
+						),
5121
+						$model_name,
5122
+						get_class($this)
5123
+					)
5124
+				);
5125
+			}
5126
+		}
5127
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5128
+	}
5129
+
5130
+
5131
+	/**
5132
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5133
+	 *
5134
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5135
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5136
+	 *                            Either one works
5137
+	 * @return string
5138
+	 */
5139
+	public function get_table_for_alias($table_alias)
5140
+	{
5141
+		$table_alias_sans_model_relation_chain_prefix =
5142
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5143
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5144
+	}
5145
+
5146
+
5147
+	/**
5148
+	 * Returns a flat array of all field son this model, instead of organizing them
5149
+	 * by table_alias as they are in the constructor.
5150
+	 *
5151
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5152
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5153
+	 */
5154
+	public function field_settings($include_db_only_fields = false)
5155
+	{
5156
+		if ($include_db_only_fields) {
5157
+			if ($this->_cached_fields === null) {
5158
+				$this->_cached_fields = [];
5159
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5160
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5161
+						$this->_cached_fields[ $field_name ] = $field_obj;
5162
+					}
5163
+				}
5164
+			}
5165
+			return $this->_cached_fields;
5166
+		}
5167
+		if ($this->_cached_fields_non_db_only === null) {
5168
+			$this->_cached_fields_non_db_only = [];
5169
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5170
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5171
+					/** @var $field_obj EE_Model_Field_Base */
5172
+					if (! $field_obj->is_db_only_field()) {
5173
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5174
+					}
5175
+				}
5176
+			}
5177
+		}
5178
+		return $this->_cached_fields_non_db_only;
5179
+	}
5180
+
5181
+
5182
+	/**
5183
+	 *        cycle though array of attendees and create objects out of each item
5184
+	 *
5185
+	 * @access        private
5186
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5187
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5188
+	 *                           numerically indexed)
5189
+	 * @throws EE_Error
5190
+	 * @throws ReflectionException
5191
+	 */
5192
+	protected function _create_objects($rows = [])
5193
+	{
5194
+		$array_of_objects = [];
5195
+		if (empty($rows)) {
5196
+			return [];
5197
+		}
5198
+		$count_if_model_has_no_primary_key = 0;
5199
+		$has_primary_key                   = $this->has_primary_key_field();
5200
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5201
+		foreach ((array) $rows as $row) {
5202
+			if (empty($row)) {
5203
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5204
+				return [];
5205
+			}
5206
+			// check if we've already set this object in the results array,
5207
+			// in which case there's no need to process it further (again)
5208
+			if ($has_primary_key) {
5209
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5210
+					$row,
5211
+					$primary_key_field->get_qualified_column(),
5212
+					$primary_key_field->get_table_column()
5213
+				);
5214
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5215
+					continue;
5216
+				}
5217
+			}
5218
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5219
+			if (! $classInstance) {
5220
+				throw new EE_Error(
5221
+					sprintf(
5222
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5223
+						$this->get_this_model_name(),
5224
+						http_build_query($row)
5225
+					)
5226
+				);
5227
+			}
5228
+			// set the timezone on the instantiated objects
5229
+			$classInstance->set_timezone($this->_timezone);
5230
+			// make sure if there is any timezone setting present that we set the timezone for the object
5231
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5232
+			$array_of_objects[ $key ] = $classInstance;
5233
+			// also, for all the relations of type BelongsTo, see if we can cache
5234
+			// those related models
5235
+			// (we could do this for other relations too, but if there are conditions
5236
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5237
+			// so it requires a little more thought than just caching them immediately...)
5238
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5239
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5240
+					// check if this model's INFO is present. If so, cache it on the model
5241
+					$other_model           = $relation_obj->get_other_model();
5242
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5243
+					// if we managed to make a model object from the results, cache it on the main model object
5244
+					if ($other_model_obj_maybe) {
5245
+						// set timezone on these other model objects if they are present
5246
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5247
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5248
+					}
5249
+				}
5250
+			}
5251
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5252
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5253
+			// the field in the CustomSelects object
5254
+			if ($this->_custom_selections instanceof CustomSelects) {
5255
+				$classInstance->setCustomSelectsValues(
5256
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5257
+				);
5258
+			}
5259
+		}
5260
+		return $array_of_objects;
5261
+	}
5262
+
5263
+
5264
+	/**
5265
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5266
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5267
+	 *
5268
+	 * @param array $db_results_row
5269
+	 * @return array
5270
+	 */
5271
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5272
+	{
5273
+		$results = [];
5274
+		if ($this->_custom_selections instanceof CustomSelects) {
5275
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5276
+				if (isset($db_results_row[ $alias ])) {
5277
+					$results[ $alias ] = $this->convertValueToDataType(
5278
+						$db_results_row[ $alias ],
5279
+						$this->_custom_selections->getDataTypeForAlias($alias)
5280
+					);
5281
+				}
5282
+			}
5283
+		}
5284
+		return $results;
5285
+	}
5286
+
5287
+
5288
+	/**
5289
+	 * This will set the value for the given alias
5290
+	 *
5291
+	 * @param string $value
5292
+	 * @param string $datatype (one of %d, %s, %f)
5293
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5294
+	 */
5295
+	protected function convertValueToDataType($value, $datatype)
5296
+	{
5297
+		switch ($datatype) {
5298
+			case '%f':
5299
+				return (float) $value;
5300
+			case '%d':
5301
+				return (int) $value;
5302
+			default:
5303
+				return (string) $value;
5304
+		}
5305
+	}
5306
+
5307
+
5308
+	/**
5309
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5310
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5311
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5312
+	 * object (as set in the model_field!).
5313
+	 *
5314
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5315
+	 * @throws EE_Error
5316
+	 * @throws ReflectionException
5317
+	 */
5318
+	public function create_default_object()
5319
+	{
5320
+		$this_model_fields_and_values = [];
5321
+		// setup the row using default values;
5322
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5323
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5324
+		}
5325
+		$className     = $this->_get_class_name();
5326
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5327
+	}
5328
+
5329
+
5330
+	/**
5331
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5332
+	 *                             or an stdClass where each property is the name of a column,
5333
+	 * @return EE_Base_Class
5334
+	 * @throws EE_Error
5335
+	 * @throws ReflectionException
5336
+	 */
5337
+	public function instantiate_class_from_array_or_object($cols_n_values)
5338
+	{
5339
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5340
+			$cols_n_values = get_object_vars($cols_n_values);
5341
+		}
5342
+		$primary_key = null;
5343
+		// make sure the array only has keys that are fields/columns on this model
5344
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5345
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5346
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5347
+		}
5348
+		$className = $this->_get_class_name();
5349
+		// check we actually found results that we can use to build our model object
5350
+		// if not, return null
5351
+		if ($this->has_primary_key_field()) {
5352
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5353
+				return null;
5354
+			}
5355
+		} elseif ($this->unique_indexes()) {
5356
+			$first_column = reset($this_model_fields_n_values);
5357
+			if (empty($first_column)) {
5358
+				return null;
5359
+			}
5360
+		}
5361
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5362
+		if ($primary_key) {
5363
+			$classInstance = $this->get_from_entity_map($primary_key);
5364
+			if (! $classInstance) {
5365
+				$classInstance = EE_Registry::instance()
5366
+											->load_class(
5367
+												$className,
5368
+												[$this_model_fields_n_values, $this->_timezone],
5369
+												true,
5370
+												false
5371
+											);
5372
+				// add this new object to the entity map
5373
+				$classInstance = $this->add_to_entity_map($classInstance);
5374
+			}
5375
+		} else {
5376
+			$classInstance = EE_Registry::instance()
5377
+										->load_class(
5378
+											$className,
5379
+											[$this_model_fields_n_values, $this->_timezone],
5380
+											true,
5381
+											false
5382
+										);
5383
+		}
5384
+		return $classInstance;
5385
+	}
5386
+
5387
+
5388
+	/**
5389
+	 * Gets the model object from the  entity map if it exists
5390
+	 *
5391
+	 * @param int|string $id the ID of the model object
5392
+	 * @return EE_Base_Class
5393
+	 */
5394
+	public function get_from_entity_map($id)
5395
+	{
5396
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5397
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5398
+	}
5399
+
5400
+
5401
+	/**
5402
+	 * add_to_entity_map
5403
+	 * Adds the object to the model's entity mappings
5404
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5405
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5406
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5407
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5408
+	 *        then this method should be called immediately after the update query
5409
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5410
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5411
+	 *
5412
+	 * @param EE_Base_Class $object
5413
+	 * @return EE_Base_Class
5414
+	 * @throws EE_Error
5415
+	 * @throws ReflectionException
5416
+	 */
5417
+	public function add_to_entity_map(EE_Base_Class $object)
5418
+	{
5419
+		$className = $this->_get_class_name();
5420
+		if (! $object instanceof $className) {
5421
+			throw new EE_Error(
5422
+				sprintf(
5423
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5424
+					is_object($object) ? get_class($object) : $object,
5425
+					$className
5426
+				)
5427
+			);
5428
+		}
5429
+		/** @var $object EE_Base_Class */
5430
+		if (! $object->ID()) {
5431
+			throw new EE_Error(
5432
+				sprintf(
5433
+					esc_html__(
5434
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5435
+						"event_espresso"
5436
+					),
5437
+					get_class($this)
5438
+				)
5439
+			);
5440
+		}
5441
+		// double check it's not already there
5442
+		$classInstance = $this->get_from_entity_map($object->ID());
5443
+		if ($classInstance) {
5444
+			return $classInstance;
5445
+		}
5446
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5447
+		return $object;
5448
+	}
5449
+
5450
+
5451
+	/**
5452
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5453
+	 * if no identifier is provided, then the entire entity map is emptied
5454
+	 *
5455
+	 * @param int|string $id the ID of the model object
5456
+	 * @return boolean
5457
+	 */
5458
+	public function clear_entity_map($id = null)
5459
+	{
5460
+		if (empty($id)) {
5461
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5462
+			return true;
5463
+		}
5464
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5465
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5466
+			return true;
5467
+		}
5468
+		return false;
5469
+	}
5470
+
5471
+
5472
+	/**
5473
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5474
+	 * Given an array where keys are column (or column alias) names and values,
5475
+	 * returns an array of their corresponding field names and database values
5476
+	 *
5477
+	 * @param array $cols_n_values
5478
+	 * @return array
5479
+	 * @throws EE_Error
5480
+	 * @throws ReflectionException
5481
+	 */
5482
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5483
+	{
5484
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5485
+	}
5486
+
5487
+
5488
+	/**
5489
+	 * _deduce_fields_n_values_from_cols_n_values
5490
+	 * Given an array where keys are column (or column alias) names and values,
5491
+	 * returns an array of their corresponding field names and database values
5492
+	 *
5493
+	 * @param array|stdClass $cols_n_values
5494
+	 * @return array
5495
+	 * @throws EE_Error
5496
+	 * @throws ReflectionException
5497
+	 */
5498
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5499
+	{
5500
+		if ($cols_n_values instanceof stdClass) {
5501
+			$cols_n_values = get_object_vars($cols_n_values);
5502
+		}
5503
+		$this_model_fields_n_values = [];
5504
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5505
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5506
+				$cols_n_values,
5507
+				$table_obj->get_fully_qualified_pk_column(),
5508
+				$table_obj->get_pk_column()
5509
+			);
5510
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5511
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5512
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5513
+					if (! $field_obj->is_db_only_field()) {
5514
+						// prepare field as if its coming from db
5515
+						$prepared_value                            =
5516
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5517
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5518
+					}
5519
+				}
5520
+			} else {
5521
+				// the table's rows existed. Use their values
5522
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5523
+					if (! $field_obj->is_db_only_field()) {
5524
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5525
+							$cols_n_values,
5526
+							$field_obj->get_qualified_column(),
5527
+							$field_obj->get_table_column()
5528
+						);
5529
+					}
5530
+				}
5531
+			}
5532
+		}
5533
+		return $this_model_fields_n_values;
5534
+	}
5535
+
5536
+
5537
+	/**
5538
+	 * @param $cols_n_values
5539
+	 * @param $qualified_column
5540
+	 * @param $regular_column
5541
+	 * @return null
5542
+	 * @throws EE_Error
5543
+	 * @throws ReflectionException
5544
+	 */
5545
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5546
+	{
5547
+		$value = null;
5548
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5549
+		// does the field on the model relate to this column retrieved from the db?
5550
+		// or is it a db-only field? (not relating to the model)
5551
+		if (isset($cols_n_values[ $qualified_column ])) {
5552
+			$value = $cols_n_values[ $qualified_column ];
5553
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5554
+			$value = $cols_n_values[ $regular_column ];
5555
+		} elseif (! empty($this->foreign_key_aliases)) {
5556
+			// no PK?  ok check if there is a foreign key alias set for this table
5557
+			// then check if that alias exists in the incoming data
5558
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5559
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5560
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5561
+					$value = $cols_n_values[ $FK_alias ];
5562
+					[$pk_class] = explode('.', $PK_column);
5563
+					$pk_model_name = "EEM_{$pk_class}";
5564
+					/** @var EEM_Base $pk_model */
5565
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5566
+					if ($pk_model instanceof EEM_Base) {
5567
+						// make sure object is pulled from db and added to entity map
5568
+						$pk_model->get_one_by_ID($value);
5569
+					}
5570
+					break;
5571
+				}
5572
+			}
5573
+		}
5574
+		return $value;
5575
+	}
5576
+
5577
+
5578
+	/**
5579
+	 * refresh_entity_map_from_db
5580
+	 * Makes sure the model object in the entity map at $id assumes the values
5581
+	 * of the database (opposite of EE_base_Class::save())
5582
+	 *
5583
+	 * @param int|string $id
5584
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5585
+	 * @throws EE_Error
5586
+	 * @throws ReflectionException
5587
+	 */
5588
+	public function refresh_entity_map_from_db($id)
5589
+	{
5590
+		$obj_in_map = $this->get_from_entity_map($id);
5591
+		if ($obj_in_map) {
5592
+			$wpdb_results = $this->_get_all_wpdb_results(
5593
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5594
+			);
5595
+			if ($wpdb_results && is_array($wpdb_results)) {
5596
+				$one_row = reset($wpdb_results);
5597
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5598
+					$obj_in_map->set_from_db($field_name, $db_value);
5599
+				}
5600
+				// clear the cache of related model objects
5601
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5602
+					$obj_in_map->clear_cache($relation_name, null, true);
5603
+				}
5604
+			}
5605
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5606
+			return $obj_in_map;
5607
+		}
5608
+		return $this->get_one_by_ID($id);
5609
+	}
5610
+
5611
+
5612
+	/**
5613
+	 * refresh_entity_map_with
5614
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5615
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5616
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5617
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5618
+	 *
5619
+	 * @param int|string    $id
5620
+	 * @param EE_Base_Class $replacing_model_obj
5621
+	 * @return EE_Base_Class
5622
+	 * @throws EE_Error
5623
+	 * @throws ReflectionException
5624
+	 */
5625
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5626
+	{
5627
+		$obj_in_map = $this->get_from_entity_map($id);
5628
+		if ($obj_in_map) {
5629
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5630
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5631
+					$obj_in_map->set($field_name, $value);
5632
+				}
5633
+				// make the model object in the entity map's cache match the $replacing_model_obj
5634
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5635
+					$obj_in_map->clear_cache($relation_name, null, true);
5636
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5637
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5638
+					}
5639
+				}
5640
+			}
5641
+			return $obj_in_map;
5642
+		}
5643
+		$this->add_to_entity_map($replacing_model_obj);
5644
+		return $replacing_model_obj;
5645
+	}
5646
+
5647
+
5648
+	/**
5649
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5650
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5651
+	 * require_once($this->_getClassName().".class.php");
5652
+	 *
5653
+	 * @return string
5654
+	 */
5655
+	private function _get_class_name()
5656
+	{
5657
+		return "EE_" . $this->get_this_model_name();
5658
+	}
5659
+
5660
+
5661
+	/**
5662
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5663
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5664
+	 * it would be 'Events'.
5665
+	 *
5666
+	 * @param int|float|null $quantity
5667
+	 * @return string
5668
+	 */
5669
+	public function item_name($quantity = 1): string
5670
+	{
5671
+		$quantity = floor($quantity);
5672
+		return apply_filters(
5673
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5674
+			$quantity > 1 ? $this->plural_item : $this->singular_item,
5675
+			$quantity,
5676
+			$this->plural_item,
5677
+			$this->singular_item
5678
+		);
5679
+	}
5680
+
5681
+
5682
+	/**
5683
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5684
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5685
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5686
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5687
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5688
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5689
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5690
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5691
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5692
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5693
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5694
+	 *        return $previousReturnValue.$returnString;
5695
+	 * }
5696
+	 * require('EEM_Answer.model.php');
5697
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5698
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5699
+	 *
5700
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5701
+	 * @param array  $args       array of original arguments passed to the function
5702
+	 * @return mixed whatever the plugin which calls add_filter decides
5703
+	 * @throws EE_Error
5704
+	 */
5705
+	public function __call($methodName, $args)
5706
+	{
5707
+		$className = get_class($this);
5708
+		$tagName   = "FHEE__{$className}__{$methodName}";
5709
+		if (! has_filter($tagName)) {
5710
+			throw new EE_Error(
5711
+				sprintf(
5712
+					esc_html__(
5713
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5714
+						'event_espresso'
5715
+					),
5716
+					$methodName,
5717
+					$className,
5718
+					$tagName,
5719
+					'<br />'
5720
+				)
5721
+			);
5722
+		}
5723
+		return apply_filters($tagName, null, $this, $args);
5724
+	}
5725
+
5726
+
5727
+	/**
5728
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5729
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5730
+	 *
5731
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5732
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5733
+	 *                                                       the object's class name
5734
+	 *                                                       or object's ID
5735
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5736
+	 *                                                       exists in the database. If it does not, we add it
5737
+	 * @return EE_Base_Class
5738
+	 * @throws EE_Error
5739
+	 * @throws ReflectionException
5740
+	 */
5741
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5742
+	{
5743
+		$className = $this->_get_class_name();
5744
+		if ($base_class_obj_or_id instanceof $className) {
5745
+			$model_object = $base_class_obj_or_id;
5746
+		} else {
5747
+			$primary_key_field = $this->get_primary_key_field();
5748
+			if (
5749
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5750
+				&& (
5751
+					is_int($base_class_obj_or_id)
5752
+					|| is_string($base_class_obj_or_id)
5753
+				)
5754
+			) {
5755
+				// assume it's an ID.
5756
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5757
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5758
+			} elseif (
5759
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5760
+				&& is_string($base_class_obj_or_id)
5761
+			) {
5762
+				// assume its a string representation of the object
5763
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5764
+			} else {
5765
+				throw new EE_Error(
5766
+					sprintf(
5767
+						esc_html__(
5768
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5769
+							'event_espresso'
5770
+						),
5771
+						$base_class_obj_or_id,
5772
+						$this->_get_class_name(),
5773
+						print_r($base_class_obj_or_id, true)
5774
+					)
5775
+				);
5776
+			}
5777
+		}
5778
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5779
+			$model_object->save();
5780
+		}
5781
+		return $model_object;
5782
+	}
5783
+
5784
+
5785
+	/**
5786
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5787
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5788
+	 * returns it ID.
5789
+	 *
5790
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5791
+	 * @return int|string depending on the type of this model object's ID
5792
+	 * @throws EE_Error
5793
+	 * @throws ReflectionException
5794
+	 */
5795
+	public function ensure_is_ID($base_class_obj_or_id)
5796
+	{
5797
+		$className = $this->_get_class_name();
5798
+		if ($base_class_obj_or_id instanceof $className) {
5799
+			/** @var $base_class_obj_or_id EE_Base_Class */
5800
+			$id = $base_class_obj_or_id->ID();
5801
+		} elseif (is_int($base_class_obj_or_id)) {
5802
+			// assume it's an ID
5803
+			$id = $base_class_obj_or_id;
5804
+		} elseif (is_string($base_class_obj_or_id)) {
5805
+			// assume its a string representation of the object
5806
+			$id = $base_class_obj_or_id;
5807
+		} else {
5808
+			throw new EE_Error(
5809
+				sprintf(
5810
+					esc_html__(
5811
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5812
+						'event_espresso'
5813
+					),
5814
+					$base_class_obj_or_id,
5815
+					$this->_get_class_name(),
5816
+					print_r($base_class_obj_or_id, true)
5817
+				)
5818
+			);
5819
+		}
5820
+		return $id;
5821
+	}
5822
+
5823
+
5824
+	/**
5825
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5826
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5827
+	 * been sanitized and converted into the appropriate domain.
5828
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5829
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5830
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5831
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5832
+	 * $EVT = EEM_Event::instance(); $old_setting =
5833
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5834
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5835
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5836
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5837
+	 *
5838
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5839
+	 * @return void
5840
+	 */
5841
+	public function assume_values_already_prepared_by_model_object(
5842
+		$values_already_prepared = self::not_prepared_by_model_object
5843
+	) {
5844
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5845
+	}
5846
+
5847
+
5848
+	/**
5849
+	 * Read comments for assume_values_already_prepared_by_model_object()
5850
+	 *
5851
+	 * @return int
5852
+	 */
5853
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5854
+	{
5855
+		return $this->_values_already_prepared_by_model_object;
5856
+	}
5857
+
5858
+
5859
+	/**
5860
+	 * Gets all the indexes on this model
5861
+	 *
5862
+	 * @return EE_Index[]
5863
+	 */
5864
+	public function indexes()
5865
+	{
5866
+		return $this->_indexes;
5867
+	}
5868
+
5869
+
5870
+	/**
5871
+	 * Gets all the Unique Indexes on this model
5872
+	 *
5873
+	 * @return EE_Unique_Index[]
5874
+	 */
5875
+	public function unique_indexes()
5876
+	{
5877
+		$unique_indexes = [];
5878
+		foreach ($this->_indexes as $name => $index) {
5879
+			if ($index instanceof EE_Unique_Index) {
5880
+				$unique_indexes [ $name ] = $index;
5881
+			}
5882
+		}
5883
+		return $unique_indexes;
5884
+	}
5885
+
5886
+
5887
+	/**
5888
+	 * Gets all the fields which, when combined, make the primary key.
5889
+	 * This is usually just an array with 1 element (the primary key), but in cases
5890
+	 * where there is no primary key, it's a combination of fields as defined
5891
+	 * on a primary index
5892
+	 *
5893
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5894
+	 * @throws EE_Error
5895
+	 */
5896
+	public function get_combined_primary_key_fields()
5897
+	{
5898
+		foreach ($this->indexes() as $index) {
5899
+			if ($index instanceof EE_Primary_Key_Index) {
5900
+				return $index->fields();
5901
+			}
5902
+		}
5903
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5904
+	}
5905
+
5906
+
5907
+	/**
5908
+	 * Used to build a primary key string (when the model has no primary key),
5909
+	 * which can be used a unique string to identify this model object.
5910
+	 *
5911
+	 * @param array $fields_n_values keys are field names, values are their values.
5912
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5913
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5914
+	 *                               before passing it to this function (that will convert it from columns-n-values
5915
+	 *                               to field-names-n-values).
5916
+	 * @return string
5917
+	 * @throws EE_Error
5918
+	 */
5919
+	public function get_index_primary_key_string($fields_n_values)
5920
+	{
5921
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5922
+			$fields_n_values,
5923
+			$this->get_combined_primary_key_fields()
5924
+		);
5925
+		return http_build_query($cols_n_values_for_primary_key_index);
5926
+	}
5927
+
5928
+
5929
+	/**
5930
+	 * Gets the field values from the primary key string
5931
+	 *
5932
+	 * @param string $index_primary_key_string
5933
+	 * @return null|array
5934
+	 * @throws EE_Error
5935
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5936
+	 */
5937
+	public function parse_index_primary_key_string($index_primary_key_string)
5938
+	{
5939
+		$key_fields = $this->get_combined_primary_key_fields();
5940
+		// check all of them are in the $id
5941
+		$key_vals_in_combined_pk = [];
5942
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5943
+		foreach ($key_fields as $key_field_name => $field_obj) {
5944
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5945
+				return null;
5946
+			}
5947
+		}
5948
+		return $key_vals_in_combined_pk;
5949
+	}
5950
+
5951
+
5952
+	/**
5953
+	 * verifies that an array of key-value pairs for model fields has a key
5954
+	 * for each field comprising the primary key index
5955
+	 *
5956
+	 * @param array $key_vals
5957
+	 * @return boolean
5958
+	 * @throws EE_Error
5959
+	 */
5960
+	public function has_all_combined_primary_key_fields($key_vals)
5961
+	{
5962
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5963
+		foreach ($keys_it_should_have as $key) {
5964
+			if (! isset($key_vals[ $key ])) {
5965
+				return false;
5966
+			}
5967
+		}
5968
+		return true;
5969
+	}
5970
+
5971
+
5972
+	/**
5973
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5974
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5975
+	 *
5976
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5977
+	 * @param array               $query_params                     @see
5978
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5979
+	 * @throws EE_Error
5980
+	 * @throws ReflectionException
5981
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5982
+	 *                                                              indexed)
5983
+	 */
5984
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5985
+	{
5986
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5987
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5988
+		} elseif (is_array($model_object_or_attributes_array)) {
5989
+			$attributes_array = $model_object_or_attributes_array;
5990
+		} else {
5991
+			throw new EE_Error(
5992
+				sprintf(
5993
+					esc_html__(
5994
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5995
+						"event_espresso"
5996
+					),
5997
+					$model_object_or_attributes_array
5998
+				)
5999
+			);
6000
+		}
6001
+		// even copies obviously won't have the same ID, so remove the primary key
6002
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6003
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6004
+			unset($attributes_array[ $this->primary_key_name() ]);
6005
+		}
6006
+		if (isset($query_params[0])) {
6007
+			$query_params[0] = array_merge($attributes_array, $query_params);
6008
+		} else {
6009
+			$query_params[0] = $attributes_array;
6010
+		}
6011
+		return $this->get_all($query_params);
6012
+	}
6013
+
6014
+
6015
+	/**
6016
+	 * Gets the first copy we find. See get_all_copies for more details
6017
+	 *
6018
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6019
+	 * @param array $query_params
6020
+	 * @return EE_Base_Class
6021
+	 * @throws EE_Error
6022
+	 * @throws ReflectionException
6023
+	 */
6024
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6025
+	{
6026
+		if (! is_array($query_params)) {
6027
+			EE_Error::doing_it_wrong(
6028
+				'EEM_Base::get_one_copy',
6029
+				sprintf(
6030
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6031
+					gettype($query_params)
6032
+				),
6033
+				'4.6.0'
6034
+			);
6035
+			$query_params = [];
6036
+		}
6037
+		$query_params['limit'] = 1;
6038
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6039
+		if (is_array($copies)) {
6040
+			return array_shift($copies);
6041
+		}
6042
+		return null;
6043
+	}
6044
+
6045
+
6046
+	/**
6047
+	 * Updates the item with the specified id. Ignores default query parameters because
6048
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6049
+	 *
6050
+	 * @param array      $fields_n_values keys are field names, values are their new values
6051
+	 * @param int|string $id              the value of the primary key to update
6052
+	 * @return int number of rows updated
6053
+	 * @throws EE_Error
6054
+	 * @throws ReflectionException
6055
+	 */
6056
+	public function update_by_ID($fields_n_values, $id)
6057
+	{
6058
+		$query_params = [
6059
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6060
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6061
+		];
6062
+		return $this->update($fields_n_values, $query_params);
6063
+	}
6064
+
6065
+
6066
+	/**
6067
+	 * Changes an operator which was supplied to the models into one usable in SQL
6068
+	 *
6069
+	 * @param string $operator_supplied
6070
+	 * @return string an operator which can be used in SQL
6071
+	 * @throws EE_Error
6072
+	 */
6073
+	private function _prepare_operator_for_sql($operator_supplied)
6074
+	{
6075
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6076
+		if ($sql_operator) {
6077
+			return $sql_operator;
6078
+		}
6079
+		throw new EE_Error(
6080
+			sprintf(
6081
+				esc_html__(
6082
+					"The operator '%s' is not in the list of valid operators: %s",
6083
+					"event_espresso"
6084
+				),
6085
+				$operator_supplied,
6086
+				implode(",", array_keys($this->_valid_operators))
6087
+			)
6088
+		);
6089
+	}
6090
+
6091
+
6092
+	/**
6093
+	 * Gets the valid operators
6094
+	 *
6095
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6096
+	 */
6097
+	public function valid_operators()
6098
+	{
6099
+		return $this->_valid_operators;
6100
+	}
6101
+
6102
+
6103
+	/**
6104
+	 * Gets the between-style operators (take 2 arguments).
6105
+	 *
6106
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6107
+	 */
6108
+	public function valid_between_style_operators()
6109
+	{
6110
+		return array_intersect(
6111
+			$this->valid_operators(),
6112
+			$this->_between_style_operators
6113
+		);
6114
+	}
6115
+
6116
+
6117
+	/**
6118
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6119
+	 *
6120
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6121
+	 */
6122
+	public function valid_like_style_operators()
6123
+	{
6124
+		return array_intersect(
6125
+			$this->valid_operators(),
6126
+			$this->_like_style_operators
6127
+		);
6128
+	}
6129
+
6130
+
6131
+	/**
6132
+	 * Gets the "in"-style operators
6133
+	 *
6134
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6135
+	 */
6136
+	public function valid_in_style_operators()
6137
+	{
6138
+		return array_intersect(
6139
+			$this->valid_operators(),
6140
+			$this->_in_style_operators
6141
+		);
6142
+	}
6143
+
6144
+
6145
+	/**
6146
+	 * Gets the "null"-style operators (accept no arguments)
6147
+	 *
6148
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6149
+	 */
6150
+	public function valid_null_style_operators()
6151
+	{
6152
+		return array_intersect(
6153
+			$this->valid_operators(),
6154
+			$this->_null_style_operators
6155
+		);
6156
+	}
6157
+
6158
+
6159
+	/**
6160
+	 * Gets an array where keys are the primary keys and values are their 'names'
6161
+	 * (as determined by the model object's name() function, which is often overridden)
6162
+	 *
6163
+	 * @param array $query_params like get_all's
6164
+	 * @return string[]
6165
+	 * @throws EE_Error
6166
+	 * @throws ReflectionException
6167
+	 */
6168
+	public function get_all_names($query_params = [])
6169
+	{
6170
+		$objs  = $this->get_all($query_params);
6171
+		$names = [];
6172
+		foreach ($objs as $obj) {
6173
+			$names[ $obj->ID() ] = $obj->name();
6174
+		}
6175
+		return $names;
6176
+	}
6177
+
6178
+
6179
+	/**
6180
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6181
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6182
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6183
+	 * array_keys() on $model_objects.
6184
+	 *
6185
+	 * @param \EE_Base_Class[] $model_objects
6186
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6187
+	 *                                               in the returned array
6188
+	 * @return array
6189
+	 * @throws EE_Error
6190
+	 * @throws ReflectionException
6191
+	 */
6192
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6193
+	{
6194
+		if (! $this->has_primary_key_field()) {
6195
+			if (WP_DEBUG) {
6196
+				EE_Error::add_error(
6197
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6198
+					__FILE__,
6199
+					__FUNCTION__,
6200
+					__LINE__
6201
+				);
6202
+			}
6203
+		}
6204
+		$IDs = [];
6205
+		foreach ($model_objects as $model_object) {
6206
+			$id = $model_object->ID();
6207
+			if (! $id) {
6208
+				if ($filter_out_empty_ids) {
6209
+					continue;
6210
+				}
6211
+				if (WP_DEBUG) {
6212
+					EE_Error::add_error(
6213
+						esc_html__(
6214
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6215
+							'event_espresso'
6216
+						),
6217
+						__FILE__,
6218
+						__FUNCTION__,
6219
+						__LINE__
6220
+					);
6221
+				}
6222
+			}
6223
+			$IDs[] = $id;
6224
+		}
6225
+		return $IDs;
6226
+	}
6227
+
6228
+
6229
+	/**
6230
+	 * Returns the string used in capabilities relating to this model. If there
6231
+	 * are no capabilities that relate to this model returns false
6232
+	 *
6233
+	 * @return string|false
6234
+	 */
6235
+	public function cap_slug()
6236
+	{
6237
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6238
+	}
6239
+
6240
+
6241
+	/**
6242
+	 * Returns the capability-restrictions array (@param string $context
6243
+	 *
6244
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6245
+	 * @throws EE_Error
6246
+	 * @see EEM_Base::_cap_restrictions).
6247
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6248
+	 *      only returns the cap restrictions array in that context (ie, the array
6249
+	 *      at that key)
6250
+	 *
6251
+	 */
6252
+	public function cap_restrictions($context = EEM_Base::caps_read)
6253
+	{
6254
+		EEM_Base::verify_is_valid_cap_context($context);
6255
+		// check if we ought to run the restriction generator first
6256
+		if (
6257
+			isset($this->_cap_restriction_generators[ $context ])
6258
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6259
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6260
+		) {
6261
+			$this->_cap_restrictions[ $context ] = array_merge(
6262
+				$this->_cap_restrictions[ $context ],
6263
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6264
+			);
6265
+		}
6266
+		// and make sure we've finalized the construction of each restriction
6267
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6268
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6269
+				$where_conditions_obj->_finalize_construct($this);
6270
+			}
6271
+		}
6272
+		return $this->_cap_restrictions[ $context ];
6273
+	}
6274
+
6275
+
6276
+	/**
6277
+	 * Indicating whether or not this model thinks its a wp core model
6278
+	 *
6279
+	 * @return boolean
6280
+	 */
6281
+	public function is_wp_core_model()
6282
+	{
6283
+		return $this->_wp_core_model;
6284
+	}
6285
+
6286
+
6287
+	/**
6288
+	 * Gets all the caps that are missing which impose a restriction on
6289
+	 * queries made in this context
6290
+	 *
6291
+	 * @param string $context one of EEM_Base::caps_ constants
6292
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6293
+	 * @throws EE_Error
6294
+	 */
6295
+	public function caps_missing($context = EEM_Base::caps_read)
6296
+	{
6297
+		$missing_caps     = [];
6298
+		$cap_restrictions = $this->cap_restrictions($context);
6299
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6300
+			if (
6301
+				! EE_Capabilities::instance()
6302
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6303
+			) {
6304
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6305
+			}
6306
+		}
6307
+		return $missing_caps;
6308
+	}
6309
+
6310
+
6311
+	/**
6312
+	 * Gets the mapping from capability contexts to action strings used in capability names
6313
+	 *
6314
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6315
+	 * one of 'read', 'edit', or 'delete'
6316
+	 */
6317
+	public function cap_contexts_to_cap_action_map()
6318
+	{
6319
+		return apply_filters(
6320
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6321
+			$this->_cap_contexts_to_cap_action_map,
6322
+			$this
6323
+		);
6324
+	}
6325
+
6326
+
6327
+	/**
6328
+	 * Gets the action string for the specified capability context
6329
+	 *
6330
+	 * @param string $context
6331
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6332
+	 * @throws EE_Error
6333
+	 */
6334
+	public function cap_action_for_context($context)
6335
+	{
6336
+		$mapping = $this->cap_contexts_to_cap_action_map();
6337
+		if (isset($mapping[ $context ])) {
6338
+			return $mapping[ $context ];
6339
+		}
6340
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6341
+			return $action;
6342
+		}
6343
+		throw new EE_Error(
6344
+			sprintf(
6345
+				esc_html__(
6346
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6347
+					'event_espresso'
6348
+				),
6349
+				$context,
6350
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6351
+			)
6352
+		);
6353
+	}
6354
+
6355
+
6356
+	/**
6357
+	 * Returns all the capability contexts which are valid when querying models
6358
+	 *
6359
+	 * @return array
6360
+	 */
6361
+	public static function valid_cap_contexts()
6362
+	{
6363
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6364
+			self::caps_read,
6365
+			self::caps_read_admin,
6366
+			self::caps_edit,
6367
+			self::caps_delete,
6368
+		]);
6369
+	}
6370
+
6371
+
6372
+	/**
6373
+	 * Returns all valid options for 'default_where_conditions'
6374
+	 *
6375
+	 * @return array
6376
+	 */
6377
+	public static function valid_default_where_conditions()
6378
+	{
6379
+		return [
6380
+			EEM_Base::default_where_conditions_all,
6381
+			EEM_Base::default_where_conditions_this_only,
6382
+			EEM_Base::default_where_conditions_others_only,
6383
+			EEM_Base::default_where_conditions_minimum_all,
6384
+			EEM_Base::default_where_conditions_minimum_others,
6385
+			EEM_Base::default_where_conditions_none,
6386
+		];
6387
+	}
6388
+
6389
+	// public static function default_where_conditions_full
6390
+
6391
+
6392
+	/**
6393
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6394
+	 *
6395
+	 * @param string $context
6396
+	 * @return bool
6397
+	 * @throws EE_Error
6398
+	 */
6399
+	public static function verify_is_valid_cap_context($context)
6400
+	{
6401
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6402
+		if (in_array($context, $valid_cap_contexts)) {
6403
+			return true;
6404
+		}
6405
+		throw new EE_Error(
6406
+			sprintf(
6407
+				esc_html__(
6408
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6409
+					'event_espresso'
6410
+				),
6411
+				$context,
6412
+				'EEM_Base',
6413
+				implode(',', $valid_cap_contexts)
6414
+			)
6415
+		);
6416
+	}
6417
+
6418
+
6419
+	/**
6420
+	 * Clears all the models field caches. This is only useful when a sub-class
6421
+	 * might have added a field or something and these caches might be invalidated
6422
+	 */
6423
+	protected function _invalidate_field_caches()
6424
+	{
6425
+		$this->_cache_foreign_key_to_fields = [];
6426
+		$this->_cached_fields               = null;
6427
+		$this->_cached_fields_non_db_only   = null;
6428
+	}
6429
+
6430
+
6431
+	/**
6432
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6433
+	 * (eg "and", "or", "not").
6434
+	 *
6435
+	 * @return array
6436
+	 */
6437
+	public function logic_query_param_keys()
6438
+	{
6439
+		return $this->_logic_query_param_keys;
6440
+	}
6441
+
6442
+
6443
+	/**
6444
+	 * Determines whether or not the where query param array key is for a logic query param.
6445
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6446
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6447
+	 *
6448
+	 * @param $query_param_key
6449
+	 * @return bool
6450
+	 */
6451
+	public function is_logic_query_param_key($query_param_key)
6452
+	{
6453
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6454
+			if (
6455
+				$query_param_key === $logic_query_param_key
6456
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6457
+			) {
6458
+				return true;
6459
+			}
6460
+		}
6461
+		return false;
6462
+	}
6463
+
6464
+
6465
+	/**
6466
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6467
+	 *
6468
+	 * @return boolean
6469
+	 * @since 4.9.74.p
6470
+	 */
6471
+	public function hasPassword()
6472
+	{
6473
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6474
+		if ($this->has_password_field === null) {
6475
+			$password_field           = $this->getPasswordField();
6476
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6477
+		}
6478
+		return $this->has_password_field;
6479
+	}
6480
+
6481
+
6482
+	/**
6483
+	 * Returns the password field on this model, if there is one
6484
+	 *
6485
+	 * @return EE_Password_Field|null
6486
+	 * @since 4.9.74.p
6487
+	 */
6488
+	public function getPasswordField()
6489
+	{
6490
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6491
+		// there's no need to search for it. If we don't know yet, then find out
6492
+		if ($this->has_password_field === null && $this->password_field === null) {
6493
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6494
+		}
6495
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6496
+		return $this->password_field;
6497
+	}
6498
+
6499
+
6500
+	/**
6501
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6502
+	 *
6503
+	 * @return EE_Model_Field_Base[]
6504
+	 * @throws EE_Error
6505
+	 * @since 4.9.74.p
6506
+	 */
6507
+	public function getPasswordProtectedFields()
6508
+	{
6509
+		$password_field = $this->getPasswordField();
6510
+		$fields         = [];
6511
+		if ($password_field instanceof EE_Password_Field) {
6512
+			$field_names = $password_field->protectedFields();
6513
+			foreach ($field_names as $field_name) {
6514
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6515
+			}
6516
+		}
6517
+		return $fields;
6518
+	}
6519
+
6520
+
6521
+	/**
6522
+	 * Checks if the current user can perform the requested action on this model
6523
+	 *
6524
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6525
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6526
+	 * @return bool
6527
+	 * @throws EE_Error
6528
+	 * @throws InvalidArgumentException
6529
+	 * @throws InvalidDataTypeException
6530
+	 * @throws InvalidInterfaceException
6531
+	 * @throws ReflectionException
6532
+	 * @throws UnexpectedEntityException
6533
+	 * @since 4.9.74.p
6534
+	 */
6535
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6536
+	{
6537
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6538
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6539
+		}
6540
+		if (! is_array($model_obj_or_fields_n_values)) {
6541
+			throw new UnexpectedEntityException(
6542
+				$model_obj_or_fields_n_values,
6543
+				'EE_Base_Class',
6544
+				sprintf(
6545
+					esc_html__(
6546
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6547
+						'event_espresso'
6548
+					),
6549
+					__FUNCTION__
6550
+				)
6551
+			);
6552
+		}
6553
+		return $this->exists(
6554
+			$this->alter_query_params_to_restrict_by_ID(
6555
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6556
+				[
6557
+					'default_where_conditions' => 'none',
6558
+					'caps'                     => $cap_to_check,
6559
+				]
6560
+			)
6561
+		);
6562
+	}
6563
+
6564
+
6565
+	/**
6566
+	 * Returns the query param where conditions key to the password affecting this model.
6567
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6568
+	 *
6569
+	 * @return null|string
6570
+	 * @throws EE_Error
6571
+	 * @throws InvalidArgumentException
6572
+	 * @throws InvalidDataTypeException
6573
+	 * @throws InvalidInterfaceException
6574
+	 * @throws ModelConfigurationException
6575
+	 * @throws ReflectionException
6576
+	 * @since 4.9.74.p
6577
+	 */
6578
+	public function modelChainAndPassword()
6579
+	{
6580
+		if ($this->model_chain_to_password === null) {
6581
+			throw new ModelConfigurationException(
6582
+				$this,
6583
+				esc_html_x(
6584
+				// @codingStandardsIgnoreStart
6585
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6586
+					// @codingStandardsIgnoreEnd
6587
+					'1: model name',
6588
+					'event_espresso'
6589
+				)
6590
+			);
6591
+		}
6592
+		if ($this->model_chain_to_password === '') {
6593
+			$model_with_password = $this;
6594
+		} else {
6595
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6596
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6597
+			} else {
6598
+				$last_model_in_chain = $this->model_chain_to_password;
6599
+			}
6600
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6601
+		}
6602
+
6603
+		$password_field = $model_with_password->getPasswordField();
6604
+		if ($password_field instanceof EE_Password_Field) {
6605
+			$password_field_name = $password_field->get_name();
6606
+		} else {
6607
+			throw new ModelConfigurationException(
6608
+				$this,
6609
+				sprintf(
6610
+					esc_html_x(
6611
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6612
+						'1: model name, 2: special string',
6613
+						'event_espresso'
6614
+					),
6615
+					$model_with_password->get_this_model_name(),
6616
+					$this->model_chain_to_password
6617
+				)
6618
+			);
6619
+		}
6620
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6621
+	}
6622
+
6623
+
6624
+	/**
6625
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6626
+	 * or if this model itself has a password affecting access to some of its other fields.
6627
+	 *
6628
+	 * @return boolean
6629
+	 * @since 4.9.74.p
6630
+	 */
6631
+	public function restrictedByRelatedModelPassword()
6632
+	{
6633
+		return $this->model_chain_to_password !== null;
6634
+	}
6635 6635
 }
Please login to merge, or discard this patch.