Completed
Branch dev (97838e)
by
unknown
18:15 queued 10:24
created
modules/add_new_state/EED_Add_New_State.module.php 2 patches
Indentation   +812 added lines, -812 removed lines patch added patch discarded remove patch
@@ -17,816 +17,816 @@
 block discarded – undo
17 17
  */
18 18
 class EED_Add_New_State extends EED_Module
19 19
 {
20
-    /**
21
-     * @return EED_Add_New_State|EED_Module
22
-     * @throws EE_Error
23
-     * @throws ReflectionException
24
-     */
25
-    public static function instance()
26
-    {
27
-        return parent::get_instance(__CLASS__);
28
-    }
29
-
30
-
31
-    /**
32
-     * set_hooks - for hooking into EE Core, other modules, etc
33
-     *
34
-     * @return void
35
-     */
36
-    public static function set_hooks()
37
-    {
38
-        add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
39
-        add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'translate_js_strings'], 0);
40
-        add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'wp_enqueue_scripts'], 10);
41
-        add_filter(
42
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
43
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
44
-            1,
45
-            1
46
-        );
47
-        add_filter(
48
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
49
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
50
-            1,
51
-            1
52
-        );
53
-        add_filter(
54
-            'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
55
-            ['EED_Add_New_State', 'unset_new_state_request_params'],
56
-            10,
57
-            1
58
-        );
59
-        add_filter(
60
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
61
-            ['EED_Add_New_State', 'inject_new_reg_state_into_options'],
62
-            10,
63
-            5
64
-        );
65
-        add_filter(
66
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
67
-            ['EED_Add_New_State', 'inject_new_reg_country_into_options'],
68
-            10,
69
-            5
70
-        );
71
-        add_filter(
72
-            'FHEE__EE_State_Select_Input____construct__state_options',
73
-            ['EED_Add_New_State', 'state_options'],
74
-            10,
75
-            1
76
-        );
77
-        add_filter(
78
-            'FHEE__EE_Country_Select_Input____construct__country_options',
79
-            ['EED_Add_New_State', 'country_options'],
80
-            10,
81
-            1
82
-        );
83
-    }
84
-
85
-
86
-    /**
87
-     * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
88
-     *
89
-     * @return void
90
-     */
91
-    public static function set_hooks_admin()
92
-    {
93
-        add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
94
-        add_filter(
95
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
96
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
97
-            1,
98
-            1
99
-        );
100
-        add_filter(
101
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
102
-            ['EED_Add_New_State', 'display_add_new_state_micro_form'],
103
-            1,
104
-            1
105
-        );
106
-        add_action('wp_ajax_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
107
-        add_action('wp_ajax_nopriv_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
108
-        add_filter(
109
-            'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
110
-            ['EED_Add_New_State', 'unset_new_state_request_params'],
111
-            10,
112
-            1
113
-        );
114
-        add_action(
115
-            'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
116
-            ['EED_Add_New_State', 'update_country_settings'],
117
-            10,
118
-            3
119
-        );
120
-        add_action(
121
-            'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
122
-            ['EED_Add_New_State', 'update_country_settings'],
123
-            10,
124
-            3
125
-        );
126
-        add_filter(
127
-            'FHEE__EE_State_Select_Input____construct__state_options',
128
-            ['EED_Add_New_State', 'state_options'],
129
-            10,
130
-            1
131
-        );
132
-        add_filter(
133
-            'FHEE__EE_Country_Select_Input____construct__country_options',
134
-            ['EED_Add_New_State', 'country_options'],
135
-            10,
136
-            1
137
-        );
138
-        add_filter(
139
-            'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
140
-            ['EED_Add_New_State', 'filter_checkout_request_params'],
141
-            10,
142
-            1
143
-        );
144
-        add_filter(
145
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
146
-            ['EED_Add_New_State', 'inject_new_reg_state_into_options'],
147
-            10,
148
-            5
149
-        );
150
-        add_filter(
151
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
152
-            ['EED_Add_New_State', 'inject_new_reg_country_into_options'],
153
-            10,
154
-            5
155
-        );
156
-    }
157
-
158
-
159
-    /**
160
-     * @return void
161
-     */
162
-    public static function set_definitions()
163
-    {
164
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
165
-        define(
166
-            'ANS_TEMPLATES_PATH',
167
-            str_replace(
168
-                '\\',
169
-                '/',
170
-                plugin_dir_path(__FILE__)
171
-            ) . 'templates/'
172
-        );
173
-    }
174
-
175
-
176
-    /**
177
-     * @param WP $WP
178
-     * @return void
179
-     */
180
-    public function run($WP)
181
-    {
182
-    }
183
-
184
-
185
-    /**
186
-     * @return void
187
-     */
188
-    public static function translate_js_strings()
189
-    {
190
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
191
-            'In order to proceed, you need to select the Country that your State/Province belongs to.',
192
-            'event_espresso'
193
-        );
194
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
195
-            'In order to proceed, you need to enter the name of your State/Province.',
196
-            'event_espresso'
197
-        );
198
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
199
-            'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
200
-            'event_espresso'
201
-        );
202
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
203
-            'The new state was successfully saved to the database.',
204
-            'event_espresso'
205
-        );
206
-        EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
207
-            'An unknown error has occurred on the server while saving the new state to the database.',
208
-            'event_espresso'
209
-        );
210
-    }
211
-
212
-
213
-    /**
214
-     * @return void
215
-     */
216
-    public static function wp_enqueue_scripts()
217
-    {
218
-        if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
219
-            wp_register_script(
220
-                'add_new_state',
221
-                ANS_ASSETS_URL . 'add_new_state.js',
222
-                ['espresso_core', 'single_page_checkout'],
223
-                EVENT_ESPRESSO_VERSION,
224
-                true
225
-            );
226
-            wp_enqueue_script('add_new_state');
227
-        }
228
-    }
229
-
230
-
231
-    /**
232
-     * display_add_new_state_micro_form
233
-     *
234
-     * @param EE_Form_Section_Proper $question_group_reg_form
235
-     * @return EE_Form_Section_Proper
236
-     * @throws EE_Error
237
-     * @throws ReflectionException
238
-     */
239
-    public static function display_add_new_state_micro_form(
240
-        EE_Form_Section_Proper $question_group_reg_form
241
-    ): EE_Form_Section_Proper {
242
-        $request = self::getRequest();
243
-        // only add the 'new_state_micro_form' when displaying reg forms,
244
-        // not during processing since we process the 'new_state_micro_form' in it's own AJAX request
245
-        $action = $request->getRequestParam('action');
246
-        // is the "state" question in this form section?
247
-        $input = $question_group_reg_form->get_subsection('state');
248
-        if ($action === 'process_reg_step' || $action === 'update_reg_step') {
249
-            // ok then all we need to do is make sure the input's HTML name is consistent
250
-            // by forcing it to set it now, like it did while getting the form for display
251
-            if ($input instanceof EE_State_Select_Input) {
252
-                $input->html_name();
253
-            }
254
-            return $question_group_reg_form;
255
-        }
256
-        // we're only doing this for state select inputs
257
-        if (
258
-            $input instanceof EE_State_Select_Input
259
-            && ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy
260
-        ) {
261
-            // grab any set values from the request
262
-            $country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
263
-            $state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
264
-            $abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
265
-            $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
266
-            $country_options     = [];
267
-            $countries           = EEM_Country::instance()->get_all_countries();
268
-            if (! empty($countries)) {
269
-                foreach ($countries as $country) {
270
-                    if ($country instanceof EE_Country) {
271
-                        $country_options[ $country->ID() ] = $country->name();
272
-                    }
273
-                }
274
-            }
275
-            $new_state_micro_form = new EE_Form_Section_Proper(
276
-                [
277
-                    'name'            => 'new_state_micro_form',
278
-                    'html_id'         => 'new_state_micro_form',
279
-                    'layout_strategy' => new EE_Div_Per_Section_Layout(),
280
-                    'subsections'     => [
281
-                        // add hidden input to indicate that a new state is being added
282
-                        'add_new_state'               => new EE_Hidden_Input(
283
-                            [
284
-                                'html_name' => str_replace(
285
-                                    'state',
286
-                                    'nsmf_add_new_state',
287
-                                    $input->html_name()
288
-                                ),
289
-                                'html_id'   => str_replace(
290
-                                    'state',
291
-                                    'nsmf_add_new_state',
292
-                                    $input->html_id()
293
-                                ),
294
-                                'default'   => 0,
295
-                            ]
296
-                        ),
297
-                        // add link for displaying hidden container
298
-                        'click_here_link'             => new EE_Form_Section_HTML(
299
-                            apply_filters(
300
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
301
-                                EEH_HTML::link(
302
-                                    '',
303
-                                    esc_html__('click here to add a new state/province', 'event_espresso'),
304
-                                    '',
305
-                                    'display-' . $input->html_id(),
306
-                                    'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
307
-                                    '',
308
-                                    'data-target="' . $input->html_id() . '"'
309
-                                )
310
-                            )
311
-                        ),
312
-                        // add initial html for hidden container
313
-                        'add_new_state_micro_form'    => new EE_Form_Section_HTML(
314
-                            apply_filters(
315
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
316
-                                EEH_HTML::div(
317
-                                    '',
318
-                                    $input->html_id() . '-dv',
319
-                                    'ee-form-add-new-state-dv',
320
-                                    'display: none;'
321
-                                ) .
322
-                                EEH_HTML::h6(
323
-                                    esc_html__(
324
-                                        'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
325
-                                        'event_espresso'
326
-                                    )
327
-                                ) .
328
-                                EEH_HTML::ul() .
329
-                                EEH_HTML::li(
330
-                                    esc_html__(
331
-                                        'first select the Country that your State/Province belongs to',
332
-                                        'event_espresso'
333
-                                    )
334
-                                ) .
335
-                                EEH_HTML::li(
336
-                                    esc_html__('enter the name of your State/Province', 'event_espresso')
337
-                                ) .
338
-                                EEH_HTML::li(
339
-                                    esc_html__(
340
-                                        'enter a two to six letter abbreviation for the name of your State/Province',
341
-                                        'event_espresso'
342
-                                    )
343
-                                ) .
344
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
345
-                                EEH_HTML::ulx()
346
-                            )
347
-                        ),
348
-                        // NEW STATE COUNTRY
349
-                        'new_state_country'           => new EE_Country_Select_Input(
350
-                            $country_options,
351
-                            [
352
-                                'html_name'       => $country_name,
353
-                                'html_id'         => str_replace(
354
-                                    'state',
355
-                                    'nsmf_new_state_country',
356
-                                    $input->html_id()
357
-                                ),
358
-                                'html_class'      => $input->html_class() . ' new-state-country',
359
-                                'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
360
-                                'default'         => $request->getRequestParam($country_name),
361
-                                'required'        => false,
362
-                            ]
363
-                        ),
364
-                        // NEW STATE NAME
365
-                        'new_state_name'              => new EE_Text_Input(
366
-                            [
367
-                                'html_name'       => $state_name,
368
-                                'html_id'         => str_replace(
369
-                                    'state',
370
-                                    'nsmf_new_state_name',
371
-                                    $input->html_id()
372
-                                ),
373
-                                'html_class'      => $input->html_class() . ' new-state-state',
374
-                                'html_label_text' => esc_html__(
375
-                                    'New State/Province Name',
376
-                                    'event_espresso'
377
-                                ),
378
-                                'default'         => $request->getRequestParam($state_name),
379
-                                'required'        => false,
380
-                            ]
381
-                        ),
382
-                        // NEW STATE NAME
383
-                        'new_state_abbrv'             => new EE_Text_Input(
384
-                            [
385
-                                'html_name'             => $abbrv_name,
386
-                                'html_id'               => str_replace(
387
-                                    'state',
388
-                                    'nsmf_new_state_abbrv',
389
-                                    $input->html_id()
390
-                                ),
391
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
392
-                                'html_label_text'       => esc_html__(
393
-                                    'New State/Province Abbreviation',
394
-                                    'event_espresso'
395
-                                ) . ' *',
396
-                                'other_html_attributes' => 'size="24"',
397
-                                'default'               => $request->getRequestParam($abbrv_name),
398
-                                'required'              => false,
399
-                            ]
400
-                        ),
401
-                        // "submit" button
402
-                        'add_new_state_submit_button' => new EE_Form_Section_HTML(
403
-                            apply_filters(
404
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
405
-                                EEH_HTML::div(
406
-                                    EEH_HTML::button(
407
-                                        esc_html__('ADD', 'event_espresso'),
408
-                                        'ee-form-add-new-state-submit button button--secondary',
409
-                                        '',
410
-                                        'submit-' . $new_state_submit_id,
411
-                                        '',
412
-                                        'data-target="' . $new_state_submit_id . '"'
413
-                                        . ' data-value-field-name="' . $input->valueFieldName() . '"'
414
-                                    ),
415
-                                    '',
416
-                                    'ee-form-add-new-state-submit-dv'
417
-                                )
418
-                            )
419
-                        ),
420
-                        // extra info
421
-                        'add_new_state_extra'         => new EE_Form_Section_HTML(
422
-                            apply_filters(
423
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
424
-                                EEH_HTML::br()
425
-                                .
426
-                                EEH_HTML::div('', '', 'small-text')
427
-                                .
428
-                                EEH_HTML::strong(
429
-                                    '* ' .
430
-                                    esc_html__(
431
-                                        'Don\'t know your State/Province Abbreviation?',
432
-                                        'event_espresso'
433
-                                    )
434
-                                )
435
-                                .
436
-                                EEH_HTML::br()
437
-                                .
438
-                                sprintf(
439
-                                    esc_html__(
440
-                                        'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
441
-                                        'event_espresso'
442
-                                    ),
443
-                                    EEH_HTML::link(
444
-                                        'https://en.wikipedia.org/wiki/ISO_3166-2',
445
-                                        'https://en.wikipedia.org/wiki/ISO_3166-2',
446
-                                        '',
447
-                                        '',
448
-                                        'ee-form-add-new-state-wiki-lnk',
449
-                                        '',
450
-                                        'target="_blank"'
451
-                                    )
452
-                                )
453
-                                .
454
-                                EEH_HTML::divx()
455
-                                .
456
-                                EEH_HTML::br()
457
-                                .
458
-                                EEH_HTML::link(
459
-                                    '',
460
-                                    esc_html__('cancel new State/Province', 'event_espresso'),
461
-                                    '',
462
-                                    'hide-' . $input->html_id(),
463
-                                    'ee-form-cancel-new-state-lnk smaller-text',
464
-                                    '',
465
-                                    'data-target="' . $input->html_id() . '"'
466
-                                )
467
-                                .
468
-                                EEH_HTML::divx()
469
-                                .
470
-                                EEH_HTML::br()
471
-                            )
472
-                        ),
473
-                    ],
474
-                ]
475
-            );
476
-            $question_group_reg_form->add_subsections(
477
-                ['new_state_micro_form' => $new_state_micro_form],
478
-                'state',
479
-                false
480
-            );
481
-        }
482
-        return $question_group_reg_form;
483
-    }
484
-
485
-
486
-    /**
487
-     * set_new_state_input_width
488
-     *
489
-     * @return int|string
490
-     * @throws EE_Error
491
-     * @throws InvalidArgumentException
492
-     * @throws InvalidDataTypeException
493
-     * @throws InvalidInterfaceException
494
-     * @throws ReflectionException
495
-     */
496
-    public static function add_new_state()
497
-    {
498
-        $request = self::getRequest();
499
-        if ($request->getRequestParam('nsmf_add_new_state', 0, 'int') === 1) {
500
-            EE_Registry::instance()->load_model('State');
501
-            // grab country ISO code, new state name, and new state abbreviation
502
-            $state_country = $request->getRequestParam('nsmf_new_state_country');
503
-            $state_name    = $request->getRequestParam('nsmf_new_state_name');
504
-            $state_abbr    = $request->getRequestParam('nsmf_new_state_abbrv');
505
-            if ($state_country && $state_name && $state_abbr) {
506
-                $new_state = EED_Add_New_State::save_new_state_to_db(
507
-                    [
508
-                        'CNT_ISO'    => strtoupper($state_country),
509
-                        'STA_abbrev' => strtoupper($state_abbr),
510
-                        'STA_name'   => ucwords($state_name),
511
-                        'STA_active' => false,
512
-                    ]
513
-                );
514
-                if ($new_state instanceof EE_State) {
515
-                    // clean house
516
-                    $request->unSetRequestParams(
517
-                        [
518
-                            'nsmf_add_new_state',
519
-                            'nsmf_new_state_country',
520
-                            'nsmf_new_state_name',
521
-                            'nsmf_new_state_abbrv',
522
-                        ]
523
-                    );
524
-                    // get any existing new states
525
-                    $new_states                     = EE_Registry::instance()->SSN->get_session_data('nsmf_new_states');
526
-                    $new_states[ $new_state->ID() ] = $new_state;
527
-                    EE_Registry::instance()->SSN->set_session_data(
528
-                        ['nsmf_new_states' => $new_states]
529
-                    );
530
-                    if ($request->isAjax()) {
531
-                        echo wp_json_encode(
532
-                            [
533
-                                'success'      => true,
534
-                                'id'           => $new_state->ID(),
535
-                                'name'         => $new_state->name(),
536
-                                'abbrev'       => $new_state->abbrev(),
537
-                                'country_iso'  => $new_state->country_iso(),
538
-                                'country_name' => $new_state->country()->name(),
539
-                            ]
540
-                        );
541
-                        exit();
542
-                    }
543
-                    return $new_state->ID();
544
-                }
545
-            } else {
546
-                $error = esc_html__(
547
-                    'A new State/Province could not be added because invalid or missing data was received.',
548
-                    'event_espresso'
549
-                );
550
-                if ($request->isAjax()) {
551
-                    echo wp_json_encode(['error' => $error]);
552
-                    exit();
553
-                }
554
-                EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
555
-            }
556
-        }
557
-        return false;
558
-    }
559
-
560
-
561
-    /**
562
-     * recursively drills down through request params to remove any that were added by this module
563
-     *
564
-     * @param array $request_params
565
-     * @return array
566
-     */
567
-    public static function filter_checkout_request_params(array $request_params): array
568
-    {
569
-        foreach ($request_params as $form_section) {
570
-            if (is_array($form_section)) {
571
-                EED_Add_New_State::unset_new_state_request_params($form_section);
572
-                EED_Add_New_State::filter_checkout_request_params($form_section);
573
-            }
574
-        }
575
-        return $request_params;
576
-    }
577
-
578
-
579
-    /**
580
-     * @param array $request_params
581
-     * @return array
582
-     */
583
-    public static function unset_new_state_request_params(array $request_params): array
584
-    {
585
-        unset(
586
-            $request_params['new_state_micro_form'],
587
-            $request_params['new_state_micro_add_new_state'],
588
-            $request_params['new_state_micro_new_state_country'],
589
-            $request_params['new_state_micro_new_state_name'],
590
-            $request_params['new_state_micro_new_state_abbrv']
591
-        );
592
-        return $request_params;
593
-    }
594
-
595
-
596
-    /**
597
-     * @param array $props_n_values
598
-     * @return EE_State|null
599
-     * @throws EE_Error
600
-     * @throws ReflectionException
601
-     */
602
-    public static function save_new_state_to_db(array $props_n_values = []): ?EE_State
603
-    {
604
-        /** @var EE_State[] $existing_state */
605
-        $existing_state = EEM_State::instance()->get_all([$props_n_values, 'limit' => 1]);
606
-        if (! empty($existing_state)) {
607
-            return array_pop($existing_state);
608
-        }
609
-        $new_state = EE_State::new_instance($props_n_values);
610
-        if ($new_state instanceof EE_State) {
611
-            $country_settings_url = add_query_arg(
612
-                [
613
-                    'page'    => 'espresso_general_settings',
614
-                    'action'  => 'country_settings',
615
-                    'country' => $new_state->country_iso(),
616
-                ],
617
-                admin_url('admin.php')
618
-            );
619
-            // if not non-ajax admin
620
-            new PersistentAdminNotice(
621
-                'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
622
-                sprintf(
623
-                    esc_html__(
624
-                        'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
625
-                        'event_espresso'
626
-                    ),
627
-                    '<b>' . $new_state->name() . '</b>',
628
-                    '<b>' . $new_state->abbrev() . '</b>',
629
-                    '<b>' . $new_state->country()->name() . '</b>',
630
-                    '<a href="'
631
-                    . $country_settings_url
632
-                    . '">'
633
-                    . esc_html__(
634
-                        'Event Espresso - General Settings > Countries Tab',
635
-                        'event_espresso'
636
-                    )
637
-                    . '</a>',
638
-                    '<br />'
639
-                )
640
-            );
641
-            $new_state->save();
642
-            EEM_State::instance()->reset_cached_states();
643
-            return $new_state;
644
-        }
645
-        return null;
646
-    }
647
-
648
-
649
-    /**
650
-     * @param string $CNT_ISO
651
-     * @param int    $STA_ID
652
-     * @param array  $cols_n_values
653
-     * @return void
654
-     * @throws DomainException
655
-     * @throws EE_Error
656
-     * @throws InvalidArgumentException
657
-     * @throws InvalidDataTypeException
658
-     * @throws InvalidInterfaceException
659
-     * @throws ReflectionException
660
-     */
661
-    public static function update_country_settings(string $CNT_ISO = '', int $STA_ID = 0, array $cols_n_values = [])
662
-    {
663
-        if (! $CNT_ISO) {
664
-            EE_Error::add_error(
665
-                esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
666
-                __FILE__,
667
-                __FUNCTION__,
668
-                __LINE__
669
-            );
670
-        }
671
-        $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
672
-            : false;
673
-        if (! $STA_abbrev && ! empty($STA_ID)) {
674
-            $state = EEM_State::instance()->get_one_by_ID($STA_ID);
675
-            if ($state instanceof EE_State) {
676
-                $STA_abbrev = $state->abbrev();
677
-            }
678
-        }
679
-        if (! $STA_abbrev) {
680
-            EE_Error::add_error(
681
-                esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
682
-                __FILE__,
683
-                __FUNCTION__,
684
-                __LINE__
685
-            );
686
-        }
687
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
688
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
689
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
690
-        );
691
-        $persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
692
-    }
693
-
694
-
695
-    /**
696
-     * @param EE_State[]                                              $state_options
697
-     * @param EE_SPCO_Reg_Step_Attendee_Information|StateOptions|null $deprecated
698
-     * @param EE_Registration                                         $registration
699
-     * @param EE_Question|null                                        $question
700
-     * @param EE_Answer|null                                          $answer
701
-     * @return array
702
-     * @throws EE_Error
703
-     * @throws ReflectionException
704
-     */
705
-    public static function inject_new_reg_state_into_options(
706
-        array $state_options,
707
-        $deprecated,
708
-        EE_Registration $registration,
709
-        ?EE_Question $question,
710
-        ?EE_Answer $answer
711
-    ): array {
712
-        if (
713
-            $answer instanceof EE_Answer && $question instanceof EE_Question
714
-            && $question->type() === EEM_Question::QST_type_state
715
-        ) {
716
-            $STA_ID = $answer->value();
717
-            if (! empty($STA_ID)) {
718
-                $state = EEM_State::instance()->get_one_by_ID($STA_ID);
719
-                if ($state instanceof EE_State) {
720
-                    $country = $state->country();
721
-                    if ($country instanceof EE_Country) {
722
-                        if (! isset($state_options[ $country->name() ])) {
723
-                            $state_options[ $country->name() ] = [];
724
-                        }
725
-                        if (! isset($state_options[ $country->name() ][ $STA_ID ])) {
726
-                            $state_options[ $country->name() ][ $STA_ID ] = $state->name();
727
-                        }
728
-                    }
729
-                }
730
-            }
731
-        }
732
-        return $state_options;
733
-    }
734
-
735
-
736
-    /**
737
-     * @param EE_Country[]                                              $country_options
738
-     * @param EE_SPCO_Reg_Step_Attendee_Information|CountryOptions|null $deprecated
739
-     * @param EE_Registration                                           $registration
740
-     * @param EE_Question|null                                          $question
741
-     * @param EE_Answer|null                                            $answer
742
-     * @return array
743
-     * @throws EE_Error
744
-     * @throws InvalidArgumentException
745
-     * @throws InvalidDataTypeException
746
-     * @throws InvalidInterfaceException
747
-     * @throws ReflectionException
748
-     */
749
-    public static function inject_new_reg_country_into_options(
750
-        array $country_options,
751
-        $deprecated,
752
-        EE_Registration $registration,
753
-        ?EE_Question $question,
754
-        ?EE_Answer $answer
755
-    ): array {
756
-        if (
757
-            $answer instanceof EE_Answer && $question instanceof EE_Question
758
-            && $question->type() === EEM_Question::QST_type_country
759
-        ) {
760
-            $CNT_ISO = $answer->value();
761
-            if (! empty($CNT_ISO)) {
762
-                $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
763
-                if ($country instanceof EE_Country) {
764
-                    if (! isset($country_options[ $CNT_ISO ])) {
765
-                        $country_options[ $CNT_ISO ] = $country->name();
766
-                    }
767
-                }
768
-            }
769
-        }
770
-        return $country_options;
771
-    }
772
-
773
-
774
-    /**
775
-     * @param EE_State[] $state_options
776
-     * @return array
777
-     * @throws EE_Error
778
-     * @throws ReflectionException
779
-     */
780
-    public static function state_options(array $state_options = []): array
781
-    {
782
-        $new_states = EED_Add_New_State::_get_new_states();
783
-        foreach ($new_states as $new_state) {
784
-            if (
785
-                $new_state instanceof EE_State
786
-                && $new_state->country() instanceof EE_Country
787
-            ) {
788
-                $state_options[ $new_state->country()->name() ][ $new_state->ID() ] = $new_state->name();
789
-            }
790
-        }
791
-        return $state_options;
792
-    }
793
-
794
-
795
-    /**
796
-     * @return array
797
-     * @throws InvalidArgumentException
798
-     * @throws InvalidDataTypeException
799
-     * @throws InvalidInterfaceException
800
-     */
801
-    protected static function _get_new_states(): array
802
-    {
803
-        $new_states = [];
804
-        if (EE_Registry::instance()->SSN instanceof EE_Session) {
805
-            $new_states = EE_Registry::instance()->SSN->get_session_data(
806
-                'nsmf_new_states'
807
-            );
808
-        }
809
-        return is_array($new_states) ? $new_states : [];
810
-    }
811
-
812
-
813
-    /**
814
-     * @param EE_Country[] $country_options
815
-     * @return array
816
-     * @throws EE_Error
817
-     * @throws ReflectionException
818
-     */
819
-    public static function country_options(array $country_options = []): array
820
-    {
821
-        $new_states = EED_Add_New_State::_get_new_states();
822
-        foreach ($new_states as $new_state) {
823
-            if (
824
-                $new_state instanceof EE_State
825
-                && $new_state->country() instanceof EE_Country
826
-            ) {
827
-                $country_options[ $new_state->country()->ID() ] = $new_state->country()->name();
828
-            }
829
-        }
830
-        return $country_options;
831
-    }
20
+	/**
21
+	 * @return EED_Add_New_State|EED_Module
22
+	 * @throws EE_Error
23
+	 * @throws ReflectionException
24
+	 */
25
+	public static function instance()
26
+	{
27
+		return parent::get_instance(__CLASS__);
28
+	}
29
+
30
+
31
+	/**
32
+	 * set_hooks - for hooking into EE Core, other modules, etc
33
+	 *
34
+	 * @return void
35
+	 */
36
+	public static function set_hooks()
37
+	{
38
+		add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
39
+		add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'translate_js_strings'], 0);
40
+		add_action('wp_enqueue_scripts', ['EED_Add_New_State', 'wp_enqueue_scripts'], 10);
41
+		add_filter(
42
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
43
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
44
+			1,
45
+			1
46
+		);
47
+		add_filter(
48
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
49
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
50
+			1,
51
+			1
52
+		);
53
+		add_filter(
54
+			'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
55
+			['EED_Add_New_State', 'unset_new_state_request_params'],
56
+			10,
57
+			1
58
+		);
59
+		add_filter(
60
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
61
+			['EED_Add_New_State', 'inject_new_reg_state_into_options'],
62
+			10,
63
+			5
64
+		);
65
+		add_filter(
66
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
67
+			['EED_Add_New_State', 'inject_new_reg_country_into_options'],
68
+			10,
69
+			5
70
+		);
71
+		add_filter(
72
+			'FHEE__EE_State_Select_Input____construct__state_options',
73
+			['EED_Add_New_State', 'state_options'],
74
+			10,
75
+			1
76
+		);
77
+		add_filter(
78
+			'FHEE__EE_Country_Select_Input____construct__country_options',
79
+			['EED_Add_New_State', 'country_options'],
80
+			10,
81
+			1
82
+		);
83
+	}
84
+
85
+
86
+	/**
87
+	 * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
88
+	 *
89
+	 * @return void
90
+	 */
91
+	public static function set_hooks_admin()
92
+	{
93
+		add_action('wp_loaded', ['EED_Add_New_State', 'set_definitions'], 2);
94
+		add_filter(
95
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
96
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
97
+			1,
98
+			1
99
+		);
100
+		add_filter(
101
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
102
+			['EED_Add_New_State', 'display_add_new_state_micro_form'],
103
+			1,
104
+			1
105
+		);
106
+		add_action('wp_ajax_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
107
+		add_action('wp_ajax_nopriv_espresso_add_new_state', ['EED_Add_New_State', 'add_new_state']);
108
+		add_filter(
109
+			'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
110
+			['EED_Add_New_State', 'unset_new_state_request_params'],
111
+			10,
112
+			1
113
+		);
114
+		add_action(
115
+			'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
116
+			['EED_Add_New_State', 'update_country_settings'],
117
+			10,
118
+			3
119
+		);
120
+		add_action(
121
+			'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
122
+			['EED_Add_New_State', 'update_country_settings'],
123
+			10,
124
+			3
125
+		);
126
+		add_filter(
127
+			'FHEE__EE_State_Select_Input____construct__state_options',
128
+			['EED_Add_New_State', 'state_options'],
129
+			10,
130
+			1
131
+		);
132
+		add_filter(
133
+			'FHEE__EE_Country_Select_Input____construct__country_options',
134
+			['EED_Add_New_State', 'country_options'],
135
+			10,
136
+			1
137
+		);
138
+		add_filter(
139
+			'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
140
+			['EED_Add_New_State', 'filter_checkout_request_params'],
141
+			10,
142
+			1
143
+		);
144
+		add_filter(
145
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
146
+			['EED_Add_New_State', 'inject_new_reg_state_into_options'],
147
+			10,
148
+			5
149
+		);
150
+		add_filter(
151
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
152
+			['EED_Add_New_State', 'inject_new_reg_country_into_options'],
153
+			10,
154
+			5
155
+		);
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return void
161
+	 */
162
+	public static function set_definitions()
163
+	{
164
+		define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
165
+		define(
166
+			'ANS_TEMPLATES_PATH',
167
+			str_replace(
168
+				'\\',
169
+				'/',
170
+				plugin_dir_path(__FILE__)
171
+			) . 'templates/'
172
+		);
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param WP $WP
178
+	 * @return void
179
+	 */
180
+	public function run($WP)
181
+	{
182
+	}
183
+
184
+
185
+	/**
186
+	 * @return void
187
+	 */
188
+	public static function translate_js_strings()
189
+	{
190
+		EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
191
+			'In order to proceed, you need to select the Country that your State/Province belongs to.',
192
+			'event_espresso'
193
+		);
194
+		EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
195
+			'In order to proceed, you need to enter the name of your State/Province.',
196
+			'event_espresso'
197
+		);
198
+		EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
199
+			'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
200
+			'event_espresso'
201
+		);
202
+		EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
203
+			'The new state was successfully saved to the database.',
204
+			'event_espresso'
205
+		);
206
+		EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
207
+			'An unknown error has occurred on the server while saving the new state to the database.',
208
+			'event_espresso'
209
+		);
210
+	}
211
+
212
+
213
+	/**
214
+	 * @return void
215
+	 */
216
+	public static function wp_enqueue_scripts()
217
+	{
218
+		if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
219
+			wp_register_script(
220
+				'add_new_state',
221
+				ANS_ASSETS_URL . 'add_new_state.js',
222
+				['espresso_core', 'single_page_checkout'],
223
+				EVENT_ESPRESSO_VERSION,
224
+				true
225
+			);
226
+			wp_enqueue_script('add_new_state');
227
+		}
228
+	}
229
+
230
+
231
+	/**
232
+	 * display_add_new_state_micro_form
233
+	 *
234
+	 * @param EE_Form_Section_Proper $question_group_reg_form
235
+	 * @return EE_Form_Section_Proper
236
+	 * @throws EE_Error
237
+	 * @throws ReflectionException
238
+	 */
239
+	public static function display_add_new_state_micro_form(
240
+		EE_Form_Section_Proper $question_group_reg_form
241
+	): EE_Form_Section_Proper {
242
+		$request = self::getRequest();
243
+		// only add the 'new_state_micro_form' when displaying reg forms,
244
+		// not during processing since we process the 'new_state_micro_form' in it's own AJAX request
245
+		$action = $request->getRequestParam('action');
246
+		// is the "state" question in this form section?
247
+		$input = $question_group_reg_form->get_subsection('state');
248
+		if ($action === 'process_reg_step' || $action === 'update_reg_step') {
249
+			// ok then all we need to do is make sure the input's HTML name is consistent
250
+			// by forcing it to set it now, like it did while getting the form for display
251
+			if ($input instanceof EE_State_Select_Input) {
252
+				$input->html_name();
253
+			}
254
+			return $question_group_reg_form;
255
+		}
256
+		// we're only doing this for state select inputs
257
+		if (
258
+			$input instanceof EE_State_Select_Input
259
+			&& ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy
260
+		) {
261
+			// grab any set values from the request
262
+			$country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
263
+			$state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
264
+			$abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
265
+			$new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
266
+			$country_options     = [];
267
+			$countries           = EEM_Country::instance()->get_all_countries();
268
+			if (! empty($countries)) {
269
+				foreach ($countries as $country) {
270
+					if ($country instanceof EE_Country) {
271
+						$country_options[ $country->ID() ] = $country->name();
272
+					}
273
+				}
274
+			}
275
+			$new_state_micro_form = new EE_Form_Section_Proper(
276
+				[
277
+					'name'            => 'new_state_micro_form',
278
+					'html_id'         => 'new_state_micro_form',
279
+					'layout_strategy' => new EE_Div_Per_Section_Layout(),
280
+					'subsections'     => [
281
+						// add hidden input to indicate that a new state is being added
282
+						'add_new_state'               => new EE_Hidden_Input(
283
+							[
284
+								'html_name' => str_replace(
285
+									'state',
286
+									'nsmf_add_new_state',
287
+									$input->html_name()
288
+								),
289
+								'html_id'   => str_replace(
290
+									'state',
291
+									'nsmf_add_new_state',
292
+									$input->html_id()
293
+								),
294
+								'default'   => 0,
295
+							]
296
+						),
297
+						// add link for displaying hidden container
298
+						'click_here_link'             => new EE_Form_Section_HTML(
299
+							apply_filters(
300
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
301
+								EEH_HTML::link(
302
+									'',
303
+									esc_html__('click here to add a new state/province', 'event_espresso'),
304
+									'',
305
+									'display-' . $input->html_id(),
306
+									'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
307
+									'',
308
+									'data-target="' . $input->html_id() . '"'
309
+								)
310
+							)
311
+						),
312
+						// add initial html for hidden container
313
+						'add_new_state_micro_form'    => new EE_Form_Section_HTML(
314
+							apply_filters(
315
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
316
+								EEH_HTML::div(
317
+									'',
318
+									$input->html_id() . '-dv',
319
+									'ee-form-add-new-state-dv',
320
+									'display: none;'
321
+								) .
322
+								EEH_HTML::h6(
323
+									esc_html__(
324
+										'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
325
+										'event_espresso'
326
+									)
327
+								) .
328
+								EEH_HTML::ul() .
329
+								EEH_HTML::li(
330
+									esc_html__(
331
+										'first select the Country that your State/Province belongs to',
332
+										'event_espresso'
333
+									)
334
+								) .
335
+								EEH_HTML::li(
336
+									esc_html__('enter the name of your State/Province', 'event_espresso')
337
+								) .
338
+								EEH_HTML::li(
339
+									esc_html__(
340
+										'enter a two to six letter abbreviation for the name of your State/Province',
341
+										'event_espresso'
342
+									)
343
+								) .
344
+								EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
345
+								EEH_HTML::ulx()
346
+							)
347
+						),
348
+						// NEW STATE COUNTRY
349
+						'new_state_country'           => new EE_Country_Select_Input(
350
+							$country_options,
351
+							[
352
+								'html_name'       => $country_name,
353
+								'html_id'         => str_replace(
354
+									'state',
355
+									'nsmf_new_state_country',
356
+									$input->html_id()
357
+								),
358
+								'html_class'      => $input->html_class() . ' new-state-country',
359
+								'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
360
+								'default'         => $request->getRequestParam($country_name),
361
+								'required'        => false,
362
+							]
363
+						),
364
+						// NEW STATE NAME
365
+						'new_state_name'              => new EE_Text_Input(
366
+							[
367
+								'html_name'       => $state_name,
368
+								'html_id'         => str_replace(
369
+									'state',
370
+									'nsmf_new_state_name',
371
+									$input->html_id()
372
+								),
373
+								'html_class'      => $input->html_class() . ' new-state-state',
374
+								'html_label_text' => esc_html__(
375
+									'New State/Province Name',
376
+									'event_espresso'
377
+								),
378
+								'default'         => $request->getRequestParam($state_name),
379
+								'required'        => false,
380
+							]
381
+						),
382
+						// NEW STATE NAME
383
+						'new_state_abbrv'             => new EE_Text_Input(
384
+							[
385
+								'html_name'             => $abbrv_name,
386
+								'html_id'               => str_replace(
387
+									'state',
388
+									'nsmf_new_state_abbrv',
389
+									$input->html_id()
390
+								),
391
+								'html_class'            => $input->html_class() . ' new-state-abbrv',
392
+								'html_label_text'       => esc_html__(
393
+									'New State/Province Abbreviation',
394
+									'event_espresso'
395
+								) . ' *',
396
+								'other_html_attributes' => 'size="24"',
397
+								'default'               => $request->getRequestParam($abbrv_name),
398
+								'required'              => false,
399
+							]
400
+						),
401
+						// "submit" button
402
+						'add_new_state_submit_button' => new EE_Form_Section_HTML(
403
+							apply_filters(
404
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
405
+								EEH_HTML::div(
406
+									EEH_HTML::button(
407
+										esc_html__('ADD', 'event_espresso'),
408
+										'ee-form-add-new-state-submit button button--secondary',
409
+										'',
410
+										'submit-' . $new_state_submit_id,
411
+										'',
412
+										'data-target="' . $new_state_submit_id . '"'
413
+										. ' data-value-field-name="' . $input->valueFieldName() . '"'
414
+									),
415
+									'',
416
+									'ee-form-add-new-state-submit-dv'
417
+								)
418
+							)
419
+						),
420
+						// extra info
421
+						'add_new_state_extra'         => new EE_Form_Section_HTML(
422
+							apply_filters(
423
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
424
+								EEH_HTML::br()
425
+								.
426
+								EEH_HTML::div('', '', 'small-text')
427
+								.
428
+								EEH_HTML::strong(
429
+									'* ' .
430
+									esc_html__(
431
+										'Don\'t know your State/Province Abbreviation?',
432
+										'event_espresso'
433
+									)
434
+								)
435
+								.
436
+								EEH_HTML::br()
437
+								.
438
+								sprintf(
439
+									esc_html__(
440
+										'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
441
+										'event_espresso'
442
+									),
443
+									EEH_HTML::link(
444
+										'https://en.wikipedia.org/wiki/ISO_3166-2',
445
+										'https://en.wikipedia.org/wiki/ISO_3166-2',
446
+										'',
447
+										'',
448
+										'ee-form-add-new-state-wiki-lnk',
449
+										'',
450
+										'target="_blank"'
451
+									)
452
+								)
453
+								.
454
+								EEH_HTML::divx()
455
+								.
456
+								EEH_HTML::br()
457
+								.
458
+								EEH_HTML::link(
459
+									'',
460
+									esc_html__('cancel new State/Province', 'event_espresso'),
461
+									'',
462
+									'hide-' . $input->html_id(),
463
+									'ee-form-cancel-new-state-lnk smaller-text',
464
+									'',
465
+									'data-target="' . $input->html_id() . '"'
466
+								)
467
+								.
468
+								EEH_HTML::divx()
469
+								.
470
+								EEH_HTML::br()
471
+							)
472
+						),
473
+					],
474
+				]
475
+			);
476
+			$question_group_reg_form->add_subsections(
477
+				['new_state_micro_form' => $new_state_micro_form],
478
+				'state',
479
+				false
480
+			);
481
+		}
482
+		return $question_group_reg_form;
483
+	}
484
+
485
+
486
+	/**
487
+	 * set_new_state_input_width
488
+	 *
489
+	 * @return int|string
490
+	 * @throws EE_Error
491
+	 * @throws InvalidArgumentException
492
+	 * @throws InvalidDataTypeException
493
+	 * @throws InvalidInterfaceException
494
+	 * @throws ReflectionException
495
+	 */
496
+	public static function add_new_state()
497
+	{
498
+		$request = self::getRequest();
499
+		if ($request->getRequestParam('nsmf_add_new_state', 0, 'int') === 1) {
500
+			EE_Registry::instance()->load_model('State');
501
+			// grab country ISO code, new state name, and new state abbreviation
502
+			$state_country = $request->getRequestParam('nsmf_new_state_country');
503
+			$state_name    = $request->getRequestParam('nsmf_new_state_name');
504
+			$state_abbr    = $request->getRequestParam('nsmf_new_state_abbrv');
505
+			if ($state_country && $state_name && $state_abbr) {
506
+				$new_state = EED_Add_New_State::save_new_state_to_db(
507
+					[
508
+						'CNT_ISO'    => strtoupper($state_country),
509
+						'STA_abbrev' => strtoupper($state_abbr),
510
+						'STA_name'   => ucwords($state_name),
511
+						'STA_active' => false,
512
+					]
513
+				);
514
+				if ($new_state instanceof EE_State) {
515
+					// clean house
516
+					$request->unSetRequestParams(
517
+						[
518
+							'nsmf_add_new_state',
519
+							'nsmf_new_state_country',
520
+							'nsmf_new_state_name',
521
+							'nsmf_new_state_abbrv',
522
+						]
523
+					);
524
+					// get any existing new states
525
+					$new_states                     = EE_Registry::instance()->SSN->get_session_data('nsmf_new_states');
526
+					$new_states[ $new_state->ID() ] = $new_state;
527
+					EE_Registry::instance()->SSN->set_session_data(
528
+						['nsmf_new_states' => $new_states]
529
+					);
530
+					if ($request->isAjax()) {
531
+						echo wp_json_encode(
532
+							[
533
+								'success'      => true,
534
+								'id'           => $new_state->ID(),
535
+								'name'         => $new_state->name(),
536
+								'abbrev'       => $new_state->abbrev(),
537
+								'country_iso'  => $new_state->country_iso(),
538
+								'country_name' => $new_state->country()->name(),
539
+							]
540
+						);
541
+						exit();
542
+					}
543
+					return $new_state->ID();
544
+				}
545
+			} else {
546
+				$error = esc_html__(
547
+					'A new State/Province could not be added because invalid or missing data was received.',
548
+					'event_espresso'
549
+				);
550
+				if ($request->isAjax()) {
551
+					echo wp_json_encode(['error' => $error]);
552
+					exit();
553
+				}
554
+				EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
555
+			}
556
+		}
557
+		return false;
558
+	}
559
+
560
+
561
+	/**
562
+	 * recursively drills down through request params to remove any that were added by this module
563
+	 *
564
+	 * @param array $request_params
565
+	 * @return array
566
+	 */
567
+	public static function filter_checkout_request_params(array $request_params): array
568
+	{
569
+		foreach ($request_params as $form_section) {
570
+			if (is_array($form_section)) {
571
+				EED_Add_New_State::unset_new_state_request_params($form_section);
572
+				EED_Add_New_State::filter_checkout_request_params($form_section);
573
+			}
574
+		}
575
+		return $request_params;
576
+	}
577
+
578
+
579
+	/**
580
+	 * @param array $request_params
581
+	 * @return array
582
+	 */
583
+	public static function unset_new_state_request_params(array $request_params): array
584
+	{
585
+		unset(
586
+			$request_params['new_state_micro_form'],
587
+			$request_params['new_state_micro_add_new_state'],
588
+			$request_params['new_state_micro_new_state_country'],
589
+			$request_params['new_state_micro_new_state_name'],
590
+			$request_params['new_state_micro_new_state_abbrv']
591
+		);
592
+		return $request_params;
593
+	}
594
+
595
+
596
+	/**
597
+	 * @param array $props_n_values
598
+	 * @return EE_State|null
599
+	 * @throws EE_Error
600
+	 * @throws ReflectionException
601
+	 */
602
+	public static function save_new_state_to_db(array $props_n_values = []): ?EE_State
603
+	{
604
+		/** @var EE_State[] $existing_state */
605
+		$existing_state = EEM_State::instance()->get_all([$props_n_values, 'limit' => 1]);
606
+		if (! empty($existing_state)) {
607
+			return array_pop($existing_state);
608
+		}
609
+		$new_state = EE_State::new_instance($props_n_values);
610
+		if ($new_state instanceof EE_State) {
611
+			$country_settings_url = add_query_arg(
612
+				[
613
+					'page'    => 'espresso_general_settings',
614
+					'action'  => 'country_settings',
615
+					'country' => $new_state->country_iso(),
616
+				],
617
+				admin_url('admin.php')
618
+			);
619
+			// if not non-ajax admin
620
+			new PersistentAdminNotice(
621
+				'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
622
+				sprintf(
623
+					esc_html__(
624
+						'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
625
+						'event_espresso'
626
+					),
627
+					'<b>' . $new_state->name() . '</b>',
628
+					'<b>' . $new_state->abbrev() . '</b>',
629
+					'<b>' . $new_state->country()->name() . '</b>',
630
+					'<a href="'
631
+					. $country_settings_url
632
+					. '">'
633
+					. esc_html__(
634
+						'Event Espresso - General Settings > Countries Tab',
635
+						'event_espresso'
636
+					)
637
+					. '</a>',
638
+					'<br />'
639
+				)
640
+			);
641
+			$new_state->save();
642
+			EEM_State::instance()->reset_cached_states();
643
+			return $new_state;
644
+		}
645
+		return null;
646
+	}
647
+
648
+
649
+	/**
650
+	 * @param string $CNT_ISO
651
+	 * @param int    $STA_ID
652
+	 * @param array  $cols_n_values
653
+	 * @return void
654
+	 * @throws DomainException
655
+	 * @throws EE_Error
656
+	 * @throws InvalidArgumentException
657
+	 * @throws InvalidDataTypeException
658
+	 * @throws InvalidInterfaceException
659
+	 * @throws ReflectionException
660
+	 */
661
+	public static function update_country_settings(string $CNT_ISO = '', int $STA_ID = 0, array $cols_n_values = [])
662
+	{
663
+		if (! $CNT_ISO) {
664
+			EE_Error::add_error(
665
+				esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
666
+				__FILE__,
667
+				__FUNCTION__,
668
+				__LINE__
669
+			);
670
+		}
671
+		$STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
672
+			: false;
673
+		if (! $STA_abbrev && ! empty($STA_ID)) {
674
+			$state = EEM_State::instance()->get_one_by_ID($STA_ID);
675
+			if ($state instanceof EE_State) {
676
+				$STA_abbrev = $state->abbrev();
677
+			}
678
+		}
679
+		if (! $STA_abbrev) {
680
+			EE_Error::add_error(
681
+				esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
682
+				__FILE__,
683
+				__FUNCTION__,
684
+				__LINE__
685
+			);
686
+		}
687
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
688
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
689
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
690
+		);
691
+		$persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
692
+	}
693
+
694
+
695
+	/**
696
+	 * @param EE_State[]                                              $state_options
697
+	 * @param EE_SPCO_Reg_Step_Attendee_Information|StateOptions|null $deprecated
698
+	 * @param EE_Registration                                         $registration
699
+	 * @param EE_Question|null                                        $question
700
+	 * @param EE_Answer|null                                          $answer
701
+	 * @return array
702
+	 * @throws EE_Error
703
+	 * @throws ReflectionException
704
+	 */
705
+	public static function inject_new_reg_state_into_options(
706
+		array $state_options,
707
+		$deprecated,
708
+		EE_Registration $registration,
709
+		?EE_Question $question,
710
+		?EE_Answer $answer
711
+	): array {
712
+		if (
713
+			$answer instanceof EE_Answer && $question instanceof EE_Question
714
+			&& $question->type() === EEM_Question::QST_type_state
715
+		) {
716
+			$STA_ID = $answer->value();
717
+			if (! empty($STA_ID)) {
718
+				$state = EEM_State::instance()->get_one_by_ID($STA_ID);
719
+				if ($state instanceof EE_State) {
720
+					$country = $state->country();
721
+					if ($country instanceof EE_Country) {
722
+						if (! isset($state_options[ $country->name() ])) {
723
+							$state_options[ $country->name() ] = [];
724
+						}
725
+						if (! isset($state_options[ $country->name() ][ $STA_ID ])) {
726
+							$state_options[ $country->name() ][ $STA_ID ] = $state->name();
727
+						}
728
+					}
729
+				}
730
+			}
731
+		}
732
+		return $state_options;
733
+	}
734
+
735
+
736
+	/**
737
+	 * @param EE_Country[]                                              $country_options
738
+	 * @param EE_SPCO_Reg_Step_Attendee_Information|CountryOptions|null $deprecated
739
+	 * @param EE_Registration                                           $registration
740
+	 * @param EE_Question|null                                          $question
741
+	 * @param EE_Answer|null                                            $answer
742
+	 * @return array
743
+	 * @throws EE_Error
744
+	 * @throws InvalidArgumentException
745
+	 * @throws InvalidDataTypeException
746
+	 * @throws InvalidInterfaceException
747
+	 * @throws ReflectionException
748
+	 */
749
+	public static function inject_new_reg_country_into_options(
750
+		array $country_options,
751
+		$deprecated,
752
+		EE_Registration $registration,
753
+		?EE_Question $question,
754
+		?EE_Answer $answer
755
+	): array {
756
+		if (
757
+			$answer instanceof EE_Answer && $question instanceof EE_Question
758
+			&& $question->type() === EEM_Question::QST_type_country
759
+		) {
760
+			$CNT_ISO = $answer->value();
761
+			if (! empty($CNT_ISO)) {
762
+				$country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
763
+				if ($country instanceof EE_Country) {
764
+					if (! isset($country_options[ $CNT_ISO ])) {
765
+						$country_options[ $CNT_ISO ] = $country->name();
766
+					}
767
+				}
768
+			}
769
+		}
770
+		return $country_options;
771
+	}
772
+
773
+
774
+	/**
775
+	 * @param EE_State[] $state_options
776
+	 * @return array
777
+	 * @throws EE_Error
778
+	 * @throws ReflectionException
779
+	 */
780
+	public static function state_options(array $state_options = []): array
781
+	{
782
+		$new_states = EED_Add_New_State::_get_new_states();
783
+		foreach ($new_states as $new_state) {
784
+			if (
785
+				$new_state instanceof EE_State
786
+				&& $new_state->country() instanceof EE_Country
787
+			) {
788
+				$state_options[ $new_state->country()->name() ][ $new_state->ID() ] = $new_state->name();
789
+			}
790
+		}
791
+		return $state_options;
792
+	}
793
+
794
+
795
+	/**
796
+	 * @return array
797
+	 * @throws InvalidArgumentException
798
+	 * @throws InvalidDataTypeException
799
+	 * @throws InvalidInterfaceException
800
+	 */
801
+	protected static function _get_new_states(): array
802
+	{
803
+		$new_states = [];
804
+		if (EE_Registry::instance()->SSN instanceof EE_Session) {
805
+			$new_states = EE_Registry::instance()->SSN->get_session_data(
806
+				'nsmf_new_states'
807
+			);
808
+		}
809
+		return is_array($new_states) ? $new_states : [];
810
+	}
811
+
812
+
813
+	/**
814
+	 * @param EE_Country[] $country_options
815
+	 * @return array
816
+	 * @throws EE_Error
817
+	 * @throws ReflectionException
818
+	 */
819
+	public static function country_options(array $country_options = []): array
820
+	{
821
+		$new_states = EED_Add_New_State::_get_new_states();
822
+		foreach ($new_states as $new_state) {
823
+			if (
824
+				$new_state instanceof EE_State
825
+				&& $new_state->country() instanceof EE_Country
826
+			) {
827
+				$country_options[ $new_state->country()->ID() ] = $new_state->country()->name();
828
+			}
829
+		}
830
+		return $country_options;
831
+	}
832 832
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
      */
162 162
     public static function set_definitions()
163 163
     {
164
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
164
+        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__).'assets/');
165 165
         define(
166 166
             'ANS_TEMPLATES_PATH',
167 167
             str_replace(
168 168
                 '\\',
169 169
                 '/',
170 170
                 plugin_dir_path(__FILE__)
171
-            ) . 'templates/'
171
+            ).'templates/'
172 172
         );
173 173
     }
174 174
 
@@ -187,19 +187,19 @@  discard block
 block discarded – undo
187 187
      */
188 188
     public static function translate_js_strings()
189 189
     {
190
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
190
+        EE_Registry::$i18n_js_strings['ans_no_country'] = esc_html__(
191 191
             'In order to proceed, you need to select the Country that your State/Province belongs to.',
192 192
             'event_espresso'
193 193
         );
194
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
194
+        EE_Registry::$i18n_js_strings['ans_no_name'] = esc_html__(
195 195
             'In order to proceed, you need to enter the name of your State/Province.',
196 196
             'event_espresso'
197 197
         );
198
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
198
+        EE_Registry::$i18n_js_strings['ans_no_abbreviation'] = esc_html__(
199 199
             'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
200 200
             'event_espresso'
201 201
         );
202
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
202
+        EE_Registry::$i18n_js_strings['ans_save_success'] = esc_html__(
203 203
             'The new state was successfully saved to the database.',
204 204
             'event_espresso'
205 205
         );
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
         if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
219 219
             wp_register_script(
220 220
                 'add_new_state',
221
-                ANS_ASSETS_URL . 'add_new_state.js',
221
+                ANS_ASSETS_URL.'add_new_state.js',
222 222
                 ['espresso_core', 'single_page_checkout'],
223 223
                 EVENT_ESPRESSO_VERSION,
224 224
                 true
@@ -265,10 +265,10 @@  discard block
 block discarded – undo
265 265
             $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
266 266
             $country_options     = [];
267 267
             $countries           = EEM_Country::instance()->get_all_countries();
268
-            if (! empty($countries)) {
268
+            if ( ! empty($countries)) {
269 269
                 foreach ($countries as $country) {
270 270
                     if ($country instanceof EE_Country) {
271
-                        $country_options[ $country->ID() ] = $country->name();
271
+                        $country_options[$country->ID()] = $country->name();
272 272
                     }
273 273
                 }
274 274
             }
@@ -302,10 +302,10 @@  discard block
 block discarded – undo
302 302
                                     '',
303 303
                                     esc_html__('click here to add a new state/province', 'event_espresso'),
304 304
                                     '',
305
-                                    'display-' . $input->html_id(),
305
+                                    'display-'.$input->html_id(),
306 306
                                     'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
307 307
                                     '',
308
-                                    'data-target="' . $input->html_id() . '"'
308
+                                    'data-target="'.$input->html_id().'"'
309 309
                                 )
310 310
                             )
311 311
                         ),
@@ -315,33 +315,33 @@  discard block
 block discarded – undo
315 315
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
316 316
                                 EEH_HTML::div(
317 317
                                     '',
318
-                                    $input->html_id() . '-dv',
318
+                                    $input->html_id().'-dv',
319 319
                                     'ee-form-add-new-state-dv',
320 320
                                     'display: none;'
321
-                                ) .
321
+                                ).
322 322
                                 EEH_HTML::h6(
323 323
                                     esc_html__(
324 324
                                         'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
325 325
                                         'event_espresso'
326 326
                                     )
327
-                                ) .
328
-                                EEH_HTML::ul() .
327
+                                ).
328
+                                EEH_HTML::ul().
329 329
                                 EEH_HTML::li(
330 330
                                     esc_html__(
331 331
                                         'first select the Country that your State/Province belongs to',
332 332
                                         'event_espresso'
333 333
                                     )
334
-                                ) .
334
+                                ).
335 335
                                 EEH_HTML::li(
336 336
                                     esc_html__('enter the name of your State/Province', 'event_espresso')
337
-                                ) .
337
+                                ).
338 338
                                 EEH_HTML::li(
339 339
                                     esc_html__(
340 340
                                         'enter a two to six letter abbreviation for the name of your State/Province',
341 341
                                         'event_espresso'
342 342
                                     )
343
-                                ) .
344
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
343
+                                ).
344
+                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')).
345 345
                                 EEH_HTML::ulx()
346 346
                             )
347 347
                         ),
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
                                     'nsmf_new_state_country',
356 356
                                     $input->html_id()
357 357
                                 ),
358
-                                'html_class'      => $input->html_class() . ' new-state-country',
358
+                                'html_class'      => $input->html_class().' new-state-country',
359 359
                                 'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
360 360
                                 'default'         => $request->getRequestParam($country_name),
361 361
                                 'required'        => false,
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
                                     'nsmf_new_state_name',
371 371
                                     $input->html_id()
372 372
                                 ),
373
-                                'html_class'      => $input->html_class() . ' new-state-state',
373
+                                'html_class'      => $input->html_class().' new-state-state',
374 374
                                 'html_label_text' => esc_html__(
375 375
                                     'New State/Province Name',
376 376
                                     'event_espresso'
@@ -388,11 +388,11 @@  discard block
 block discarded – undo
388 388
                                     'nsmf_new_state_abbrv',
389 389
                                     $input->html_id()
390 390
                                 ),
391
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
391
+                                'html_class'            => $input->html_class().' new-state-abbrv',
392 392
                                 'html_label_text'       => esc_html__(
393 393
                                     'New State/Province Abbreviation',
394 394
                                     'event_espresso'
395
-                                ) . ' *',
395
+                                ).' *',
396 396
                                 'other_html_attributes' => 'size="24"',
397 397
                                 'default'               => $request->getRequestParam($abbrv_name),
398 398
                                 'required'              => false,
@@ -407,10 +407,10 @@  discard block
 block discarded – undo
407 407
                                         esc_html__('ADD', 'event_espresso'),
408 408
                                         'ee-form-add-new-state-submit button button--secondary',
409 409
                                         '',
410
-                                        'submit-' . $new_state_submit_id,
410
+                                        'submit-'.$new_state_submit_id,
411 411
                                         '',
412
-                                        'data-target="' . $new_state_submit_id . '"'
413
-                                        . ' data-value-field-name="' . $input->valueFieldName() . '"'
412
+                                        'data-target="'.$new_state_submit_id.'"'
413
+                                        . ' data-value-field-name="'.$input->valueFieldName().'"'
414 414
                                     ),
415 415
                                     '',
416 416
                                     'ee-form-add-new-state-submit-dv'
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
                                 EEH_HTML::div('', '', 'small-text')
427 427
                                 .
428 428
                                 EEH_HTML::strong(
429
-                                    '* ' .
429
+                                    '* '.
430 430
                                     esc_html__(
431 431
                                         'Don\'t know your State/Province Abbreviation?',
432 432
                                         'event_espresso'
@@ -459,10 +459,10 @@  discard block
 block discarded – undo
459 459
                                     '',
460 460
                                     esc_html__('cancel new State/Province', 'event_espresso'),
461 461
                                     '',
462
-                                    'hide-' . $input->html_id(),
462
+                                    'hide-'.$input->html_id(),
463 463
                                     'ee-form-cancel-new-state-lnk smaller-text',
464 464
                                     '',
465
-                                    'data-target="' . $input->html_id() . '"'
465
+                                    'data-target="'.$input->html_id().'"'
466 466
                                 )
467 467
                                 .
468 468
                                 EEH_HTML::divx()
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
                     );
524 524
                     // get any existing new states
525 525
                     $new_states                     = EE_Registry::instance()->SSN->get_session_data('nsmf_new_states');
526
-                    $new_states[ $new_state->ID() ] = $new_state;
526
+                    $new_states[$new_state->ID()] = $new_state;
527 527
                     EE_Registry::instance()->SSN->set_session_data(
528 528
                         ['nsmf_new_states' => $new_states]
529 529
                     );
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
     {
604 604
         /** @var EE_State[] $existing_state */
605 605
         $existing_state = EEM_State::instance()->get_all([$props_n_values, 'limit' => 1]);
606
-        if (! empty($existing_state)) {
606
+        if ( ! empty($existing_state)) {
607 607
             return array_pop($existing_state);
608 608
         }
609 609
         $new_state = EE_State::new_instance($props_n_values);
@@ -618,15 +618,15 @@  discard block
 block discarded – undo
618 618
             );
619 619
             // if not non-ajax admin
620 620
             new PersistentAdminNotice(
621
-                'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev(),
621
+                'new-state-added-'.$new_state->country_iso().'-'.$new_state->abbrev(),
622 622
                 sprintf(
623 623
                     esc_html__(
624 624
                         'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
625 625
                         'event_espresso'
626 626
                     ),
627
-                    '<b>' . $new_state->name() . '</b>',
628
-                    '<b>' . $new_state->abbrev() . '</b>',
629
-                    '<b>' . $new_state->country()->name() . '</b>',
627
+                    '<b>'.$new_state->name().'</b>',
628
+                    '<b>'.$new_state->abbrev().'</b>',
629
+                    '<b>'.$new_state->country()->name().'</b>',
630 630
                     '<a href="'
631 631
                     . $country_settings_url
632 632
                     . '">'
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
      */
661 661
     public static function update_country_settings(string $CNT_ISO = '', int $STA_ID = 0, array $cols_n_values = [])
662 662
     {
663
-        if (! $CNT_ISO) {
663
+        if ( ! $CNT_ISO) {
664 664
             EE_Error::add_error(
665 665
                 esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
666 666
                 __FILE__,
@@ -670,13 +670,13 @@  discard block
 block discarded – undo
670 670
         }
671 671
         $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
672 672
             : false;
673
-        if (! $STA_abbrev && ! empty($STA_ID)) {
673
+        if ( ! $STA_abbrev && ! empty($STA_ID)) {
674 674
             $state = EEM_State::instance()->get_one_by_ID($STA_ID);
675 675
             if ($state instanceof EE_State) {
676 676
                 $STA_abbrev = $state->abbrev();
677 677
             }
678 678
         }
679
-        if (! $STA_abbrev) {
679
+        if ( ! $STA_abbrev) {
680 680
             EE_Error::add_error(
681 681
                 esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
682 682
                 __FILE__,
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
         $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
689 689
             'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
690 690
         );
691
-        $persistent_admin_notice_manager->dismissNotice($CNT_ISO . '-' . $STA_abbrev, true, true);
691
+        $persistent_admin_notice_manager->dismissNotice($CNT_ISO.'-'.$STA_abbrev, true, true);
692 692
     }
693 693
 
694 694
 
@@ -714,16 +714,16 @@  discard block
 block discarded – undo
714 714
             && $question->type() === EEM_Question::QST_type_state
715 715
         ) {
716 716
             $STA_ID = $answer->value();
717
-            if (! empty($STA_ID)) {
717
+            if ( ! empty($STA_ID)) {
718 718
                 $state = EEM_State::instance()->get_one_by_ID($STA_ID);
719 719
                 if ($state instanceof EE_State) {
720 720
                     $country = $state->country();
721 721
                     if ($country instanceof EE_Country) {
722
-                        if (! isset($state_options[ $country->name() ])) {
723
-                            $state_options[ $country->name() ] = [];
722
+                        if ( ! isset($state_options[$country->name()])) {
723
+                            $state_options[$country->name()] = [];
724 724
                         }
725
-                        if (! isset($state_options[ $country->name() ][ $STA_ID ])) {
726
-                            $state_options[ $country->name() ][ $STA_ID ] = $state->name();
725
+                        if ( ! isset($state_options[$country->name()][$STA_ID])) {
726
+                            $state_options[$country->name()][$STA_ID] = $state->name();
727 727
                         }
728 728
                     }
729 729
                 }
@@ -758,11 +758,11 @@  discard block
 block discarded – undo
758 758
             && $question->type() === EEM_Question::QST_type_country
759 759
         ) {
760 760
             $CNT_ISO = $answer->value();
761
-            if (! empty($CNT_ISO)) {
761
+            if ( ! empty($CNT_ISO)) {
762 762
                 $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
763 763
                 if ($country instanceof EE_Country) {
764
-                    if (! isset($country_options[ $CNT_ISO ])) {
765
-                        $country_options[ $CNT_ISO ] = $country->name();
764
+                    if ( ! isset($country_options[$CNT_ISO])) {
765
+                        $country_options[$CNT_ISO] = $country->name();
766 766
                     }
767 767
                 }
768 768
             }
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
                 $new_state instanceof EE_State
786 786
                 && $new_state->country() instanceof EE_Country
787 787
             ) {
788
-                $state_options[ $new_state->country()->name() ][ $new_state->ID() ] = $new_state->name();
788
+                $state_options[$new_state->country()->name()][$new_state->ID()] = $new_state->name();
789 789
             }
790 790
         }
791 791
         return $state_options;
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
                 $new_state instanceof EE_State
825 825
                 && $new_state->country() instanceof EE_Country
826 826
             ) {
827
-                $country_options[ $new_state->country()->ID() ] = $new_state->country()->name();
827
+                $country_options[$new_state->country()->ID()] = $new_state->country()->name();
828 828
             }
829 829
         }
830 830
         return $country_options;
Please login to merge, or discard this patch.
core/business/EE_Processor_Base.class.php 2 patches
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -10,73 +10,73 @@
 block discarded – undo
10 10
  */
11 11
 class EE_Processor_Base
12 12
 {
13
-    /**
14
-     * Used to indicate whether current request is for an IPN or not.
15
-     *
16
-     * @var bool
17
-     */
18
-    protected static $IPN = false;
13
+	/**
14
+	 * Used to indicate whether current request is for an IPN or not.
15
+	 *
16
+	 * @var bool
17
+	 */
18
+	protected static $IPN = false;
19 19
 
20
-    /**
21
-     * Used to indicate whether SPCO is being revisited by registrant or not.
22
-     *
23
-     * @var bool
24
-     */
25
-    protected $_revisit = false;
20
+	/**
21
+	 * Used to indicate whether SPCO is being revisited by registrant or not.
22
+	 *
23
+	 * @var bool
24
+	 */
25
+	protected $_revisit = false;
26 26
 
27 27
 
28
-    /**
29
-     * @param bool|int|string|null $IPN
30
-     */
31
-    public static function set_IPN($IPN)
32
-    {
33
-        self::$IPN = filter_var($IPN, FILTER_VALIDATE_BOOLEAN);
34
-    }
28
+	/**
29
+	 * @param bool|int|string|null $IPN
30
+	 */
31
+	public static function set_IPN($IPN)
32
+	{
33
+		self::$IPN = filter_var($IPN, FILTER_VALIDATE_BOOLEAN);
34
+	}
35 35
 
36 36
 
37
-    /**
38
-     * Allows external class (usually checkout) to set whether SPCO is being revisited by registrant or not.
39
-     *
40
-     * @param bool|int|string|null $revisit
41
-     * @return void
42
-     */
43
-    public function set_revisit($revisit = false)
44
-    {
45
-        $this->_revisit = filter_var($revisit, FILTER_VALIDATE_BOOLEAN);
46
-    }
37
+	/**
38
+	 * Allows external class (usually checkout) to set whether SPCO is being revisited by registrant or not.
39
+	 *
40
+	 * @param bool|int|string|null $revisit
41
+	 * @return void
42
+	 */
43
+	public function set_revisit($revisit = false)
44
+	{
45
+		$this->_revisit = filter_var($revisit, FILTER_VALIDATE_BOOLEAN);
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * debug
51
-     *
52
-     * @param string              $class
53
-     * @param string              $func
54
-     * @param int|string              $line
55
-     * @param EE_Transaction|null $transaction
56
-     * @param array               $info
57
-     * @param bool                $display_request
58
-     * @throws EE_Error
59
-     * @throws ReflectionException
60
-     */
61
-    protected function log(
62
-        string $class = '',
63
-        string $func = '',
64
-        $line = '',
65
-        ?EE_Transaction $transaction = null,
66
-        array $info = [],
67
-        bool $display_request = false
68
-    ) {
69
-        if (WP_DEBUG && false) {
70
-            if ($transaction instanceof EE_Transaction) {
71
-                // don't serialize objects
72
-                $info = EEH_Debug_Tools::strip_objects($info);
73
-                if ($transaction->ID()) {
74
-                    $info['TXN_status']    = $transaction->status_ID();
75
-                    $info['TXN_reg_steps'] = $transaction->reg_steps();
76
-                    $index                 = 'EE_Transaction: ' . $transaction->ID();
77
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
78
-                }
79
-            }
80
-        }
81
-    }
49
+	/**
50
+	 * debug
51
+	 *
52
+	 * @param string              $class
53
+	 * @param string              $func
54
+	 * @param int|string              $line
55
+	 * @param EE_Transaction|null $transaction
56
+	 * @param array               $info
57
+	 * @param bool                $display_request
58
+	 * @throws EE_Error
59
+	 * @throws ReflectionException
60
+	 */
61
+	protected function log(
62
+		string $class = '',
63
+		string $func = '',
64
+		$line = '',
65
+		?EE_Transaction $transaction = null,
66
+		array $info = [],
67
+		bool $display_request = false
68
+	) {
69
+		if (WP_DEBUG && false) {
70
+			if ($transaction instanceof EE_Transaction) {
71
+				// don't serialize objects
72
+				$info = EEH_Debug_Tools::strip_objects($info);
73
+				if ($transaction->ID()) {
74
+					$info['TXN_status']    = $transaction->status_ID();
75
+					$info['TXN_reg_steps'] = $transaction->reg_steps();
76
+					$index                 = 'EE_Transaction: ' . $transaction->ID();
77
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
78
+				}
79
+			}
80
+		}
81
+	}
82 82
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@
 block discarded – undo
73 73
                 if ($transaction->ID()) {
74 74
                     $info['TXN_status']    = $transaction->status_ID();
75 75
                     $info['TXN_reg_steps'] = $transaction->reg_steps();
76
-                    $index                 = 'EE_Transaction: ' . $transaction->ID();
76
+                    $index                 = 'EE_Transaction: '.$transaction->ID();
77 77
                     EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
78 78
                 }
79 79
             }
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Event_Strategy.core.php 1 patch
Indentation   +243 added lines, -243 removed lines patch added patch discarded remove patch
@@ -9,247 +9,247 @@
 block discarded – undo
9 9
  */
10 10
 class EE_CPT_Event_Strategy
11 11
 {
12
-    /**
13
-     * the current page, if it utilizes CPTs
14
-     *
15
-     * @var object $CPT
16
-     */
17
-    protected $CPT;
18
-
19
-
20
-    /**
21
-     * @param array|WP_Query $wp_query
22
-     * @param array          $CPT
23
-     */
24
-    public function __construct($wp_query, array $CPT = [])
25
-    {
26
-        if ($wp_query instanceof WP_Query) {
27
-            $WP_Query  = $wp_query;
28
-            $this->CPT = $CPT;
29
-        } else {
30
-            $WP_Query  = $wp_query['WP_Query'] ?? null;
31
-            $this->CPT = $wp_query['CPT'] ?? null;
32
-        }
33
-        // !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
34
-        // here's the list of available filters in the WP_Query object
35
-        // 'posts_where'
36
-        // 'posts_where_paged'
37
-        // 'posts_groupby'
38
-        // 'posts_join_paged'
39
-        // 'posts_orderby'
40
-        // 'posts_distinct'
41
-        // 'post_limits'
42
-        // 'posts_fields'
43
-        // 'posts_join'
44
-        $this->_add_filters();
45
-        if ($WP_Query instanceof WP_Query) {
46
-            $WP_Query->is_espresso_event_single   = is_singular()
47
-                                                    && isset($WP_Query->query->post_type)
48
-                                                    && $WP_Query->query->post_type === 'espresso_events';
49
-            $WP_Query->is_espresso_event_archive  = is_post_type_archive('espresso_events');
50
-            $WP_Query->is_espresso_event_taxonomy = is_tax('espresso_event_categories');
51
-        }
52
-    }
53
-
54
-
55
-    /**
56
-     * When an instance of this class is created, we add our filters
57
-     * (which will get removed in case the next call to get_posts ISN'T
58
-     * for event CPTs)
59
-     */
60
-    protected function _add_filters()
61
-    {
62
-        add_filter('posts_fields', [$this, 'posts_fields'], 1, 2);
63
-        add_filter('posts_join', [$this, 'posts_join'], 1, 2);
64
-        add_filter('posts_where', [$this, 'posts_where'], 10, 2);
65
-        // add_filter( 'the_posts', array( $this, 'the_posts' ), 1, 2 );
66
-        add_filter('posts_orderby', [$this, 'posts_orderby'], 1, 2);
67
-        add_filter('posts_groupby', [$this, 'posts_groupby'], 1, 2);
68
-        add_action('posts_selection', [$this, 'remove_filters']);
69
-    }
70
-
71
-
72
-    /**
73
-     * public access to _remove_filters()
74
-     *
75
-     * @since 4.9.63.p
76
-     */
77
-    public function remove_filters()
78
-    {
79
-        $this->_remove_filters();
80
-    }
81
-
82
-
83
-    /**
84
-     * Should eb called when the last filter or hook is fired for this CPT strategy.
85
-     * This is to avoid applying this CPT strategy for other posts or CPTs (eg,
86
-     * we don't want to join to the datetime table when querying for venues, do we!?)
87
-     */
88
-    protected function _remove_filters()
89
-    {
90
-        remove_filter('posts_fields', [$this, 'posts_fields'], 1);
91
-        remove_filter('posts_join', [$this, 'posts_join'], 1);
92
-        remove_filter('posts_where', [$this, 'posts_where']);
93
-        // remove_filter( 'the_posts', array( $this, 'the_posts' ), 1 );
94
-        remove_filter('posts_orderby', [$this, 'posts_orderby'], 1);
95
-        remove_filter('posts_groupby', [$this, 'posts_groupby'], 1);
96
-        remove_action('posts_selection', [$this, 'remove_filters']);
97
-    }
98
-
99
-
100
-    /**
101
-     * @param string        $SQL
102
-     * @param WP_Query|null $wp_query
103
-     * @return    string
104
-     * @throws EE_Error
105
-     * @throws ReflectionException
106
-     */
107
-    public function posts_fields(string $SQL, ?WP_Query $wp_query): string
108
-    {
109
-        if (
110
-            $wp_query instanceof WP_Query
111
-            && (
112
-                $wp_query->is_espresso_event_single
113
-                || $wp_query->is_espresso_event_archive
114
-                || $wp_query->is_espresso_event_taxonomy
115
-            )
116
-        ) {
117
-            // adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
118
-            $SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
119
-            if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
120
-                // because we only want to retrieve the next upcoming datetime for each event:
121
-                // add something like:
122
-                // ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
123
-                // to WP Query SELECT statement
124
-                $SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
125
-            }
126
-        }
127
-        return $SQL;
128
-    }
129
-
130
-
131
-    /**
132
-     * @param string        $SQL
133
-     * @param WP_Query|null $wp_query
134
-     * @return string
135
-     * @throws EE_Error
136
-     * @throws ReflectionException
137
-     */
138
-    public function posts_join(string $SQL, ?WP_Query $wp_query): string
139
-    {
140
-        if (
141
-            $wp_query instanceof WP_Query
142
-            && (
143
-                $wp_query->is_espresso_event_single
144
-                || $wp_query->is_espresso_event_archive
145
-                || $wp_query->is_espresso_event_taxonomy
146
-            )
147
-        ) {
148
-            // adds something like:
149
-            // " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
150
-            // to WP Query JOIN statement
151
-            $SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
152
-                    . '.ID = ' . EEM_Datetime::instance()->table() . '.'
153
-                    . EEM_Event::instance()->primary_key_name() . ' ) ';
154
-        }
155
-        return $SQL;
156
-    }
157
-
158
-
159
-    /**
160
-     * @param string        $SQL
161
-     * @param WP_Query|null $wp_query
162
-     * @return string
163
-     * @throws EE_Error
164
-     * @throws ReflectionException
165
-     */
166
-    public function posts_where(string $SQL, ?WP_Query $wp_query): string
167
-    {
168
-        if (
169
-            $wp_query instanceof WP_Query
170
-            && (
171
-                $wp_query->is_espresso_event_archive
172
-                || $wp_query->is_espresso_event_taxonomy
173
-            )
174
-        ) {
175
-            if (
176
-                ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive)
177
-                || ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
178
-                || ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
179
-            ) {
180
-                $SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
181
-                        . current_time('mysql', true) . "' ";
182
-            }
183
-        }
184
-        return $SQL;
185
-    }
186
-
187
-
188
-    /**
189
-     * @param string        $SQL
190
-     * @param WP_Query|null $wp_query
191
-     * @return string
192
-     */
193
-    public function posts_orderby(string $SQL, ?WP_Query $wp_query): string
194
-    {
195
-        if (
196
-            $wp_query instanceof WP_Query
197
-            && (
198
-                $wp_query->is_espresso_event_archive
199
-                || $wp_query->is_espresso_event_taxonomy
200
-            )
201
-        ) {
202
-            $SQL = ' event_start_date ASC ';
203
-        }
204
-        return $SQL;
205
-    }
206
-
207
-
208
-    /**
209
-     * @param string        $SQL
210
-     * @param WP_Query|null $wp_query
211
-     * @return string
212
-     */
213
-    public function posts_groupby(string $SQL, ?WP_Query $wp_query): string
214
-    {
215
-        if (
216
-            $wp_query instanceof WP_Query
217
-            && (
218
-                $wp_query->is_espresso_event_archive
219
-                || $wp_query->is_espresso_event_taxonomy
220
-            )
221
-        ) {
222
-            // TODO: add event list option for displaying ALL datetimes in event list or only primary datetime (default)
223
-            // we're joining to the datetimes table, where there can be MANY datetimes for a single event,
224
-            // but we want to only show each event only once
225
-            // (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
226
-            global $wpdb;
227
-            $SQL = $wpdb->posts . '.ID ';
228
-        }
229
-        return $SQL;
230
-    }
231
-
232
-
233
-    /**
234
-     * @param array         $posts
235
-     * @param WP_Query|null $wp_query
236
-     * @return array
237
-     */
238
-    public function the_posts(array $posts, WP_Query $wp_query): array
239
-    {
240
-        return $posts;
241
-    }
242
-
243
-
244
-    /**
245
-     * @param mixed $meta_value
246
-     * @param       $post_id
247
-     * @param       $meta_key
248
-     * @param       $single
249
-     * @return mixed
250
-     */
251
-    public function get_EE_post_type_metadata($meta_value, $post_id, $meta_key, $single)
252
-    {
253
-        return $meta_value;
254
-    }
12
+	/**
13
+	 * the current page, if it utilizes CPTs
14
+	 *
15
+	 * @var object $CPT
16
+	 */
17
+	protected $CPT;
18
+
19
+
20
+	/**
21
+	 * @param array|WP_Query $wp_query
22
+	 * @param array          $CPT
23
+	 */
24
+	public function __construct($wp_query, array $CPT = [])
25
+	{
26
+		if ($wp_query instanceof WP_Query) {
27
+			$WP_Query  = $wp_query;
28
+			$this->CPT = $CPT;
29
+		} else {
30
+			$WP_Query  = $wp_query['WP_Query'] ?? null;
31
+			$this->CPT = $wp_query['CPT'] ?? null;
32
+		}
33
+		// !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
34
+		// here's the list of available filters in the WP_Query object
35
+		// 'posts_where'
36
+		// 'posts_where_paged'
37
+		// 'posts_groupby'
38
+		// 'posts_join_paged'
39
+		// 'posts_orderby'
40
+		// 'posts_distinct'
41
+		// 'post_limits'
42
+		// 'posts_fields'
43
+		// 'posts_join'
44
+		$this->_add_filters();
45
+		if ($WP_Query instanceof WP_Query) {
46
+			$WP_Query->is_espresso_event_single   = is_singular()
47
+													&& isset($WP_Query->query->post_type)
48
+													&& $WP_Query->query->post_type === 'espresso_events';
49
+			$WP_Query->is_espresso_event_archive  = is_post_type_archive('espresso_events');
50
+			$WP_Query->is_espresso_event_taxonomy = is_tax('espresso_event_categories');
51
+		}
52
+	}
53
+
54
+
55
+	/**
56
+	 * When an instance of this class is created, we add our filters
57
+	 * (which will get removed in case the next call to get_posts ISN'T
58
+	 * for event CPTs)
59
+	 */
60
+	protected function _add_filters()
61
+	{
62
+		add_filter('posts_fields', [$this, 'posts_fields'], 1, 2);
63
+		add_filter('posts_join', [$this, 'posts_join'], 1, 2);
64
+		add_filter('posts_where', [$this, 'posts_where'], 10, 2);
65
+		// add_filter( 'the_posts', array( $this, 'the_posts' ), 1, 2 );
66
+		add_filter('posts_orderby', [$this, 'posts_orderby'], 1, 2);
67
+		add_filter('posts_groupby', [$this, 'posts_groupby'], 1, 2);
68
+		add_action('posts_selection', [$this, 'remove_filters']);
69
+	}
70
+
71
+
72
+	/**
73
+	 * public access to _remove_filters()
74
+	 *
75
+	 * @since 4.9.63.p
76
+	 */
77
+	public function remove_filters()
78
+	{
79
+		$this->_remove_filters();
80
+	}
81
+
82
+
83
+	/**
84
+	 * Should eb called when the last filter or hook is fired for this CPT strategy.
85
+	 * This is to avoid applying this CPT strategy for other posts or CPTs (eg,
86
+	 * we don't want to join to the datetime table when querying for venues, do we!?)
87
+	 */
88
+	protected function _remove_filters()
89
+	{
90
+		remove_filter('posts_fields', [$this, 'posts_fields'], 1);
91
+		remove_filter('posts_join', [$this, 'posts_join'], 1);
92
+		remove_filter('posts_where', [$this, 'posts_where']);
93
+		// remove_filter( 'the_posts', array( $this, 'the_posts' ), 1 );
94
+		remove_filter('posts_orderby', [$this, 'posts_orderby'], 1);
95
+		remove_filter('posts_groupby', [$this, 'posts_groupby'], 1);
96
+		remove_action('posts_selection', [$this, 'remove_filters']);
97
+	}
98
+
99
+
100
+	/**
101
+	 * @param string        $SQL
102
+	 * @param WP_Query|null $wp_query
103
+	 * @return    string
104
+	 * @throws EE_Error
105
+	 * @throws ReflectionException
106
+	 */
107
+	public function posts_fields(string $SQL, ?WP_Query $wp_query): string
108
+	{
109
+		if (
110
+			$wp_query instanceof WP_Query
111
+			&& (
112
+				$wp_query->is_espresso_event_single
113
+				|| $wp_query->is_espresso_event_archive
114
+				|| $wp_query->is_espresso_event_taxonomy
115
+			)
116
+		) {
117
+			// adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
118
+			$SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
119
+			if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
120
+				// because we only want to retrieve the next upcoming datetime for each event:
121
+				// add something like:
122
+				// ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
123
+				// to WP Query SELECT statement
124
+				$SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
125
+			}
126
+		}
127
+		return $SQL;
128
+	}
129
+
130
+
131
+	/**
132
+	 * @param string        $SQL
133
+	 * @param WP_Query|null $wp_query
134
+	 * @return string
135
+	 * @throws EE_Error
136
+	 * @throws ReflectionException
137
+	 */
138
+	public function posts_join(string $SQL, ?WP_Query $wp_query): string
139
+	{
140
+		if (
141
+			$wp_query instanceof WP_Query
142
+			&& (
143
+				$wp_query->is_espresso_event_single
144
+				|| $wp_query->is_espresso_event_archive
145
+				|| $wp_query->is_espresso_event_taxonomy
146
+			)
147
+		) {
148
+			// adds something like:
149
+			// " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
150
+			// to WP Query JOIN statement
151
+			$SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
152
+					. '.ID = ' . EEM_Datetime::instance()->table() . '.'
153
+					. EEM_Event::instance()->primary_key_name() . ' ) ';
154
+		}
155
+		return $SQL;
156
+	}
157
+
158
+
159
+	/**
160
+	 * @param string        $SQL
161
+	 * @param WP_Query|null $wp_query
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 * @throws ReflectionException
165
+	 */
166
+	public function posts_where(string $SQL, ?WP_Query $wp_query): string
167
+	{
168
+		if (
169
+			$wp_query instanceof WP_Query
170
+			&& (
171
+				$wp_query->is_espresso_event_archive
172
+				|| $wp_query->is_espresso_event_taxonomy
173
+			)
174
+		) {
175
+			if (
176
+				! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive)
177
+				|| ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
178
+				|| ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
179
+			) {
180
+				$SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
181
+						. current_time('mysql', true) . "' ";
182
+			}
183
+		}
184
+		return $SQL;
185
+	}
186
+
187
+
188
+	/**
189
+	 * @param string        $SQL
190
+	 * @param WP_Query|null $wp_query
191
+	 * @return string
192
+	 */
193
+	public function posts_orderby(string $SQL, ?WP_Query $wp_query): string
194
+	{
195
+		if (
196
+			$wp_query instanceof WP_Query
197
+			&& (
198
+				$wp_query->is_espresso_event_archive
199
+				|| $wp_query->is_espresso_event_taxonomy
200
+			)
201
+		) {
202
+			$SQL = ' event_start_date ASC ';
203
+		}
204
+		return $SQL;
205
+	}
206
+
207
+
208
+	/**
209
+	 * @param string        $SQL
210
+	 * @param WP_Query|null $wp_query
211
+	 * @return string
212
+	 */
213
+	public function posts_groupby(string $SQL, ?WP_Query $wp_query): string
214
+	{
215
+		if (
216
+			$wp_query instanceof WP_Query
217
+			&& (
218
+				$wp_query->is_espresso_event_archive
219
+				|| $wp_query->is_espresso_event_taxonomy
220
+			)
221
+		) {
222
+			// TODO: add event list option for displaying ALL datetimes in event list or only primary datetime (default)
223
+			// we're joining to the datetimes table, where there can be MANY datetimes for a single event,
224
+			// but we want to only show each event only once
225
+			// (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
226
+			global $wpdb;
227
+			$SQL = $wpdb->posts . '.ID ';
228
+		}
229
+		return $SQL;
230
+	}
231
+
232
+
233
+	/**
234
+	 * @param array         $posts
235
+	 * @param WP_Query|null $wp_query
236
+	 * @return array
237
+	 */
238
+	public function the_posts(array $posts, WP_Query $wp_query): array
239
+	{
240
+		return $posts;
241
+	}
242
+
243
+
244
+	/**
245
+	 * @param mixed $meta_value
246
+	 * @param       $post_id
247
+	 * @param       $meta_key
248
+	 * @param       $single
249
+	 * @return mixed
250
+	 */
251
+	public function get_EE_post_type_metadata($meta_value, $post_id, $meta_key, $single)
252
+	{
253
+		return $meta_value;
254
+	}
255 255
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Term.model.php 2 patches
Indentation   +240 added lines, -240 removed lines patch added patch discarded remove patch
@@ -13,266 +13,266 @@
 block discarded – undo
13 13
  */
14 14
 class EEM_Term extends EEM_Base
15 15
 {
16
-    // private instance of the Attendee object
17
-    protected static $_instance = null;
16
+	// private instance of the Attendee object
17
+	protected static $_instance = null;
18 18
 
19 19
 
20 20
 
21
-    /**
22
-     *__construct
23
-     *
24
-     * @param string $timezone
25
-     */
26
-    protected function __construct($timezone = null)
27
-    {
28
-        $this->singular_item = esc_html__('Term', 'event_espresso');
29
-        $this->plural_item = esc_html__('Terms', 'event_espresso');
30
-        $this->_tables = array(
31
-            'Term' => new EE_Primary_Table('terms', 'term_id'),
32
-        );
33
-        $this->_fields = array(
34
-            'Term' => array(
35
-                'term_id'    => new EE_Primary_Key_Int_Field('term_id', esc_html__('Term ID', 'event_espresso')),
36
-                'name'       => new EE_Plain_Text_Field('name', esc_html__('Term Name', 'event_espresso'), false, ''),
37
-                'slug'       => new EE_Slug_Field('slug', esc_html__('Term Slug', 'event_espresso'), false),
38
-                'term_group' => new EE_Integer_Field('term_group', esc_html__("Term Group", "event_espresso"), false, 0),
39
-            ),
40
-        );
41
-        $this->_model_relations = array(
42
-            'Term_Taxonomy' => new EE_Has_Many_Relation(),
43
-        );
44
-        $this->_wp_core_model = true;
45
-        $path_to_tax_model = 'Term_Taxonomy';
46
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
47
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Taxonomy_Protected(
48
-            $path_to_tax_model
49
-        );
50
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = false;
51
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = false;
52
-        $path_to_tax_model = $path_to_tax_model . '.';
53
-        // add cap restrictions for editing relating to the "ee_edit_*"
54
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
55
-            array(
56
-                $path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
57
-            )
58
-        );
59
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
60
-            array(
61
-                $path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
62
-            )
63
-        );
64
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
65
-            array(
66
-                $path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
67
-            )
68
-        );
69
-        // add cap restrictions for deleting relating to the "ee_deleting_*"
70
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
71
-            array(
72
-                $path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
73
-            )
74
-        );
75
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
76
-            array(
77
-                $path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
78
-            )
79
-        );
80
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
81
-            array(
82
-                $path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
83
-            )
84
-        );
85
-        parent::__construct($timezone);
86
-        add_filter('FHEE__Read__create_model_query_params', array('EEM_Term', 'rest_api_query_params'), 10, 3);
87
-    }
21
+	/**
22
+	 *__construct
23
+	 *
24
+	 * @param string $timezone
25
+	 */
26
+	protected function __construct($timezone = null)
27
+	{
28
+		$this->singular_item = esc_html__('Term', 'event_espresso');
29
+		$this->plural_item = esc_html__('Terms', 'event_espresso');
30
+		$this->_tables = array(
31
+			'Term' => new EE_Primary_Table('terms', 'term_id'),
32
+		);
33
+		$this->_fields = array(
34
+			'Term' => array(
35
+				'term_id'    => new EE_Primary_Key_Int_Field('term_id', esc_html__('Term ID', 'event_espresso')),
36
+				'name'       => new EE_Plain_Text_Field('name', esc_html__('Term Name', 'event_espresso'), false, ''),
37
+				'slug'       => new EE_Slug_Field('slug', esc_html__('Term Slug', 'event_espresso'), false),
38
+				'term_group' => new EE_Integer_Field('term_group', esc_html__("Term Group", "event_espresso"), false, 0),
39
+			),
40
+		);
41
+		$this->_model_relations = array(
42
+			'Term_Taxonomy' => new EE_Has_Many_Relation(),
43
+		);
44
+		$this->_wp_core_model = true;
45
+		$path_to_tax_model = 'Term_Taxonomy';
46
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
47
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Taxonomy_Protected(
48
+			$path_to_tax_model
49
+		);
50
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = false;
51
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = false;
52
+		$path_to_tax_model = $path_to_tax_model . '.';
53
+		// add cap restrictions for editing relating to the "ee_edit_*"
54
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
55
+			array(
56
+				$path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
57
+			)
58
+		);
59
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
60
+			array(
61
+				$path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
62
+			)
63
+		);
64
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
65
+			array(
66
+				$path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
67
+			)
68
+		);
69
+		// add cap restrictions for deleting relating to the "ee_deleting_*"
70
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
71
+			array(
72
+				$path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
73
+			)
74
+		);
75
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
76
+			array(
77
+				$path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
78
+			)
79
+		);
80
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
81
+			array(
82
+				$path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
83
+			)
84
+		);
85
+		parent::__construct($timezone);
86
+		add_filter('FHEE__Read__create_model_query_params', array('EEM_Term', 'rest_api_query_params'), 10, 3);
87
+	}
88 88
 
89 89
 
90 90
 
91
-    /**
92
-     * retrieves a list of all EE event categories
93
-     *
94
-     * @access public
95
-     * @param bool $show_uncategorized
96
-     * @return \EE_Base_Class[]
97
-     */
98
-    public function get_all_ee_categories($show_uncategorized = false)
99
-    {
100
-        $where_params = array(
101
-            'Term_Taxonomy.taxonomy' => 'espresso_event_categories',
102
-            'NOT'                    => array('name' => esc_html__('Uncategorized', 'event_espresso')),
103
-        );
104
-        if ($show_uncategorized) {
105
-            unset($where_params['NOT']);
106
-        }
107
-        return EEM_Term::instance()->get_all(
108
-            array(
109
-                $where_params,
110
-                'order_by' => array('name' => 'ASC'),
111
-            )
112
-        );
113
-    }
91
+	/**
92
+	 * retrieves a list of all EE event categories
93
+	 *
94
+	 * @access public
95
+	 * @param bool $show_uncategorized
96
+	 * @return \EE_Base_Class[]
97
+	 */
98
+	public function get_all_ee_categories($show_uncategorized = false)
99
+	{
100
+		$where_params = array(
101
+			'Term_Taxonomy.taxonomy' => 'espresso_event_categories',
102
+			'NOT'                    => array('name' => esc_html__('Uncategorized', 'event_espresso')),
103
+		);
104
+		if ($show_uncategorized) {
105
+			unset($where_params['NOT']);
106
+		}
107
+		return EEM_Term::instance()->get_all(
108
+			array(
109
+				$where_params,
110
+				'order_by' => array('name' => 'ASC'),
111
+			)
112
+		);
113
+	}
114 114
 
115 115
 
116 116
 
117
-    /**
118
-     * retrieves a list of all post_tags associated with an EE CPT
119
-     *
120
-     * @access public
121
-     * @param string $post_type
122
-     * @return array
123
-     */
124
-    public function get_all_CPT_post_tags($post_type = '')
125
-    {
126
-        switch ($post_type) {
127
-            case 'espresso_events':
128
-                return $this->get_all_event_post_tags();
129
-                break;
130
-            case 'espresso_venues':
131
-                return $this->get_all_venue_post_tags();
132
-                break;
133
-            default:
134
-                $event_tags = $this->get_all_event_post_tags();
135
-                $venue_tags = $this->get_all_venue_post_tags();
136
-                return array_merge($event_tags, $venue_tags);
137
-        }
138
-    }
117
+	/**
118
+	 * retrieves a list of all post_tags associated with an EE CPT
119
+	 *
120
+	 * @access public
121
+	 * @param string $post_type
122
+	 * @return array
123
+	 */
124
+	public function get_all_CPT_post_tags($post_type = '')
125
+	{
126
+		switch ($post_type) {
127
+			case 'espresso_events':
128
+				return $this->get_all_event_post_tags();
129
+				break;
130
+			case 'espresso_venues':
131
+				return $this->get_all_venue_post_tags();
132
+				break;
133
+			default:
134
+				$event_tags = $this->get_all_event_post_tags();
135
+				$venue_tags = $this->get_all_venue_post_tags();
136
+				return array_merge($event_tags, $venue_tags);
137
+		}
138
+	}
139 139
 
140 140
 
141
-    /**
142
-     * returns an EE_Term object for the given tag
143
-     * if it has been utilized by any EE_Events or EE_Venues
144
-     *
145
-     * @param string $tag
146
-     * @return EE_Term|null
147
-     * @throws EE_Error
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     */
152
-    public function get_post_tag_for_event_or_venue($tag)
153
-    {
154
-        $post_tag_results = $this->get_all_wpdb_results(
155
-            array(
156
-                array(
157
-                    'slug' => $tag,
158
-                    'Term_Taxonomy.taxonomy' => 'post_tag',
159
-                    'OR' => array(
160
-                        'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
161
-                        'Term_Taxonomy.Event.post_type' => 'espresso_events',
162
-                    ),
163
-                ),
164
-                'default_where_conditions' => 'none',
165
-                'extra_selects' => array(
166
-                    'event_post_type' => array('Term_Taxonomy___Event_CPT.post_type', '%s'),
167
-                    'venue_post_type' => array('Term_Taxonomy___Venue_CPT.post_type', '%s')
168
-                ),
169
-                'group_by' => array(
170
-                    'event_post_type',
171
-                    'venue_post_type',
172
-                ),
173
-                'limit' => 2
174
-            )
175
-        );
176
-        if (! $post_tag_results) {
177
-            return null;
178
-        }
141
+	/**
142
+	 * returns an EE_Term object for the given tag
143
+	 * if it has been utilized by any EE_Events or EE_Venues
144
+	 *
145
+	 * @param string $tag
146
+	 * @return EE_Term|null
147
+	 * @throws EE_Error
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 */
152
+	public function get_post_tag_for_event_or_venue($tag)
153
+	{
154
+		$post_tag_results = $this->get_all_wpdb_results(
155
+			array(
156
+				array(
157
+					'slug' => $tag,
158
+					'Term_Taxonomy.taxonomy' => 'post_tag',
159
+					'OR' => array(
160
+						'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
161
+						'Term_Taxonomy.Event.post_type' => 'espresso_events',
162
+					),
163
+				),
164
+				'default_where_conditions' => 'none',
165
+				'extra_selects' => array(
166
+					'event_post_type' => array('Term_Taxonomy___Event_CPT.post_type', '%s'),
167
+					'venue_post_type' => array('Term_Taxonomy___Venue_CPT.post_type', '%s')
168
+				),
169
+				'group_by' => array(
170
+					'event_post_type',
171
+					'venue_post_type',
172
+				),
173
+				'limit' => 2
174
+			)
175
+		);
176
+		if (! $post_tag_results) {
177
+			return null;
178
+		}
179 179
 
180
-        $post_types = array();
181
-        foreach ((array) $post_tag_results as $row) {
182
-            if ($row['event_post_type'] === 'espresso_events') {
183
-                $post_types[] = EEM_Event::instance()->post_type();
184
-            } elseif ($row['venue_post_type'] === 'espresso_venues') {
185
-                $post_types[] = EEM_Venue::instance()->post_type();
186
-            }
187
-        }
188
-        $post_tag_row = reset($post_tag_results);
189
-        $post_tag = $this->instantiate_class_from_array_or_object($post_tag_row);
190
-        if (! $post_tag instanceof EE_Term) {
191
-            return null;
192
-        }
180
+		$post_types = array();
181
+		foreach ((array) $post_tag_results as $row) {
182
+			if ($row['event_post_type'] === 'espresso_events') {
183
+				$post_types[] = EEM_Event::instance()->post_type();
184
+			} elseif ($row['venue_post_type'] === 'espresso_venues') {
185
+				$post_types[] = EEM_Venue::instance()->post_type();
186
+			}
187
+		}
188
+		$post_tag_row = reset($post_tag_results);
189
+		$post_tag = $this->instantiate_class_from_array_or_object($post_tag_row);
190
+		if (! $post_tag instanceof EE_Term) {
191
+			return null;
192
+		}
193 193
 
194
-        if ($post_tag->post_type === null) {
195
-            $post_tag->post_type = array();
196
-        }
197
-        $post_tag->post_type = array_merge($post_tag->post_type, array_unique($post_types));
198
-        return $post_tag;
199
-    }
194
+		if ($post_tag->post_type === null) {
195
+			$post_tag->post_type = array();
196
+		}
197
+		$post_tag->post_type = array_merge($post_tag->post_type, array_unique($post_types));
198
+		return $post_tag;
199
+	}
200 200
 
201 201
 
202 202
 
203
-    /**
204
-     * get_all_event_post_tags
205
-     *
206
-     * @return EE_Base_Class[]
207
-     */
208
-    public function get_all_event_post_tags()
209
-    {
210
-        $post_tags = EEM_Term::instance()->get_all(
211
-            array(
212
-                array(
213
-                    'Term_Taxonomy.taxonomy'        => 'post_tag',
214
-                    'Term_Taxonomy.Event.post_type' => 'espresso_events',
215
-                ),
216
-                'order_by'   => array('name' => 'ASC'),
217
-                'force_join' => array('Term_Taxonomy.Event'),
218
-            )
219
-        );
220
-        foreach ($post_tags as $key => $post_tag) {
221
-            if (! isset($post_tags[ $key ]->post_type)) {
222
-                $post_tags[ $key ]->post_type = array();
223
-            }
224
-            $post_tags[ $key ]->post_type[] = 'espresso_events';
225
-        }
226
-        return $post_tags;
227
-    }
203
+	/**
204
+	 * get_all_event_post_tags
205
+	 *
206
+	 * @return EE_Base_Class[]
207
+	 */
208
+	public function get_all_event_post_tags()
209
+	{
210
+		$post_tags = EEM_Term::instance()->get_all(
211
+			array(
212
+				array(
213
+					'Term_Taxonomy.taxonomy'        => 'post_tag',
214
+					'Term_Taxonomy.Event.post_type' => 'espresso_events',
215
+				),
216
+				'order_by'   => array('name' => 'ASC'),
217
+				'force_join' => array('Term_Taxonomy.Event'),
218
+			)
219
+		);
220
+		foreach ($post_tags as $key => $post_tag) {
221
+			if (! isset($post_tags[ $key ]->post_type)) {
222
+				$post_tags[ $key ]->post_type = array();
223
+			}
224
+			$post_tags[ $key ]->post_type[] = 'espresso_events';
225
+		}
226
+		return $post_tags;
227
+	}
228 228
 
229 229
 
230 230
 
231
-    /**
232
-     * get_all_venue_post_tags
233
-     *
234
-     * @return EE_Base_Class[]
235
-     */
236
-    public function get_all_venue_post_tags()
237
-    {
238
-        $post_tags = EEM_Term::instance()->get_all(
239
-            array(
240
-                array(
241
-                    'Term_Taxonomy.taxonomy'        => 'post_tag',
242
-                    'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
243
-                ),
244
-                'order_by'   => array('name' => 'ASC'),
245
-                'force_join' => array('Term_Taxonomy'),
246
-            )
247
-        );
248
-        foreach ($post_tags as $key => $post_tag) {
249
-            if (! isset($post_tags[ $key ]->post_type)) {
250
-                $post_tags[ $key ]->post_type = array();
251
-            }
252
-            $post_tags[ $key ]->post_type[] = 'espresso_venues';
253
-        }
254
-        return $post_tags;
255
-    }
231
+	/**
232
+	 * get_all_venue_post_tags
233
+	 *
234
+	 * @return EE_Base_Class[]
235
+	 */
236
+	public function get_all_venue_post_tags()
237
+	{
238
+		$post_tags = EEM_Term::instance()->get_all(
239
+			array(
240
+				array(
241
+					'Term_Taxonomy.taxonomy'        => 'post_tag',
242
+					'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
243
+				),
244
+				'order_by'   => array('name' => 'ASC'),
245
+				'force_join' => array('Term_Taxonomy'),
246
+			)
247
+		);
248
+		foreach ($post_tags as $key => $post_tag) {
249
+			if (! isset($post_tags[ $key ]->post_type)) {
250
+				$post_tags[ $key ]->post_type = array();
251
+			}
252
+			$post_tags[ $key ]->post_type[] = 'espresso_venues';
253
+		}
254
+		return $post_tags;
255
+	}
256 256
 
257 257
 
258 258
 
259
-    /**
260
-     * Makes sure that during REST API queries, we only return terms
261
-     * for term taxonomies which should be shown in the rest api
262
-     *
263
-     * @param array    $model_query_params
264
-     * @param array    $querystring_query_params
265
-     * @param EEM_Base $model
266
-     * @return array
267
-     */
268
-    public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
269
-    {
270
-        if ($model === EEM_Term::instance()) {
271
-            $taxonomies = get_taxonomies(array('show_in_rest' => true));
272
-            if (! empty($taxonomies)) {
273
-                $model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
274
-            }
275
-        }
276
-        return $model_query_params;
277
-    }
259
+	/**
260
+	 * Makes sure that during REST API queries, we only return terms
261
+	 * for term taxonomies which should be shown in the rest api
262
+	 *
263
+	 * @param array    $model_query_params
264
+	 * @param array    $querystring_query_params
265
+	 * @param EEM_Base $model
266
+	 * @return array
267
+	 */
268
+	public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
269
+	{
270
+		if ($model === EEM_Term::instance()) {
271
+			$taxonomies = get_taxonomies(array('show_in_rest' => true));
272
+			if (! empty($taxonomies)) {
273
+				$model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
274
+			}
275
+		}
276
+		return $model_query_params;
277
+	}
278 278
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -43,43 +43,43 @@  discard block
 block discarded – undo
43 43
         );
44 44
         $this->_wp_core_model = true;
45 45
         $path_to_tax_model = 'Term_Taxonomy';
46
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
47
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Taxonomy_Protected(
46
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
47
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Taxonomy_Protected(
48 48
             $path_to_tax_model
49 49
         );
50
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = false;
51
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = false;
52
-        $path_to_tax_model = $path_to_tax_model . '.';
50
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = false;
51
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = false;
52
+        $path_to_tax_model = $path_to_tax_model.'.';
53 53
         // add cap restrictions for editing relating to the "ee_edit_*"
54
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
54
+        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
55 55
             array(
56
-                $path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
56
+                $path_to_tax_model.'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
57 57
             )
58 58
         );
59
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
59
+        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
60 60
             array(
61
-                $path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
61
+                $path_to_tax_model.'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
62 62
             )
63 63
         );
64
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
64
+        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
65 65
             array(
66
-                $path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
66
+                $path_to_tax_model.'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
67 67
             )
68 68
         );
69 69
         // add cap restrictions for deleting relating to the "ee_deleting_*"
70
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
70
+        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
71 71
             array(
72
-                $path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
72
+                $path_to_tax_model.'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
73 73
             )
74 74
         );
75
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
75
+        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
76 76
             array(
77
-                $path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
77
+                $path_to_tax_model.'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
78 78
             )
79 79
         );
80
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
80
+        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
81 81
             array(
82
-                $path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
82
+                $path_to_tax_model.'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
83 83
             )
84 84
         );
85 85
         parent::__construct($timezone);
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
                 'limit' => 2
174 174
             )
175 175
         );
176
-        if (! $post_tag_results) {
176
+        if ( ! $post_tag_results) {
177 177
             return null;
178 178
         }
179 179
 
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
         }
188 188
         $post_tag_row = reset($post_tag_results);
189 189
         $post_tag = $this->instantiate_class_from_array_or_object($post_tag_row);
190
-        if (! $post_tag instanceof EE_Term) {
190
+        if ( ! $post_tag instanceof EE_Term) {
191 191
             return null;
192 192
         }
193 193
 
@@ -218,10 +218,10 @@  discard block
 block discarded – undo
218 218
             )
219 219
         );
220 220
         foreach ($post_tags as $key => $post_tag) {
221
-            if (! isset($post_tags[ $key ]->post_type)) {
222
-                $post_tags[ $key ]->post_type = array();
221
+            if ( ! isset($post_tags[$key]->post_type)) {
222
+                $post_tags[$key]->post_type = array();
223 223
             }
224
-            $post_tags[ $key ]->post_type[] = 'espresso_events';
224
+            $post_tags[$key]->post_type[] = 'espresso_events';
225 225
         }
226 226
         return $post_tags;
227 227
     }
@@ -246,10 +246,10 @@  discard block
 block discarded – undo
246 246
             )
247 247
         );
248 248
         foreach ($post_tags as $key => $post_tag) {
249
-            if (! isset($post_tags[ $key ]->post_type)) {
250
-                $post_tags[ $key ]->post_type = array();
249
+            if ( ! isset($post_tags[$key]->post_type)) {
250
+                $post_tags[$key]->post_type = array();
251 251
             }
252
-            $post_tags[ $key ]->post_type[] = 'espresso_venues';
252
+            $post_tags[$key]->post_type[] = 'espresso_venues';
253 253
         }
254 254
         return $post_tags;
255 255
     }
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
     {
270 270
         if ($model === EEM_Term::instance()) {
271 271
             $taxonomies = get_taxonomies(array('show_in_rest' => true));
272
-            if (! empty($taxonomies)) {
272
+            if ( ! empty($taxonomies)) {
273 273
                 $model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
274 274
             }
275 275
         }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Datetime_Field.php 2 patches
Indentation   +752 added lines, -752 removed lines patch added patch discarded remove patch
@@ -15,757 +15,757 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Datetime_Field extends EE_Model_Field_Base
17 17
 {
18
-    /**
19
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
20
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
21
-     *
22
-     * @type string unix_timestamp_regex
23
-     */
24
-    const unix_timestamp_regex = '/[0-9]{10,}/';
25
-
26
-    /**
27
-     * @type string mysql_timestamp_format
28
-     */
29
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
30
-
31
-    /**
32
-     * @type string mysql_date_format
33
-     */
34
-    const mysql_date_format = 'Y-m-d';
35
-
36
-    /**
37
-     * @type string mysql_time_format
38
-     */
39
-    const mysql_time_format = 'H:i:s';
40
-
41
-    /**
42
-     * Const for using in the default value. If the field's default is set to this,
43
-     * then we will return the time of calling `get_default_value()`, not
44
-     * just the current time at construction
45
-     */
46
-    const now = 'now';
47
-
48
-    /**
49
-     * The following properties hold the default formats for date and time.
50
-     * Defaults are set via the constructor and can be overridden on class instantiation.
51
-     * However they can also be overridden later by the set_format() method
52
-     * (and corresponding set_date_format, set_time_format methods);
53
-     */
54
-    /**
55
-     * @type string $_date_format
56
-     */
57
-    protected $_date_format = '';
58
-
59
-    /**
60
-     * @type string $_time_format
61
-     */
62
-    protected $_time_format = '';
63
-
64
-    /**
65
-     * @type string $_pretty_date_format
66
-     */
67
-    protected $_pretty_date_format = '';
68
-
69
-    /**
70
-     * @type string $_pretty_time_format
71
-     */
72
-    protected $_pretty_time_format = '';
73
-
74
-    /**
75
-     * @type DateTimeZone $_DateTimeZone
76
-     */
77
-    protected $_DateTimeZone;
78
-
79
-    /**
80
-     * @type DateTimeZone $_UTC_DateTimeZone
81
-     */
82
-    protected $_UTC_DateTimeZone;
83
-
84
-    /**
85
-     * @type DateTimeZone $_blog_DateTimeZone
86
-     */
87
-    protected $_blog_DateTimeZone;
88
-
89
-
90
-    /**
91
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
92
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
93
-     * and time returned via getters.
94
-     *
95
-     * @var mixed (null|string)
96
-     */
97
-    protected $_date_time_output;
98
-
99
-
100
-    /**
101
-     * timezone string
102
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
103
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
104
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
105
-     *
106
-     * @var string
107
-     */
108
-    protected $_timezone_string;
109
-
110
-
111
-    /**
112
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
113
-     * offsets for comparison purposes).
114
-     *
115
-     * @var int
116
-     */
117
-    protected $_blog_offset;
118
-
119
-
120
-
121
-    /**
122
-     * @param string $table_column
123
-     * @param string $nice_name
124
-     * @param bool   $nullable
125
-     * @param string $default_value
126
-     * @param string $timezone_string
127
-     * @param string $date_format
128
-     * @param string $time_format
129
-     * @param string $pretty_date_format
130
-     * @param string $pretty_time_format
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     */
134
-    public function __construct(
135
-        $table_column,
136
-        $nice_name,
137
-        $nullable,
138
-        $default_value,
139
-        $timezone_string = '',
140
-        $date_format = '',
141
-        $time_format = '',
142
-        $pretty_date_format = '',
143
-        $pretty_time_format = ''
144
-    ) {
145
-
146
-        $this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
147
-        $this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
148
-        $this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
149
-        $this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
150
-
151
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
152
-        $this->set_timezone($timezone_string);
153
-        $this->setSchemaFormat('date-time');
154
-    }
155
-
156
-
157
-    /**
158
-     * @return DateTimeZone
159
-     * @throws \EE_Error
160
-     */
161
-    public function get_UTC_DateTimeZone()
162
-    {
163
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
164
-            ? $this->_UTC_DateTimeZone
165
-            : $this->_create_timezone_object_from_timezone_string('UTC');
166
-    }
167
-
168
-
169
-    /**
170
-     * @return DateTimeZone
171
-     * @throws \EE_Error
172
-     */
173
-    public function get_blog_DateTimeZone()
174
-    {
175
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
176
-            ? $this->_blog_DateTimeZone
177
-            : $this->_create_timezone_object_from_timezone_string('');
178
-    }
179
-
180
-
181
-    /**
182
-     * this prepares any incoming date data and make sure its converted to a utc unix timestamp
183
-     *
184
-     * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
185
-     *                                                              timestamp
186
-     * @return DateTime
187
-     */
188
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
189
-    {
190
-        return $this->_get_date_object($value_inputted_for_field_on_model_object);
191
-    }
192
-
193
-
194
-    /**
195
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
196
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
197
-     *
198
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
199
-     * @return string    The final assembled format string.
200
-     */
201
-    protected function _get_date_time_output($pretty = false)
202
-    {
203
-
204
-        switch ($this->_date_time_output) {
205
-            case 'time':
206
-                return $pretty ? $this->_pretty_time_format : $this->_time_format;
207
-                break;
208
-
209
-            case 'date':
210
-                return $pretty ? $this->_pretty_date_format : $this->_date_format;
211
-                break;
212
-
213
-            default:
214
-                return $pretty
215
-                    ? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
216
-                    : trim($this->_date_format . ' ' . $this->_time_format);
217
-        }
218
-    }
219
-
220
-
221
-    /**
222
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
223
-     * returned (using the format properties)
224
-     *
225
-     * @param string $what acceptable values are 'time' or 'date'.
226
-     *                     Any other value will be set but will always result
227
-     *                     in both 'date' and 'time' being returned.
228
-     * @return void
229
-     */
230
-    public function set_date_time_output($what = null)
231
-    {
232
-        $this->_date_time_output = $what;
233
-    }
234
-
235
-
236
-    /**
237
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
238
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
239
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
240
-     * We also set some other properties in this method.
241
-     *
242
-     * @param string $timezone_string A valid timezone string as described by @link
243
-     *                                http://www.php.net/manual/en/timezones.php
244
-     * @return void
245
-     * @throws InvalidArgumentException
246
-     * @throws InvalidDataTypeException
247
-     * @throws InvalidInterfaceException
248
-     */
249
-    public function set_timezone($timezone_string)
250
-    {
251
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
252
-            // leave the timezone AS-IS if we already have one and
253
-            // the function arg didn't provide one
254
-            return;
255
-        }
256
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
257
-        $this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
258
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
259
-    }
260
-
261
-
262
-    /**
263
-     * _create_timezone_object_from_timezone_name
264
-     *
265
-     * @access protected
266
-     * @param string $timezone_string
267
-     * @return \DateTimeZone
268
-     * @throws InvalidArgumentException
269
-     * @throws InvalidDataTypeException
270
-     * @throws InvalidInterfaceException
271
-     */
272
-    protected function _create_timezone_object_from_timezone_string($timezone_string = '')
273
-    {
274
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
275
-    }
276
-
277
-
278
-    /**
279
-     * This just returns whatever is set for the current timezone.
280
-     *
281
-     * @access public
282
-     * @return string timezone string
283
-     */
284
-    public function get_timezone()
285
-    {
286
-        return $this->_timezone_string;
287
-    }
288
-
289
-
290
-    /**
291
-     * set the $_date_format property
292
-     *
293
-     * @access public
294
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
295
-     * @param bool   $pretty Whether to set pretty format or not.
296
-     * @return void
297
-     */
298
-    public function set_date_format($format, $pretty = false)
299
-    {
300
-        if ($pretty) {
301
-            $this->_pretty_date_format = $format;
302
-        } else {
303
-            $this->_date_format = $format;
304
-        }
305
-    }
306
-
307
-
308
-    /**
309
-     * return the $_date_format property value.
310
-     *
311
-     * @param bool $pretty Whether to get pretty format or not.
312
-     * @return string
313
-     */
314
-    public function get_date_format($pretty = false)
315
-    {
316
-        return $pretty ? $this->_pretty_date_format : $this->_date_format;
317
-    }
318
-
319
-
320
-    /**
321
-     * set the $_time_format property
322
-     *
323
-     * @access public
324
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
325
-     * @param bool   $pretty Whether to set pretty format or not.
326
-     * @return void
327
-     */
328
-    public function set_time_format($format, $pretty = false)
329
-    {
330
-        if ($pretty) {
331
-            $this->_pretty_time_format = $format;
332
-        } else {
333
-            $this->_time_format = $format;
334
-        }
335
-    }
336
-
337
-
338
-    /**
339
-     * return the $_time_format property value.
340
-     *
341
-     * @param bool $pretty Whether to get pretty format or not.
342
-     * @return string
343
-     */
344
-    public function get_time_format($pretty = false)
345
-    {
346
-        return $pretty ? $this->_pretty_time_format : $this->_time_format;
347
-    }
348
-
349
-
350
-    /**
351
-     * set the $_pretty_date_format property
352
-     *
353
-     * @access public
354
-     * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
355
-     * @return void
356
-     */
357
-    public function set_pretty_date_format($format)
358
-    {
359
-        $this->_pretty_date_format = $format;
360
-    }
361
-
362
-
363
-    /**
364
-     * set the $_pretty_time_format property
365
-     *
366
-     * @access public
367
-     * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
368
-     * @return void
369
-     */
370
-    public function set_pretty_time_format($format)
371
-    {
372
-        $this->_pretty_time_format = $format;
373
-    }
374
-
375
-
376
-    /**
377
-     * Only sets the time portion of the datetime.
378
-     *
379
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
380
-     * @param DateTime        $current            current DateTime object for the datetime field
381
-     * @return DateTime
382
-     */
383
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
384
-    {
385
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
386
-        // Otherwise parse the string.
387
-        if ($time_to_set_string instanceof DateTime) {
388
-            $parsed = array(
389
-                'hour'   => $time_to_set_string->format('H'),
390
-                'minute' => $time_to_set_string->format('i'),
391
-                'second' => $time_to_set_string->format('s'),
392
-            );
393
-        } else {
394
-            // parse incoming string
395
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
396
-        }
397
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
398
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
399
-    }
400
-
401
-
402
-    /**
403
-     * Only sets the date portion of the datetime.
404
-     *
405
-     * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
406
-     * @param DateTime        $current            current DateTime object for the datetime field
407
-     * @return DateTime
408
-     */
409
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
410
-    {
411
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
412
-        // Otherwise parse the string.
413
-        if ($date_to_set_string instanceof DateTime) {
414
-            $parsed = array(
415
-                'year'  => $date_to_set_string->format('Y'),
416
-                'month' => $date_to_set_string->format('m'),
417
-                'day'   => $date_to_set_string->format('d'),
418
-            );
419
-        } else {
420
-            // parse incoming string
421
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
422
-        }
423
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
424
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
425
-    }
426
-
427
-
428
-    /**
429
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
430
-     * datetime gets to this stage it should ALREADY be in UTC time
431
-     *
432
-     * @param  DateTime $DateTime
433
-     * @return string formatted date time for given timezone
434
-     * @throws \EE_Error
435
-     */
436
-    public function prepare_for_get($DateTime)
437
-    {
438
-        return $this->_prepare_for_display($DateTime);
439
-    }
440
-
441
-
442
-    /**
443
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
444
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
445
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
446
-     * abbreviation to the date_string.
447
-     *
448
-     * @param mixed $DateTime
449
-     * @param null  $schema
450
-     * @return string
451
-     * @throws \EE_Error
452
-     */
453
-    public function prepare_for_pretty_echoing($DateTime, $schema = null)
454
-    {
455
-        return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
456
-    }
457
-
458
-
459
-    /**
460
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
461
-     * timezone).
462
-     *
463
-     * @param DateTime    $DateTime
464
-     * @param bool|string $schema
465
-     * @return string
466
-     * @throws \EE_Error
467
-     */
468
-    protected function _prepare_for_display($DateTime, $schema = false)
469
-    {
470
-        if (! $DateTime instanceof DateTime) {
471
-            if ($this->_nullable) {
472
-                return '';
473
-            } else {
474
-                if (WP_DEBUG) {
475
-                    throw new EE_Error(
476
-                        sprintf(
477
-                            esc_html__(
478
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
479
-                                'event_espresso'
480
-                            ),
481
-                            $this->_nicename
482
-                        )
483
-                    );
484
-                } else {
485
-                    $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
486
-                    EE_Error::add_error(
487
-                        sprintf(
488
-                            esc_html__(
489
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
490
-                                'event_espresso'
491
-                            ),
492
-                            $this->_nicename
493
-                        )
494
-                    );
495
-                }
496
-            }
497
-        }
498
-        $format_string = $this->_get_date_time_output($schema);
499
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
500
-        if ($schema) {
501
-            if ($this->_display_timezone()) {
502
-                // must be explicit because schema could equal true.
503
-                if ($schema === 'no_html') {
504
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
505
-                } else {
506
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
507
-                }
508
-            } else {
509
-                $timezone_string = '';
510
-            }
511
-
512
-            return $DateTime->format($format_string) . $timezone_string;
513
-        }
514
-        return $DateTime->format($format_string);
515
-    }
516
-
517
-
518
-    /**
519
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
520
-     * timezone).
521
-     *
522
-     * @param  mixed $datetime_value u
523
-     * @return string mysql timestamp in UTC
524
-     * @throws \EE_Error
525
-     */
526
-    public function prepare_for_use_in_db($datetime_value)
527
-    {
528
-        // we allow an empty value or DateTime object, but nothing else.
529
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
530
-            throw new EE_Error(
531
-                sprintf(
532
-                    esc_html__(
533
-                        'The incoming value being prepared for setting in the database must either be empty or a php 
18
+	/**
19
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
20
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
21
+	 *
22
+	 * @type string unix_timestamp_regex
23
+	 */
24
+	const unix_timestamp_regex = '/[0-9]{10,}/';
25
+
26
+	/**
27
+	 * @type string mysql_timestamp_format
28
+	 */
29
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
30
+
31
+	/**
32
+	 * @type string mysql_date_format
33
+	 */
34
+	const mysql_date_format = 'Y-m-d';
35
+
36
+	/**
37
+	 * @type string mysql_time_format
38
+	 */
39
+	const mysql_time_format = 'H:i:s';
40
+
41
+	/**
42
+	 * Const for using in the default value. If the field's default is set to this,
43
+	 * then we will return the time of calling `get_default_value()`, not
44
+	 * just the current time at construction
45
+	 */
46
+	const now = 'now';
47
+
48
+	/**
49
+	 * The following properties hold the default formats for date and time.
50
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
51
+	 * However they can also be overridden later by the set_format() method
52
+	 * (and corresponding set_date_format, set_time_format methods);
53
+	 */
54
+	/**
55
+	 * @type string $_date_format
56
+	 */
57
+	protected $_date_format = '';
58
+
59
+	/**
60
+	 * @type string $_time_format
61
+	 */
62
+	protected $_time_format = '';
63
+
64
+	/**
65
+	 * @type string $_pretty_date_format
66
+	 */
67
+	protected $_pretty_date_format = '';
68
+
69
+	/**
70
+	 * @type string $_pretty_time_format
71
+	 */
72
+	protected $_pretty_time_format = '';
73
+
74
+	/**
75
+	 * @type DateTimeZone $_DateTimeZone
76
+	 */
77
+	protected $_DateTimeZone;
78
+
79
+	/**
80
+	 * @type DateTimeZone $_UTC_DateTimeZone
81
+	 */
82
+	protected $_UTC_DateTimeZone;
83
+
84
+	/**
85
+	 * @type DateTimeZone $_blog_DateTimeZone
86
+	 */
87
+	protected $_blog_DateTimeZone;
88
+
89
+
90
+	/**
91
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
92
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
93
+	 * and time returned via getters.
94
+	 *
95
+	 * @var mixed (null|string)
96
+	 */
97
+	protected $_date_time_output;
98
+
99
+
100
+	/**
101
+	 * timezone string
102
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
103
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
104
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
105
+	 *
106
+	 * @var string
107
+	 */
108
+	protected $_timezone_string;
109
+
110
+
111
+	/**
112
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
113
+	 * offsets for comparison purposes).
114
+	 *
115
+	 * @var int
116
+	 */
117
+	protected $_blog_offset;
118
+
119
+
120
+
121
+	/**
122
+	 * @param string $table_column
123
+	 * @param string $nice_name
124
+	 * @param bool   $nullable
125
+	 * @param string $default_value
126
+	 * @param string $timezone_string
127
+	 * @param string $date_format
128
+	 * @param string $time_format
129
+	 * @param string $pretty_date_format
130
+	 * @param string $pretty_time_format
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 */
134
+	public function __construct(
135
+		$table_column,
136
+		$nice_name,
137
+		$nullable,
138
+		$default_value,
139
+		$timezone_string = '',
140
+		$date_format = '',
141
+		$time_format = '',
142
+		$pretty_date_format = '',
143
+		$pretty_time_format = ''
144
+	) {
145
+
146
+		$this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
147
+		$this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
148
+		$this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
149
+		$this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
150
+
151
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
152
+		$this->set_timezone($timezone_string);
153
+		$this->setSchemaFormat('date-time');
154
+	}
155
+
156
+
157
+	/**
158
+	 * @return DateTimeZone
159
+	 * @throws \EE_Error
160
+	 */
161
+	public function get_UTC_DateTimeZone()
162
+	{
163
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
164
+			? $this->_UTC_DateTimeZone
165
+			: $this->_create_timezone_object_from_timezone_string('UTC');
166
+	}
167
+
168
+
169
+	/**
170
+	 * @return DateTimeZone
171
+	 * @throws \EE_Error
172
+	 */
173
+	public function get_blog_DateTimeZone()
174
+	{
175
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
176
+			? $this->_blog_DateTimeZone
177
+			: $this->_create_timezone_object_from_timezone_string('');
178
+	}
179
+
180
+
181
+	/**
182
+	 * this prepares any incoming date data and make sure its converted to a utc unix timestamp
183
+	 *
184
+	 * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
185
+	 *                                                              timestamp
186
+	 * @return DateTime
187
+	 */
188
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
189
+	{
190
+		return $this->_get_date_object($value_inputted_for_field_on_model_object);
191
+	}
192
+
193
+
194
+	/**
195
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
196
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
197
+	 *
198
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
199
+	 * @return string    The final assembled format string.
200
+	 */
201
+	protected function _get_date_time_output($pretty = false)
202
+	{
203
+
204
+		switch ($this->_date_time_output) {
205
+			case 'time':
206
+				return $pretty ? $this->_pretty_time_format : $this->_time_format;
207
+				break;
208
+
209
+			case 'date':
210
+				return $pretty ? $this->_pretty_date_format : $this->_date_format;
211
+				break;
212
+
213
+			default:
214
+				return $pretty
215
+					? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
216
+					: trim($this->_date_format . ' ' . $this->_time_format);
217
+		}
218
+	}
219
+
220
+
221
+	/**
222
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
223
+	 * returned (using the format properties)
224
+	 *
225
+	 * @param string $what acceptable values are 'time' or 'date'.
226
+	 *                     Any other value will be set but will always result
227
+	 *                     in both 'date' and 'time' being returned.
228
+	 * @return void
229
+	 */
230
+	public function set_date_time_output($what = null)
231
+	{
232
+		$this->_date_time_output = $what;
233
+	}
234
+
235
+
236
+	/**
237
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
238
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
239
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
240
+	 * We also set some other properties in this method.
241
+	 *
242
+	 * @param string $timezone_string A valid timezone string as described by @link
243
+	 *                                http://www.php.net/manual/en/timezones.php
244
+	 * @return void
245
+	 * @throws InvalidArgumentException
246
+	 * @throws InvalidDataTypeException
247
+	 * @throws InvalidInterfaceException
248
+	 */
249
+	public function set_timezone($timezone_string)
250
+	{
251
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
252
+			// leave the timezone AS-IS if we already have one and
253
+			// the function arg didn't provide one
254
+			return;
255
+		}
256
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
257
+		$this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
258
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
259
+	}
260
+
261
+
262
+	/**
263
+	 * _create_timezone_object_from_timezone_name
264
+	 *
265
+	 * @access protected
266
+	 * @param string $timezone_string
267
+	 * @return \DateTimeZone
268
+	 * @throws InvalidArgumentException
269
+	 * @throws InvalidDataTypeException
270
+	 * @throws InvalidInterfaceException
271
+	 */
272
+	protected function _create_timezone_object_from_timezone_string($timezone_string = '')
273
+	{
274
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
275
+	}
276
+
277
+
278
+	/**
279
+	 * This just returns whatever is set for the current timezone.
280
+	 *
281
+	 * @access public
282
+	 * @return string timezone string
283
+	 */
284
+	public function get_timezone()
285
+	{
286
+		return $this->_timezone_string;
287
+	}
288
+
289
+
290
+	/**
291
+	 * set the $_date_format property
292
+	 *
293
+	 * @access public
294
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
295
+	 * @param bool   $pretty Whether to set pretty format or not.
296
+	 * @return void
297
+	 */
298
+	public function set_date_format($format, $pretty = false)
299
+	{
300
+		if ($pretty) {
301
+			$this->_pretty_date_format = $format;
302
+		} else {
303
+			$this->_date_format = $format;
304
+		}
305
+	}
306
+
307
+
308
+	/**
309
+	 * return the $_date_format property value.
310
+	 *
311
+	 * @param bool $pretty Whether to get pretty format or not.
312
+	 * @return string
313
+	 */
314
+	public function get_date_format($pretty = false)
315
+	{
316
+		return $pretty ? $this->_pretty_date_format : $this->_date_format;
317
+	}
318
+
319
+
320
+	/**
321
+	 * set the $_time_format property
322
+	 *
323
+	 * @access public
324
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
325
+	 * @param bool   $pretty Whether to set pretty format or not.
326
+	 * @return void
327
+	 */
328
+	public function set_time_format($format, $pretty = false)
329
+	{
330
+		if ($pretty) {
331
+			$this->_pretty_time_format = $format;
332
+		} else {
333
+			$this->_time_format = $format;
334
+		}
335
+	}
336
+
337
+
338
+	/**
339
+	 * return the $_time_format property value.
340
+	 *
341
+	 * @param bool $pretty Whether to get pretty format or not.
342
+	 * @return string
343
+	 */
344
+	public function get_time_format($pretty = false)
345
+	{
346
+		return $pretty ? $this->_pretty_time_format : $this->_time_format;
347
+	}
348
+
349
+
350
+	/**
351
+	 * set the $_pretty_date_format property
352
+	 *
353
+	 * @access public
354
+	 * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
355
+	 * @return void
356
+	 */
357
+	public function set_pretty_date_format($format)
358
+	{
359
+		$this->_pretty_date_format = $format;
360
+	}
361
+
362
+
363
+	/**
364
+	 * set the $_pretty_time_format property
365
+	 *
366
+	 * @access public
367
+	 * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
368
+	 * @return void
369
+	 */
370
+	public function set_pretty_time_format($format)
371
+	{
372
+		$this->_pretty_time_format = $format;
373
+	}
374
+
375
+
376
+	/**
377
+	 * Only sets the time portion of the datetime.
378
+	 *
379
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
380
+	 * @param DateTime        $current            current DateTime object for the datetime field
381
+	 * @return DateTime
382
+	 */
383
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
384
+	{
385
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
386
+		// Otherwise parse the string.
387
+		if ($time_to_set_string instanceof DateTime) {
388
+			$parsed = array(
389
+				'hour'   => $time_to_set_string->format('H'),
390
+				'minute' => $time_to_set_string->format('i'),
391
+				'second' => $time_to_set_string->format('s'),
392
+			);
393
+		} else {
394
+			// parse incoming string
395
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
396
+		}
397
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
398
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
399
+	}
400
+
401
+
402
+	/**
403
+	 * Only sets the date portion of the datetime.
404
+	 *
405
+	 * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
406
+	 * @param DateTime        $current            current DateTime object for the datetime field
407
+	 * @return DateTime
408
+	 */
409
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
410
+	{
411
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
412
+		// Otherwise parse the string.
413
+		if ($date_to_set_string instanceof DateTime) {
414
+			$parsed = array(
415
+				'year'  => $date_to_set_string->format('Y'),
416
+				'month' => $date_to_set_string->format('m'),
417
+				'day'   => $date_to_set_string->format('d'),
418
+			);
419
+		} else {
420
+			// parse incoming string
421
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
422
+		}
423
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
424
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
425
+	}
426
+
427
+
428
+	/**
429
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
430
+	 * datetime gets to this stage it should ALREADY be in UTC time
431
+	 *
432
+	 * @param  DateTime $DateTime
433
+	 * @return string formatted date time for given timezone
434
+	 * @throws \EE_Error
435
+	 */
436
+	public function prepare_for_get($DateTime)
437
+	{
438
+		return $this->_prepare_for_display($DateTime);
439
+	}
440
+
441
+
442
+	/**
443
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
444
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
445
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
446
+	 * abbreviation to the date_string.
447
+	 *
448
+	 * @param mixed $DateTime
449
+	 * @param null  $schema
450
+	 * @return string
451
+	 * @throws \EE_Error
452
+	 */
453
+	public function prepare_for_pretty_echoing($DateTime, $schema = null)
454
+	{
455
+		return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
456
+	}
457
+
458
+
459
+	/**
460
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
461
+	 * timezone).
462
+	 *
463
+	 * @param DateTime    $DateTime
464
+	 * @param bool|string $schema
465
+	 * @return string
466
+	 * @throws \EE_Error
467
+	 */
468
+	protected function _prepare_for_display($DateTime, $schema = false)
469
+	{
470
+		if (! $DateTime instanceof DateTime) {
471
+			if ($this->_nullable) {
472
+				return '';
473
+			} else {
474
+				if (WP_DEBUG) {
475
+					throw new EE_Error(
476
+						sprintf(
477
+							esc_html__(
478
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
479
+								'event_espresso'
480
+							),
481
+							$this->_nicename
482
+						)
483
+					);
484
+				} else {
485
+					$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
486
+					EE_Error::add_error(
487
+						sprintf(
488
+							esc_html__(
489
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
490
+								'event_espresso'
491
+							),
492
+							$this->_nicename
493
+						)
494
+					);
495
+				}
496
+			}
497
+		}
498
+		$format_string = $this->_get_date_time_output($schema);
499
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
500
+		if ($schema) {
501
+			if ($this->_display_timezone()) {
502
+				// must be explicit because schema could equal true.
503
+				if ($schema === 'no_html') {
504
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
505
+				} else {
506
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
507
+				}
508
+			} else {
509
+				$timezone_string = '';
510
+			}
511
+
512
+			return $DateTime->format($format_string) . $timezone_string;
513
+		}
514
+		return $DateTime->format($format_string);
515
+	}
516
+
517
+
518
+	/**
519
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
520
+	 * timezone).
521
+	 *
522
+	 * @param  mixed $datetime_value u
523
+	 * @return string mysql timestamp in UTC
524
+	 * @throws \EE_Error
525
+	 */
526
+	public function prepare_for_use_in_db($datetime_value)
527
+	{
528
+		// we allow an empty value or DateTime object, but nothing else.
529
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
530
+			throw new EE_Error(
531
+				sprintf(
532
+					esc_html__(
533
+						'The incoming value being prepared for setting in the database must either be empty or a php 
534 534
             		    DateTime object, instead of: %1$s %2$s',
535
-                        'event_espresso'
536
-                    ),
537
-                    '<br />',
538
-                    print_r($datetime_value, true)
539
-                )
540
-            );
541
-        }
542
-
543
-        if ($datetime_value instanceof DateTime) {
544
-            if (! $datetime_value instanceof DbSafeDateTime) {
545
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
546
-            }
547
-            EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
548
-            return $datetime_value->format(
549
-                EE_Datetime_Field::mysql_timestamp_format
550
-            );
551
-        }
552
-
553
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
554
-        return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
555
-    }
556
-
557
-
558
-    /**
559
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
560
-     * allowed)
561
-     *
562
-     * @param string $datetime_string mysql timestamp in UTC
563
-     * @return  mixed null | DateTime
564
-     * @throws \EE_Error
565
-     */
566
-    public function prepare_for_set_from_db($datetime_string)
567
-    {
568
-        // if $datetime_value is empty, and ! $this->_nullable, just use time()
569
-        if (empty($datetime_string) && $this->_nullable) {
570
-            return null;
571
-        }
572
-        // datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
573
-        if (empty($datetime_string)) {
574
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
575
-        } else {
576
-            $DateTime = DbSafeDateTime::createFromFormat(
577
-                EE_Datetime_Field::mysql_timestamp_format,
578
-                $datetime_string,
579
-                $this->get_UTC_DateTimeZone()
580
-            );
581
-        }
582
-
583
-        if (! $DateTime instanceof DbSafeDateTime) {
584
-            // if still no datetime object, then let's just use now
585
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
586
-        }
587
-        // THEN apply the field's set DateTimeZone
588
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
589
-        return $DateTime;
590
-    }
591
-
592
-
593
-    /**
594
-     * All this method does is determine if we're going to display the timezone string or not on any output.
595
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
596
-     * If so, then true.
597
-     *
598
-     * @return bool true for yes false for no
599
-     * @throws \EE_Error
600
-     */
601
-    protected function _display_timezone()
602
-    {
603
-
604
-        // first let's do a comparison of timezone strings.
605
-        // If they match then we can get out without any further calculations
606
-        $blog_string = get_option('timezone_string');
607
-        if ($blog_string === $this->_timezone_string) {
608
-            return false;
609
-        }
610
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
611
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
612
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
613
-        // now compare
614
-        return $blog_offset !== $this_offset;
615
-    }
616
-
617
-
618
-    /**
619
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
620
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
621
-     * with.
622
-     *
623
-     * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
624
-     *                                                    in the format that is set on the date_field (or DateTime
625
-     *                                                    object)!
626
-     * @return DateTime
627
-     */
628
-    protected function _get_date_object($date_string)
629
-    {
630
-        // first if this is an empty date_string and nullable is allowed, just return null.
631
-        if ($this->_nullable && empty($date_string)) {
632
-            return null;
633
-        }
634
-
635
-        // if incoming date
636
-        if ($date_string instanceof DateTime) {
637
-            EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
638
-            return $date_string;
639
-        }
640
-        // if empty date_string and made it here.
641
-        // Return a datetime object for now in the given timezone.
642
-        if (empty($date_string)) {
643
-            return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
644
-        }
645
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
646
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
647
-            try {
648
-                // This is operating under the assumption that the incoming Unix timestamp
649
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
650
-                $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
651
-                $DateTime->setTimestamp($date_string);
652
-
653
-                return $DateTime;
654
-            } catch (Exception $e) {
655
-                // should be rare, but if things got fooled then let's just continue
656
-            }
657
-        }
658
-        // not a unix timestamp.  So we will use the set format on this object and set timezone to
659
-        // create the DateTime object.
660
-        $format = $this->_date_format . ' ' . $this->_time_format;
661
-        try {
662
-            $DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
663
-            if (! $DateTime instanceof DbSafeDateTime) {
664
-                throw new EE_Error(
665
-                    sprintf(
666
-                        esc_html__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
667
-                        $date_string,
668
-                        $format
669
-                    )
670
-                );
671
-            }
672
-        } catch (Exception $e) {
673
-            // if we made it here then likely then something went really wrong.
674
-            // Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
675
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
676
-        }
677
-
678
-        return $DateTime;
679
-    }
680
-
681
-
682
-
683
-    /**
684
-     * get_timezone_transitions
685
-     *
686
-     * @param \DateTimeZone $DateTimeZone
687
-     * @param int           $time
688
-     * @param bool          $first_only
689
-     * @return mixed
690
-     */
691
-    public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
692
-    {
693
-        return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
694
-    }
695
-
696
-
697
-
698
-    /**
699
-     * get_timezone_offset
700
-     *
701
-     * @param \DateTimeZone $DateTimeZone
702
-     * @param int           $time
703
-     * @return mixed
704
-     * @throws \DomainException
705
-     */
706
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
707
-    {
708
-        return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
709
-    }
710
-
711
-
712
-    /**
713
-     * This will take an incoming timezone string and return the abbreviation for that timezone
714
-     *
715
-     * @param  string $timezone_string
716
-     * @return string           abbreviation
717
-     * @throws \EE_Error
718
-     */
719
-    public function get_timezone_abbrev($timezone_string)
720
-    {
721
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
722
-        $dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
723
-
724
-        return $dateTime->format('T');
725
-    }
726
-
727
-    /**
728
-     * Overrides the parent to allow for having a dynamic "now" value
729
-     *
730
-     * @return mixed
731
-     */
732
-    public function get_default_value()
733
-    {
734
-        if ($this->_default_value === EE_Datetime_Field::now) {
735
-            return time();
736
-        } else {
737
-            return parent::get_default_value();
738
-        }
739
-    }
740
-
741
-    /**
742
-     * Gets the default datetime object from the field's default time
743
-     * @since 4.9.66.p
744
-     * @return DbSafeDateTime|null
745
-     * @throws InvalidArgumentException
746
-     * @throws InvalidDataTypeException
747
-     * @throws InvalidInterfaceException
748
-     */
749
-    public function getDefaultDateTimeObj()
750
-    {
751
-        $default_raw = $this->get_default_value();
752
-        if ($default_raw instanceof DateTime) {
753
-            return $default_raw;
754
-        } elseif (is_null($default_raw)) {
755
-            return $default_raw;
756
-        } else {
757
-            return new DbSafeDateTime(
758
-                $this->get_default_value(),
759
-                EEH_DTT_Helper::get_valid_timezone_string($this->get_timezone())
760
-            );
761
-        }
762
-    }
763
-
764
-    public function getSchemaDescription()
765
-    {
766
-        return sprintf(
767
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
768
-            $this->get_nicename()
769
-        );
770
-    }
535
+						'event_espresso'
536
+					),
537
+					'<br />',
538
+					print_r($datetime_value, true)
539
+				)
540
+			);
541
+		}
542
+
543
+		if ($datetime_value instanceof DateTime) {
544
+			if (! $datetime_value instanceof DbSafeDateTime) {
545
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
546
+			}
547
+			EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
548
+			return $datetime_value->format(
549
+				EE_Datetime_Field::mysql_timestamp_format
550
+			);
551
+		}
552
+
553
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
554
+		return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
555
+	}
556
+
557
+
558
+	/**
559
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
560
+	 * allowed)
561
+	 *
562
+	 * @param string $datetime_string mysql timestamp in UTC
563
+	 * @return  mixed null | DateTime
564
+	 * @throws \EE_Error
565
+	 */
566
+	public function prepare_for_set_from_db($datetime_string)
567
+	{
568
+		// if $datetime_value is empty, and ! $this->_nullable, just use time()
569
+		if (empty($datetime_string) && $this->_nullable) {
570
+			return null;
571
+		}
572
+		// datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
573
+		if (empty($datetime_string)) {
574
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
575
+		} else {
576
+			$DateTime = DbSafeDateTime::createFromFormat(
577
+				EE_Datetime_Field::mysql_timestamp_format,
578
+				$datetime_string,
579
+				$this->get_UTC_DateTimeZone()
580
+			);
581
+		}
582
+
583
+		if (! $DateTime instanceof DbSafeDateTime) {
584
+			// if still no datetime object, then let's just use now
585
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
586
+		}
587
+		// THEN apply the field's set DateTimeZone
588
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
589
+		return $DateTime;
590
+	}
591
+
592
+
593
+	/**
594
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
595
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
596
+	 * If so, then true.
597
+	 *
598
+	 * @return bool true for yes false for no
599
+	 * @throws \EE_Error
600
+	 */
601
+	protected function _display_timezone()
602
+	{
603
+
604
+		// first let's do a comparison of timezone strings.
605
+		// If they match then we can get out without any further calculations
606
+		$blog_string = get_option('timezone_string');
607
+		if ($blog_string === $this->_timezone_string) {
608
+			return false;
609
+		}
610
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
611
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
612
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
613
+		// now compare
614
+		return $blog_offset !== $this_offset;
615
+	}
616
+
617
+
618
+	/**
619
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
620
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
621
+	 * with.
622
+	 *
623
+	 * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
624
+	 *                                                    in the format that is set on the date_field (or DateTime
625
+	 *                                                    object)!
626
+	 * @return DateTime
627
+	 */
628
+	protected function _get_date_object($date_string)
629
+	{
630
+		// first if this is an empty date_string and nullable is allowed, just return null.
631
+		if ($this->_nullable && empty($date_string)) {
632
+			return null;
633
+		}
634
+
635
+		// if incoming date
636
+		if ($date_string instanceof DateTime) {
637
+			EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
638
+			return $date_string;
639
+		}
640
+		// if empty date_string and made it here.
641
+		// Return a datetime object for now in the given timezone.
642
+		if (empty($date_string)) {
643
+			return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
644
+		}
645
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
646
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
647
+			try {
648
+				// This is operating under the assumption that the incoming Unix timestamp
649
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
650
+				$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
651
+				$DateTime->setTimestamp($date_string);
652
+
653
+				return $DateTime;
654
+			} catch (Exception $e) {
655
+				// should be rare, but if things got fooled then let's just continue
656
+			}
657
+		}
658
+		// not a unix timestamp.  So we will use the set format on this object and set timezone to
659
+		// create the DateTime object.
660
+		$format = $this->_date_format . ' ' . $this->_time_format;
661
+		try {
662
+			$DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
663
+			if (! $DateTime instanceof DbSafeDateTime) {
664
+				throw new EE_Error(
665
+					sprintf(
666
+						esc_html__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
667
+						$date_string,
668
+						$format
669
+					)
670
+				);
671
+			}
672
+		} catch (Exception $e) {
673
+			// if we made it here then likely then something went really wrong.
674
+			// Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
675
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
676
+		}
677
+
678
+		return $DateTime;
679
+	}
680
+
681
+
682
+
683
+	/**
684
+	 * get_timezone_transitions
685
+	 *
686
+	 * @param \DateTimeZone $DateTimeZone
687
+	 * @param int           $time
688
+	 * @param bool          $first_only
689
+	 * @return mixed
690
+	 */
691
+	public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
692
+	{
693
+		return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
694
+	}
695
+
696
+
697
+
698
+	/**
699
+	 * get_timezone_offset
700
+	 *
701
+	 * @param \DateTimeZone $DateTimeZone
702
+	 * @param int           $time
703
+	 * @return mixed
704
+	 * @throws \DomainException
705
+	 */
706
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
707
+	{
708
+		return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
709
+	}
710
+
711
+
712
+	/**
713
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
714
+	 *
715
+	 * @param  string $timezone_string
716
+	 * @return string           abbreviation
717
+	 * @throws \EE_Error
718
+	 */
719
+	public function get_timezone_abbrev($timezone_string)
720
+	{
721
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
722
+		$dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
723
+
724
+		return $dateTime->format('T');
725
+	}
726
+
727
+	/**
728
+	 * Overrides the parent to allow for having a dynamic "now" value
729
+	 *
730
+	 * @return mixed
731
+	 */
732
+	public function get_default_value()
733
+	{
734
+		if ($this->_default_value === EE_Datetime_Field::now) {
735
+			return time();
736
+		} else {
737
+			return parent::get_default_value();
738
+		}
739
+	}
740
+
741
+	/**
742
+	 * Gets the default datetime object from the field's default time
743
+	 * @since 4.9.66.p
744
+	 * @return DbSafeDateTime|null
745
+	 * @throws InvalidArgumentException
746
+	 * @throws InvalidDataTypeException
747
+	 * @throws InvalidInterfaceException
748
+	 */
749
+	public function getDefaultDateTimeObj()
750
+	{
751
+		$default_raw = $this->get_default_value();
752
+		if ($default_raw instanceof DateTime) {
753
+			return $default_raw;
754
+		} elseif (is_null($default_raw)) {
755
+			return $default_raw;
756
+		} else {
757
+			return new DbSafeDateTime(
758
+				$this->get_default_value(),
759
+				EEH_DTT_Helper::get_valid_timezone_string($this->get_timezone())
760
+			);
761
+		}
762
+	}
763
+
764
+	public function getSchemaDescription()
765
+	{
766
+		return sprintf(
767
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
768
+			$this->get_nicename()
769
+		);
770
+	}
771 771
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -212,8 +212,8 @@  discard block
 block discarded – undo
212 212
 
213 213
             default:
214 214
                 return $pretty
215
-                    ? trim($this->_pretty_date_format . ' ' . $this->_pretty_time_format)
216
-                    : trim($this->_date_format . ' ' . $this->_time_format);
215
+                    ? trim($this->_pretty_date_format.' '.$this->_pretty_time_format)
216
+                    : trim($this->_date_format.' '.$this->_time_format);
217 217
         }
218 218
     }
219 219
 
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
      */
468 468
     protected function _prepare_for_display($DateTime, $schema = false)
469 469
     {
470
-        if (! $DateTime instanceof DateTime) {
470
+        if ( ! $DateTime instanceof DateTime) {
471 471
             if ($this->_nullable) {
472 472
                 return '';
473 473
             } else {
@@ -501,15 +501,15 @@  discard block
 block discarded – undo
501 501
             if ($this->_display_timezone()) {
502 502
                 // must be explicit because schema could equal true.
503 503
                 if ($schema === 'no_html') {
504
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
504
+                    $timezone_string = ' ('.$DateTime->format('T').')';
505 505
                 } else {
506
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
506
+                    $timezone_string = ' <span class="ee_dtt_timezone_string">('.$DateTime->format('T').')</span>';
507 507
                 }
508 508
             } else {
509 509
                 $timezone_string = '';
510 510
             }
511 511
 
512
-            return $DateTime->format($format_string) . $timezone_string;
512
+            return $DateTime->format($format_string).$timezone_string;
513 513
         }
514 514
         return $DateTime->format($format_string);
515 515
     }
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
     public function prepare_for_use_in_db($datetime_value)
527 527
     {
528 528
         // we allow an empty value or DateTime object, but nothing else.
529
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
529
+        if ( ! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
530 530
             throw new EE_Error(
531 531
                 sprintf(
532 532
                     esc_html__(
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
         }
542 542
 
543 543
         if ($datetime_value instanceof DateTime) {
544
-            if (! $datetime_value instanceof DbSafeDateTime) {
544
+            if ( ! $datetime_value instanceof DbSafeDateTime) {
545 545
                 $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
546 546
             }
547 547
             EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
             );
581 581
         }
582 582
 
583
-        if (! $DateTime instanceof DbSafeDateTime) {
583
+        if ( ! $DateTime instanceof DbSafeDateTime) {
584 584
             // if still no datetime object, then let's just use now
585 585
             $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
586 586
         }
@@ -657,10 +657,10 @@  discard block
 block discarded – undo
657 657
         }
658 658
         // not a unix timestamp.  So we will use the set format on this object and set timezone to
659 659
         // create the DateTime object.
660
-        $format = $this->_date_format . ' ' . $this->_time_format;
660
+        $format = $this->_date_format.' '.$this->_time_format;
661 661
         try {
662 662
             $DateTime = DbSafeDateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
663
-            if (! $DateTime instanceof DbSafeDateTime) {
663
+            if ( ! $DateTime instanceof DbSafeDateTime) {
664 664
                 throw new EE_Error(
665 665
                     sprintf(
666 666
                         esc_html__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6582 added lines, -6582 removed lines patch added patch discarded remove patch
@@ -37,6590 +37,6590 @@
 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
-                /** @var $table_obj EE_Secondary_Table */
596
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
597
-            }
598
-        }
599
-        /**
600
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
601
-         * EE_Register_Model_Extension
602
-         *
603
-         * @param EE_Model_Field_Base[] $_fields
604
-         */
605
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
-        $this->_invalidate_field_caches();
607
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
608
-            if (! array_key_exists($table_alias, $this->_tables)) {
609
-                throw new EE_Error(
610
-                    sprintf(
611
-                        esc_html__(
612
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
613
-                            'event_espresso'
614
-                        ),
615
-                        $table_alias,
616
-                        implode(",", $this->_fields)
617
-                    )
618
-                );
619
-            }
620
-            foreach ($fields_for_table as $field_name => $field_obj) {
621
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
622
-                // primary key field base has a slightly different _construct_finalize
623
-                /** @var $field_obj EE_Model_Field_Base */
624
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
625
-            }
626
-        }
627
-        // everything is related to Extra_Meta
628
-        if (get_class($this) !== 'EEM_Extra_Meta') {
629
-            // make extra meta related to everything, but don't block deleting things just
630
-            // because they have related extra meta info. For now just orphan those extra meta
631
-            // in the future we should automatically delete them
632
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
633
-        }
634
-        // and change logs
635
-        if (get_class($this) !== 'EEM_Change_Log') {
636
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
637
-        }
638
-        /**
639
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
640
-         * EE_Register_Model_Extension
641
-         *
642
-         * @param EE_Model_Relation_Base[] $_model_relations
643
-         */
644
-        $this->_model_relations = (array) apply_filters(
645
-            'FHEE__' . get_class($this) . '__construct__model_relations',
646
-            $this->_model_relations
647
-        );
648
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
649
-            /** @var $relation_obj EE_Model_Relation_Base */
650
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
651
-        }
652
-        foreach ($this->_indexes as $index_name => $index_obj) {
653
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
654
-        }
655
-        $this->set_timezone($timezone);
656
-        // finalize default where condition strategy, or set default
657
-        if (! $this->_default_where_conditions_strategy) {
658
-            // nothing was set during child constructor, so set default
659
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660
-        }
661
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
662
-        if (! $this->_minimum_where_conditions_strategy) {
663
-            // nothing was set during child constructor, so set default
664
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665
-        }
666
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
667
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
668
-        // to indicate to NOT set it, set it to the logical default
669
-        if ($this->_caps_slug === null) {
670
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
671
-        }
672
-        // initialize the standard cap restriction generators if none were specified by the child constructor
673
-        if (is_array($this->_cap_restriction_generators)) {
674
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678
-                        new EE_Restriction_Generator_Protected(),
679
-                        $cap_context,
680
-                        $this
681
-                    );
682
-                }
683
-            }
684
-        }
685
-        // if there are cap restriction generators, use them to make the default cap restrictions
686
-        if (is_array($this->_cap_restriction_generators)) {
687
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
-                if (! $generator_object) {
689
-                    continue;
690
-                }
691
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
692
-                    throw new EE_Error(
693
-                        sprintf(
694
-                            esc_html__(
695
-                                '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.',
696
-                                'event_espresso'
697
-                            ),
698
-                            $context,
699
-                            $this->get_this_model_name()
700
-                        )
701
-                    );
702
-                }
703
-                $action = $this->cap_action_for_context($context);
704
-                if (! $generator_object->construction_finalized()) {
705
-                    $generator_object->_construct_finalize($this, $action);
706
-                }
707
-            }
708
-        }
709
-        do_action('AHEE__' . get_class($this) . '__construct__end');
710
-    }
711
-
712
-
713
-    /**
714
-     * @return LoaderInterface
715
-     * @throws InvalidArgumentException
716
-     * @throws InvalidDataTypeException
717
-     * @throws InvalidInterfaceException
718
-     */
719
-    protected static function getLoader(): LoaderInterface
720
-    {
721
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
722
-            EEM_Base::$loader = LoaderFactory::getLoader();
723
-        }
724
-        return EEM_Base::$loader;
725
-    }
726
-
727
-
728
-    /**
729
-     * @return Mirror
730
-     * @since   $VID:$
731
-     */
732
-    private static function getMirror(): Mirror
733
-    {
734
-        if (! EEM_Base::$mirror instanceof Mirror) {
735
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736
-        }
737
-        return EEM_Base::$mirror;
738
-    }
739
-
740
-
741
-    /**
742
-     * @param string $model_class_Name
743
-     * @param string $timezone
744
-     * @return array
745
-     * @throws ReflectionException
746
-     * @since   $VID:$
747
-     */
748
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
749
-    {
750
-        $arguments = [$timezone];
751
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
752
-        if (count($params) > 1) {
753
-            if ($params[1]->getName() === 'model_field_factory') {
754
-                $arguments = [
755
-                    $timezone,
756
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
757
-                ];
758
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
759
-                $arguments = [
760
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
-                    $timezone,
762
-                ];
763
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
764
-                $arguments = [
765
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
766
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
767
-                    $timezone,
768
-                ];
769
-            }
770
-        }
771
-        return $arguments;
772
-    }
773
-
774
-
775
-    /**
776
-     * This function is a singleton method used to instantiate the Espresso_model object
777
-     *
778
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
779
-     *                                (and any incoming timezone data that gets saved).
780
-     *                                Note this just sends the timezone info to the date time model field objects.
781
-     *                                Default is NULL
782
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
783
-     * @return static (as in the concrete child class)
784
-     * @throws EE_Error
785
-     * @throws ReflectionException
786
-     */
787
-    public static function instance($timezone = null)
788
-    {
789
-        // check if instance of Espresso_model already exists
790
-        if (! static::$_instance instanceof static) {
791
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792
-            $model     = new static(...$arguments);
793
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
794
-            static::$_instance = $model;
795
-        }
796
-        // we might have a timezone set, let set_timezone decide what to do with it
797
-        if ($timezone) {
798
-            static::$_instance->set_timezone($timezone);
799
-        }
800
-        // Espresso_model object
801
-        return static::$_instance;
802
-    }
803
-
804
-
805
-    /**
806
-     * resets the model and returns it
807
-     *
808
-     * @param string|null $timezone
809
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
810
-     * all its properties reset; if it wasn't instantiated, returns null)
811
-     * @throws EE_Error
812
-     * @throws ReflectionException
813
-     * @throws InvalidArgumentException
814
-     * @throws InvalidDataTypeException
815
-     * @throws InvalidInterfaceException
816
-     */
817
-    public static function reset($timezone = null)
818
-    {
819
-        if (! static::$_instance instanceof EEM_Base) {
820
-            return null;
821
-        }
822
-        // Let's NOT swap out the current instance for a new one
823
-        // because if someone has a reference to it, we can't remove their reference.
824
-        // It's best to keep using the same reference but change the original object instead,
825
-        // so reset all its properties to their original values as defined in the class.
826
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
827
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828
-            // don't set instance to null like it was originally,
829
-            // but it's static anyways, and we're ignoring static properties (for now at least)
830
-            if (! isset($static_properties[ $property ])) {
831
-                static::$_instance->{$property} = $value;
832
-            }
833
-        }
834
-        // and then directly call its constructor again, like we would if we were creating a new one
835
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
836
-        static::$_instance->__construct(...$arguments);
837
-        return self::instance();
838
-    }
839
-
840
-
841
-    /**
842
-     * Used to set the $_model_query_blog_id static property.
843
-     *
844
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
845
-     *                      value for get_current_blog_id() will be used.
846
-     */
847
-    public static function set_model_query_blog_id($blog_id = 0)
848
-    {
849
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
850
-            ? (int) $blog_id
851
-            : get_current_blog_id();
852
-    }
853
-
854
-
855
-    /**
856
-     * Returns whatever is set as the internal $model_query_blog_id.
857
-     *
858
-     * @return int
859
-     */
860
-    public static function get_model_query_blog_id()
861
-    {
862
-        return EEM_Base::$_model_query_blog_id;
863
-    }
864
-
865
-
866
-    /**
867
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
868
-     *
869
-     * @param boolean $translated return localized strings or JUST the array.
870
-     * @return array
871
-     * @throws EE_Error
872
-     * @throws InvalidArgumentException
873
-     * @throws InvalidDataTypeException
874
-     * @throws InvalidInterfaceException
875
-     * @throws ReflectionException
876
-     */
877
-    public function status_array($translated = false)
878
-    {
879
-        if (! array_key_exists('Status', $this->_model_relations)) {
880
-            return [];
881
-        }
882
-        $model_name   = $this->get_this_model_name();
883
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
884
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
885
-        $status_array = [];
886
-        foreach ($stati as $status) {
887
-            $status_array[ $status->ID() ] = $status->get('STS_code');
888
-        }
889
-        return $translated
890
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
891
-            : $status_array;
892
-    }
893
-
894
-
895
-    /**
896
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
897
-     *
898
-     * @param array $query_params             @see
899
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
900
-     *                                        or if you have the development copy of EE you can view this at the path:
901
-     *                                        /docs/G--Model-System/model-query-params.md
902
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
903
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
904
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
905
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
906
-     *                                        EEM_Transaction::instance()->get_all( array( array(
907
-     *                                        'OR'=>array(
908
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
909
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
910
-     *                                        )
911
-     *                                        ),
912
-     *                                        'limit'=>10,
913
-     *                                        'group_by'=>'TXN_ID'
914
-     *                                        ));
915
-     *                                        get all the answers to the question titled "shirt size" for event with id
916
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
917
-     *                                        'Question.QST_display_text'=>'shirt size',
918
-     *                                        'Registration.Event.EVT_ID'=>12
919
-     *                                        ),
920
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
921
-     *                                        ));
922
-     * @throws EE_Error
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
-     */
945
-    public function alter_query_params_to_only_include_mine($query_params = [])
946
-    {
947
-        $wp_user_field_name = $this->wp_user_field_name();
948
-        if ($wp_user_field_name) {
949
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
950
-        }
951
-        return $query_params;
952
-    }
953
-
954
-
955
-    /**
956
-     * Returns the name of the field's name that points to the WP_User table
957
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
958
-     * foreign key to the WP_User table)
959
-     *
960
-     * @return string|boolean string on success, boolean false when there is no
961
-     * foreign key to the WP_User table
962
-     * @throws ReflectionException
963
-     * @throws ReflectionException
964
-     */
965
-    public function wp_user_field_name()
966
-    {
967
-        try {
968
-            if (! empty($this->_model_chain_to_wp_user)) {
969
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
970
-                $last_model_name              = end($models_to_follow_to_wp_users);
971
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
972
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
973
-            } else {
974
-                $model_with_fk_to_wp_users = $this;
975
-                $model_chain_to_wp_user    = '';
976
-            }
977
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
978
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
979
-        } catch (EE_Error $e) {
980
-            return false;
981
-        }
982
-    }
983
-
984
-
985
-    /**
986
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
987
-     * (or transiently-related model) has a foreign key to the wp_users table;
988
-     * useful for finding if model objects of this type are 'owned' by the current user.
989
-     * This is an empty string when the foreign key is on this model and when it isn't,
990
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
991
-     * (or transiently-related model)
992
-     *
993
-     * @return string
994
-     */
995
-    public function model_chain_to_wp_user()
996
-    {
997
-        return $this->_model_chain_to_wp_user;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1003
-     * like how registrations don't have a foreign key to wp_users, but the
1004
-     * events they are for are), or is unrelated to wp users.
1005
-     * generally available
1006
-     *
1007
-     * @return boolean
1008
-     */
1009
-    public function is_owned()
1010
-    {
1011
-        if ($this->model_chain_to_wp_user()) {
1012
-            return true;
1013
-        }
1014
-        try {
1015
-            $this->get_foreign_key_to('WP_User');
1016
-            return true;
1017
-        } catch (EE_Error $e) {
1018
-            return false;
1019
-        }
1020
-    }
1021
-
1022
-
1023
-    /**
1024
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1025
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1026
-     * the model)
1027
-     *
1028
-     * @param array  $query_params      @see
1029
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1030
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1031
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1032
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1033
-     *                                  override this and set the select to "*", or a specific column name, like
1034
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1035
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1036
-     *                                  the aliases used to refer to this selection, and values are to be
1037
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1038
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1039
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1040
-     * @throws EE_Error
1041
-     * @throws InvalidArgumentException
1042
-     */
1043
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1044
-    {
1045
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1046
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1047
-        $select_expressions       = $columns_to_select === null
1048
-            ? $this->_construct_default_select_sql($model_query_info)
1049
-            : '';
1050
-        if ($this->_custom_selections instanceof CustomSelects) {
1051
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1052
-            $select_expressions .= $select_expressions
1053
-                ? ', ' . $custom_expressions
1054
-                : $custom_expressions;
1055
-        }
1056
-
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1059
-    }
1060
-
1061
-
1062
-    /**
1063
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1064
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1065
-     * method of including extra select information.
1066
-     *
1067
-     * @param array             $query_params
1068
-     * @param null|array|string $columns_to_select
1069
-     * @return null|CustomSelects
1070
-     * @throws InvalidArgumentException
1071
-     */
1072
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1073
-    {
1074
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1075
-            return null;
1076
-        }
1077
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1078
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1079
-        return new CustomSelects($selects);
1080
-    }
1081
-
1082
-
1083
-    /**
1084
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1085
-     * but you can use the model query params to more easily
1086
-     * take care of joins, field preparation etc.
1087
-     *
1088
-     * @param array  $query_params      @see
1089
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1090
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1091
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1092
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1093
-     *                                  override this and set the select to "*", or a specific column name, like
1094
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1095
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1096
-     *                                  the aliases used to refer to this selection, and values are to be
1097
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1098
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1099
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1100
-     * @throws EE_Error
1101
-     */
1102
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1103
-    {
1104
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * For creating a custom select statement
1110
-     *
1111
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1112
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1113
-     *                                 SQL, and 1=>is the datatype
1114
-     * @return string
1115
-     * @throws EE_Error
1116
-     */
1117
-    private function _construct_select_from_input($columns_to_select)
1118
-    {
1119
-        if (is_array($columns_to_select)) {
1120
-            $select_sql_array = [];
1121
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1122
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1123
-                    throw new EE_Error(
1124
-                        sprintf(
1125
-                            esc_html__(
1126
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1127
-                                'event_espresso'
1128
-                            ),
1129
-                            $selection_and_datatype,
1130
-                            $alias
1131
-                        )
1132
-                    );
1133
-                }
1134
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1135
-                    throw new EE_Error(
1136
-                        sprintf(
1137
-                            esc_html__(
1138
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1139
-                                'event_espresso'
1140
-                            ),
1141
-                            $selection_and_datatype[1],
1142
-                            $selection_and_datatype[0],
1143
-                            $alias,
1144
-                            implode(', ', $this->_valid_wpdb_data_types)
1145
-                        )
1146
-                    );
1147
-                }
1148
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1149
-            }
1150
-            $columns_to_select_string = implode(', ', $select_sql_array);
1151
-        } else {
1152
-            $columns_to_select_string = $columns_to_select;
1153
-        }
1154
-        return $columns_to_select_string;
1155
-    }
1156
-
1157
-
1158
-    /**
1159
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1160
-     *
1161
-     * @return string
1162
-     * @throws EE_Error
1163
-     */
1164
-    public function primary_key_name()
1165
-    {
1166
-        return $this->get_primary_key_field()->get_name();
1167
-    }
1168
-
1169
-
1170
-    /**
1171
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1172
-     * If there is no primary key on this model, $id is treated as primary key string
1173
-     *
1174
-     * @param mixed $id int or string, depending on the type of the model's primary key
1175
-     * @return EE_Base_Class|mixed|null
1176
-     * @throws EE_Error
1177
-     */
1178
-    public function get_one_by_ID($id)
1179
-    {
1180
-        if ($this->get_from_entity_map($id)) {
1181
-            return $this->get_from_entity_map($id);
1182
-        }
1183
-        $model_object = $this->get_one(
1184
-            $this->alter_query_params_to_restrict_by_ID(
1185
-                $id,
1186
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1187
-            )
1188
-        );
1189
-        $className    = $this->_get_class_name();
1190
-        if ($model_object instanceof $className) {
1191
-            // make sure valid objects get added to the entity map
1192
-            // so that the next call to this method doesn't trigger another trip to the db
1193
-            $this->add_to_entity_map($model_object);
1194
-        }
1195
-        return $model_object;
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * Alters query parameters to only get items with this ID are returned.
1201
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1202
-     * or could just be a simple primary key ID
1203
-     *
1204
-     * @param int   $id
1205
-     * @param array $query_params
1206
-     * @return array of normal query params, @see
1207
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1208
-     * @throws EE_Error
1209
-     */
1210
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1211
-    {
1212
-        if (! isset($query_params[0])) {
1213
-            $query_params[0] = [];
1214
-        }
1215
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1216
-        if ($conditions_from_id === null) {
1217
-            $query_params[0][ $this->primary_key_name() ] = $id;
1218
-        } else {
1219
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1220
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1221
-        }
1222
-        return $query_params;
1223
-    }
1224
-
1225
-
1226
-    /**
1227
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1228
-     * array. If no item is found, null is returned.
1229
-     *
1230
-     * @param array $query_params like EEM_Base's $query_params variable.
1231
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1232
-     * @throws EE_Error
1233
-     */
1234
-    public function get_one($query_params = [])
1235
-    {
1236
-        if (! is_array($query_params)) {
1237
-            EE_Error::doing_it_wrong(
1238
-                'EEM_Base::get_one',
1239
-                sprintf(
1240
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1241
-                    gettype($query_params)
1242
-                ),
1243
-                '4.6.0'
1244
-            );
1245
-            $query_params = [];
1246
-        }
1247
-        $query_params['limit'] = 1;
1248
-        $items                 = $this->get_all($query_params);
1249
-        if (empty($items)) {
1250
-            return null;
1251
-        }
1252
-        return array_shift($items);
1253
-    }
1254
-
1255
-
1256
-    /**
1257
-     * Returns the next x number of items in sequence from the given value as
1258
-     * found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function next_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = [],
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive(
1280
-            $current_field_value,
1281
-            '>',
1282
-            $field_to_order_by,
1283
-            $limit,
1284
-            $query_params,
1285
-            $columns_to_select
1286
-        );
1287
-    }
1288
-
1289
-
1290
-    /**
1291
-     * Returns the previous x number of items in sequence from the given value
1292
-     * as found in the database matching the given query conditions.
1293
-     *
1294
-     * @param mixed $current_field_value    Value used for the reference point.
1295
-     * @param null  $field_to_order_by      What field is used for the
1296
-     *                                      reference point.
1297
-     * @param int   $limit                  How many to return.
1298
-     * @param array $query_params           Extra conditions on the query.
1299
-     * @param null  $columns_to_select      If left null, then an array of
1300
-     *                                      EE_Base_Class objects is returned,
1301
-     *                                      otherwise you can indicate just the
1302
-     *                                      columns you want returned.
1303
-     * @return EE_Base_Class[]|array
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function previous_x(
1307
-        $current_field_value,
1308
-        $field_to_order_by = null,
1309
-        $limit = 1,
1310
-        $query_params = [],
1311
-        $columns_to_select = null
1312
-    ) {
1313
-        return $this->_get_consecutive(
1314
-            $current_field_value,
1315
-            '<',
1316
-            $field_to_order_by,
1317
-            $limit,
1318
-            $query_params,
1319
-            $columns_to_select
1320
-        );
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * Returns the next item in sequence from the given value as found in the
1326
-     * database matching the given query conditions.
1327
-     *
1328
-     * @param mixed $current_field_value    Value used for the reference point.
1329
-     * @param null  $field_to_order_by      What field is used for the
1330
-     *                                      reference point.
1331
-     * @param array $query_params           Extra conditions on the query.
1332
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1333
-     *                                      object is returned, otherwise you
1334
-     *                                      can indicate just the columns you
1335
-     *                                      want and a single array indexed by
1336
-     *                                      the columns will be returned.
1337
-     * @return EE_Base_Class|null|array()
1338
-     * @throws EE_Error
1339
-     */
1340
-    public function next(
1341
-        $current_field_value,
1342
-        $field_to_order_by = null,
1343
-        $query_params = [],
1344
-        $columns_to_select = null
1345
-    ) {
1346
-        $results = $this->_get_consecutive(
1347
-            $current_field_value,
1348
-            '>',
1349
-            $field_to_order_by,
1350
-            1,
1351
-            $query_params,
1352
-            $columns_to_select
1353
-        );
1354
-        return empty($results) ? null : reset($results);
1355
-    }
1356
-
1357
-
1358
-    /**
1359
-     * Returns the previous item in sequence from the given value as found in
1360
-     * the database matching the given query conditions.
1361
-     *
1362
-     * @param mixed $current_field_value    Value used for the reference point.
1363
-     * @param null  $field_to_order_by      What field is used for the
1364
-     *                                      reference point.
1365
-     * @param array $query_params           Extra conditions on the query.
1366
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1367
-     *                                      object is returned, otherwise you
1368
-     *                                      can indicate just the columns you
1369
-     *                                      want and a single array indexed by
1370
-     *                                      the columns will be returned.
1371
-     * @return EE_Base_Class|null|array()
1372
-     * @throws EE_Error
1373
-     */
1374
-    public function previous(
1375
-        $current_field_value,
1376
-        $field_to_order_by = null,
1377
-        $query_params = [],
1378
-        $columns_to_select = null
1379
-    ) {
1380
-        $results = $this->_get_consecutive(
1381
-            $current_field_value,
1382
-            '<',
1383
-            $field_to_order_by,
1384
-            1,
1385
-            $query_params,
1386
-            $columns_to_select
1387
-        );
1388
-        return empty($results) ? null : reset($results);
1389
-    }
1390
-
1391
-
1392
-    /**
1393
-     * Returns the a consecutive number of items in sequence from the given
1394
-     * value as found in the database matching the given query conditions.
1395
-     *
1396
-     * @param mixed  $current_field_value   Value used for the reference point.
1397
-     * @param string $operand               What operand is used for the sequence.
1398
-     * @param string $field_to_order_by     What field is used for the reference point.
1399
-     * @param int    $limit                 How many to return.
1400
-     * @param array  $query_params          Extra conditions on the query.
1401
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1402
-     *                                      otherwise you can indicate just the columns you want returned.
1403
-     * @return EE_Base_Class[]|array
1404
-     * @throws EE_Error
1405
-     */
1406
-    protected function _get_consecutive(
1407
-        $current_field_value,
1408
-        $operand = '>',
1409
-        $field_to_order_by = null,
1410
-        $limit = 1,
1411
-        $query_params = [],
1412
-        $columns_to_select = null
1413
-    ) {
1414
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1415
-        if (empty($field_to_order_by)) {
1416
-            if ($this->has_primary_key_field()) {
1417
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1418
-            } else {
1419
-                if (WP_DEBUG) {
1420
-                    throw new EE_Error(
1421
-                        esc_html__(
1422
-                            '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).',
1423
-                            'event_espresso'
1424
-                        )
1425
-                    );
1426
-                }
1427
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1428
-                return [];
1429
-            }
1430
-        }
1431
-        if (! is_array($query_params)) {
1432
-            EE_Error::doing_it_wrong(
1433
-                'EEM_Base::_get_consecutive',
1434
-                sprintf(
1435
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1436
-                    gettype($query_params)
1437
-                ),
1438
-                '4.6.0'
1439
-            );
1440
-            $query_params = [];
1441
-        }
1442
-        // let's add the where query param for consecutive look up.
1443
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1444
-        $query_params['limit']                 = $limit;
1445
-        // set direction
1446
-        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1447
-        $query_params['order_by'] = $operand === '>'
1448
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1449
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1450
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
-        if (empty($columns_to_select)) {
1452
-            return $this->get_all($query_params);
1453
-        }
1454
-        // getting just the fields
1455
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * This sets the _timezone property after model object has been instantiated.
1461
-     *
1462
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1463
-     */
1464
-    public function set_timezone($timezone)
1465
-    {
1466
-        if ($timezone !== null) {
1467
-            $this->_timezone = $timezone;
1468
-        }
1469
-        // note we need to loop through relations and set the timezone on those objects as well.
1470
-        foreach ($this->_model_relations as $relation) {
1471
-            $relation->set_timezone($timezone);
1472
-        }
1473
-        // and finally we do the same for any datetime fields
1474
-        foreach ($this->_fields as $field) {
1475
-            if ($field instanceof EE_Datetime_Field) {
1476
-                $field->set_timezone($timezone);
1477
-            }
1478
-        }
1479
-    }
1480
-
1481
-
1482
-    /**
1483
-     * This just returns whatever is set for the current timezone.
1484
-     *
1485
-     * @access public
1486
-     * @return string
1487
-     */
1488
-    public function get_timezone()
1489
-    {
1490
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1491
-        if (empty($this->_timezone)) {
1492
-            foreach ($this->_fields as $field) {
1493
-                if ($field instanceof EE_Datetime_Field) {
1494
-                    $this->set_timezone($field->get_timezone());
1495
-                    break;
1496
-                }
1497
-            }
1498
-        }
1499
-        // if timezone STILL empty then return the default timezone for the site.
1500
-        if (empty($this->_timezone)) {
1501
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1502
-        }
1503
-        return $this->_timezone;
1504
-    }
1505
-
1506
-
1507
-    /**
1508
-     * This returns the date formats set for the given field name and also ensures that
1509
-     * $this->_timezone property is set correctly.
1510
-     *
1511
-     * @param string $field_name The name of the field the formats are being retrieved for.
1512
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513
-     * @return array formats in an array with the date format first, and the time format last.
1514
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1515
-     * @since 4.6.x
1516
-     */
1517
-    public function get_formats_for($field_name, $pretty = false)
1518
-    {
1519
-        $field_settings = $this->field_settings_for($field_name);
1520
-        // if not a valid EE_Datetime_Field then throw error
1521
-        if (! $field_settings instanceof EE_Datetime_Field) {
1522
-            throw new EE_Error(
1523
-                sprintf(
1524
-                    esc_html__(
1525
-                        '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.',
1526
-                        'event_espresso'
1527
-                    ),
1528
-                    $field_name
1529
-                )
1530
-            );
1531
-        }
1532
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1533
-        // the field.
1534
-        $this->_timezone = $field_settings->get_timezone();
1535
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * This returns the current time in a format setup for a query on this model.
1541
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1542
-     * it will return:
1543
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1544
-     *  NOW
1545
-     *  - or a unix timestamp (equivalent to time())
1546
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1547
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1548
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1549
-     *
1550
-     * @param string $field_name       The field the current time is needed for.
1551
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1552
-     *                                 formatted string matching the set format for the field in the set timezone will
1553
-     *                                 be returned.
1554
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1555
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1556
-     *                                 exception is triggered.
1557
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1558
-     * @since 4.6.x
1559
-     */
1560
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1561
-    {
1562
-        $formats  = $this->get_formats_for($field_name);
1563
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1564
-        if ($timestamp) {
1565
-            return $DateTime->format('U');
1566
-        }
1567
-        // not returning timestamp, so return formatted string in timezone.
1568
-        switch ($what) {
1569
-            case 'time':
1570
-                return $DateTime->format($formats[1]);
1571
-                break;
1572
-            case 'date':
1573
-                return $DateTime->format($formats[0]);
1574
-                break;
1575
-            default:
1576
-                return $DateTime->format(implode(' ', $formats));
1577
-                break;
1578
-        }
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1584
-     * for the model are.  Returns a DateTime object.
1585
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1586
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1587
-     * ignored.
1588
-     *
1589
-     * @param string $field_name      The field being setup.
1590
-     * @param string $timestring      The date time string being used.
1591
-     * @param string $incoming_format The format for the time string.
1592
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1593
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1594
-     *                                format is
1595
-     *                                'U', this is ignored.
1596
-     * @return DateTime
1597
-     * @throws EE_Error
1598
-     */
1599
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1600
-    {
1601
-        // just using this to ensure the timezone is set correctly internally
1602
-        $this->get_formats_for($field_name);
1603
-        // load EEH_DTT_Helper
1604
-        $set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1605
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1606
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1607
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1613
-     *
1614
-     * @return EE_Table_Base[]
1615
-     */
1616
-    public function get_tables()
1617
-    {
1618
-        return $this->_tables;
1619
-    }
1620
-
1621
-
1622
-    /**
1623
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1624
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1625
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1626
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1627
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1628
-     * model object with EVT_ID = 1
1629
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1630
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1631
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1632
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1633
-     * are not specified)
1634
-     *
1635
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1636
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1637
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1638
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1639
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1640
-     *                                         ID=34, we'd use this method as follows:
1641
-     *                                         EEM_Transaction::instance()->update(
1642
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1643
-     *                                         array(array('TXN_ID'=>34)));
1644
-     * @param array   $query_params            @see
1645
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1646
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1647
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1648
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1649
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1650
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1651
-     *                                         TRUE, it is assumed that you've already called
1652
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1653
-     *                                         malicious javascript. However, if
1654
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1655
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1656
-     *                                         and every other field, before insertion. We provide this parameter
1657
-     *                                         because model objects perform their prepare_for_set function on all
1658
-     *                                         their values, and so don't need to be called again (and in many cases,
1659
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1660
-     *                                         prepare_for_set method...)
1661
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1662
-     *                                         in this model's entity map according to $fields_n_values that match
1663
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1664
-     *                                         by setting this to FALSE, but be aware that model objects being used
1665
-     *                                         could get out-of-sync with the database
1666
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1667
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1668
-     *                                         bad)
1669
-     * @throws EE_Error
1670
-     * @throws ReflectionException
1671
-     */
1672
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1673
-    {
1674
-        if (! is_array($query_params)) {
1675
-            EE_Error::doing_it_wrong(
1676
-                'EEM_Base::update',
1677
-                sprintf(
1678
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1679
-                    gettype($query_params)
1680
-                ),
1681
-                '4.6.0'
1682
-            );
1683
-            $query_params = [];
1684
-        }
1685
-        /**
1686
-         * Action called before a model update call has been made.
1687
-         *
1688
-         * @param EEM_Base $model
1689
-         * @param array    $fields_n_values the updated fields and their new values
1690
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1691
-         */
1692
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1693
-        /**
1694
-         * Filters the fields about to be updated given the query parameters. You can provide the
1695
-         * $query_params to $this->get_all() to find exactly which records will be updated
1696
-         *
1697
-         * @param array    $fields_n_values fields and their new values
1698
-         * @param EEM_Base $model           the model being queried
1699
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1700
-         */
1701
-        $fields_n_values = (array) apply_filters(
1702
-            'FHEE__EEM_Base__update__fields_n_values',
1703
-            $fields_n_values,
1704
-            $this,
1705
-            $query_params
1706
-        );
1707
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1708
-        // to do that, for each table, verify that it's PK isn't null.
1709
-        $tables = $this->get_tables();
1710
-        // 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
1711
-        // NOTE: we should make this code more efficient by NOT querying twice
1712
-        // before the real update, but that needs to first go through ALPHA testing
1713
-        // as it's dangerous. says Mike August 8 2014
1714
-        // we want to make sure the default_where strategy is ignored
1715
-        $this->_ignore_where_strategy = true;
1716
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1717
-        foreach ($wpdb_select_results as $wpdb_result) {
1718
-            // type cast stdClass as array
1719
-            $wpdb_result = (array) $wpdb_result;
1720
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1721
-            if ($this->has_primary_key_field()) {
1722
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1723
-            } else {
1724
-                // 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)
1725
-                $main_table_pk_value = null;
1726
-            }
1727
-            // 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
1728
-            // 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
1729
-            if (count($tables) > 1) {
1730
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1731
-                // in that table, and so we'll want to insert one
1732
-                foreach ($tables as $table_obj) {
1733
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1734
-                    // if there is no private key for this table on the results, it means there's no entry
1735
-                    // in this table, right? so insert a row in the current table, using any fields available
1736
-                    if (
1737
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1738
-                           && $wpdb_result[ $this_table_pk_column ])
1739
-                    ) {
1740
-                        $success = $this->_insert_into_specific_table(
1741
-                            $table_obj,
1742
-                            $fields_n_values,
1743
-                            $main_table_pk_value
1744
-                        );
1745
-                        // if we died here, report the error
1746
-                        if (! $success) {
1747
-                            return false;
1748
-                        }
1749
-                    }
1750
-                }
1751
-            }
1752
-            //              //and now check that if we have cached any models by that ID on the model, that
1753
-            //              //they also get updated properly
1754
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1755
-            //              if( $model_object ){
1756
-            //                  foreach( $fields_n_values as $field => $value ){
1757
-            //                      $model_object->set($field, $value);
1758
-            // let's make sure default_where strategy is followed now
1759
-            $this->_ignore_where_strategy = false;
1760
-        }
1761
-        // if we want to keep model objects in sync, AND
1762
-        // if this wasn't called from a model object (to update itself)
1763
-        // then we want to make sure we keep all the existing
1764
-        // model objects in sync with the db
1765
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1766
-            if ($this->has_primary_key_field()) {
1767
-                $model_objs_affected_ids = $this->get_col($query_params);
1768
-            } else {
1769
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1770
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1771
-                $model_objs_affected_ids     = [];
1772
-                foreach ($models_affected_key_columns as $row) {
1773
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1774
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1775
-                }
1776
-            }
1777
-            if (! $model_objs_affected_ids) {
1778
-                // wait wait wait- if nothing was affected let's stop here
1779
-                return 0;
1780
-            }
1781
-            foreach ($model_objs_affected_ids as $id) {
1782
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1783
-                if ($model_obj_in_entity_map) {
1784
-                    foreach ($fields_n_values as $field => $new_value) {
1785
-                        $model_obj_in_entity_map->set($field, $new_value);
1786
-                    }
1787
-                }
1788
-            }
1789
-            // if there is a primary key on this model, we can now do a slight optimization
1790
-            if ($this->has_primary_key_field()) {
1791
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1792
-                $query_params = [
1793
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1794
-                    'limit'                    => count($model_objs_affected_ids),
1795
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1796
-                ];
1797
-            }
1798
-        }
1799
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1800
-
1801
-        $SQL = "UPDATE {$model_query_info->get_full_join_sql()}
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
+				/** @var $table_obj EE_Secondary_Table */
596
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
597
+			}
598
+		}
599
+		/**
600
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
601
+		 * EE_Register_Model_Extension
602
+		 *
603
+		 * @param EE_Model_Field_Base[] $_fields
604
+		 */
605
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
+		$this->_invalidate_field_caches();
607
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
608
+			if (! array_key_exists($table_alias, $this->_tables)) {
609
+				throw new EE_Error(
610
+					sprintf(
611
+						esc_html__(
612
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
613
+							'event_espresso'
614
+						),
615
+						$table_alias,
616
+						implode(",", $this->_fields)
617
+					)
618
+				);
619
+			}
620
+			foreach ($fields_for_table as $field_name => $field_obj) {
621
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
622
+				// primary key field base has a slightly different _construct_finalize
623
+				/** @var $field_obj EE_Model_Field_Base */
624
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
625
+			}
626
+		}
627
+		// everything is related to Extra_Meta
628
+		if (get_class($this) !== 'EEM_Extra_Meta') {
629
+			// make extra meta related to everything, but don't block deleting things just
630
+			// because they have related extra meta info. For now just orphan those extra meta
631
+			// in the future we should automatically delete them
632
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
633
+		}
634
+		// and change logs
635
+		if (get_class($this) !== 'EEM_Change_Log') {
636
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
637
+		}
638
+		/**
639
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
640
+		 * EE_Register_Model_Extension
641
+		 *
642
+		 * @param EE_Model_Relation_Base[] $_model_relations
643
+		 */
644
+		$this->_model_relations = (array) apply_filters(
645
+			'FHEE__' . get_class($this) . '__construct__model_relations',
646
+			$this->_model_relations
647
+		);
648
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
649
+			/** @var $relation_obj EE_Model_Relation_Base */
650
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
651
+		}
652
+		foreach ($this->_indexes as $index_name => $index_obj) {
653
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
654
+		}
655
+		$this->set_timezone($timezone);
656
+		// finalize default where condition strategy, or set default
657
+		if (! $this->_default_where_conditions_strategy) {
658
+			// nothing was set during child constructor, so set default
659
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660
+		}
661
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
662
+		if (! $this->_minimum_where_conditions_strategy) {
663
+			// nothing was set during child constructor, so set default
664
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665
+		}
666
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
667
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
668
+		// to indicate to NOT set it, set it to the logical default
669
+		if ($this->_caps_slug === null) {
670
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
671
+		}
672
+		// initialize the standard cap restriction generators if none were specified by the child constructor
673
+		if (is_array($this->_cap_restriction_generators)) {
674
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678
+						new EE_Restriction_Generator_Protected(),
679
+						$cap_context,
680
+						$this
681
+					);
682
+				}
683
+			}
684
+		}
685
+		// if there are cap restriction generators, use them to make the default cap restrictions
686
+		if (is_array($this->_cap_restriction_generators)) {
687
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
+				if (! $generator_object) {
689
+					continue;
690
+				}
691
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
692
+					throw new EE_Error(
693
+						sprintf(
694
+							esc_html__(
695
+								'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.',
696
+								'event_espresso'
697
+							),
698
+							$context,
699
+							$this->get_this_model_name()
700
+						)
701
+					);
702
+				}
703
+				$action = $this->cap_action_for_context($context);
704
+				if (! $generator_object->construction_finalized()) {
705
+					$generator_object->_construct_finalize($this, $action);
706
+				}
707
+			}
708
+		}
709
+		do_action('AHEE__' . get_class($this) . '__construct__end');
710
+	}
711
+
712
+
713
+	/**
714
+	 * @return LoaderInterface
715
+	 * @throws InvalidArgumentException
716
+	 * @throws InvalidDataTypeException
717
+	 * @throws InvalidInterfaceException
718
+	 */
719
+	protected static function getLoader(): LoaderInterface
720
+	{
721
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
722
+			EEM_Base::$loader = LoaderFactory::getLoader();
723
+		}
724
+		return EEM_Base::$loader;
725
+	}
726
+
727
+
728
+	/**
729
+	 * @return Mirror
730
+	 * @since   $VID:$
731
+	 */
732
+	private static function getMirror(): Mirror
733
+	{
734
+		if (! EEM_Base::$mirror instanceof Mirror) {
735
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736
+		}
737
+		return EEM_Base::$mirror;
738
+	}
739
+
740
+
741
+	/**
742
+	 * @param string $model_class_Name
743
+	 * @param string $timezone
744
+	 * @return array
745
+	 * @throws ReflectionException
746
+	 * @since   $VID:$
747
+	 */
748
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
749
+	{
750
+		$arguments = [$timezone];
751
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
752
+		if (count($params) > 1) {
753
+			if ($params[1]->getName() === 'model_field_factory') {
754
+				$arguments = [
755
+					$timezone,
756
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
757
+				];
758
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
759
+				$arguments = [
760
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
+					$timezone,
762
+				];
763
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
764
+				$arguments = [
765
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
766
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
767
+					$timezone,
768
+				];
769
+			}
770
+		}
771
+		return $arguments;
772
+	}
773
+
774
+
775
+	/**
776
+	 * This function is a singleton method used to instantiate the Espresso_model object
777
+	 *
778
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
779
+	 *                                (and any incoming timezone data that gets saved).
780
+	 *                                Note this just sends the timezone info to the date time model field objects.
781
+	 *                                Default is NULL
782
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
783
+	 * @return static (as in the concrete child class)
784
+	 * @throws EE_Error
785
+	 * @throws ReflectionException
786
+	 */
787
+	public static function instance($timezone = null)
788
+	{
789
+		// check if instance of Espresso_model already exists
790
+		if (! static::$_instance instanceof static) {
791
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792
+			$model     = new static(...$arguments);
793
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
794
+			static::$_instance = $model;
795
+		}
796
+		// we might have a timezone set, let set_timezone decide what to do with it
797
+		if ($timezone) {
798
+			static::$_instance->set_timezone($timezone);
799
+		}
800
+		// Espresso_model object
801
+		return static::$_instance;
802
+	}
803
+
804
+
805
+	/**
806
+	 * resets the model and returns it
807
+	 *
808
+	 * @param string|null $timezone
809
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
810
+	 * all its properties reset; if it wasn't instantiated, returns null)
811
+	 * @throws EE_Error
812
+	 * @throws ReflectionException
813
+	 * @throws InvalidArgumentException
814
+	 * @throws InvalidDataTypeException
815
+	 * @throws InvalidInterfaceException
816
+	 */
817
+	public static function reset($timezone = null)
818
+	{
819
+		if (! static::$_instance instanceof EEM_Base) {
820
+			return null;
821
+		}
822
+		// Let's NOT swap out the current instance for a new one
823
+		// because if someone has a reference to it, we can't remove their reference.
824
+		// It's best to keep using the same reference but change the original object instead,
825
+		// so reset all its properties to their original values as defined in the class.
826
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
827
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828
+			// don't set instance to null like it was originally,
829
+			// but it's static anyways, and we're ignoring static properties (for now at least)
830
+			if (! isset($static_properties[ $property ])) {
831
+				static::$_instance->{$property} = $value;
832
+			}
833
+		}
834
+		// and then directly call its constructor again, like we would if we were creating a new one
835
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
836
+		static::$_instance->__construct(...$arguments);
837
+		return self::instance();
838
+	}
839
+
840
+
841
+	/**
842
+	 * Used to set the $_model_query_blog_id static property.
843
+	 *
844
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
845
+	 *                      value for get_current_blog_id() will be used.
846
+	 */
847
+	public static function set_model_query_blog_id($blog_id = 0)
848
+	{
849
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
850
+			? (int) $blog_id
851
+			: get_current_blog_id();
852
+	}
853
+
854
+
855
+	/**
856
+	 * Returns whatever is set as the internal $model_query_blog_id.
857
+	 *
858
+	 * @return int
859
+	 */
860
+	public static function get_model_query_blog_id()
861
+	{
862
+		return EEM_Base::$_model_query_blog_id;
863
+	}
864
+
865
+
866
+	/**
867
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
868
+	 *
869
+	 * @param boolean $translated return localized strings or JUST the array.
870
+	 * @return array
871
+	 * @throws EE_Error
872
+	 * @throws InvalidArgumentException
873
+	 * @throws InvalidDataTypeException
874
+	 * @throws InvalidInterfaceException
875
+	 * @throws ReflectionException
876
+	 */
877
+	public function status_array($translated = false)
878
+	{
879
+		if (! array_key_exists('Status', $this->_model_relations)) {
880
+			return [];
881
+		}
882
+		$model_name   = $this->get_this_model_name();
883
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
884
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
885
+		$status_array = [];
886
+		foreach ($stati as $status) {
887
+			$status_array[ $status->ID() ] = $status->get('STS_code');
888
+		}
889
+		return $translated
890
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
891
+			: $status_array;
892
+	}
893
+
894
+
895
+	/**
896
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
897
+	 *
898
+	 * @param array $query_params             @see
899
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
900
+	 *                                        or if you have the development copy of EE you can view this at the path:
901
+	 *                                        /docs/G--Model-System/model-query-params.md
902
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
903
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
904
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
905
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
906
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
907
+	 *                                        'OR'=>array(
908
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
909
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
910
+	 *                                        )
911
+	 *                                        ),
912
+	 *                                        'limit'=>10,
913
+	 *                                        'group_by'=>'TXN_ID'
914
+	 *                                        ));
915
+	 *                                        get all the answers to the question titled "shirt size" for event with id
916
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
917
+	 *                                        'Question.QST_display_text'=>'shirt size',
918
+	 *                                        'Registration.Event.EVT_ID'=>12
919
+	 *                                        ),
920
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
921
+	 *                                        ));
922
+	 * @throws EE_Error
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
+	 */
945
+	public function alter_query_params_to_only_include_mine($query_params = [])
946
+	{
947
+		$wp_user_field_name = $this->wp_user_field_name();
948
+		if ($wp_user_field_name) {
949
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
950
+		}
951
+		return $query_params;
952
+	}
953
+
954
+
955
+	/**
956
+	 * Returns the name of the field's name that points to the WP_User table
957
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
958
+	 * foreign key to the WP_User table)
959
+	 *
960
+	 * @return string|boolean string on success, boolean false when there is no
961
+	 * foreign key to the WP_User table
962
+	 * @throws ReflectionException
963
+	 * @throws ReflectionException
964
+	 */
965
+	public function wp_user_field_name()
966
+	{
967
+		try {
968
+			if (! empty($this->_model_chain_to_wp_user)) {
969
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
970
+				$last_model_name              = end($models_to_follow_to_wp_users);
971
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
972
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
973
+			} else {
974
+				$model_with_fk_to_wp_users = $this;
975
+				$model_chain_to_wp_user    = '';
976
+			}
977
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
978
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
979
+		} catch (EE_Error $e) {
980
+			return false;
981
+		}
982
+	}
983
+
984
+
985
+	/**
986
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
987
+	 * (or transiently-related model) has a foreign key to the wp_users table;
988
+	 * useful for finding if model objects of this type are 'owned' by the current user.
989
+	 * This is an empty string when the foreign key is on this model and when it isn't,
990
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
991
+	 * (or transiently-related model)
992
+	 *
993
+	 * @return string
994
+	 */
995
+	public function model_chain_to_wp_user()
996
+	{
997
+		return $this->_model_chain_to_wp_user;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1003
+	 * like how registrations don't have a foreign key to wp_users, but the
1004
+	 * events they are for are), or is unrelated to wp users.
1005
+	 * generally available
1006
+	 *
1007
+	 * @return boolean
1008
+	 */
1009
+	public function is_owned()
1010
+	{
1011
+		if ($this->model_chain_to_wp_user()) {
1012
+			return true;
1013
+		}
1014
+		try {
1015
+			$this->get_foreign_key_to('WP_User');
1016
+			return true;
1017
+		} catch (EE_Error $e) {
1018
+			return false;
1019
+		}
1020
+	}
1021
+
1022
+
1023
+	/**
1024
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1025
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1026
+	 * the model)
1027
+	 *
1028
+	 * @param array  $query_params      @see
1029
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1030
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1031
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1032
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1033
+	 *                                  override this and set the select to "*", or a specific column name, like
1034
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1035
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1036
+	 *                                  the aliases used to refer to this selection, and values are to be
1037
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1038
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1039
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1040
+	 * @throws EE_Error
1041
+	 * @throws InvalidArgumentException
1042
+	 */
1043
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1044
+	{
1045
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1046
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1047
+		$select_expressions       = $columns_to_select === null
1048
+			? $this->_construct_default_select_sql($model_query_info)
1049
+			: '';
1050
+		if ($this->_custom_selections instanceof CustomSelects) {
1051
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1052
+			$select_expressions .= $select_expressions
1053
+				? ', ' . $custom_expressions
1054
+				: $custom_expressions;
1055
+		}
1056
+
1057
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1059
+	}
1060
+
1061
+
1062
+	/**
1063
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1064
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1065
+	 * method of including extra select information.
1066
+	 *
1067
+	 * @param array             $query_params
1068
+	 * @param null|array|string $columns_to_select
1069
+	 * @return null|CustomSelects
1070
+	 * @throws InvalidArgumentException
1071
+	 */
1072
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1073
+	{
1074
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1075
+			return null;
1076
+		}
1077
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1078
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1079
+		return new CustomSelects($selects);
1080
+	}
1081
+
1082
+
1083
+	/**
1084
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1085
+	 * but you can use the model query params to more easily
1086
+	 * take care of joins, field preparation etc.
1087
+	 *
1088
+	 * @param array  $query_params      @see
1089
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1090
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1091
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1092
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1093
+	 *                                  override this and set the select to "*", or a specific column name, like
1094
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1095
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1096
+	 *                                  the aliases used to refer to this selection, and values are to be
1097
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1098
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1099
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1100
+	 * @throws EE_Error
1101
+	 */
1102
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1103
+	{
1104
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * For creating a custom select statement
1110
+	 *
1111
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1112
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1113
+	 *                                 SQL, and 1=>is the datatype
1114
+	 * @return string
1115
+	 * @throws EE_Error
1116
+	 */
1117
+	private function _construct_select_from_input($columns_to_select)
1118
+	{
1119
+		if (is_array($columns_to_select)) {
1120
+			$select_sql_array = [];
1121
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1122
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1123
+					throw new EE_Error(
1124
+						sprintf(
1125
+							esc_html__(
1126
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1127
+								'event_espresso'
1128
+							),
1129
+							$selection_and_datatype,
1130
+							$alias
1131
+						)
1132
+					);
1133
+				}
1134
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1135
+					throw new EE_Error(
1136
+						sprintf(
1137
+							esc_html__(
1138
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1139
+								'event_espresso'
1140
+							),
1141
+							$selection_and_datatype[1],
1142
+							$selection_and_datatype[0],
1143
+							$alias,
1144
+							implode(', ', $this->_valid_wpdb_data_types)
1145
+						)
1146
+					);
1147
+				}
1148
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1149
+			}
1150
+			$columns_to_select_string = implode(', ', $select_sql_array);
1151
+		} else {
1152
+			$columns_to_select_string = $columns_to_select;
1153
+		}
1154
+		return $columns_to_select_string;
1155
+	}
1156
+
1157
+
1158
+	/**
1159
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1160
+	 *
1161
+	 * @return string
1162
+	 * @throws EE_Error
1163
+	 */
1164
+	public function primary_key_name()
1165
+	{
1166
+		return $this->get_primary_key_field()->get_name();
1167
+	}
1168
+
1169
+
1170
+	/**
1171
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1172
+	 * If there is no primary key on this model, $id is treated as primary key string
1173
+	 *
1174
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1175
+	 * @return EE_Base_Class|mixed|null
1176
+	 * @throws EE_Error
1177
+	 */
1178
+	public function get_one_by_ID($id)
1179
+	{
1180
+		if ($this->get_from_entity_map($id)) {
1181
+			return $this->get_from_entity_map($id);
1182
+		}
1183
+		$model_object = $this->get_one(
1184
+			$this->alter_query_params_to_restrict_by_ID(
1185
+				$id,
1186
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1187
+			)
1188
+		);
1189
+		$className    = $this->_get_class_name();
1190
+		if ($model_object instanceof $className) {
1191
+			// make sure valid objects get added to the entity map
1192
+			// so that the next call to this method doesn't trigger another trip to the db
1193
+			$this->add_to_entity_map($model_object);
1194
+		}
1195
+		return $model_object;
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * Alters query parameters to only get items with this ID are returned.
1201
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1202
+	 * or could just be a simple primary key ID
1203
+	 *
1204
+	 * @param int   $id
1205
+	 * @param array $query_params
1206
+	 * @return array of normal query params, @see
1207
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1208
+	 * @throws EE_Error
1209
+	 */
1210
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1211
+	{
1212
+		if (! isset($query_params[0])) {
1213
+			$query_params[0] = [];
1214
+		}
1215
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1216
+		if ($conditions_from_id === null) {
1217
+			$query_params[0][ $this->primary_key_name() ] = $id;
1218
+		} else {
1219
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1220
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1221
+		}
1222
+		return $query_params;
1223
+	}
1224
+
1225
+
1226
+	/**
1227
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1228
+	 * array. If no item is found, null is returned.
1229
+	 *
1230
+	 * @param array $query_params like EEM_Base's $query_params variable.
1231
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1232
+	 * @throws EE_Error
1233
+	 */
1234
+	public function get_one($query_params = [])
1235
+	{
1236
+		if (! is_array($query_params)) {
1237
+			EE_Error::doing_it_wrong(
1238
+				'EEM_Base::get_one',
1239
+				sprintf(
1240
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1241
+					gettype($query_params)
1242
+				),
1243
+				'4.6.0'
1244
+			);
1245
+			$query_params = [];
1246
+		}
1247
+		$query_params['limit'] = 1;
1248
+		$items                 = $this->get_all($query_params);
1249
+		if (empty($items)) {
1250
+			return null;
1251
+		}
1252
+		return array_shift($items);
1253
+	}
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the next x number of items in sequence from the given value as
1258
+	 * found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function next_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = [],
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive(
1280
+			$current_field_value,
1281
+			'>',
1282
+			$field_to_order_by,
1283
+			$limit,
1284
+			$query_params,
1285
+			$columns_to_select
1286
+		);
1287
+	}
1288
+
1289
+
1290
+	/**
1291
+	 * Returns the previous x number of items in sequence from the given value
1292
+	 * as found in the database matching the given query conditions.
1293
+	 *
1294
+	 * @param mixed $current_field_value    Value used for the reference point.
1295
+	 * @param null  $field_to_order_by      What field is used for the
1296
+	 *                                      reference point.
1297
+	 * @param int   $limit                  How many to return.
1298
+	 * @param array $query_params           Extra conditions on the query.
1299
+	 * @param null  $columns_to_select      If left null, then an array of
1300
+	 *                                      EE_Base_Class objects is returned,
1301
+	 *                                      otherwise you can indicate just the
1302
+	 *                                      columns you want returned.
1303
+	 * @return EE_Base_Class[]|array
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function previous_x(
1307
+		$current_field_value,
1308
+		$field_to_order_by = null,
1309
+		$limit = 1,
1310
+		$query_params = [],
1311
+		$columns_to_select = null
1312
+	) {
1313
+		return $this->_get_consecutive(
1314
+			$current_field_value,
1315
+			'<',
1316
+			$field_to_order_by,
1317
+			$limit,
1318
+			$query_params,
1319
+			$columns_to_select
1320
+		);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * Returns the next item in sequence from the given value as found in the
1326
+	 * database matching the given query conditions.
1327
+	 *
1328
+	 * @param mixed $current_field_value    Value used for the reference point.
1329
+	 * @param null  $field_to_order_by      What field is used for the
1330
+	 *                                      reference point.
1331
+	 * @param array $query_params           Extra conditions on the query.
1332
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1333
+	 *                                      object is returned, otherwise you
1334
+	 *                                      can indicate just the columns you
1335
+	 *                                      want and a single array indexed by
1336
+	 *                                      the columns will be returned.
1337
+	 * @return EE_Base_Class|null|array()
1338
+	 * @throws EE_Error
1339
+	 */
1340
+	public function next(
1341
+		$current_field_value,
1342
+		$field_to_order_by = null,
1343
+		$query_params = [],
1344
+		$columns_to_select = null
1345
+	) {
1346
+		$results = $this->_get_consecutive(
1347
+			$current_field_value,
1348
+			'>',
1349
+			$field_to_order_by,
1350
+			1,
1351
+			$query_params,
1352
+			$columns_to_select
1353
+		);
1354
+		return empty($results) ? null : reset($results);
1355
+	}
1356
+
1357
+
1358
+	/**
1359
+	 * Returns the previous item in sequence from the given value as found in
1360
+	 * the database matching the given query conditions.
1361
+	 *
1362
+	 * @param mixed $current_field_value    Value used for the reference point.
1363
+	 * @param null  $field_to_order_by      What field is used for the
1364
+	 *                                      reference point.
1365
+	 * @param array $query_params           Extra conditions on the query.
1366
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1367
+	 *                                      object is returned, otherwise you
1368
+	 *                                      can indicate just the columns you
1369
+	 *                                      want and a single array indexed by
1370
+	 *                                      the columns will be returned.
1371
+	 * @return EE_Base_Class|null|array()
1372
+	 * @throws EE_Error
1373
+	 */
1374
+	public function previous(
1375
+		$current_field_value,
1376
+		$field_to_order_by = null,
1377
+		$query_params = [],
1378
+		$columns_to_select = null
1379
+	) {
1380
+		$results = $this->_get_consecutive(
1381
+			$current_field_value,
1382
+			'<',
1383
+			$field_to_order_by,
1384
+			1,
1385
+			$query_params,
1386
+			$columns_to_select
1387
+		);
1388
+		return empty($results) ? null : reset($results);
1389
+	}
1390
+
1391
+
1392
+	/**
1393
+	 * Returns the a consecutive number of items in sequence from the given
1394
+	 * value as found in the database matching the given query conditions.
1395
+	 *
1396
+	 * @param mixed  $current_field_value   Value used for the reference point.
1397
+	 * @param string $operand               What operand is used for the sequence.
1398
+	 * @param string $field_to_order_by     What field is used for the reference point.
1399
+	 * @param int    $limit                 How many to return.
1400
+	 * @param array  $query_params          Extra conditions on the query.
1401
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1402
+	 *                                      otherwise you can indicate just the columns you want returned.
1403
+	 * @return EE_Base_Class[]|array
1404
+	 * @throws EE_Error
1405
+	 */
1406
+	protected function _get_consecutive(
1407
+		$current_field_value,
1408
+		$operand = '>',
1409
+		$field_to_order_by = null,
1410
+		$limit = 1,
1411
+		$query_params = [],
1412
+		$columns_to_select = null
1413
+	) {
1414
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1415
+		if (empty($field_to_order_by)) {
1416
+			if ($this->has_primary_key_field()) {
1417
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1418
+			} else {
1419
+				if (WP_DEBUG) {
1420
+					throw new EE_Error(
1421
+						esc_html__(
1422
+							'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).',
1423
+							'event_espresso'
1424
+						)
1425
+					);
1426
+				}
1427
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1428
+				return [];
1429
+			}
1430
+		}
1431
+		if (! is_array($query_params)) {
1432
+			EE_Error::doing_it_wrong(
1433
+				'EEM_Base::_get_consecutive',
1434
+				sprintf(
1435
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1436
+					gettype($query_params)
1437
+				),
1438
+				'4.6.0'
1439
+			);
1440
+			$query_params = [];
1441
+		}
1442
+		// let's add the where query param for consecutive look up.
1443
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1444
+		$query_params['limit']                 = $limit;
1445
+		// set direction
1446
+		$incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1447
+		$query_params['order_by'] = $operand === '>'
1448
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1449
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1450
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
+		if (empty($columns_to_select)) {
1452
+			return $this->get_all($query_params);
1453
+		}
1454
+		// getting just the fields
1455
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * This sets the _timezone property after model object has been instantiated.
1461
+	 *
1462
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1463
+	 */
1464
+	public function set_timezone($timezone)
1465
+	{
1466
+		if ($timezone !== null) {
1467
+			$this->_timezone = $timezone;
1468
+		}
1469
+		// note we need to loop through relations and set the timezone on those objects as well.
1470
+		foreach ($this->_model_relations as $relation) {
1471
+			$relation->set_timezone($timezone);
1472
+		}
1473
+		// and finally we do the same for any datetime fields
1474
+		foreach ($this->_fields as $field) {
1475
+			if ($field instanceof EE_Datetime_Field) {
1476
+				$field->set_timezone($timezone);
1477
+			}
1478
+		}
1479
+	}
1480
+
1481
+
1482
+	/**
1483
+	 * This just returns whatever is set for the current timezone.
1484
+	 *
1485
+	 * @access public
1486
+	 * @return string
1487
+	 */
1488
+	public function get_timezone()
1489
+	{
1490
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1491
+		if (empty($this->_timezone)) {
1492
+			foreach ($this->_fields as $field) {
1493
+				if ($field instanceof EE_Datetime_Field) {
1494
+					$this->set_timezone($field->get_timezone());
1495
+					break;
1496
+				}
1497
+			}
1498
+		}
1499
+		// if timezone STILL empty then return the default timezone for the site.
1500
+		if (empty($this->_timezone)) {
1501
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1502
+		}
1503
+		return $this->_timezone;
1504
+	}
1505
+
1506
+
1507
+	/**
1508
+	 * This returns the date formats set for the given field name and also ensures that
1509
+	 * $this->_timezone property is set correctly.
1510
+	 *
1511
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1512
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513
+	 * @return array formats in an array with the date format first, and the time format last.
1514
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1515
+	 * @since 4.6.x
1516
+	 */
1517
+	public function get_formats_for($field_name, $pretty = false)
1518
+	{
1519
+		$field_settings = $this->field_settings_for($field_name);
1520
+		// if not a valid EE_Datetime_Field then throw error
1521
+		if (! $field_settings instanceof EE_Datetime_Field) {
1522
+			throw new EE_Error(
1523
+				sprintf(
1524
+					esc_html__(
1525
+						'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.',
1526
+						'event_espresso'
1527
+					),
1528
+					$field_name
1529
+				)
1530
+			);
1531
+		}
1532
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1533
+		// the field.
1534
+		$this->_timezone = $field_settings->get_timezone();
1535
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * This returns the current time in a format setup for a query on this model.
1541
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1542
+	 * it will return:
1543
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1544
+	 *  NOW
1545
+	 *  - or a unix timestamp (equivalent to time())
1546
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1547
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1548
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1549
+	 *
1550
+	 * @param string $field_name       The field the current time is needed for.
1551
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1552
+	 *                                 formatted string matching the set format for the field in the set timezone will
1553
+	 *                                 be returned.
1554
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1555
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1556
+	 *                                 exception is triggered.
1557
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1558
+	 * @since 4.6.x
1559
+	 */
1560
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1561
+	{
1562
+		$formats  = $this->get_formats_for($field_name);
1563
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1564
+		if ($timestamp) {
1565
+			return $DateTime->format('U');
1566
+		}
1567
+		// not returning timestamp, so return formatted string in timezone.
1568
+		switch ($what) {
1569
+			case 'time':
1570
+				return $DateTime->format($formats[1]);
1571
+				break;
1572
+			case 'date':
1573
+				return $DateTime->format($formats[0]);
1574
+				break;
1575
+			default:
1576
+				return $DateTime->format(implode(' ', $formats));
1577
+				break;
1578
+		}
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1584
+	 * for the model are.  Returns a DateTime object.
1585
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1586
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1587
+	 * ignored.
1588
+	 *
1589
+	 * @param string $field_name      The field being setup.
1590
+	 * @param string $timestring      The date time string being used.
1591
+	 * @param string $incoming_format The format for the time string.
1592
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1593
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1594
+	 *                                format is
1595
+	 *                                'U', this is ignored.
1596
+	 * @return DateTime
1597
+	 * @throws EE_Error
1598
+	 */
1599
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1600
+	{
1601
+		// just using this to ensure the timezone is set correctly internally
1602
+		$this->get_formats_for($field_name);
1603
+		// load EEH_DTT_Helper
1604
+		$set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1605
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1606
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1607
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1613
+	 *
1614
+	 * @return EE_Table_Base[]
1615
+	 */
1616
+	public function get_tables()
1617
+	{
1618
+		return $this->_tables;
1619
+	}
1620
+
1621
+
1622
+	/**
1623
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1624
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1625
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1626
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1627
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1628
+	 * model object with EVT_ID = 1
1629
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1630
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1631
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1632
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1633
+	 * are not specified)
1634
+	 *
1635
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1636
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1637
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1638
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1639
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1640
+	 *                                         ID=34, we'd use this method as follows:
1641
+	 *                                         EEM_Transaction::instance()->update(
1642
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1643
+	 *                                         array(array('TXN_ID'=>34)));
1644
+	 * @param array   $query_params            @see
1645
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1646
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1647
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1648
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1649
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1650
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1651
+	 *                                         TRUE, it is assumed that you've already called
1652
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1653
+	 *                                         malicious javascript. However, if
1654
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1655
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1656
+	 *                                         and every other field, before insertion. We provide this parameter
1657
+	 *                                         because model objects perform their prepare_for_set function on all
1658
+	 *                                         their values, and so don't need to be called again (and in many cases,
1659
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1660
+	 *                                         prepare_for_set method...)
1661
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1662
+	 *                                         in this model's entity map according to $fields_n_values that match
1663
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1664
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1665
+	 *                                         could get out-of-sync with the database
1666
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1667
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1668
+	 *                                         bad)
1669
+	 * @throws EE_Error
1670
+	 * @throws ReflectionException
1671
+	 */
1672
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1673
+	{
1674
+		if (! is_array($query_params)) {
1675
+			EE_Error::doing_it_wrong(
1676
+				'EEM_Base::update',
1677
+				sprintf(
1678
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1679
+					gettype($query_params)
1680
+				),
1681
+				'4.6.0'
1682
+			);
1683
+			$query_params = [];
1684
+		}
1685
+		/**
1686
+		 * Action called before a model update call has been made.
1687
+		 *
1688
+		 * @param EEM_Base $model
1689
+		 * @param array    $fields_n_values the updated fields and their new values
1690
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1691
+		 */
1692
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1693
+		/**
1694
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1695
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1696
+		 *
1697
+		 * @param array    $fields_n_values fields and their new values
1698
+		 * @param EEM_Base $model           the model being queried
1699
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1700
+		 */
1701
+		$fields_n_values = (array) apply_filters(
1702
+			'FHEE__EEM_Base__update__fields_n_values',
1703
+			$fields_n_values,
1704
+			$this,
1705
+			$query_params
1706
+		);
1707
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1708
+		// to do that, for each table, verify that it's PK isn't null.
1709
+		$tables = $this->get_tables();
1710
+		// 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
1711
+		// NOTE: we should make this code more efficient by NOT querying twice
1712
+		// before the real update, but that needs to first go through ALPHA testing
1713
+		// as it's dangerous. says Mike August 8 2014
1714
+		// we want to make sure the default_where strategy is ignored
1715
+		$this->_ignore_where_strategy = true;
1716
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1717
+		foreach ($wpdb_select_results as $wpdb_result) {
1718
+			// type cast stdClass as array
1719
+			$wpdb_result = (array) $wpdb_result;
1720
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1721
+			if ($this->has_primary_key_field()) {
1722
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1723
+			} else {
1724
+				// 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)
1725
+				$main_table_pk_value = null;
1726
+			}
1727
+			// 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
1728
+			// 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
1729
+			if (count($tables) > 1) {
1730
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1731
+				// in that table, and so we'll want to insert one
1732
+				foreach ($tables as $table_obj) {
1733
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1734
+					// if there is no private key for this table on the results, it means there's no entry
1735
+					// in this table, right? so insert a row in the current table, using any fields available
1736
+					if (
1737
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1738
+						   && $wpdb_result[ $this_table_pk_column ])
1739
+					) {
1740
+						$success = $this->_insert_into_specific_table(
1741
+							$table_obj,
1742
+							$fields_n_values,
1743
+							$main_table_pk_value
1744
+						);
1745
+						// if we died here, report the error
1746
+						if (! $success) {
1747
+							return false;
1748
+						}
1749
+					}
1750
+				}
1751
+			}
1752
+			//              //and now check that if we have cached any models by that ID on the model, that
1753
+			//              //they also get updated properly
1754
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1755
+			//              if( $model_object ){
1756
+			//                  foreach( $fields_n_values as $field => $value ){
1757
+			//                      $model_object->set($field, $value);
1758
+			// let's make sure default_where strategy is followed now
1759
+			$this->_ignore_where_strategy = false;
1760
+		}
1761
+		// if we want to keep model objects in sync, AND
1762
+		// if this wasn't called from a model object (to update itself)
1763
+		// then we want to make sure we keep all the existing
1764
+		// model objects in sync with the db
1765
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1766
+			if ($this->has_primary_key_field()) {
1767
+				$model_objs_affected_ids = $this->get_col($query_params);
1768
+			} else {
1769
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1770
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1771
+				$model_objs_affected_ids     = [];
1772
+				foreach ($models_affected_key_columns as $row) {
1773
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1774
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1775
+				}
1776
+			}
1777
+			if (! $model_objs_affected_ids) {
1778
+				// wait wait wait- if nothing was affected let's stop here
1779
+				return 0;
1780
+			}
1781
+			foreach ($model_objs_affected_ids as $id) {
1782
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1783
+				if ($model_obj_in_entity_map) {
1784
+					foreach ($fields_n_values as $field => $new_value) {
1785
+						$model_obj_in_entity_map->set($field, $new_value);
1786
+					}
1787
+				}
1788
+			}
1789
+			// if there is a primary key on this model, we can now do a slight optimization
1790
+			if ($this->has_primary_key_field()) {
1791
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1792
+				$query_params = [
1793
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1794
+					'limit'                    => count($model_objs_affected_ids),
1795
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1796
+				];
1797
+			}
1798
+		}
1799
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1800
+
1801
+		$SQL = "UPDATE {$model_query_info->get_full_join_sql()}
1802 1802
                 SET {$this->_construct_update_sql($fields_n_values)}
1803 1803
                 {$model_query_info->get_where_sql()}";
1804
-        // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1806
-        /**
1807
-         * Action called after a model update call has been made.
1808
-         *
1809
-         * @param EEM_Base $model
1810
-         * @param array    $fields_n_values the updated fields and their new values
1811
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1812
-         * @param int      $rows_affected
1813
-         */
1814
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1815
-        return $rows_affected;// how many supposedly got updated
1816
-    }
1817
-
1818
-
1819
-    /**
1820
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1821
-     * are teh values of the field specified (or by default the primary key field)
1822
-     * that matched the query params. Note that you should pass the name of the
1823
-     * model FIELD, not the database table's column name.
1824
-     *
1825
-     * @param array  $query_params @see
1826
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1827
-     * @param string $field_to_select
1828
-     * @return array just like $wpdb->get_col()
1829
-     * @throws EE_Error
1830
-     */
1831
-    public function get_col($query_params = [], $field_to_select = null)
1832
-    {
1833
-        if ($field_to_select) {
1834
-            $field = $this->field_settings_for($field_to_select);
1835
-        } elseif ($this->has_primary_key_field()) {
1836
-            $field = $this->get_primary_key_field();
1837
-        } else {
1838
-            // no primary key, just grab the first column
1839
-            $field_settings = $this->field_settings();
1840
-            $field          = reset($field_settings);
1841
-        }
1842
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1843
-        $select_expressions = $field->get_qualified_column();
1844
-        $SQL                =
1845
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1846
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1847
-    }
1848
-
1849
-
1850
-    /**
1851
-     * Returns a single column value for a single row from the database
1852
-     *
1853
-     * @param array  $query_params    @see
1854
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1855
-     * @param string $field_to_select @see EEM_Base::get_col()
1856
-     * @return string
1857
-     * @throws EE_Error
1858
-     */
1859
-    public function get_var($query_params = [], $field_to_select = null)
1860
-    {
1861
-        $query_params['limit'] = 1;
1862
-        $col                   = $this->get_col($query_params, $field_to_select);
1863
-        if (! empty($col)) {
1864
-            return reset($col);
1865
-        }
1866
-        return null;
1867
-    }
1868
-
1869
-
1870
-    /**
1871
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1872
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1873
-     * injection, but currently no further filtering is done
1874
-     *
1875
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1876
-     *                               be updated to in the DB
1877
-     * @return string of SQL
1878
-     * @throws EE_Error
1879
-     * @global      $wpdb
1880
-     */
1881
-    public function _construct_update_sql($fields_n_values)
1882
-    {
1883
-        /** @type WPDB $wpdb */
1884
-        global $wpdb;
1885
-        $cols_n_values = [];
1886
-        foreach ($fields_n_values as $field_name => $value) {
1887
-            $field_obj = $this->field_settings_for($field_name);
1888
-            // if the value is NULL, we want to assign the value to that.
1889
-            // wpdb->prepare doesn't really handle that properly
1890
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891
-            $value_sql       = $prepared_value === null ? 'NULL'
1892
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1894
-        }
1895
-        return implode(",", $cols_n_values);
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1901
-     * Performs a HARD delete, meaning the database row should always be removed,
1902
-     * not just have a flag field on it switched
1903
-     * Wrapper for EEM_Base::delete_permanently()
1904
-     *
1905
-     * @param mixed   $id
1906
-     * @param boolean $allow_blocking
1907
-     * @return int the number of rows deleted
1908
-     * @throws EE_Error
1909
-     */
1910
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1911
-    {
1912
-        return $this->delete_permanently(
1913
-            [
1914
-                [$this->get_primary_key_field()->get_name() => $id],
1915
-                'limit' => 1,
1916
-            ],
1917
-            $allow_blocking
1918
-        );
1919
-    }
1920
-
1921
-
1922
-    /**
1923
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1924
-     * Wrapper for EEM_Base::delete()
1925
-     *
1926
-     * @param mixed   $id
1927
-     * @param boolean $allow_blocking
1928
-     * @return int the number of rows deleted
1929
-     * @throws EE_Error
1930
-     */
1931
-    public function delete_by_ID($id, $allow_blocking = true)
1932
-    {
1933
-        return $this->delete(
1934
-            [
1935
-                [$this->get_primary_key_field()->get_name() => $id],
1936
-                'limit' => 1,
1937
-            ],
1938
-            $allow_blocking
1939
-        );
1940
-    }
1941
-
1942
-
1943
-    /**
1944
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1945
-     * meaning if the model has a field that indicates its been "trashed" or
1946
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1947
-     *
1948
-     * @param array   $query_params
1949
-     * @param boolean $allow_blocking
1950
-     * @return int how many rows got deleted
1951
-     * @throws EE_Error
1952
-     * @see EEM_Base::delete_permanently
1953
-     */
1954
-    public function delete($query_params, $allow_blocking = true)
1955
-    {
1956
-        return $this->delete_permanently($query_params, $allow_blocking);
1957
-    }
1958
-
1959
-
1960
-    /**
1961
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1962
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1963
-     * as archived, not actually deleted
1964
-     *
1965
-     * @param array   $query_params   @see
1966
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1967
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1968
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1969
-     *                                deletes regardless of other objects which may depend on it. Its generally
1970
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1971
-     *                                DB
1972
-     * @return int how many rows got deleted
1973
-     * @throws EE_Error
1974
-     * @throws ReflectionException
1975
-     */
1976
-    public function delete_permanently($query_params, $allow_blocking = true)
1977
-    {
1978
-        /**
1979
-         * Action called just before performing a real deletion query. You can use the
1980
-         * model and its $query_params to find exactly which items will be deleted
1981
-         *
1982
-         * @param EEM_Base $model
1983
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1984
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1985
-         *                                 to block (prevent) this deletion
1986
-         */
1987
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1988
-        // some MySQL databases may be running safe mode, which may restrict
1989
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1990
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1991
-        // to delete them
1992
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1993
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1994
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1995
-            $columns_and_ids_for_deleting
1996
-        );
1997
-        /**
1998
-         * Allows client code to act on the items being deleted before the query is actually executed.
1999
-         *
2000
-         * @param EEM_Base $this                            The model instance being acted on.
2001
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2002
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2003
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2004
-         *                                                  derived from the incoming query parameters.
2005
-         * @see details on the structure of this array in the phpdocs
2006
-         *                                                  for the `_get_ids_for_delete_method`
2007
-         *
2008
-         */
2009
-        do_action(
2010
-            'AHEE__EEM_Base__delete__before_query',
2011
-            $this,
2012
-            $query_params,
2013
-            $allow_blocking,
2014
-            $columns_and_ids_for_deleting
2015
-        );
2016
-        if ($deletion_where_query_part) {
2017
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2018
-            $table_aliases    = array_keys($this->_tables);
2019
-            $SQL              = "DELETE "
2020
-                                . implode(", ", $table_aliases)
2021
-                                . " FROM "
2022
-                                . $model_query_info->get_full_join_sql()
2023
-                                . " WHERE "
2024
-                                . $deletion_where_query_part;
2025
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2026
-        } else {
2027
-            $rows_deleted = 0;
2028
-        }
2029
-
2030
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2031
-        // there was no error with the delete query.
2032
-        if (
2033
-            $this->has_primary_key_field()
2034
-            && $rows_deleted !== false
2035
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2036
-        ) {
2037
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2038
-            foreach ($ids_for_removal as $id) {
2039
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2040
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2041
-                }
2042
-            }
2043
-
2044
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2045
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2046
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2047
-            // (although it is possible).
2048
-            // Note this can be skipped by using the provided filter and returning false.
2049
-            if (
2050
-                apply_filters(
2051
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2052
-                    ! $this instanceof EEM_Extra_Meta,
2053
-                    $this
2054
-                )
2055
-            ) {
2056
-                EEM_Extra_Meta::instance()->delete_permanently([
2057
-                                                                   0 => [
2058
-                                                                       'EXM_type' => $this->get_this_model_name(),
2059
-                                                                       'OBJ_ID'   => [
2060
-                                                                           'IN',
2061
-                                                                           $ids_for_removal,
2062
-                                                                       ],
2063
-                                                                   ],
2064
-                                                               ]);
2065
-            }
2066
-        }
2067
-
2068
-        /**
2069
-         * Action called just after performing a real deletion query. Although at this point the
2070
-         * items should have been deleted
2071
-         *
2072
-         * @param EEM_Base $model
2073
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2074
-         * @param int      $rows_deleted
2075
-         */
2076
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2077
-        return $rows_deleted;// how many supposedly got deleted
2078
-    }
2079
-
2080
-
2081
-    /**
2082
-     * Checks all the relations that throw error messages when there are blocking related objects
2083
-     * for related model objects. If there are any related model objects on those relations,
2084
-     * adds an EE_Error, and return true
2085
-     *
2086
-     * @param EE_Base_Class|int $this_model_obj_or_id
2087
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2088
-     *                                                 should be ignored when determining whether there are related
2089
-     *                                                 model objects which block this model object's deletion. Useful
2090
-     *                                                 if you know A is related to B and are considering deleting A,
2091
-     *                                                 but want to see if A has any other objects blocking its deletion
2092
-     *                                                 before removing the relation between A and B
2093
-     * @return boolean
2094
-     * @throws EE_Error
2095
-     * @throws ReflectionException
2096
-     */
2097
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2098
-    {
2099
-        // first, if $ignore_this_model_obj was supplied, get its model
2100
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2101
-            $ignored_model = $ignore_this_model_obj->get_model();
2102
-        } else {
2103
-            $ignored_model = null;
2104
-        }
2105
-        // now check all the relations of $this_model_obj_or_id and see if there
2106
-        // are any related model objects blocking it?
2107
-        $is_blocked = false;
2108
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2109
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2110
-                // if $ignore_this_model_obj was supplied, then for the query
2111
-                // on that model needs to be told to ignore $ignore_this_model_obj
2112
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2113
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2114
-                        [
2115
-                            $ignored_model->get_primary_key_field()->get_name() => [
2116
-                                '!=',
2117
-                                $ignore_this_model_obj->ID(),
2118
-                            ],
2119
-                        ],
2120
-                    ]);
2121
-                } else {
2122
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2123
-                }
2124
-                if ($related_model_objects) {
2125
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2126
-                    $is_blocked = true;
2127
-                }
2128
-            }
2129
-        }
2130
-        return $is_blocked;
2131
-    }
2132
-
2133
-
2134
-    /**
2135
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2136
-     *
2137
-     * @param array $row_results_for_deleting
2138
-     * @param bool  $allow_blocking
2139
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2140
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2141
-     *                              dimension array where the key is the fully qualified primary key column and the
2142
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2143
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2144
-     *                              be a two dimensional array where each element is a group of columns and values that
2145
-     *                              get deleted. Example: array(
2146
-     *                              0 => array(
2147
-     *                              'Term_Relationship.object_id' => 1
2148
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2149
-     *                              ),
2150
-     *                              1 => array(
2151
-     *                              'Term_Relationship.object_id' => 1
2152
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2153
-     *                              )
2154
-     *                              )
2155
-     * @throws EE_Error
2156
-     */
2157
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2158
-    {
2159
-        $ids_to_delete_indexed_by_column = [];
2160
-        if ($this->has_primary_key_field()) {
2161
-            $primary_table                   = $this->_get_main_table();
2162
-            $primary_table_pk_field          =
2163
-                $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2164
-            $other_tables                    = $this->_get_other_tables();
2165
-            $ids_to_delete_indexed_by_column = $query = [];
2166
-            foreach ($row_results_for_deleting as $item_to_delete) {
2167
-                // before we mark this item for deletion,
2168
-                // make sure there's no related entities blocking its deletion (if we're checking)
2169
-                if (
2170
-                    $allow_blocking
2171
-                    && $this->delete_is_blocked_by_related_models(
2172
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2173
-                    )
2174
-                ) {
2175
-                    continue;
2176
-                }
2177
-                // primary table deletes
2178
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2179
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2180
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2181
-                }
2182
-            }
2183
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2184
-            $fields = $this->get_combined_primary_key_fields();
2185
-            foreach ($row_results_for_deleting as $item_to_delete) {
2186
-                $ids_to_delete_indexed_by_column_for_row = [];
2187
-                foreach ($fields as $cpk_field) {
2188
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2189
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2190
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2191
-                    }
2192
-                }
2193
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2194
-            }
2195
-        } else {
2196
-            // so there's no primary key and no combined key...
2197
-            // sorry, can't help you
2198
-            throw new EE_Error(
2199
-                sprintf(
2200
-                    esc_html__(
2201
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2202
-                        "event_espresso"
2203
-                    ),
2204
-                    get_class($this)
2205
-                )
2206
-            );
2207
-        }
2208
-        return $ids_to_delete_indexed_by_column;
2209
-    }
2210
-
2211
-
2212
-    /**
2213
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2214
-     * the corresponding query_part for the query performing the delete.
2215
-     *
2216
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2217
-     * @return string
2218
-     * @throws EE_Error
2219
-     */
2220
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2221
-    {
2222
-        $query_part = '';
2223
-        if (empty($ids_to_delete_indexed_by_column)) {
2224
-            return $query_part;
2225
-        } elseif ($this->has_primary_key_field()) {
2226
-            $query = [];
2227
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2228
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2229
-            }
2230
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2231
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2232
-            $ways_to_identify_a_row = [];
2233
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2234
-                $values_for_each_combined_primary_key_for_a_row = [];
2235
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2236
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2237
-                }
2238
-                $ways_to_identify_a_row[] = '('
2239
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2240
-                                            . ')';
2241
-            }
2242
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2243
-        }
2244
-        return $query_part;
2245
-    }
2246
-
2247
-
2248
-    /**
2249
-     * Gets the model field by the fully qualified name
2250
-     *
2251
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2252
-     * @return EE_Model_Field_Base
2253
-     * @throws EE_Error
2254
-     * @throws EE_Error
2255
-     */
2256
-    public function get_field_by_column($qualified_column_name)
2257
-    {
2258
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2259
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2260
-                return $field_obj;
2261
-            }
2262
-        }
2263
-        throw new EE_Error(
2264
-            sprintf(
2265
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2266
-                $this->get_this_model_name(),
2267
-                $qualified_column_name
2268
-            )
2269
-        );
2270
-    }
2271
-
2272
-
2273
-    /**
2274
-     * Count all the rows that match criteria the model query params.
2275
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2276
-     * column
2277
-     *
2278
-     * @param array  $query_params   @see
2279
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2280
-     * @param string $field_to_count field on model to count by (not column name)
2281
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2282
-     *                               that by the setting $distinct to TRUE;
2283
-     * @return int
2284
-     * @throws EE_Error
2285
-     */
2286
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2287
-    {
2288
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2289
-        if ($field_to_count) {
2290
-            $field_obj       = $this->field_settings_for($field_to_count);
2291
-            $column_to_count = $field_obj->get_qualified_column();
2292
-        } elseif ($this->has_primary_key_field()) {
2293
-            $pk_field_obj    = $this->get_primary_key_field();
2294
-            $column_to_count = $pk_field_obj->get_qualified_column();
2295
-        } else {
2296
-            // there's no primary key
2297
-            // if we're counting distinct items, and there's no primary key,
2298
-            // we need to list out the columns for distinction;
2299
-            // otherwise we can just use star
2300
-            if ($distinct) {
2301
-                $columns_to_use = [];
2302
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2303
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2304
-                }
2305
-                $column_to_count = implode(',', $columns_to_use);
2306
-            } else {
2307
-                $column_to_count = '*';
2308
-            }
2309
-        }
2310
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2311
-        $SQL             =
2312
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2314
-    }
2315
-
2316
-
2317
-    /**
2318
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2319
-     *
2320
-     * @param array  $query_params @see
2321
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2322
-     * @param string $field_to_sum name of field (array key in $_fields array)
2323
-     * @return float
2324
-     * @throws EE_Error
2325
-     */
2326
-    public function sum($query_params, $field_to_sum = null)
2327
-    {
2328
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2329
-        if ($field_to_sum) {
2330
-            $field_obj = $this->field_settings_for($field_to_sum);
2331
-        } else {
2332
-            $field_obj = $this->get_primary_key_field();
2333
-        }
2334
-        $column_to_count = $field_obj->get_qualified_column();
2335
-        $SQL             =
2336
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2337
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2338
-        $data_type       = $field_obj->get_wpdb_data_type();
2339
-        if ($data_type === '%d' || $data_type === '%s') {
2340
-            return (float) $return_value;
2341
-        }
2342
-        // must be %f
2343
-        return (float) $return_value;
2344
-    }
2345
-
2346
-
2347
-    /**
2348
-     * Just calls the specified method on $wpdb with the given arguments
2349
-     * Consolidates a little extra error handling code
2350
-     *
2351
-     * @param string $wpdb_method
2352
-     * @param array  $arguments_to_provide
2353
-     * @return mixed
2354
-     * @throws EE_Error
2355
-     * @global wpdb  $wpdb
2356
-     */
2357
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2358
-    {
2359
-        // if we're in maintenance mode level 2, DON'T run any queries
2360
-        // because level 2 indicates the database needs updating and
2361
-        // is probably out of sync with the code
2362
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2363
-            throw new EE_Error(
2364
-                sprintf(
2365
-                    esc_html__(
2366
-                        "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.",
2367
-                        "event_espresso"
2368
-                    )
2369
-                )
2370
-            );
2371
-        }
2372
-        /** @type WPDB $wpdb */
2373
-        global $wpdb;
2374
-        if (! method_exists($wpdb, $wpdb_method)) {
2375
-            throw new EE_Error(
2376
-                sprintf(
2377
-                    esc_html__(
2378
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2379
-                        'event_espresso'
2380
-                    ),
2381
-                    $wpdb_method
2382
-                )
2383
-            );
2384
-        }
2385
-        if (WP_DEBUG) {
2386
-            $old_show_errors_value = $wpdb->show_errors;
2387
-            $wpdb->show_errors(false);
2388
-        }
2389
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2390
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2391
-        if (WP_DEBUG) {
2392
-            $wpdb->show_errors($old_show_errors_value);
2393
-            if (! empty($wpdb->last_error)) {
2394
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2395
-            }
2396
-            if ($result === false) {
2397
-                throw new EE_Error(
2398
-                    sprintf(
2399
-                        esc_html__(
2400
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2401
-                            'event_espresso'
2402
-                        ),
2403
-                        $wpdb_method,
2404
-                        var_export($arguments_to_provide, true)
2405
-                    )
2406
-                );
2407
-            }
2408
-        } elseif ($result === false) {
2409
-            EE_Error::add_error(
2410
-                sprintf(
2411
-                    esc_html__(
2412
-                        '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"',
2413
-                        'event_espresso'
2414
-                    ),
2415
-                    $wpdb_method,
2416
-                    var_export($arguments_to_provide, true),
2417
-                    $wpdb->last_error
2418
-                ),
2419
-                __FILE__,
2420
-                __FUNCTION__,
2421
-                __LINE__
2422
-            );
2423
-        }
2424
-        return $result;
2425
-    }
2426
-
2427
-
2428
-    /**
2429
-     * Attempts to run the indicated WPDB method with the provided arguments,
2430
-     * and if there's an error tries to verify the DB is correct. Uses
2431
-     * the static property EEM_Base::$_db_verification_level to determine whether
2432
-     * we should try to fix the EE core db, the addons, or just give up
2433
-     *
2434
-     * @param string $wpdb_method
2435
-     * @param array  $arguments_to_provide
2436
-     * @return mixed
2437
-     */
2438
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2439
-    {
2440
-        /** @type WPDB $wpdb */
2441
-        global $wpdb;
2442
-        $wpdb->last_error = null;
2443
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2444
-        // was there an error running the query? but we don't care on new activations
2445
-        // (we're going to setup the DB anyway on new activations)
2446
-        if (
2447
-            ($result === false || ! empty($wpdb->last_error))
2448
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2449
-        ) {
2450
-            switch (EEM_Base::$_db_verification_level) {
2451
-                case EEM_Base::db_verified_none:
2452
-                    // let's double-check core's DB
2453
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2454
-                    break;
2455
-                case EEM_Base::db_verified_core:
2456
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2457
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2458
-                    break;
2459
-                case EEM_Base::db_verified_addons:
2460
-                    // ummmm... you in trouble
2461
-                    return $result;
2462
-                    break;
2463
-            }
2464
-            if (! empty($error_message)) {
2465
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466
-                trigger_error($error_message);
2467
-            }
2468
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2469
-        }
2470
-        return $result;
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * Verifies the EE core database is up-to-date and records that we've done it on
2476
-     * EEM_Base::$_db_verification_level
2477
-     *
2478
-     * @param string $wpdb_method
2479
-     * @param array  $arguments_to_provide
2480
-     * @return string
2481
-     */
2482
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2483
-    {
2484
-        /** @type WPDB $wpdb */
2485
-        global $wpdb;
2486
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2487
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2488
-        $error_message                    = sprintf(
2489
-            esc_html__(
2490
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2491
-                'event_espresso'
2492
-            ),
2493
-            $wpdb->last_error,
2494
-            $wpdb_method,
2495
-            wp_json_encode($arguments_to_provide)
2496
-        );
2497
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2498
-        return $error_message;
2499
-    }
2500
-
2501
-
2502
-    /**
2503
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2504
-     * EEM_Base::$_db_verification_level
2505
-     *
2506
-     * @param $wpdb_method
2507
-     * @param $arguments_to_provide
2508
-     * @return string
2509
-     */
2510
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2511
-    {
2512
-        /** @type WPDB $wpdb */
2513
-        global $wpdb;
2514
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2515
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2516
-        $error_message                    = sprintf(
2517
-            esc_html__(
2518
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2519
-                'event_espresso'
2520
-            ),
2521
-            $wpdb->last_error,
2522
-            $wpdb_method,
2523
-            wp_json_encode($arguments_to_provide)
2524
-        );
2525
-        EE_System::instance()->initialize_addons();
2526
-        return $error_message;
2527
-    }
2528
-
2529
-
2530
-    /**
2531
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2532
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2533
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2534
-     * ..."
2535
-     *
2536
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2537
-     * @return string
2538
-     */
2539
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2540
-    {
2541
-        return " FROM " . $model_query_info->get_full_join_sql() .
2542
-               $model_query_info->get_where_sql() .
2543
-               $model_query_info->get_group_by_sql() .
2544
-               $model_query_info->get_having_sql() .
2545
-               $model_query_info->get_order_by_sql() .
2546
-               $model_query_info->get_limit_sql();
2547
-    }
2548
-
2549
-
2550
-    /**
2551
-     * Set to easily debug the next X queries ran from this model.
2552
-     *
2553
-     * @param int $count
2554
-     */
2555
-    public function show_next_x_db_queries($count = 1)
2556
-    {
2557
-        $this->_show_next_x_db_queries = $count;
2558
-    }
2559
-
2560
-
2561
-    /**
2562
-     * @param $sql_query
2563
-     */
2564
-    public function show_db_query_if_previously_requested($sql_query)
2565
-    {
2566
-        if ($this->_show_next_x_db_queries > 0) {
2567
-            echo esc_html($sql_query);
2568
-            $this->_show_next_x_db_queries--;
2569
-        }
2570
-    }
2571
-
2572
-
2573
-    /**
2574
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2575
-     * There are the 3 cases:
2576
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2577
-     * $otherModelObject has no ID, it is first saved.
2578
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2579
-     * has no ID, it is first saved.
2580
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2581
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2582
-     * join table
2583
-     *
2584
-     * @param EE_Base_Class                     /int $thisModelObject
2585
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2586
-     * @param string $relationName                     , key in EEM_Base::_relations
2587
-     *                                                 an attendee to a group, you also want to specify which role they
2588
-     *                                                 will have in that group. So you would use this parameter to
2589
-     *                                                 specify array('role-column-name'=>'role-id')
2590
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2591
-     *                                                 to for relation to methods that allow you to further specify
2592
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2593
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2594
-     *                                                 because these will be inserted in any new rows created as well.
2595
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2596
-     * @throws EE_Error
2597
-     */
2598
-    public function add_relationship_to(
2599
-        $id_or_obj,
2600
-        $other_model_id_or_obj,
2601
-        $relationName,
2602
-        $extra_join_model_fields_n_values = []
2603
-    ) {
2604
-        $relation_obj = $this->related_settings_for($relationName);
2605
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2611
-     * There are the 3 cases:
2612
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2613
-     * error
2614
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2615
-     * an error
2616
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2617
-     *
2618
-     * @param EE_Base_Class /int $id_or_obj
2619
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2620
-     * @param string $relationName key in EEM_Base::_relations
2621
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2622
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2623
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2624
-     *                             because these will be inserted in any new rows created as well.
2625
-     * @return boolean of success
2626
-     * @throws EE_Error
2627
-     */
2628
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2629
-    {
2630
-        $relation_obj = $this->related_settings_for($relationName);
2631
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2632
-    }
2633
-
2634
-
2635
-    /**
2636
-     * @param mixed  $id_or_obj
2637
-     * @param string $relationName
2638
-     * @param array  $where_query_params
2639
-     * @param EE_Base_Class[] objects to which relations were removed
2640
-     * @return EE_Base_Class[]
2641
-     * @throws EE_Error
2642
-     */
2643
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2644
-    {
2645
-        $relation_obj = $this->related_settings_for($relationName);
2646
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2647
-    }
2648
-
2649
-
2650
-    /**
2651
-     * Gets all the related items of the specified $model_name, using $query_params.
2652
-     * Note: by default, we remove the "default query params"
2653
-     * because we want to get even deleted items etc.
2654
-     *
2655
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2656
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2657
-     * @param array  $query_params @see
2658
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2659
-     * @return EE_Base_Class[]
2660
-     * @throws EE_Error
2661
-     */
2662
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2663
-    {
2664
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2665
-        $relation_settings = $this->related_settings_for($model_name);
2666
-        return $relation_settings->get_all_related($model_obj, $query_params);
2667
-    }
2668
-
2669
-
2670
-    /**
2671
-     * Deletes all the model objects across the relation indicated by $model_name
2672
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2673
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2674
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2675
-     *
2676
-     * @param EE_Base_Class|int|string $id_or_obj
2677
-     * @param string                   $model_name
2678
-     * @param array                    $query_params
2679
-     * @return int how many deleted
2680
-     * @throws EE_Error
2681
-     */
2682
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2683
-    {
2684
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2685
-        $relation_settings = $this->related_settings_for($model_name);
2686
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2687
-    }
2688
-
2689
-
2690
-    /**
2691
-     * Hard deletes all the model objects across the relation indicated by $model_name
2692
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2693
-     * the model objects can't be hard deleted because of blocking related model objects,
2694
-     * just does a soft-delete on them instead.
2695
-     *
2696
-     * @param EE_Base_Class|int|string $id_or_obj
2697
-     * @param string                   $model_name
2698
-     * @param array                    $query_params
2699
-     * @return int how many deleted
2700
-     * @throws EE_Error
2701
-     */
2702
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2703
-    {
2704
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2705
-        $relation_settings = $this->related_settings_for($model_name);
2706
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2707
-    }
2708
-
2709
-
2710
-    /**
2711
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2712
-     * unless otherwise specified in the $query_params
2713
-     *
2714
-     * @param int             /EE_Base_Class $id_or_obj
2715
-     * @param string $model_name     like 'Event', or 'Registration'
2716
-     * @param array  $query_params   @see
2717
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2718
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2719
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2720
-     *                               that by the setting $distinct to TRUE;
2721
-     * @return int
2722
-     * @throws EE_Error
2723
-     */
2724
-    public function count_related(
2725
-        $id_or_obj,
2726
-        $model_name,
2727
-        $query_params = [],
2728
-        $field_to_count = null,
2729
-        $distinct = false
2730
-    ) {
2731
-        $related_model = $this->get_related_model_obj($model_name);
2732
-        // we're just going to use the query params on the related model's normal get_all query,
2733
-        // except add a condition to say to match the current mod
2734
-        if (! isset($query_params['default_where_conditions'])) {
2735
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2736
-        }
2737
-        $this_model_name                                                 = $this->get_this_model_name();
2738
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2739
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2740
-        return $related_model->count($query_params, $field_to_count, $distinct);
2741
-    }
2742
-
2743
-
2744
-    /**
2745
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2746
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2747
-     *
2748
-     * @param int           /EE_Base_Class $id_or_obj
2749
-     * @param string $model_name   like 'Event', or 'Registration'
2750
-     * @param array  $query_params @see
2751
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2752
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2753
-     * @return float
2754
-     * @throws EE_Error
2755
-     */
2756
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2757
-    {
2758
-        $related_model = $this->get_related_model_obj($model_name);
2759
-        if (! is_array($query_params)) {
2760
-            EE_Error::doing_it_wrong(
2761
-                'EEM_Base::sum_related',
2762
-                sprintf(
2763
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2764
-                    gettype($query_params)
2765
-                ),
2766
-                '4.6.0'
2767
-            );
2768
-            $query_params = [];
2769
-        }
2770
-        // we're just going to use the query params on the related model's normal get_all query,
2771
-        // except add a condition to say to match the current mod
2772
-        if (! isset($query_params['default_where_conditions'])) {
2773
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2774
-        }
2775
-        $this_model_name                                                 = $this->get_this_model_name();
2776
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2777
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2778
-        return $related_model->sum($query_params, $field_to_sum);
2779
-    }
2780
-
2781
-
2782
-    /**
2783
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2784
-     * $modelObject
2785
-     *
2786
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2787
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2788
-     * @param array               $query_params     @see
2789
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2790
-     * @return EE_Base_Class
2791
-     * @throws EE_Error
2792
-     */
2793
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2794
-    {
2795
-        $query_params['limit'] = 1;
2796
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2797
-        if ($results) {
2798
-            return array_shift($results);
2799
-        }
2800
-        return null;
2801
-    }
2802
-
2803
-
2804
-    /**
2805
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2806
-     *
2807
-     * @return string
2808
-     */
2809
-    public function get_this_model_name()
2810
-    {
2811
-        return str_replace("EEM_", "", get_class($this));
2812
-    }
2813
-
2814
-
2815
-    /**
2816
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2817
-     *
2818
-     * @return EE_Any_Foreign_Model_Name_Field
2819
-     * @throws EE_Error
2820
-     */
2821
-    public function get_field_containing_related_model_name()
2822
-    {
2823
-        foreach ($this->field_settings(true) as $field) {
2824
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2825
-                $field_with_model_name = $field;
2826
-            }
2827
-        }
2828
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2829
-            throw new EE_Error(
2830
-                sprintf(
2831
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2832
-                    $this->get_this_model_name()
2833
-                )
2834
-            );
2835
-        }
2836
-        return $field_with_model_name;
2837
-    }
2838
-
2839
-
2840
-    /**
2841
-     * Inserts a new entry into the database, for each table.
2842
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2843
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2844
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2845
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2846
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2847
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2848
-     *
2849
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2850
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2851
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2852
-     *                              of EEM_Base)
2853
-     * @return int|string new primary key on main table that got inserted
2854
-     * @throws EE_Error
2855
-     */
2856
-    public function insert($field_n_values)
2857
-    {
2858
-        /**
2859
-         * Filters the fields and their values before inserting an item using the models
2860
-         *
2861
-         * @param array    $fields_n_values keys are the fields and values are their new values
2862
-         * @param EEM_Base $model           the model used
2863
-         */
2864
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2865
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2866
-            $main_table = $this->_get_main_table();
2867
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2868
-            if ($new_id !== false) {
2869
-                foreach ($this->_get_other_tables() as $other_table) {
2870
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2871
-                }
2872
-            }
2873
-            /**
2874
-             * Done just after attempting to insert a new model object
2875
-             *
2876
-             * @param EEM_Base $model           used
2877
-             * @param array    $fields_n_values fields and their values
2878
-             * @param int|string the              ID of the newly-inserted model object
2879
-             */
2880
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2881
-            return $new_id;
2882
-        }
2883
-        return false;
2884
-    }
2885
-
2886
-
2887
-    /**
2888
-     * Checks that the result would satisfy the unique indexes on this model
2889
-     *
2890
-     * @param array  $field_n_values
2891
-     * @param string $action
2892
-     * @return boolean
2893
-     * @throws EE_Error
2894
-     */
2895
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2896
-    {
2897
-        foreach ($this->unique_indexes() as $index_name => $index) {
2898
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2899
-            if ($this->exists([$uniqueness_where_params])) {
2900
-                EE_Error::add_error(
2901
-                    sprintf(
2902
-                        esc_html__(
2903
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2904
-                            "event_espresso"
2905
-                        ),
2906
-                        $action,
2907
-                        $this->_get_class_name(),
2908
-                        $index_name,
2909
-                        implode(",", $index->field_names()),
2910
-                        http_build_query($uniqueness_where_params)
2911
-                    ),
2912
-                    __FILE__,
2913
-                    __FUNCTION__,
2914
-                    __LINE__
2915
-                );
2916
-                return false;
2917
-            }
2918
-        }
2919
-        return true;
2920
-    }
2921
-
2922
-
2923
-    /**
2924
-     * Checks the database for an item that conflicts (ie, if this item were
2925
-     * saved to the DB would break some uniqueness requirement, like a primary key
2926
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2927
-     * can be either an EE_Base_Class or an array of fields n values
2928
-     *
2929
-     * @param EE_Base_Class|array $obj_or_fields_array
2930
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2931
-     *                                                 when looking for conflicts
2932
-     *                                                 (ie, if false, we ignore the model object's primary key
2933
-     *                                                 when finding "conflicts". If true, it's also considered).
2934
-     *                                                 Only works for INT primary key,
2935
-     *                                                 STRING primary keys cannot be ignored
2936
-     * @return EE_Base_Class|array
2937
-     * @throws EE_Error
2938
-     * @throws ReflectionException
2939
-     */
2940
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2941
-    {
2942
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2943
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2944
-        } elseif (is_array($obj_or_fields_array)) {
2945
-            $fields_n_values = $obj_or_fields_array;
2946
-        } else {
2947
-            throw new EE_Error(
2948
-                sprintf(
2949
-                    esc_html__(
2950
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2951
-                        "event_espresso"
2952
-                    ),
2953
-                    get_class($this),
2954
-                    $obj_or_fields_array
2955
-                )
2956
-            );
2957
-        }
2958
-        $query_params = [];
2959
-        if (
2960
-            $this->has_primary_key_field()
2961
-            && ($include_primary_key
2962
-                || $this->get_primary_key_field()
2963
-                   instanceof
2964
-                   EE_Primary_Key_String_Field)
2965
-            && isset($fields_n_values[ $this->primary_key_name() ])
2966
-        ) {
2967
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2968
-        }
2969
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2970
-            $uniqueness_where_params                              =
2971
-                array_intersect_key($fields_n_values, $unique_index->fields());
2972
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2973
-        }
2974
-        // if there is nothing to base this search on, then we shouldn't find anything
2975
-        if (empty($query_params)) {
2976
-            return [];
2977
-        }
2978
-        return $this->get_one($query_params);
2979
-    }
2980
-
2981
-
2982
-    /**
2983
-     * Like count, but is optimized and returns a boolean instead of an int
2984
-     *
2985
-     * @param array $query_params
2986
-     * @return boolean
2987
-     * @throws EE_Error
2988
-     */
2989
-    public function exists($query_params)
2990
-    {
2991
-        $query_params['limit'] = 1;
2992
-        return $this->count($query_params) > 0;
2993
-    }
2994
-
2995
-
2996
-    /**
2997
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2998
-     *
2999
-     * @param int|string $id
3000
-     * @return boolean
3001
-     * @throws EE_Error
3002
-     */
3003
-    public function exists_by_ID($id)
3004
-    {
3005
-        return $this->exists(
3006
-            [
3007
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3008
-                [
3009
-                    $this->primary_key_name() => $id,
3010
-                ],
3011
-            ]
3012
-        );
3013
-    }
3014
-
3015
-
3016
-    /**
3017
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3018
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3019
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3020
-     * on the main table)
3021
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3022
-     * cases where we want to call it directly rather than via insert().
3023
-     *
3024
-     * @access   protected
3025
-     * @param EE_Table_Base $table
3026
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3027
-     *                                       float
3028
-     * @param int           $new_id          for now we assume only int keys
3029
-     * @return int ID of new row inserted, or FALSE on failure
3030
-     * @throws EE_Error
3031
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3032
-     */
3033
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3034
-    {
3035
-        global $wpdb;
3036
-        $insertion_col_n_values = [];
3037
-        $format_for_insertion   = [];
3038
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3039
-        foreach ($fields_on_table as $field_name => $field_obj) {
3040
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3041
-            if ($field_obj->is_auto_increment()) {
3042
-                continue;
3043
-            }
3044
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3046
-            if ($prepared_value !== null) {
3047
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3048
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3049
-            }
3050
-        }
3051
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3052
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3053
-            // so add the fk to the main table as a column
3054
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
-            $format_for_insertion[]                              =
3056
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3057
-        }
3058
-
3059
-        // insert the new entry
3060
-        $result = $this->_do_wpdb_query(
3061
-            'insert',
3062
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3063
-        );
3064
-        if ($result === false) {
3065
-            return false;
3066
-        }
3067
-        // ok, now what do we return for the ID of the newly-inserted thing?
3068
-        if ($this->has_primary_key_field()) {
3069
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3070
-                return $wpdb->insert_id;
3071
-            }
3072
-            // it's not an auto-increment primary key, so
3073
-            // it must have been supplied
3074
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3075
-        }
3076
-        // we can't return a  primary key because there is none. instead return
3077
-        // a unique string indicating this model
3078
-        return $this->get_index_primary_key_string($fields_n_values);
3079
-    }
3080
-
3081
-
3082
-    /**
3083
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3084
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3085
-     * and there is no default, we pass it along. WPDB will take care of it)
3086
-     *
3087
-     * @param EE_Model_Field_Base $field_obj
3088
-     * @param array               $fields_n_values
3089
-     * @return mixed string|int|float depending on what the table column will be expecting
3090
-     * @throws EE_Error
3091
-     */
3092
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3093
-    {
3094
-        $field_name = $field_obj->get_name();
3095
-        // if this field doesn't allow nullable, don't allow it
3096
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3097
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3098
-        }
3099
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3100
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3101
-    }
3102
-
3103
-
3104
-    /**
3105
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3106
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3107
-     * the field's prepare_for_set() method.
3108
-     *
3109
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3110
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3111
-     *                                   top of file)
3112
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3113
-     *                                   $value is a custom selection
3114
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3115
-     */
3116
-    private function _prepare_value_for_use_in_db($value, $field)
3117
-    {
3118
-        if ($field instanceof EE_Model_Field_Base) {
3119
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3120
-            switch ($this->_values_already_prepared_by_model_object) {
3121
-                /** @noinspection PhpMissingBreakStatementInspection */
3122
-                case self::not_prepared_by_model_object:
3123
-                    $value = $field->prepare_for_set($value);
3124
-                // purposefully left out "return"
3125
-                // no break
3126
-                case self::prepared_by_model_object:
3127
-                    /** @noinspection SuspiciousAssignmentsInspection */
3128
-                    $value = $field->prepare_for_use_in_db($value);
3129
-                // no break
3130
-                case self::prepared_for_use_in_db:
3131
-                    // leave the value alone
3132
-            }
3133
-            // phpcs:enable
3134
-        }
3135
-        return $value;
3136
-    }
3137
-
3138
-
3139
-    /**
3140
-     * Returns the main table on this model
3141
-     *
3142
-     * @return EE_Primary_Table
3143
-     * @throws EE_Error
3144
-     */
3145
-    protected function _get_main_table()
3146
-    {
3147
-        foreach ($this->_tables as $table) {
3148
-            if ($table instanceof EE_Primary_Table) {
3149
-                return $table;
3150
-            }
3151
-        }
3152
-        throw new EE_Error(
3153
-            sprintf(
3154
-                esc_html__(
3155
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3156
-                    'event_espresso'
3157
-                ),
3158
-                get_class($this)
3159
-            )
3160
-        );
3161
-    }
3162
-
3163
-
3164
-    /**
3165
-     * table
3166
-     * returns EE_Primary_Table table name
3167
-     *
3168
-     * @return string
3169
-     * @throws EE_Error
3170
-     */
3171
-    public function table()
3172
-    {
3173
-        return $this->_get_main_table()->get_table_name();
3174
-    }
3175
-
3176
-
3177
-    /**
3178
-     * table
3179
-     * returns first EE_Secondary_Table table name
3180
-     *
3181
-     * @return string
3182
-     */
3183
-    public function second_table()
3184
-    {
3185
-        // grab second table from tables array
3186
-        $second_table = end($this->_tables);
3187
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * get_table_obj_by_alias
3193
-     * returns table name given it's alias
3194
-     *
3195
-     * @param string $table_alias
3196
-     * @return EE_Primary_Table | EE_Secondary_Table
3197
-     */
3198
-    public function get_table_obj_by_alias($table_alias = '')
3199
-    {
3200
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3201
-    }
3202
-
3203
-
3204
-    /**
3205
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3206
-     *
3207
-     * @return EE_Secondary_Table[]
3208
-     */
3209
-    protected function _get_other_tables()
3210
-    {
3211
-        $other_tables = [];
3212
-        foreach ($this->_tables as $table_alias => $table) {
3213
-            if ($table instanceof EE_Secondary_Table) {
3214
-                $other_tables[ $table_alias ] = $table;
3215
-            }
3216
-        }
3217
-        return $other_tables;
3218
-    }
3219
-
3220
-
3221
-    /**
3222
-     * Finds all the fields that correspond to the given table
3223
-     *
3224
-     * @param string $table_alias , array key in EEM_Base::_tables
3225
-     * @return EE_Model_Field_Base[]
3226
-     */
3227
-    public function _get_fields_for_table($table_alias)
3228
-    {
3229
-        return $this->_fields[ $table_alias ];
3230
-    }
3231
-
3232
-
3233
-    /**
3234
-     * Recurses through all the where parameters, and finds all the related models we'll need
3235
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3236
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3237
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3238
-     * related Registration, Transaction, and Payment models.
3239
-     *
3240
-     * @param array $query_params @see
3241
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3242
-     * @return EE_Model_Query_Info_Carrier
3243
-     * @throws EE_Error
3244
-     */
3245
-    public function _extract_related_models_from_query($query_params)
3246
-    {
3247
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3248
-        if (array_key_exists(0, $query_params)) {
3249
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3250
-        }
3251
-        if (array_key_exists('group_by', $query_params)) {
3252
-            if (is_array($query_params['group_by'])) {
3253
-                $this->_extract_related_models_from_sub_params_array_values(
3254
-                    $query_params['group_by'],
3255
-                    $query_info_carrier,
3256
-                    'group_by'
3257
-                );
3258
-            } elseif (! empty($query_params['group_by'])) {
3259
-                $this->_extract_related_model_info_from_query_param(
3260
-                    $query_params['group_by'],
3261
-                    $query_info_carrier,
3262
-                    'group_by'
3263
-                );
3264
-            }
3265
-        }
3266
-        if (array_key_exists('having', $query_params)) {
3267
-            $this->_extract_related_models_from_sub_params_array_keys(
3268
-                $query_params[0],
3269
-                $query_info_carrier,
3270
-                'having'
3271
-            );
3272
-        }
3273
-        if (array_key_exists('order_by', $query_params)) {
3274
-            if (is_array($query_params['order_by'])) {
3275
-                $this->_extract_related_models_from_sub_params_array_keys(
3276
-                    $query_params['order_by'],
3277
-                    $query_info_carrier,
3278
-                    'order_by'
3279
-                );
3280
-            } elseif (! empty($query_params['order_by'])) {
3281
-                $this->_extract_related_model_info_from_query_param(
3282
-                    $query_params['order_by'],
3283
-                    $query_info_carrier,
3284
-                    'order_by'
3285
-                );
3286
-            }
3287
-        }
3288
-        if (array_key_exists('force_join', $query_params)) {
3289
-            $this->_extract_related_models_from_sub_params_array_values(
3290
-                $query_params['force_join'],
3291
-                $query_info_carrier,
3292
-                'force_join'
3293
-            );
3294
-        }
3295
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3296
-        return $query_info_carrier;
3297
-    }
3298
-
3299
-
3300
-    /**
3301
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3302
-     *
3303
-     * @param array                       $sub_query_params @see
3304
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3305
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3306
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3307
-     * @return EE_Model_Query_Info_Carrier
3308
-     * @throws EE_Error
3309
-     */
3310
-    private function _extract_related_models_from_sub_params_array_keys(
3311
-        $sub_query_params,
3312
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3313
-        $query_param_type
3314
-    ) {
3315
-        if (! empty($sub_query_params)) {
3316
-            $sub_query_params = (array) $sub_query_params;
3317
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3318
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3319
-                $this->_extract_related_model_info_from_query_param(
3320
-                    $param,
3321
-                    $model_query_info_carrier,
3322
-                    $query_param_type
3323
-                );
3324
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3325
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3326
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3327
-                // of array('Registration.TXN_ID'=>23)
3328
-                $query_param_sans_stars =
3329
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3330
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3331
-                    if (! is_array($possibly_array_of_params)) {
3332
-                        throw new EE_Error(
3333
-                            sprintf(
3334
-                                esc_html__(
3335
-                                    "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'))",
3336
-                                    "event_espresso"
3337
-                                ),
3338
-                                $param,
3339
-                                $possibly_array_of_params
3340
-                            )
3341
-                        );
3342
-                    }
3343
-                    $this->_extract_related_models_from_sub_params_array_keys(
3344
-                        $possibly_array_of_params,
3345
-                        $model_query_info_carrier,
3346
-                        $query_param_type
3347
-                    );
3348
-                } elseif (
3349
-                    $query_param_type === 0 // ie WHERE
3350
-                    && is_array($possibly_array_of_params)
3351
-                    && isset($possibly_array_of_params[2])
3352
-                    && $possibly_array_of_params[2] == true
3353
-                ) {
3354
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3355
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3356
-                    // from which we should extract query parameters!
3357
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3358
-                        throw new EE_Error(
3359
-                            sprintf(
3360
-                                esc_html__(
3361
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3362
-                                    "event_espresso"
3363
-                                ),
3364
-                                $query_param_type,
3365
-                                implode(",", $possibly_array_of_params)
3366
-                            )
3367
-                        );
3368
-                    }
3369
-                    $this->_extract_related_model_info_from_query_param(
3370
-                        $possibly_array_of_params[1],
3371
-                        $model_query_info_carrier,
3372
-                        $query_param_type
3373
-                    );
3374
-                }
3375
-            }
3376
-        }
3377
-        return $model_query_info_carrier;
3378
-    }
3379
-
3380
-
3381
-    /**
3382
-     * For extracting related models from forced_joins, where the array values contain the info about what
3383
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3384
-     *
3385
-     * @param array                       $sub_query_params @see
3386
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3387
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3388
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3389
-     * @return EE_Model_Query_Info_Carrier
3390
-     * @throws EE_Error
3391
-     */
3392
-    private function _extract_related_models_from_sub_params_array_values(
3393
-        $sub_query_params,
3394
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3395
-        $query_param_type
3396
-    ) {
3397
-        if (! empty($sub_query_params)) {
3398
-            if (! is_array($sub_query_params)) {
3399
-                throw new EE_Error(
3400
-                    sprintf(
3401
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3402
-                        $sub_query_params
3403
-                    )
3404
-                );
3405
-            }
3406
-            foreach ($sub_query_params as $param) {
3407
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3408
-                $this->_extract_related_model_info_from_query_param(
3409
-                    $param,
3410
-                    $model_query_info_carrier,
3411
-                    $query_param_type
3412
-                );
3413
-            }
3414
-        }
3415
-        return $model_query_info_carrier;
3416
-    }
3417
-
3418
-
3419
-    /**
3420
-     * Extract all the query parts from  model query params
3421
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3422
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3423
-     * but use them in a different order. Eg, we need to know what models we are querying
3424
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3425
-     * other models before we can finalize the where clause SQL.
3426
-     *
3427
-     * @param array $query_params @see
3428
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3429
-     * @return EE_Model_Query_Info_Carrier
3430
-     * @throws EE_Error
3431
-     * @throws ModelConfigurationException*@throws ReflectionException
3432
-     */
3433
-    public function _create_model_query_info_carrier($query_params)
3434
-    {
3435
-        if (! is_array($query_params)) {
3436
-            EE_Error::doing_it_wrong(
3437
-                'EEM_Base::_create_model_query_info_carrier',
3438
-                sprintf(
3439
-                    esc_html__(
3440
-                        '$query_params should be an array, you passed a variable of type %s',
3441
-                        'event_espresso'
3442
-                    ),
3443
-                    gettype($query_params)
3444
-                ),
3445
-                '4.6.0'
3446
-            );
3447
-            $query_params = [];
3448
-        }
3449
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3450
-        // first check if we should alter the query to account for caps or not
3451
-        // because the caps might require us to do extra joins
3452
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3453
-            $query_params[0] = array_replace_recursive(
3454
-                $query_params[0],
3455
-                $this->caps_where_conditions($query_params['caps'])
3456
-            );
3457
-        }
3458
-
3459
-        // check if we should alter the query to remove data related to protected
3460
-        // custom post types
3461
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3462
-            $where_param_key_for_password = $this->modelChainAndPassword();
3463
-            // only include if related to a cpt where no password has been set
3464
-            $query_params[0]['OR*nopassword'] = [
3465
-                $where_param_key_for_password       => '',
3466
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3467
-            ];
3468
-        }
3469
-        $query_object = $this->_extract_related_models_from_query($query_params);
3470
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3471
-        foreach ($query_params[0] as $key => $value) {
3472
-            if (is_int($key)) {
3473
-                throw new EE_Error(
3474
-                    sprintf(
3475
-                        esc_html__(
3476
-                            "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.",
3477
-                            "event_espresso"
3478
-                        ),
3479
-                        $key,
3480
-                        var_export($value, true),
3481
-                        var_export($query_params, true),
3482
-                        get_class($this)
3483
-                    )
3484
-                );
3485
-            }
3486
-        }
3487
-        if (
3488
-            array_key_exists('default_where_conditions', $query_params)
3489
-            && ! empty($query_params['default_where_conditions'])
3490
-        ) {
3491
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3492
-        } else {
3493
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3494
-        }
3495
-        $query_params[0] = array_merge(
3496
-            $this->_get_default_where_conditions_for_models_in_query(
3497
-                $query_object,
3498
-                $use_default_where_conditions,
3499
-                $query_params[0]
3500
-            ),
3501
-            $query_params[0]
3502
-        );
3503
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3504
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3505
-        // So we need to setup a subquery and use that for the main join.
3506
-        // Note for now this only works on the primary table for the model.
3507
-        // So for instance, you could set the limit array like this:
3508
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3509
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3510
-            $query_object->set_main_model_join_sql(
3511
-                $this->_construct_limit_join_select(
3512
-                    $query_params['on_join_limit'][0],
3513
-                    $query_params['on_join_limit'][1]
3514
-                )
3515
-            );
3516
-        }
3517
-        // set limit
3518
-        if (array_key_exists('limit', $query_params)) {
3519
-            if (is_array($query_params['limit'])) {
3520
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3521
-                    $e = sprintf(
3522
-                        esc_html__(
3523
-                            "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)",
3524
-                            "event_espresso"
3525
-                        ),
3526
-                        http_build_query($query_params['limit'])
3527
-                    );
3528
-                    throw new EE_Error($e . "|" . $e);
3529
-                }
3530
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3531
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3532
-            } elseif (! empty($query_params['limit'])) {
3533
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3534
-            }
3535
-        }
3536
-        // set order by
3537
-        if (array_key_exists('order_by', $query_params)) {
3538
-            if (is_array($query_params['order_by'])) {
3539
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3540
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3541
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3542
-                if (array_key_exists('order', $query_params)) {
3543
-                    throw new EE_Error(
3544
-                        sprintf(
3545
-                            esc_html__(
3546
-                                "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 ",
3547
-                                "event_espresso"
3548
-                            ),
3549
-                            get_class($this),
3550
-                            implode(", ", array_keys($query_params['order_by'])),
3551
-                            implode(", ", $query_params['order_by']),
3552
-                            $query_params['order']
3553
-                        )
3554
-                    );
3555
-                }
3556
-                $this->_extract_related_models_from_sub_params_array_keys(
3557
-                    $query_params['order_by'],
3558
-                    $query_object,
3559
-                    'order_by'
3560
-                );
3561
-                // assume it's an array of fields to order by
3562
-                $order_array = [];
3563
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3564
-                    $order         = $this->_extract_order($order);
3565
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3566
-                }
3567
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3568
-            } elseif (! empty($query_params['order_by'])) {
3569
-                $this->_extract_related_model_info_from_query_param(
3570
-                    $query_params['order_by'],
3571
-                    $query_object,
3572
-                    'order',
3573
-                    $query_params['order_by']
3574
-                );
3575
-                $order = isset($query_params['order'])
3576
-                    ? $this->_extract_order($query_params['order'])
3577
-                    : 'DESC';
3578
-                $query_object->set_order_by_sql(
3579
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3580
-                );
3581
-            }
3582
-        }
3583
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3584
-        if (
3585
-            ! array_key_exists('order_by', $query_params)
3586
-            && array_key_exists('order', $query_params)
3587
-            && ! empty($query_params['order'])
3588
-        ) {
3589
-            $pk_field = $this->get_primary_key_field();
3590
-            $order    = $this->_extract_order($query_params['order']);
3591
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3592
-        }
3593
-        // set group by
3594
-        if (array_key_exists('group_by', $query_params)) {
3595
-            if (is_array($query_params['group_by'])) {
3596
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3597
-                $group_by_array = [];
3598
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3599
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3600
-                }
3601
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3602
-            } elseif (! empty($query_params['group_by'])) {
3603
-                $query_object->set_group_by_sql(
3604
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3605
-                );
3606
-            }
3607
-        }
3608
-        // set having
3609
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3610
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3611
-        }
3612
-        // now, just verify they didn't pass anything wack
3613
-        foreach ($query_params as $query_key => $query_value) {
3614
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3615
-                throw new EE_Error(
3616
-                    sprintf(
3617
-                        esc_html__(
3618
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3619
-                            'event_espresso'
3620
-                        ),
3621
-                        $query_key,
3622
-                        get_class($this),
3623
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3624
-                        implode(',', $this->_allowed_query_params)
3625
-                    )
3626
-                );
3627
-            }
3628
-        }
3629
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3630
-        if (empty($main_model_join_sql)) {
3631
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3632
-        }
3633
-        return $query_object;
3634
-    }
3635
-
3636
-
3637
-    /**
3638
-     * Gets the where conditions that should be imposed on the query based on the
3639
-     * context (eg reading frontend, backend, edit or delete).
3640
-     *
3641
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3642
-     * @return array @see
3643
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3644
-     * @throws EE_Error
3645
-     */
3646
-    public function caps_where_conditions($context = self::caps_read)
3647
-    {
3648
-        EEM_Base::verify_is_valid_cap_context($context);
3649
-        $cap_where_conditions = [];
3650
-        $cap_restrictions     = $this->caps_missing($context);
3651
-        /**
3652
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3653
-         */
3654
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3655
-            $cap_where_conditions = array_replace_recursive(
3656
-                $cap_where_conditions,
3657
-                $restriction_if_no_cap->get_default_where_conditions()
3658
-            );
3659
-        }
3660
-        return apply_filters(
3661
-            'FHEE__EEM_Base__caps_where_conditions__return',
3662
-            $cap_where_conditions,
3663
-            $this,
3664
-            $context,
3665
-            $cap_restrictions
3666
-        );
3667
-    }
3668
-
3669
-
3670
-    /**
3671
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3672
-     * otherwise throws an exception
3673
-     *
3674
-     * @param string $should_be_order_string
3675
-     * @return string either ASC, asc, DESC or desc
3676
-     * @throws EE_Error
3677
-     */
3678
-    private function _extract_order($should_be_order_string)
3679
-    {
3680
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3681
-            return $should_be_order_string;
3682
-        }
3683
-        throw new EE_Error(
3684
-            sprintf(
3685
-                esc_html__(
3686
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3687
-                    "event_espresso"
3688
-                ),
3689
-                get_class($this),
3690
-                $should_be_order_string
3691
-            )
3692
-        );
3693
-    }
3694
-
3695
-
3696
-    /**
3697
-     * Looks at all the models which are included in this query, and asks each
3698
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3699
-     * so they can be merged
3700
-     *
3701
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3702
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3703
-     *                                                                  'none' means NO default where conditions will
3704
-     *                                                                  be used AT ALL during this query.
3705
-     *                                                                  'other_models_only' means default where
3706
-     *                                                                  conditions from other models will be used, but
3707
-     *                                                                  not for this primary model. 'all', the default,
3708
-     *                                                                  means default where conditions will apply as
3709
-     *                                                                  normal
3710
-     * @param array                       $where_query_params           @see
3711
-     *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3712
-     * @return array @see
3713
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3714
-     * @throws EE_Error
3715
-     */
3716
-    private function _get_default_where_conditions_for_models_in_query(
3717
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3718
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3719
-        $where_query_params = []
3720
-    ) {
3721
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3722
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3723
-            throw new EE_Error(
3724
-                sprintf(
3725
-                    esc_html__(
3726
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3727
-                        "event_espresso"
3728
-                    ),
3729
-                    $use_default_where_conditions,
3730
-                    implode(", ", $allowed_used_default_where_conditions_values)
3731
-                )
3732
-            );
3733
-        }
3734
-        $universal_query_params = [];
3735
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3736
-            $universal_query_params = $this->_get_default_where_conditions();
3737
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3738
-            $universal_query_params = $this->_get_minimum_where_conditions();
3739
-        }
3740
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3741
-            $related_model = $this->get_related_model_obj($model_name);
3742
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3743
-                $related_model_universal_where_params =
3744
-                    $related_model->_get_default_where_conditions($model_relation_path);
3745
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3746
-                $related_model_universal_where_params =
3747
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3748
-            } else {
3749
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3750
-                continue;
3751
-            }
3752
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3753
-                $related_model_universal_where_params,
3754
-                $where_query_params,
3755
-                $related_model,
3756
-                $model_relation_path
3757
-            );
3758
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3759
-                $universal_query_params,
3760
-                $overrides
3761
-            );
3762
-        }
3763
-        return $universal_query_params;
3764
-    }
3765
-
3766
-
3767
-    /**
3768
-     * Determines whether or not we should use default where conditions for the model in question
3769
-     * (this model, or other related models).
3770
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3771
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3772
-     * We should use default where conditions on related models when they requested to use default where conditions
3773
-     * on all models, or specifically just on other related models
3774
-     *
3775
-     * @param      $default_where_conditions_value
3776
-     * @param bool $for_this_model false means this is for OTHER related models
3777
-     * @return bool
3778
-     */
3779
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3780
-    {
3781
-        return (
3782
-                   $for_this_model
3783
-                   && in_array(
3784
-                       $default_where_conditions_value,
3785
-                       [
3786
-                           EEM_Base::default_where_conditions_all,
3787
-                           EEM_Base::default_where_conditions_this_only,
3788
-                           EEM_Base::default_where_conditions_minimum_others,
3789
-                       ],
3790
-                       true
3791
-                   )
3792
-               )
3793
-               || (
3794
-                   ! $for_this_model
3795
-                   && in_array(
3796
-                       $default_where_conditions_value,
3797
-                       [
3798
-                           EEM_Base::default_where_conditions_all,
3799
-                           EEM_Base::default_where_conditions_others_only,
3800
-                       ],
3801
-                       true
3802
-                   )
3803
-               );
3804
-    }
3805
-
3806
-
3807
-    /**
3808
-     * Determines whether or not we should use default minimum conditions for the model in question
3809
-     * (this model, or other related models).
3810
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3811
-     * where conditions.
3812
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3813
-     * on this model or others
3814
-     *
3815
-     * @param      $default_where_conditions_value
3816
-     * @param bool $for_this_model false means this is for OTHER related models
3817
-     * @return bool
3818
-     */
3819
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3820
-    {
3821
-        return (
3822
-                   $for_this_model
3823
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3824
-               )
3825
-               || (
3826
-                   ! $for_this_model
3827
-                   && in_array(
3828
-                       $default_where_conditions_value,
3829
-                       [
3830
-                           EEM_Base::default_where_conditions_minimum_others,
3831
-                           EEM_Base::default_where_conditions_minimum_all,
3832
-                       ],
3833
-                       true
3834
-                   )
3835
-               );
3836
-    }
3837
-
3838
-
3839
-    /**
3840
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3841
-     * then we also add a special where condition which allows for that model's primary key
3842
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3843
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3844
-     *
3845
-     * @param array    $default_where_conditions
3846
-     * @param array    $provided_where_conditions
3847
-     * @param EEM_Base $model
3848
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3849
-     * @return array @see
3850
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
-     * @throws EE_Error
3852
-     */
3853
-    private function _override_defaults_or_make_null_friendly(
3854
-        $default_where_conditions,
3855
-        $provided_where_conditions,
3856
-        $model,
3857
-        $model_relation_path
3858
-    ) {
3859
-        $null_friendly_where_conditions = [];
3860
-        $none_overridden                = true;
3861
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3862
-        foreach ($default_where_conditions as $key => $val) {
3863
-            if (isset($provided_where_conditions[ $key ])) {
3864
-                $none_overridden = false;
3865
-            } else {
3866
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3867
-            }
3868
-        }
3869
-        if ($none_overridden && $default_where_conditions) {
3870
-            if ($model->has_primary_key_field()) {
3871
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3872
-                                                                                   . "."
3873
-                                                                                   . $model->primary_key_name() ] =
3874
-                    ['IS NULL'];
3875
-            }/*else{
1804
+		// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1806
+		/**
1807
+		 * Action called after a model update call has been made.
1808
+		 *
1809
+		 * @param EEM_Base $model
1810
+		 * @param array    $fields_n_values the updated fields and their new values
1811
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1812
+		 * @param int      $rows_affected
1813
+		 */
1814
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1815
+		return $rows_affected;// how many supposedly got updated
1816
+	}
1817
+
1818
+
1819
+	/**
1820
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1821
+	 * are teh values of the field specified (or by default the primary key field)
1822
+	 * that matched the query params. Note that you should pass the name of the
1823
+	 * model FIELD, not the database table's column name.
1824
+	 *
1825
+	 * @param array  $query_params @see
1826
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1827
+	 * @param string $field_to_select
1828
+	 * @return array just like $wpdb->get_col()
1829
+	 * @throws EE_Error
1830
+	 */
1831
+	public function get_col($query_params = [], $field_to_select = null)
1832
+	{
1833
+		if ($field_to_select) {
1834
+			$field = $this->field_settings_for($field_to_select);
1835
+		} elseif ($this->has_primary_key_field()) {
1836
+			$field = $this->get_primary_key_field();
1837
+		} else {
1838
+			// no primary key, just grab the first column
1839
+			$field_settings = $this->field_settings();
1840
+			$field          = reset($field_settings);
1841
+		}
1842
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1843
+		$select_expressions = $field->get_qualified_column();
1844
+		$SQL                =
1845
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1846
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1847
+	}
1848
+
1849
+
1850
+	/**
1851
+	 * Returns a single column value for a single row from the database
1852
+	 *
1853
+	 * @param array  $query_params    @see
1854
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1855
+	 * @param string $field_to_select @see EEM_Base::get_col()
1856
+	 * @return string
1857
+	 * @throws EE_Error
1858
+	 */
1859
+	public function get_var($query_params = [], $field_to_select = null)
1860
+	{
1861
+		$query_params['limit'] = 1;
1862
+		$col                   = $this->get_col($query_params, $field_to_select);
1863
+		if (! empty($col)) {
1864
+			return reset($col);
1865
+		}
1866
+		return null;
1867
+	}
1868
+
1869
+
1870
+	/**
1871
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1872
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1873
+	 * injection, but currently no further filtering is done
1874
+	 *
1875
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1876
+	 *                               be updated to in the DB
1877
+	 * @return string of SQL
1878
+	 * @throws EE_Error
1879
+	 * @global      $wpdb
1880
+	 */
1881
+	public function _construct_update_sql($fields_n_values)
1882
+	{
1883
+		/** @type WPDB $wpdb */
1884
+		global $wpdb;
1885
+		$cols_n_values = [];
1886
+		foreach ($fields_n_values as $field_name => $value) {
1887
+			$field_obj = $this->field_settings_for($field_name);
1888
+			// if the value is NULL, we want to assign the value to that.
1889
+			// wpdb->prepare doesn't really handle that properly
1890
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891
+			$value_sql       = $prepared_value === null ? 'NULL'
1892
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1894
+		}
1895
+		return implode(",", $cols_n_values);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1901
+	 * Performs a HARD delete, meaning the database row should always be removed,
1902
+	 * not just have a flag field on it switched
1903
+	 * Wrapper for EEM_Base::delete_permanently()
1904
+	 *
1905
+	 * @param mixed   $id
1906
+	 * @param boolean $allow_blocking
1907
+	 * @return int the number of rows deleted
1908
+	 * @throws EE_Error
1909
+	 */
1910
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1911
+	{
1912
+		return $this->delete_permanently(
1913
+			[
1914
+				[$this->get_primary_key_field()->get_name() => $id],
1915
+				'limit' => 1,
1916
+			],
1917
+			$allow_blocking
1918
+		);
1919
+	}
1920
+
1921
+
1922
+	/**
1923
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1924
+	 * Wrapper for EEM_Base::delete()
1925
+	 *
1926
+	 * @param mixed   $id
1927
+	 * @param boolean $allow_blocking
1928
+	 * @return int the number of rows deleted
1929
+	 * @throws EE_Error
1930
+	 */
1931
+	public function delete_by_ID($id, $allow_blocking = true)
1932
+	{
1933
+		return $this->delete(
1934
+			[
1935
+				[$this->get_primary_key_field()->get_name() => $id],
1936
+				'limit' => 1,
1937
+			],
1938
+			$allow_blocking
1939
+		);
1940
+	}
1941
+
1942
+
1943
+	/**
1944
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1945
+	 * meaning if the model has a field that indicates its been "trashed" or
1946
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1947
+	 *
1948
+	 * @param array   $query_params
1949
+	 * @param boolean $allow_blocking
1950
+	 * @return int how many rows got deleted
1951
+	 * @throws EE_Error
1952
+	 * @see EEM_Base::delete_permanently
1953
+	 */
1954
+	public function delete($query_params, $allow_blocking = true)
1955
+	{
1956
+		return $this->delete_permanently($query_params, $allow_blocking);
1957
+	}
1958
+
1959
+
1960
+	/**
1961
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1962
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1963
+	 * as archived, not actually deleted
1964
+	 *
1965
+	 * @param array   $query_params   @see
1966
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1967
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1968
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1969
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1970
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1971
+	 *                                DB
1972
+	 * @return int how many rows got deleted
1973
+	 * @throws EE_Error
1974
+	 * @throws ReflectionException
1975
+	 */
1976
+	public function delete_permanently($query_params, $allow_blocking = true)
1977
+	{
1978
+		/**
1979
+		 * Action called just before performing a real deletion query. You can use the
1980
+		 * model and its $query_params to find exactly which items will be deleted
1981
+		 *
1982
+		 * @param EEM_Base $model
1983
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1984
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1985
+		 *                                 to block (prevent) this deletion
1986
+		 */
1987
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1988
+		// some MySQL databases may be running safe mode, which may restrict
1989
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1990
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1991
+		// to delete them
1992
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1993
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1994
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1995
+			$columns_and_ids_for_deleting
1996
+		);
1997
+		/**
1998
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1999
+		 *
2000
+		 * @param EEM_Base $this                            The model instance being acted on.
2001
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
2002
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
2003
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
2004
+		 *                                                  derived from the incoming query parameters.
2005
+		 * @see details on the structure of this array in the phpdocs
2006
+		 *                                                  for the `_get_ids_for_delete_method`
2007
+		 *
2008
+		 */
2009
+		do_action(
2010
+			'AHEE__EEM_Base__delete__before_query',
2011
+			$this,
2012
+			$query_params,
2013
+			$allow_blocking,
2014
+			$columns_and_ids_for_deleting
2015
+		);
2016
+		if ($deletion_where_query_part) {
2017
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2018
+			$table_aliases    = array_keys($this->_tables);
2019
+			$SQL              = "DELETE "
2020
+								. implode(", ", $table_aliases)
2021
+								. " FROM "
2022
+								. $model_query_info->get_full_join_sql()
2023
+								. " WHERE "
2024
+								. $deletion_where_query_part;
2025
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2026
+		} else {
2027
+			$rows_deleted = 0;
2028
+		}
2029
+
2030
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2031
+		// there was no error with the delete query.
2032
+		if (
2033
+			$this->has_primary_key_field()
2034
+			&& $rows_deleted !== false
2035
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2036
+		) {
2037
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2038
+			foreach ($ids_for_removal as $id) {
2039
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2040
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2041
+				}
2042
+			}
2043
+
2044
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2045
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2046
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2047
+			// (although it is possible).
2048
+			// Note this can be skipped by using the provided filter and returning false.
2049
+			if (
2050
+				apply_filters(
2051
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2052
+					! $this instanceof EEM_Extra_Meta,
2053
+					$this
2054
+				)
2055
+			) {
2056
+				EEM_Extra_Meta::instance()->delete_permanently([
2057
+																   0 => [
2058
+																	   'EXM_type' => $this->get_this_model_name(),
2059
+																	   'OBJ_ID'   => [
2060
+																		   'IN',
2061
+																		   $ids_for_removal,
2062
+																	   ],
2063
+																   ],
2064
+															   ]);
2065
+			}
2066
+		}
2067
+
2068
+		/**
2069
+		 * Action called just after performing a real deletion query. Although at this point the
2070
+		 * items should have been deleted
2071
+		 *
2072
+		 * @param EEM_Base $model
2073
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2074
+		 * @param int      $rows_deleted
2075
+		 */
2076
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2077
+		return $rows_deleted;// how many supposedly got deleted
2078
+	}
2079
+
2080
+
2081
+	/**
2082
+	 * Checks all the relations that throw error messages when there are blocking related objects
2083
+	 * for related model objects. If there are any related model objects on those relations,
2084
+	 * adds an EE_Error, and return true
2085
+	 *
2086
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2087
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2088
+	 *                                                 should be ignored when determining whether there are related
2089
+	 *                                                 model objects which block this model object's deletion. Useful
2090
+	 *                                                 if you know A is related to B and are considering deleting A,
2091
+	 *                                                 but want to see if A has any other objects blocking its deletion
2092
+	 *                                                 before removing the relation between A and B
2093
+	 * @return boolean
2094
+	 * @throws EE_Error
2095
+	 * @throws ReflectionException
2096
+	 */
2097
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2098
+	{
2099
+		// first, if $ignore_this_model_obj was supplied, get its model
2100
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2101
+			$ignored_model = $ignore_this_model_obj->get_model();
2102
+		} else {
2103
+			$ignored_model = null;
2104
+		}
2105
+		// now check all the relations of $this_model_obj_or_id and see if there
2106
+		// are any related model objects blocking it?
2107
+		$is_blocked = false;
2108
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2109
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2110
+				// if $ignore_this_model_obj was supplied, then for the query
2111
+				// on that model needs to be told to ignore $ignore_this_model_obj
2112
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2113
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2114
+						[
2115
+							$ignored_model->get_primary_key_field()->get_name() => [
2116
+								'!=',
2117
+								$ignore_this_model_obj->ID(),
2118
+							],
2119
+						],
2120
+					]);
2121
+				} else {
2122
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2123
+				}
2124
+				if ($related_model_objects) {
2125
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2126
+					$is_blocked = true;
2127
+				}
2128
+			}
2129
+		}
2130
+		return $is_blocked;
2131
+	}
2132
+
2133
+
2134
+	/**
2135
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2136
+	 *
2137
+	 * @param array $row_results_for_deleting
2138
+	 * @param bool  $allow_blocking
2139
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2140
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2141
+	 *                              dimension array where the key is the fully qualified primary key column and the
2142
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2143
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2144
+	 *                              be a two dimensional array where each element is a group of columns and values that
2145
+	 *                              get deleted. Example: array(
2146
+	 *                              0 => array(
2147
+	 *                              'Term_Relationship.object_id' => 1
2148
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2149
+	 *                              ),
2150
+	 *                              1 => array(
2151
+	 *                              'Term_Relationship.object_id' => 1
2152
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2153
+	 *                              )
2154
+	 *                              )
2155
+	 * @throws EE_Error
2156
+	 */
2157
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2158
+	{
2159
+		$ids_to_delete_indexed_by_column = [];
2160
+		if ($this->has_primary_key_field()) {
2161
+			$primary_table                   = $this->_get_main_table();
2162
+			$primary_table_pk_field          =
2163
+				$this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2164
+			$other_tables                    = $this->_get_other_tables();
2165
+			$ids_to_delete_indexed_by_column = $query = [];
2166
+			foreach ($row_results_for_deleting as $item_to_delete) {
2167
+				// before we mark this item for deletion,
2168
+				// make sure there's no related entities blocking its deletion (if we're checking)
2169
+				if (
2170
+					$allow_blocking
2171
+					&& $this->delete_is_blocked_by_related_models(
2172
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2173
+					)
2174
+				) {
2175
+					continue;
2176
+				}
2177
+				// primary table deletes
2178
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2179
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2180
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2181
+				}
2182
+			}
2183
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2184
+			$fields = $this->get_combined_primary_key_fields();
2185
+			foreach ($row_results_for_deleting as $item_to_delete) {
2186
+				$ids_to_delete_indexed_by_column_for_row = [];
2187
+				foreach ($fields as $cpk_field) {
2188
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2189
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2190
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2191
+					}
2192
+				}
2193
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2194
+			}
2195
+		} else {
2196
+			// so there's no primary key and no combined key...
2197
+			// sorry, can't help you
2198
+			throw new EE_Error(
2199
+				sprintf(
2200
+					esc_html__(
2201
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2202
+						"event_espresso"
2203
+					),
2204
+					get_class($this)
2205
+				)
2206
+			);
2207
+		}
2208
+		return $ids_to_delete_indexed_by_column;
2209
+	}
2210
+
2211
+
2212
+	/**
2213
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2214
+	 * the corresponding query_part for the query performing the delete.
2215
+	 *
2216
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2217
+	 * @return string
2218
+	 * @throws EE_Error
2219
+	 */
2220
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2221
+	{
2222
+		$query_part = '';
2223
+		if (empty($ids_to_delete_indexed_by_column)) {
2224
+			return $query_part;
2225
+		} elseif ($this->has_primary_key_field()) {
2226
+			$query = [];
2227
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2228
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2229
+			}
2230
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2231
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2232
+			$ways_to_identify_a_row = [];
2233
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2234
+				$values_for_each_combined_primary_key_for_a_row = [];
2235
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2236
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2237
+				}
2238
+				$ways_to_identify_a_row[] = '('
2239
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2240
+											. ')';
2241
+			}
2242
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2243
+		}
2244
+		return $query_part;
2245
+	}
2246
+
2247
+
2248
+	/**
2249
+	 * Gets the model field by the fully qualified name
2250
+	 *
2251
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2252
+	 * @return EE_Model_Field_Base
2253
+	 * @throws EE_Error
2254
+	 * @throws EE_Error
2255
+	 */
2256
+	public function get_field_by_column($qualified_column_name)
2257
+	{
2258
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2259
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2260
+				return $field_obj;
2261
+			}
2262
+		}
2263
+		throw new EE_Error(
2264
+			sprintf(
2265
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2266
+				$this->get_this_model_name(),
2267
+				$qualified_column_name
2268
+			)
2269
+		);
2270
+	}
2271
+
2272
+
2273
+	/**
2274
+	 * Count all the rows that match criteria the model query params.
2275
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2276
+	 * column
2277
+	 *
2278
+	 * @param array  $query_params   @see
2279
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2280
+	 * @param string $field_to_count field on model to count by (not column name)
2281
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2282
+	 *                               that by the setting $distinct to TRUE;
2283
+	 * @return int
2284
+	 * @throws EE_Error
2285
+	 */
2286
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2287
+	{
2288
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2289
+		if ($field_to_count) {
2290
+			$field_obj       = $this->field_settings_for($field_to_count);
2291
+			$column_to_count = $field_obj->get_qualified_column();
2292
+		} elseif ($this->has_primary_key_field()) {
2293
+			$pk_field_obj    = $this->get_primary_key_field();
2294
+			$column_to_count = $pk_field_obj->get_qualified_column();
2295
+		} else {
2296
+			// there's no primary key
2297
+			// if we're counting distinct items, and there's no primary key,
2298
+			// we need to list out the columns for distinction;
2299
+			// otherwise we can just use star
2300
+			if ($distinct) {
2301
+				$columns_to_use = [];
2302
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2303
+					$columns_to_use[] = $field_obj->get_qualified_column();
2304
+				}
2305
+				$column_to_count = implode(',', $columns_to_use);
2306
+			} else {
2307
+				$column_to_count = '*';
2308
+			}
2309
+		}
2310
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2311
+		$SQL             =
2312
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2314
+	}
2315
+
2316
+
2317
+	/**
2318
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2319
+	 *
2320
+	 * @param array  $query_params @see
2321
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2322
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2323
+	 * @return float
2324
+	 * @throws EE_Error
2325
+	 */
2326
+	public function sum($query_params, $field_to_sum = null)
2327
+	{
2328
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2329
+		if ($field_to_sum) {
2330
+			$field_obj = $this->field_settings_for($field_to_sum);
2331
+		} else {
2332
+			$field_obj = $this->get_primary_key_field();
2333
+		}
2334
+		$column_to_count = $field_obj->get_qualified_column();
2335
+		$SQL             =
2336
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2337
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2338
+		$data_type       = $field_obj->get_wpdb_data_type();
2339
+		if ($data_type === '%d' || $data_type === '%s') {
2340
+			return (float) $return_value;
2341
+		}
2342
+		// must be %f
2343
+		return (float) $return_value;
2344
+	}
2345
+
2346
+
2347
+	/**
2348
+	 * Just calls the specified method on $wpdb with the given arguments
2349
+	 * Consolidates a little extra error handling code
2350
+	 *
2351
+	 * @param string $wpdb_method
2352
+	 * @param array  $arguments_to_provide
2353
+	 * @return mixed
2354
+	 * @throws EE_Error
2355
+	 * @global wpdb  $wpdb
2356
+	 */
2357
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2358
+	{
2359
+		// if we're in maintenance mode level 2, DON'T run any queries
2360
+		// because level 2 indicates the database needs updating and
2361
+		// is probably out of sync with the code
2362
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2363
+			throw new EE_Error(
2364
+				sprintf(
2365
+					esc_html__(
2366
+						"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.",
2367
+						"event_espresso"
2368
+					)
2369
+				)
2370
+			);
2371
+		}
2372
+		/** @type WPDB $wpdb */
2373
+		global $wpdb;
2374
+		if (! method_exists($wpdb, $wpdb_method)) {
2375
+			throw new EE_Error(
2376
+				sprintf(
2377
+					esc_html__(
2378
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2379
+						'event_espresso'
2380
+					),
2381
+					$wpdb_method
2382
+				)
2383
+			);
2384
+		}
2385
+		if (WP_DEBUG) {
2386
+			$old_show_errors_value = $wpdb->show_errors;
2387
+			$wpdb->show_errors(false);
2388
+		}
2389
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2390
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2391
+		if (WP_DEBUG) {
2392
+			$wpdb->show_errors($old_show_errors_value);
2393
+			if (! empty($wpdb->last_error)) {
2394
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2395
+			}
2396
+			if ($result === false) {
2397
+				throw new EE_Error(
2398
+					sprintf(
2399
+						esc_html__(
2400
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2401
+							'event_espresso'
2402
+						),
2403
+						$wpdb_method,
2404
+						var_export($arguments_to_provide, true)
2405
+					)
2406
+				);
2407
+			}
2408
+		} elseif ($result === false) {
2409
+			EE_Error::add_error(
2410
+				sprintf(
2411
+					esc_html__(
2412
+						'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"',
2413
+						'event_espresso'
2414
+					),
2415
+					$wpdb_method,
2416
+					var_export($arguments_to_provide, true),
2417
+					$wpdb->last_error
2418
+				),
2419
+				__FILE__,
2420
+				__FUNCTION__,
2421
+				__LINE__
2422
+			);
2423
+		}
2424
+		return $result;
2425
+	}
2426
+
2427
+
2428
+	/**
2429
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2430
+	 * and if there's an error tries to verify the DB is correct. Uses
2431
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2432
+	 * we should try to fix the EE core db, the addons, or just give up
2433
+	 *
2434
+	 * @param string $wpdb_method
2435
+	 * @param array  $arguments_to_provide
2436
+	 * @return mixed
2437
+	 */
2438
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2439
+	{
2440
+		/** @type WPDB $wpdb */
2441
+		global $wpdb;
2442
+		$wpdb->last_error = null;
2443
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2444
+		// was there an error running the query? but we don't care on new activations
2445
+		// (we're going to setup the DB anyway on new activations)
2446
+		if (
2447
+			($result === false || ! empty($wpdb->last_error))
2448
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2449
+		) {
2450
+			switch (EEM_Base::$_db_verification_level) {
2451
+				case EEM_Base::db_verified_none:
2452
+					// let's double-check core's DB
2453
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2454
+					break;
2455
+				case EEM_Base::db_verified_core:
2456
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2457
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2458
+					break;
2459
+				case EEM_Base::db_verified_addons:
2460
+					// ummmm... you in trouble
2461
+					return $result;
2462
+					break;
2463
+			}
2464
+			if (! empty($error_message)) {
2465
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2466
+				trigger_error($error_message);
2467
+			}
2468
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2469
+		}
2470
+		return $result;
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2476
+	 * EEM_Base::$_db_verification_level
2477
+	 *
2478
+	 * @param string $wpdb_method
2479
+	 * @param array  $arguments_to_provide
2480
+	 * @return string
2481
+	 */
2482
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2483
+	{
2484
+		/** @type WPDB $wpdb */
2485
+		global $wpdb;
2486
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2487
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2488
+		$error_message                    = sprintf(
2489
+			esc_html__(
2490
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2491
+				'event_espresso'
2492
+			),
2493
+			$wpdb->last_error,
2494
+			$wpdb_method,
2495
+			wp_json_encode($arguments_to_provide)
2496
+		);
2497
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2498
+		return $error_message;
2499
+	}
2500
+
2501
+
2502
+	/**
2503
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2504
+	 * EEM_Base::$_db_verification_level
2505
+	 *
2506
+	 * @param $wpdb_method
2507
+	 * @param $arguments_to_provide
2508
+	 * @return string
2509
+	 */
2510
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2511
+	{
2512
+		/** @type WPDB $wpdb */
2513
+		global $wpdb;
2514
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2515
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2516
+		$error_message                    = sprintf(
2517
+			esc_html__(
2518
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2519
+				'event_espresso'
2520
+			),
2521
+			$wpdb->last_error,
2522
+			$wpdb_method,
2523
+			wp_json_encode($arguments_to_provide)
2524
+		);
2525
+		EE_System::instance()->initialize_addons();
2526
+		return $error_message;
2527
+	}
2528
+
2529
+
2530
+	/**
2531
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2532
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2533
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2534
+	 * ..."
2535
+	 *
2536
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2537
+	 * @return string
2538
+	 */
2539
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2540
+	{
2541
+		return " FROM " . $model_query_info->get_full_join_sql() .
2542
+			   $model_query_info->get_where_sql() .
2543
+			   $model_query_info->get_group_by_sql() .
2544
+			   $model_query_info->get_having_sql() .
2545
+			   $model_query_info->get_order_by_sql() .
2546
+			   $model_query_info->get_limit_sql();
2547
+	}
2548
+
2549
+
2550
+	/**
2551
+	 * Set to easily debug the next X queries ran from this model.
2552
+	 *
2553
+	 * @param int $count
2554
+	 */
2555
+	public function show_next_x_db_queries($count = 1)
2556
+	{
2557
+		$this->_show_next_x_db_queries = $count;
2558
+	}
2559
+
2560
+
2561
+	/**
2562
+	 * @param $sql_query
2563
+	 */
2564
+	public function show_db_query_if_previously_requested($sql_query)
2565
+	{
2566
+		if ($this->_show_next_x_db_queries > 0) {
2567
+			echo esc_html($sql_query);
2568
+			$this->_show_next_x_db_queries--;
2569
+		}
2570
+	}
2571
+
2572
+
2573
+	/**
2574
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2575
+	 * There are the 3 cases:
2576
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2577
+	 * $otherModelObject has no ID, it is first saved.
2578
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2579
+	 * has no ID, it is first saved.
2580
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2581
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2582
+	 * join table
2583
+	 *
2584
+	 * @param EE_Base_Class                     /int $thisModelObject
2585
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2586
+	 * @param string $relationName                     , key in EEM_Base::_relations
2587
+	 *                                                 an attendee to a group, you also want to specify which role they
2588
+	 *                                                 will have in that group. So you would use this parameter to
2589
+	 *                                                 specify array('role-column-name'=>'role-id')
2590
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2591
+	 *                                                 to for relation to methods that allow you to further specify
2592
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2593
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2594
+	 *                                                 because these will be inserted in any new rows created as well.
2595
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2596
+	 * @throws EE_Error
2597
+	 */
2598
+	public function add_relationship_to(
2599
+		$id_or_obj,
2600
+		$other_model_id_or_obj,
2601
+		$relationName,
2602
+		$extra_join_model_fields_n_values = []
2603
+	) {
2604
+		$relation_obj = $this->related_settings_for($relationName);
2605
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2611
+	 * There are the 3 cases:
2612
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2613
+	 * error
2614
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2615
+	 * an error
2616
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2617
+	 *
2618
+	 * @param EE_Base_Class /int $id_or_obj
2619
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2620
+	 * @param string $relationName key in EEM_Base::_relations
2621
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2622
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2623
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2624
+	 *                             because these will be inserted in any new rows created as well.
2625
+	 * @return boolean of success
2626
+	 * @throws EE_Error
2627
+	 */
2628
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2629
+	{
2630
+		$relation_obj = $this->related_settings_for($relationName);
2631
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2632
+	}
2633
+
2634
+
2635
+	/**
2636
+	 * @param mixed  $id_or_obj
2637
+	 * @param string $relationName
2638
+	 * @param array  $where_query_params
2639
+	 * @param EE_Base_Class[] objects to which relations were removed
2640
+	 * @return EE_Base_Class[]
2641
+	 * @throws EE_Error
2642
+	 */
2643
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2644
+	{
2645
+		$relation_obj = $this->related_settings_for($relationName);
2646
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2647
+	}
2648
+
2649
+
2650
+	/**
2651
+	 * Gets all the related items of the specified $model_name, using $query_params.
2652
+	 * Note: by default, we remove the "default query params"
2653
+	 * because we want to get even deleted items etc.
2654
+	 *
2655
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2656
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2657
+	 * @param array  $query_params @see
2658
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2659
+	 * @return EE_Base_Class[]
2660
+	 * @throws EE_Error
2661
+	 */
2662
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2663
+	{
2664
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2665
+		$relation_settings = $this->related_settings_for($model_name);
2666
+		return $relation_settings->get_all_related($model_obj, $query_params);
2667
+	}
2668
+
2669
+
2670
+	/**
2671
+	 * Deletes all the model objects across the relation indicated by $model_name
2672
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2673
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2674
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2675
+	 *
2676
+	 * @param EE_Base_Class|int|string $id_or_obj
2677
+	 * @param string                   $model_name
2678
+	 * @param array                    $query_params
2679
+	 * @return int how many deleted
2680
+	 * @throws EE_Error
2681
+	 */
2682
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2683
+	{
2684
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2685
+		$relation_settings = $this->related_settings_for($model_name);
2686
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2687
+	}
2688
+
2689
+
2690
+	/**
2691
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2692
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2693
+	 * the model objects can't be hard deleted because of blocking related model objects,
2694
+	 * just does a soft-delete on them instead.
2695
+	 *
2696
+	 * @param EE_Base_Class|int|string $id_or_obj
2697
+	 * @param string                   $model_name
2698
+	 * @param array                    $query_params
2699
+	 * @return int how many deleted
2700
+	 * @throws EE_Error
2701
+	 */
2702
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2703
+	{
2704
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2705
+		$relation_settings = $this->related_settings_for($model_name);
2706
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2707
+	}
2708
+
2709
+
2710
+	/**
2711
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2712
+	 * unless otherwise specified in the $query_params
2713
+	 *
2714
+	 * @param int             /EE_Base_Class $id_or_obj
2715
+	 * @param string $model_name     like 'Event', or 'Registration'
2716
+	 * @param array  $query_params   @see
2717
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2718
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2719
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2720
+	 *                               that by the setting $distinct to TRUE;
2721
+	 * @return int
2722
+	 * @throws EE_Error
2723
+	 */
2724
+	public function count_related(
2725
+		$id_or_obj,
2726
+		$model_name,
2727
+		$query_params = [],
2728
+		$field_to_count = null,
2729
+		$distinct = false
2730
+	) {
2731
+		$related_model = $this->get_related_model_obj($model_name);
2732
+		// we're just going to use the query params on the related model's normal get_all query,
2733
+		// except add a condition to say to match the current mod
2734
+		if (! isset($query_params['default_where_conditions'])) {
2735
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2736
+		}
2737
+		$this_model_name                                                 = $this->get_this_model_name();
2738
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2739
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2740
+		return $related_model->count($query_params, $field_to_count, $distinct);
2741
+	}
2742
+
2743
+
2744
+	/**
2745
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2746
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2747
+	 *
2748
+	 * @param int           /EE_Base_Class $id_or_obj
2749
+	 * @param string $model_name   like 'Event', or 'Registration'
2750
+	 * @param array  $query_params @see
2751
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2752
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2753
+	 * @return float
2754
+	 * @throws EE_Error
2755
+	 */
2756
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2757
+	{
2758
+		$related_model = $this->get_related_model_obj($model_name);
2759
+		if (! is_array($query_params)) {
2760
+			EE_Error::doing_it_wrong(
2761
+				'EEM_Base::sum_related',
2762
+				sprintf(
2763
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2764
+					gettype($query_params)
2765
+				),
2766
+				'4.6.0'
2767
+			);
2768
+			$query_params = [];
2769
+		}
2770
+		// we're just going to use the query params on the related model's normal get_all query,
2771
+		// except add a condition to say to match the current mod
2772
+		if (! isset($query_params['default_where_conditions'])) {
2773
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2774
+		}
2775
+		$this_model_name                                                 = $this->get_this_model_name();
2776
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2777
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2778
+		return $related_model->sum($query_params, $field_to_sum);
2779
+	}
2780
+
2781
+
2782
+	/**
2783
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2784
+	 * $modelObject
2785
+	 *
2786
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2787
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2788
+	 * @param array               $query_params     @see
2789
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2790
+	 * @return EE_Base_Class
2791
+	 * @throws EE_Error
2792
+	 */
2793
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2794
+	{
2795
+		$query_params['limit'] = 1;
2796
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2797
+		if ($results) {
2798
+			return array_shift($results);
2799
+		}
2800
+		return null;
2801
+	}
2802
+
2803
+
2804
+	/**
2805
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2806
+	 *
2807
+	 * @return string
2808
+	 */
2809
+	public function get_this_model_name()
2810
+	{
2811
+		return str_replace("EEM_", "", get_class($this));
2812
+	}
2813
+
2814
+
2815
+	/**
2816
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2817
+	 *
2818
+	 * @return EE_Any_Foreign_Model_Name_Field
2819
+	 * @throws EE_Error
2820
+	 */
2821
+	public function get_field_containing_related_model_name()
2822
+	{
2823
+		foreach ($this->field_settings(true) as $field) {
2824
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2825
+				$field_with_model_name = $field;
2826
+			}
2827
+		}
2828
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2829
+			throw new EE_Error(
2830
+				sprintf(
2831
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2832
+					$this->get_this_model_name()
2833
+				)
2834
+			);
2835
+		}
2836
+		return $field_with_model_name;
2837
+	}
2838
+
2839
+
2840
+	/**
2841
+	 * Inserts a new entry into the database, for each table.
2842
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2843
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2844
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2845
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2846
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2847
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2848
+	 *
2849
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2850
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2851
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2852
+	 *                              of EEM_Base)
2853
+	 * @return int|string new primary key on main table that got inserted
2854
+	 * @throws EE_Error
2855
+	 */
2856
+	public function insert($field_n_values)
2857
+	{
2858
+		/**
2859
+		 * Filters the fields and their values before inserting an item using the models
2860
+		 *
2861
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2862
+		 * @param EEM_Base $model           the model used
2863
+		 */
2864
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2865
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2866
+			$main_table = $this->_get_main_table();
2867
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2868
+			if ($new_id !== false) {
2869
+				foreach ($this->_get_other_tables() as $other_table) {
2870
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2871
+				}
2872
+			}
2873
+			/**
2874
+			 * Done just after attempting to insert a new model object
2875
+			 *
2876
+			 * @param EEM_Base $model           used
2877
+			 * @param array    $fields_n_values fields and their values
2878
+			 * @param int|string the              ID of the newly-inserted model object
2879
+			 */
2880
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2881
+			return $new_id;
2882
+		}
2883
+		return false;
2884
+	}
2885
+
2886
+
2887
+	/**
2888
+	 * Checks that the result would satisfy the unique indexes on this model
2889
+	 *
2890
+	 * @param array  $field_n_values
2891
+	 * @param string $action
2892
+	 * @return boolean
2893
+	 * @throws EE_Error
2894
+	 */
2895
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2896
+	{
2897
+		foreach ($this->unique_indexes() as $index_name => $index) {
2898
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2899
+			if ($this->exists([$uniqueness_where_params])) {
2900
+				EE_Error::add_error(
2901
+					sprintf(
2902
+						esc_html__(
2903
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2904
+							"event_espresso"
2905
+						),
2906
+						$action,
2907
+						$this->_get_class_name(),
2908
+						$index_name,
2909
+						implode(",", $index->field_names()),
2910
+						http_build_query($uniqueness_where_params)
2911
+					),
2912
+					__FILE__,
2913
+					__FUNCTION__,
2914
+					__LINE__
2915
+				);
2916
+				return false;
2917
+			}
2918
+		}
2919
+		return true;
2920
+	}
2921
+
2922
+
2923
+	/**
2924
+	 * Checks the database for an item that conflicts (ie, if this item were
2925
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2926
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2927
+	 * can be either an EE_Base_Class or an array of fields n values
2928
+	 *
2929
+	 * @param EE_Base_Class|array $obj_or_fields_array
2930
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2931
+	 *                                                 when looking for conflicts
2932
+	 *                                                 (ie, if false, we ignore the model object's primary key
2933
+	 *                                                 when finding "conflicts". If true, it's also considered).
2934
+	 *                                                 Only works for INT primary key,
2935
+	 *                                                 STRING primary keys cannot be ignored
2936
+	 * @return EE_Base_Class|array
2937
+	 * @throws EE_Error
2938
+	 * @throws ReflectionException
2939
+	 */
2940
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2941
+	{
2942
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2943
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2944
+		} elseif (is_array($obj_or_fields_array)) {
2945
+			$fields_n_values = $obj_or_fields_array;
2946
+		} else {
2947
+			throw new EE_Error(
2948
+				sprintf(
2949
+					esc_html__(
2950
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2951
+						"event_espresso"
2952
+					),
2953
+					get_class($this),
2954
+					$obj_or_fields_array
2955
+				)
2956
+			);
2957
+		}
2958
+		$query_params = [];
2959
+		if (
2960
+			$this->has_primary_key_field()
2961
+			&& ($include_primary_key
2962
+				|| $this->get_primary_key_field()
2963
+				   instanceof
2964
+				   EE_Primary_Key_String_Field)
2965
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2966
+		) {
2967
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2968
+		}
2969
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2970
+			$uniqueness_where_params                              =
2971
+				array_intersect_key($fields_n_values, $unique_index->fields());
2972
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2973
+		}
2974
+		// if there is nothing to base this search on, then we shouldn't find anything
2975
+		if (empty($query_params)) {
2976
+			return [];
2977
+		}
2978
+		return $this->get_one($query_params);
2979
+	}
2980
+
2981
+
2982
+	/**
2983
+	 * Like count, but is optimized and returns a boolean instead of an int
2984
+	 *
2985
+	 * @param array $query_params
2986
+	 * @return boolean
2987
+	 * @throws EE_Error
2988
+	 */
2989
+	public function exists($query_params)
2990
+	{
2991
+		$query_params['limit'] = 1;
2992
+		return $this->count($query_params) > 0;
2993
+	}
2994
+
2995
+
2996
+	/**
2997
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2998
+	 *
2999
+	 * @param int|string $id
3000
+	 * @return boolean
3001
+	 * @throws EE_Error
3002
+	 */
3003
+	public function exists_by_ID($id)
3004
+	{
3005
+		return $this->exists(
3006
+			[
3007
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3008
+				[
3009
+					$this->primary_key_name() => $id,
3010
+				],
3011
+			]
3012
+		);
3013
+	}
3014
+
3015
+
3016
+	/**
3017
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3018
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3019
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3020
+	 * on the main table)
3021
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3022
+	 * cases where we want to call it directly rather than via insert().
3023
+	 *
3024
+	 * @access   protected
3025
+	 * @param EE_Table_Base $table
3026
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3027
+	 *                                       float
3028
+	 * @param int           $new_id          for now we assume only int keys
3029
+	 * @return int ID of new row inserted, or FALSE on failure
3030
+	 * @throws EE_Error
3031
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3032
+	 */
3033
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3034
+	{
3035
+		global $wpdb;
3036
+		$insertion_col_n_values = [];
3037
+		$format_for_insertion   = [];
3038
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3039
+		foreach ($fields_on_table as $field_name => $field_obj) {
3040
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3041
+			if ($field_obj->is_auto_increment()) {
3042
+				continue;
3043
+			}
3044
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3046
+			if ($prepared_value !== null) {
3047
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3048
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3049
+			}
3050
+		}
3051
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3052
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3053
+			// so add the fk to the main table as a column
3054
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
+			$format_for_insertion[]                              =
3056
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3057
+		}
3058
+
3059
+		// insert the new entry
3060
+		$result = $this->_do_wpdb_query(
3061
+			'insert',
3062
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3063
+		);
3064
+		if ($result === false) {
3065
+			return false;
3066
+		}
3067
+		// ok, now what do we return for the ID of the newly-inserted thing?
3068
+		if ($this->has_primary_key_field()) {
3069
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3070
+				return $wpdb->insert_id;
3071
+			}
3072
+			// it's not an auto-increment primary key, so
3073
+			// it must have been supplied
3074
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3075
+		}
3076
+		// we can't return a  primary key because there is none. instead return
3077
+		// a unique string indicating this model
3078
+		return $this->get_index_primary_key_string($fields_n_values);
3079
+	}
3080
+
3081
+
3082
+	/**
3083
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3084
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3085
+	 * and there is no default, we pass it along. WPDB will take care of it)
3086
+	 *
3087
+	 * @param EE_Model_Field_Base $field_obj
3088
+	 * @param array               $fields_n_values
3089
+	 * @return mixed string|int|float depending on what the table column will be expecting
3090
+	 * @throws EE_Error
3091
+	 */
3092
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3093
+	{
3094
+		$field_name = $field_obj->get_name();
3095
+		// if this field doesn't allow nullable, don't allow it
3096
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3097
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3098
+		}
3099
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3100
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3101
+	}
3102
+
3103
+
3104
+	/**
3105
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3106
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3107
+	 * the field's prepare_for_set() method.
3108
+	 *
3109
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3110
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3111
+	 *                                   top of file)
3112
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3113
+	 *                                   $value is a custom selection
3114
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3115
+	 */
3116
+	private function _prepare_value_for_use_in_db($value, $field)
3117
+	{
3118
+		if ($field instanceof EE_Model_Field_Base) {
3119
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3120
+			switch ($this->_values_already_prepared_by_model_object) {
3121
+				/** @noinspection PhpMissingBreakStatementInspection */
3122
+				case self::not_prepared_by_model_object:
3123
+					$value = $field->prepare_for_set($value);
3124
+				// purposefully left out "return"
3125
+				// no break
3126
+				case self::prepared_by_model_object:
3127
+					/** @noinspection SuspiciousAssignmentsInspection */
3128
+					$value = $field->prepare_for_use_in_db($value);
3129
+				// no break
3130
+				case self::prepared_for_use_in_db:
3131
+					// leave the value alone
3132
+			}
3133
+			// phpcs:enable
3134
+		}
3135
+		return $value;
3136
+	}
3137
+
3138
+
3139
+	/**
3140
+	 * Returns the main table on this model
3141
+	 *
3142
+	 * @return EE_Primary_Table
3143
+	 * @throws EE_Error
3144
+	 */
3145
+	protected function _get_main_table()
3146
+	{
3147
+		foreach ($this->_tables as $table) {
3148
+			if ($table instanceof EE_Primary_Table) {
3149
+				return $table;
3150
+			}
3151
+		}
3152
+		throw new EE_Error(
3153
+			sprintf(
3154
+				esc_html__(
3155
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3156
+					'event_espresso'
3157
+				),
3158
+				get_class($this)
3159
+			)
3160
+		);
3161
+	}
3162
+
3163
+
3164
+	/**
3165
+	 * table
3166
+	 * returns EE_Primary_Table table name
3167
+	 *
3168
+	 * @return string
3169
+	 * @throws EE_Error
3170
+	 */
3171
+	public function table()
3172
+	{
3173
+		return $this->_get_main_table()->get_table_name();
3174
+	}
3175
+
3176
+
3177
+	/**
3178
+	 * table
3179
+	 * returns first EE_Secondary_Table table name
3180
+	 *
3181
+	 * @return string
3182
+	 */
3183
+	public function second_table()
3184
+	{
3185
+		// grab second table from tables array
3186
+		$second_table = end($this->_tables);
3187
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * get_table_obj_by_alias
3193
+	 * returns table name given it's alias
3194
+	 *
3195
+	 * @param string $table_alias
3196
+	 * @return EE_Primary_Table | EE_Secondary_Table
3197
+	 */
3198
+	public function get_table_obj_by_alias($table_alias = '')
3199
+	{
3200
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3201
+	}
3202
+
3203
+
3204
+	/**
3205
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3206
+	 *
3207
+	 * @return EE_Secondary_Table[]
3208
+	 */
3209
+	protected function _get_other_tables()
3210
+	{
3211
+		$other_tables = [];
3212
+		foreach ($this->_tables as $table_alias => $table) {
3213
+			if ($table instanceof EE_Secondary_Table) {
3214
+				$other_tables[ $table_alias ] = $table;
3215
+			}
3216
+		}
3217
+		return $other_tables;
3218
+	}
3219
+
3220
+
3221
+	/**
3222
+	 * Finds all the fields that correspond to the given table
3223
+	 *
3224
+	 * @param string $table_alias , array key in EEM_Base::_tables
3225
+	 * @return EE_Model_Field_Base[]
3226
+	 */
3227
+	public function _get_fields_for_table($table_alias)
3228
+	{
3229
+		return $this->_fields[ $table_alias ];
3230
+	}
3231
+
3232
+
3233
+	/**
3234
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3235
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3236
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3237
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3238
+	 * related Registration, Transaction, and Payment models.
3239
+	 *
3240
+	 * @param array $query_params @see
3241
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3242
+	 * @return EE_Model_Query_Info_Carrier
3243
+	 * @throws EE_Error
3244
+	 */
3245
+	public function _extract_related_models_from_query($query_params)
3246
+	{
3247
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3248
+		if (array_key_exists(0, $query_params)) {
3249
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3250
+		}
3251
+		if (array_key_exists('group_by', $query_params)) {
3252
+			if (is_array($query_params['group_by'])) {
3253
+				$this->_extract_related_models_from_sub_params_array_values(
3254
+					$query_params['group_by'],
3255
+					$query_info_carrier,
3256
+					'group_by'
3257
+				);
3258
+			} elseif (! empty($query_params['group_by'])) {
3259
+				$this->_extract_related_model_info_from_query_param(
3260
+					$query_params['group_by'],
3261
+					$query_info_carrier,
3262
+					'group_by'
3263
+				);
3264
+			}
3265
+		}
3266
+		if (array_key_exists('having', $query_params)) {
3267
+			$this->_extract_related_models_from_sub_params_array_keys(
3268
+				$query_params[0],
3269
+				$query_info_carrier,
3270
+				'having'
3271
+			);
3272
+		}
3273
+		if (array_key_exists('order_by', $query_params)) {
3274
+			if (is_array($query_params['order_by'])) {
3275
+				$this->_extract_related_models_from_sub_params_array_keys(
3276
+					$query_params['order_by'],
3277
+					$query_info_carrier,
3278
+					'order_by'
3279
+				);
3280
+			} elseif (! empty($query_params['order_by'])) {
3281
+				$this->_extract_related_model_info_from_query_param(
3282
+					$query_params['order_by'],
3283
+					$query_info_carrier,
3284
+					'order_by'
3285
+				);
3286
+			}
3287
+		}
3288
+		if (array_key_exists('force_join', $query_params)) {
3289
+			$this->_extract_related_models_from_sub_params_array_values(
3290
+				$query_params['force_join'],
3291
+				$query_info_carrier,
3292
+				'force_join'
3293
+			);
3294
+		}
3295
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3296
+		return $query_info_carrier;
3297
+	}
3298
+
3299
+
3300
+	/**
3301
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3302
+	 *
3303
+	 * @param array                       $sub_query_params @see
3304
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3305
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3306
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3307
+	 * @return EE_Model_Query_Info_Carrier
3308
+	 * @throws EE_Error
3309
+	 */
3310
+	private function _extract_related_models_from_sub_params_array_keys(
3311
+		$sub_query_params,
3312
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3313
+		$query_param_type
3314
+	) {
3315
+		if (! empty($sub_query_params)) {
3316
+			$sub_query_params = (array) $sub_query_params;
3317
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3318
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3319
+				$this->_extract_related_model_info_from_query_param(
3320
+					$param,
3321
+					$model_query_info_carrier,
3322
+					$query_param_type
3323
+				);
3324
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3325
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3326
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3327
+				// of array('Registration.TXN_ID'=>23)
3328
+				$query_param_sans_stars =
3329
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3330
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3331
+					if (! is_array($possibly_array_of_params)) {
3332
+						throw new EE_Error(
3333
+							sprintf(
3334
+								esc_html__(
3335
+									"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'))",
3336
+									"event_espresso"
3337
+								),
3338
+								$param,
3339
+								$possibly_array_of_params
3340
+							)
3341
+						);
3342
+					}
3343
+					$this->_extract_related_models_from_sub_params_array_keys(
3344
+						$possibly_array_of_params,
3345
+						$model_query_info_carrier,
3346
+						$query_param_type
3347
+					);
3348
+				} elseif (
3349
+					$query_param_type === 0 // ie WHERE
3350
+					&& is_array($possibly_array_of_params)
3351
+					&& isset($possibly_array_of_params[2])
3352
+					&& $possibly_array_of_params[2] == true
3353
+				) {
3354
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3355
+					// indicating that $possible_array_of_params[1] is actually a field name,
3356
+					// from which we should extract query parameters!
3357
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3358
+						throw new EE_Error(
3359
+							sprintf(
3360
+								esc_html__(
3361
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3362
+									"event_espresso"
3363
+								),
3364
+								$query_param_type,
3365
+								implode(",", $possibly_array_of_params)
3366
+							)
3367
+						);
3368
+					}
3369
+					$this->_extract_related_model_info_from_query_param(
3370
+						$possibly_array_of_params[1],
3371
+						$model_query_info_carrier,
3372
+						$query_param_type
3373
+					);
3374
+				}
3375
+			}
3376
+		}
3377
+		return $model_query_info_carrier;
3378
+	}
3379
+
3380
+
3381
+	/**
3382
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3383
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3384
+	 *
3385
+	 * @param array                       $sub_query_params @see
3386
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3387
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3388
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3389
+	 * @return EE_Model_Query_Info_Carrier
3390
+	 * @throws EE_Error
3391
+	 */
3392
+	private function _extract_related_models_from_sub_params_array_values(
3393
+		$sub_query_params,
3394
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3395
+		$query_param_type
3396
+	) {
3397
+		if (! empty($sub_query_params)) {
3398
+			if (! is_array($sub_query_params)) {
3399
+				throw new EE_Error(
3400
+					sprintf(
3401
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3402
+						$sub_query_params
3403
+					)
3404
+				);
3405
+			}
3406
+			foreach ($sub_query_params as $param) {
3407
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3408
+				$this->_extract_related_model_info_from_query_param(
3409
+					$param,
3410
+					$model_query_info_carrier,
3411
+					$query_param_type
3412
+				);
3413
+			}
3414
+		}
3415
+		return $model_query_info_carrier;
3416
+	}
3417
+
3418
+
3419
+	/**
3420
+	 * Extract all the query parts from  model query params
3421
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3422
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3423
+	 * but use them in a different order. Eg, we need to know what models we are querying
3424
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3425
+	 * other models before we can finalize the where clause SQL.
3426
+	 *
3427
+	 * @param array $query_params @see
3428
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3429
+	 * @return EE_Model_Query_Info_Carrier
3430
+	 * @throws EE_Error
3431
+	 * @throws ModelConfigurationException*@throws ReflectionException
3432
+	 */
3433
+	public function _create_model_query_info_carrier($query_params)
3434
+	{
3435
+		if (! is_array($query_params)) {
3436
+			EE_Error::doing_it_wrong(
3437
+				'EEM_Base::_create_model_query_info_carrier',
3438
+				sprintf(
3439
+					esc_html__(
3440
+						'$query_params should be an array, you passed a variable of type %s',
3441
+						'event_espresso'
3442
+					),
3443
+					gettype($query_params)
3444
+				),
3445
+				'4.6.0'
3446
+			);
3447
+			$query_params = [];
3448
+		}
3449
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3450
+		// first check if we should alter the query to account for caps or not
3451
+		// because the caps might require us to do extra joins
3452
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3453
+			$query_params[0] = array_replace_recursive(
3454
+				$query_params[0],
3455
+				$this->caps_where_conditions($query_params['caps'])
3456
+			);
3457
+		}
3458
+
3459
+		// check if we should alter the query to remove data related to protected
3460
+		// custom post types
3461
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3462
+			$where_param_key_for_password = $this->modelChainAndPassword();
3463
+			// only include if related to a cpt where no password has been set
3464
+			$query_params[0]['OR*nopassword'] = [
3465
+				$where_param_key_for_password       => '',
3466
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3467
+			];
3468
+		}
3469
+		$query_object = $this->_extract_related_models_from_query($query_params);
3470
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3471
+		foreach ($query_params[0] as $key => $value) {
3472
+			if (is_int($key)) {
3473
+				throw new EE_Error(
3474
+					sprintf(
3475
+						esc_html__(
3476
+							"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.",
3477
+							"event_espresso"
3478
+						),
3479
+						$key,
3480
+						var_export($value, true),
3481
+						var_export($query_params, true),
3482
+						get_class($this)
3483
+					)
3484
+				);
3485
+			}
3486
+		}
3487
+		if (
3488
+			array_key_exists('default_where_conditions', $query_params)
3489
+			&& ! empty($query_params['default_where_conditions'])
3490
+		) {
3491
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3492
+		} else {
3493
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3494
+		}
3495
+		$query_params[0] = array_merge(
3496
+			$this->_get_default_where_conditions_for_models_in_query(
3497
+				$query_object,
3498
+				$use_default_where_conditions,
3499
+				$query_params[0]
3500
+			),
3501
+			$query_params[0]
3502
+		);
3503
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3504
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3505
+		// So we need to setup a subquery and use that for the main join.
3506
+		// Note for now this only works on the primary table for the model.
3507
+		// So for instance, you could set the limit array like this:
3508
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3509
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3510
+			$query_object->set_main_model_join_sql(
3511
+				$this->_construct_limit_join_select(
3512
+					$query_params['on_join_limit'][0],
3513
+					$query_params['on_join_limit'][1]
3514
+				)
3515
+			);
3516
+		}
3517
+		// set limit
3518
+		if (array_key_exists('limit', $query_params)) {
3519
+			if (is_array($query_params['limit'])) {
3520
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3521
+					$e = sprintf(
3522
+						esc_html__(
3523
+							"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)",
3524
+							"event_espresso"
3525
+						),
3526
+						http_build_query($query_params['limit'])
3527
+					);
3528
+					throw new EE_Error($e . "|" . $e);
3529
+				}
3530
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3531
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3532
+			} elseif (! empty($query_params['limit'])) {
3533
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3534
+			}
3535
+		}
3536
+		// set order by
3537
+		if (array_key_exists('order_by', $query_params)) {
3538
+			if (is_array($query_params['order_by'])) {
3539
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3540
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3541
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3542
+				if (array_key_exists('order', $query_params)) {
3543
+					throw new EE_Error(
3544
+						sprintf(
3545
+							esc_html__(
3546
+								"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 ",
3547
+								"event_espresso"
3548
+							),
3549
+							get_class($this),
3550
+							implode(", ", array_keys($query_params['order_by'])),
3551
+							implode(", ", $query_params['order_by']),
3552
+							$query_params['order']
3553
+						)
3554
+					);
3555
+				}
3556
+				$this->_extract_related_models_from_sub_params_array_keys(
3557
+					$query_params['order_by'],
3558
+					$query_object,
3559
+					'order_by'
3560
+				);
3561
+				// assume it's an array of fields to order by
3562
+				$order_array = [];
3563
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3564
+					$order         = $this->_extract_order($order);
3565
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3566
+				}
3567
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3568
+			} elseif (! empty($query_params['order_by'])) {
3569
+				$this->_extract_related_model_info_from_query_param(
3570
+					$query_params['order_by'],
3571
+					$query_object,
3572
+					'order',
3573
+					$query_params['order_by']
3574
+				);
3575
+				$order = isset($query_params['order'])
3576
+					? $this->_extract_order($query_params['order'])
3577
+					: 'DESC';
3578
+				$query_object->set_order_by_sql(
3579
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3580
+				);
3581
+			}
3582
+		}
3583
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3584
+		if (
3585
+			! array_key_exists('order_by', $query_params)
3586
+			&& array_key_exists('order', $query_params)
3587
+			&& ! empty($query_params['order'])
3588
+		) {
3589
+			$pk_field = $this->get_primary_key_field();
3590
+			$order    = $this->_extract_order($query_params['order']);
3591
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3592
+		}
3593
+		// set group by
3594
+		if (array_key_exists('group_by', $query_params)) {
3595
+			if (is_array($query_params['group_by'])) {
3596
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3597
+				$group_by_array = [];
3598
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3599
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3600
+				}
3601
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3602
+			} elseif (! empty($query_params['group_by'])) {
3603
+				$query_object->set_group_by_sql(
3604
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3605
+				);
3606
+			}
3607
+		}
3608
+		// set having
3609
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3610
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3611
+		}
3612
+		// now, just verify they didn't pass anything wack
3613
+		foreach ($query_params as $query_key => $query_value) {
3614
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3615
+				throw new EE_Error(
3616
+					sprintf(
3617
+						esc_html__(
3618
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3619
+							'event_espresso'
3620
+						),
3621
+						$query_key,
3622
+						get_class($this),
3623
+						//                      print_r( $this->_allowed_query_params, TRUE )
3624
+						implode(',', $this->_allowed_query_params)
3625
+					)
3626
+				);
3627
+			}
3628
+		}
3629
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3630
+		if (empty($main_model_join_sql)) {
3631
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3632
+		}
3633
+		return $query_object;
3634
+	}
3635
+
3636
+
3637
+	/**
3638
+	 * Gets the where conditions that should be imposed on the query based on the
3639
+	 * context (eg reading frontend, backend, edit or delete).
3640
+	 *
3641
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3642
+	 * @return array @see
3643
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3644
+	 * @throws EE_Error
3645
+	 */
3646
+	public function caps_where_conditions($context = self::caps_read)
3647
+	{
3648
+		EEM_Base::verify_is_valid_cap_context($context);
3649
+		$cap_where_conditions = [];
3650
+		$cap_restrictions     = $this->caps_missing($context);
3651
+		/**
3652
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3653
+		 */
3654
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3655
+			$cap_where_conditions = array_replace_recursive(
3656
+				$cap_where_conditions,
3657
+				$restriction_if_no_cap->get_default_where_conditions()
3658
+			);
3659
+		}
3660
+		return apply_filters(
3661
+			'FHEE__EEM_Base__caps_where_conditions__return',
3662
+			$cap_where_conditions,
3663
+			$this,
3664
+			$context,
3665
+			$cap_restrictions
3666
+		);
3667
+	}
3668
+
3669
+
3670
+	/**
3671
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3672
+	 * otherwise throws an exception
3673
+	 *
3674
+	 * @param string $should_be_order_string
3675
+	 * @return string either ASC, asc, DESC or desc
3676
+	 * @throws EE_Error
3677
+	 */
3678
+	private function _extract_order($should_be_order_string)
3679
+	{
3680
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3681
+			return $should_be_order_string;
3682
+		}
3683
+		throw new EE_Error(
3684
+			sprintf(
3685
+				esc_html__(
3686
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3687
+					"event_espresso"
3688
+				),
3689
+				get_class($this),
3690
+				$should_be_order_string
3691
+			)
3692
+		);
3693
+	}
3694
+
3695
+
3696
+	/**
3697
+	 * Looks at all the models which are included in this query, and asks each
3698
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3699
+	 * so they can be merged
3700
+	 *
3701
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3702
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3703
+	 *                                                                  'none' means NO default where conditions will
3704
+	 *                                                                  be used AT ALL during this query.
3705
+	 *                                                                  'other_models_only' means default where
3706
+	 *                                                                  conditions from other models will be used, but
3707
+	 *                                                                  not for this primary model. 'all', the default,
3708
+	 *                                                                  means default where conditions will apply as
3709
+	 *                                                                  normal
3710
+	 * @param array                       $where_query_params           @see
3711
+	 *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3712
+	 * @return array @see
3713
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3714
+	 * @throws EE_Error
3715
+	 */
3716
+	private function _get_default_where_conditions_for_models_in_query(
3717
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3718
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3719
+		$where_query_params = []
3720
+	) {
3721
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3722
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3723
+			throw new EE_Error(
3724
+				sprintf(
3725
+					esc_html__(
3726
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3727
+						"event_espresso"
3728
+					),
3729
+					$use_default_where_conditions,
3730
+					implode(", ", $allowed_used_default_where_conditions_values)
3731
+				)
3732
+			);
3733
+		}
3734
+		$universal_query_params = [];
3735
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3736
+			$universal_query_params = $this->_get_default_where_conditions();
3737
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3738
+			$universal_query_params = $this->_get_minimum_where_conditions();
3739
+		}
3740
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3741
+			$related_model = $this->get_related_model_obj($model_name);
3742
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3743
+				$related_model_universal_where_params =
3744
+					$related_model->_get_default_where_conditions($model_relation_path);
3745
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3746
+				$related_model_universal_where_params =
3747
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3748
+			} else {
3749
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3750
+				continue;
3751
+			}
3752
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3753
+				$related_model_universal_where_params,
3754
+				$where_query_params,
3755
+				$related_model,
3756
+				$model_relation_path
3757
+			);
3758
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3759
+				$universal_query_params,
3760
+				$overrides
3761
+			);
3762
+		}
3763
+		return $universal_query_params;
3764
+	}
3765
+
3766
+
3767
+	/**
3768
+	 * Determines whether or not we should use default where conditions for the model in question
3769
+	 * (this model, or other related models).
3770
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3771
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3772
+	 * We should use default where conditions on related models when they requested to use default where conditions
3773
+	 * on all models, or specifically just on other related models
3774
+	 *
3775
+	 * @param      $default_where_conditions_value
3776
+	 * @param bool $for_this_model false means this is for OTHER related models
3777
+	 * @return bool
3778
+	 */
3779
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3780
+	{
3781
+		return (
3782
+				   $for_this_model
3783
+				   && in_array(
3784
+					   $default_where_conditions_value,
3785
+					   [
3786
+						   EEM_Base::default_where_conditions_all,
3787
+						   EEM_Base::default_where_conditions_this_only,
3788
+						   EEM_Base::default_where_conditions_minimum_others,
3789
+					   ],
3790
+					   true
3791
+				   )
3792
+			   )
3793
+			   || (
3794
+				   ! $for_this_model
3795
+				   && in_array(
3796
+					   $default_where_conditions_value,
3797
+					   [
3798
+						   EEM_Base::default_where_conditions_all,
3799
+						   EEM_Base::default_where_conditions_others_only,
3800
+					   ],
3801
+					   true
3802
+				   )
3803
+			   );
3804
+	}
3805
+
3806
+
3807
+	/**
3808
+	 * Determines whether or not we should use default minimum conditions for the model in question
3809
+	 * (this model, or other related models).
3810
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3811
+	 * where conditions.
3812
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3813
+	 * on this model or others
3814
+	 *
3815
+	 * @param      $default_where_conditions_value
3816
+	 * @param bool $for_this_model false means this is for OTHER related models
3817
+	 * @return bool
3818
+	 */
3819
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3820
+	{
3821
+		return (
3822
+				   $for_this_model
3823
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3824
+			   )
3825
+			   || (
3826
+				   ! $for_this_model
3827
+				   && in_array(
3828
+					   $default_where_conditions_value,
3829
+					   [
3830
+						   EEM_Base::default_where_conditions_minimum_others,
3831
+						   EEM_Base::default_where_conditions_minimum_all,
3832
+					   ],
3833
+					   true
3834
+				   )
3835
+			   );
3836
+	}
3837
+
3838
+
3839
+	/**
3840
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3841
+	 * then we also add a special where condition which allows for that model's primary key
3842
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3843
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3844
+	 *
3845
+	 * @param array    $default_where_conditions
3846
+	 * @param array    $provided_where_conditions
3847
+	 * @param EEM_Base $model
3848
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3849
+	 * @return array @see
3850
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
+	 * @throws EE_Error
3852
+	 */
3853
+	private function _override_defaults_or_make_null_friendly(
3854
+		$default_where_conditions,
3855
+		$provided_where_conditions,
3856
+		$model,
3857
+		$model_relation_path
3858
+	) {
3859
+		$null_friendly_where_conditions = [];
3860
+		$none_overridden                = true;
3861
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3862
+		foreach ($default_where_conditions as $key => $val) {
3863
+			if (isset($provided_where_conditions[ $key ])) {
3864
+				$none_overridden = false;
3865
+			} else {
3866
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3867
+			}
3868
+		}
3869
+		if ($none_overridden && $default_where_conditions) {
3870
+			if ($model->has_primary_key_field()) {
3871
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3872
+																				   . "."
3873
+																				   . $model->primary_key_name() ] =
3874
+					['IS NULL'];
3875
+			}/*else{
3876 3876
                 //@todo NO PK, use other defaults
3877 3877
             }*/
3878
-        }
3879
-        return $null_friendly_where_conditions;
3880
-    }
3881
-
3882
-
3883
-    /**
3884
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3885
-     * default where conditions on all get_all, update, and delete queries done by this model.
3886
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3887
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3888
-     *
3889
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3890
-     * @return array @see
3891
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3892
-     * @throws EE_Error
3893
-     * @throws EE_Error
3894
-     */
3895
-    private function _get_default_where_conditions($model_relation_path = '')
3896
-    {
3897
-        if ($this->_ignore_where_strategy) {
3898
-            return [];
3899
-        }
3900
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3901
-    }
3902
-
3903
-
3904
-    /**
3905
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3906
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3907
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3908
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3909
-     * Similar to _get_default_where_conditions
3910
-     *
3911
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3912
-     * @return array @see
3913
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3914
-     * @throws EE_Error
3915
-     * @throws EE_Error
3916
-     */
3917
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3918
-    {
3919
-        if ($this->_ignore_where_strategy) {
3920
-            return [];
3921
-        }
3922
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3923
-    }
3924
-
3925
-
3926
-    /**
3927
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3928
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3929
-     *
3930
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3931
-     * @return string
3932
-     * @throws EE_Error
3933
-     */
3934
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3935
-    {
3936
-        $selects = $this->_get_columns_to_select_for_this_model();
3937
-        foreach (
3938
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3939
-        ) {
3940
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3941
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3942
-            foreach ($other_model_selects as $key => $value) {
3943
-                $selects[] = $value;
3944
-            }
3945
-        }
3946
-        return implode(", ", $selects);
3947
-    }
3948
-
3949
-
3950
-    /**
3951
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3952
-     * So that's going to be the columns for all the fields on the model
3953
-     *
3954
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3955
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3956
-     */
3957
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3958
-    {
3959
-        $fields                                       = $this->field_settings();
3960
-        $selects                                      = [];
3961
-        $table_alias_with_model_relation_chain_prefix =
3962
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3963
-                $model_relation_chain,
3964
-                $this->get_this_model_name()
3965
-            );
3966
-        foreach ($fields as $field_obj) {
3967
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3968
-                         . $field_obj->get_table_alias()
3969
-                         . "."
3970
-                         . $field_obj->get_table_column()
3971
-                         . " AS '"
3972
-                         . $table_alias_with_model_relation_chain_prefix
3973
-                         . $field_obj->get_table_alias()
3974
-                         . "."
3975
-                         . $field_obj->get_table_column()
3976
-                         . "'";
3977
-        }
3978
-        // make sure we are also getting the PKs of each table
3979
-        $tables = $this->get_tables();
3980
-        if (count($tables) > 1) {
3981
-            foreach ($tables as $table_obj) {
3982
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3983
-                                       . $table_obj->get_fully_qualified_pk_column();
3984
-                if (! in_array($qualified_pk_column, $selects)) {
3985
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3986
-                }
3987
-            }
3988
-        }
3989
-        return $selects;
3990
-    }
3991
-
3992
-
3993
-    /**
3994
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3995
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3996
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3997
-     * SQL for joining, and the data types
3998
-     *
3999
-     * @param null|string                 $original_query_param
4000
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4001
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4002
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4003
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4004
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4005
-     *                                                          or 'Registration's
4006
-     * @param string                      $original_query_param what it originally was (eg
4007
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4008
-     *                                                          matches $query_param
4009
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4010
-     * @throws EE_Error
4011
-     */
4012
-    private function _extract_related_model_info_from_query_param(
4013
-        $query_param,
4014
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4015
-        $query_param_type,
4016
-        $original_query_param = null
4017
-    ) {
4018
-        if ($original_query_param === null) {
4019
-            $original_query_param = $query_param;
4020
-        }
4021
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4022
-        // check to see if we have a field on this model
4023
-        $this_model_fields = $this->field_settings(true);
4024
-        if (array_key_exists($query_param, $this_model_fields)) {
4025
-            $field_is_allowed = in_array(
4026
-                $query_param_type,
4027
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4028
-                true
4029
-            );
4030
-            if ($field_is_allowed) {
4031
-                return;
4032
-            }
4033
-            throw new EE_Error(
4034
-                sprintf(
4035
-                    esc_html__(
4036
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4037
-                        "event_espresso"
4038
-                    ),
4039
-                    $query_param,
4040
-                    get_class($this),
4041
-                    $query_param_type,
4042
-                    $original_query_param
4043
-                )
4044
-            );
4045
-        }
4046
-        // check if this is a special logic query param
4047
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4048
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4049
-            if ($operator_is_allowed) {
4050
-                return;
4051
-            }
4052
-            throw new EE_Error(
4053
-                sprintf(
4054
-                    esc_html__(
4055
-                        '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',
4056
-                        'event_espresso'
4057
-                    ),
4058
-                    implode('", "', $this->_logic_query_param_keys),
4059
-                    $query_param,
4060
-                    get_class($this),
4061
-                    '<br />',
4062
-                    "\t"
4063
-                    . ' $passed_in_query_info = <pre>'
4064
-                    . print_r($passed_in_query_info, true)
4065
-                    . '</pre>'
4066
-                    . "\n\t"
4067
-                    . ' $query_param_type = '
4068
-                    . $query_param_type
4069
-                    . "\n\t"
4070
-                    . ' $original_query_param = '
4071
-                    . $original_query_param
4072
-                )
4073
-            );
4074
-        }
4075
-        // check if it's a custom selection
4076
-        if (
4077
-            $this->_custom_selections instanceof CustomSelects
4078
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4079
-        ) {
4080
-            return;
4081
-        }
4082
-        // check if has a model name at the beginning
4083
-        // and
4084
-        // check if it's a field on a related model
4085
-        if (
4086
-            $this->extractJoinModelFromQueryParams(
4087
-                $passed_in_query_info,
4088
-                $query_param,
4089
-                $original_query_param,
4090
-                $query_param_type
4091
-            )
4092
-        ) {
4093
-            return;
4094
-        }
4095
-
4096
-        // ok so $query_param didn't start with a model name
4097
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4098
-        // it's wack, that's what it is
4099
-        throw new EE_Error(
4100
-            sprintf(
4101
-                esc_html__(
4102
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4103
-                    "event_espresso"
4104
-                ),
4105
-                $query_param,
4106
-                get_class($this),
4107
-                $query_param_type,
4108
-                $original_query_param
4109
-            )
4110
-        );
4111
-    }
4112
-
4113
-
4114
-    /**
4115
-     * Extracts any possible join model information from the provided possible_join_string.
4116
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4117
-     * join
4118
-     * parts that should be added to the query.
4119
-     *
4120
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4121
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4122
-     * @param null|string                 $original_query_param
4123
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4124
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4125
-     *                                                           etc.)
4126
-     * @return bool  returns true if a join was added and false if not.
4127
-     * @throws EE_Error
4128
-     */
4129
-    private function extractJoinModelFromQueryParams(
4130
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4131
-        $possible_join_string,
4132
-        $original_query_param,
4133
-        $query_parameter_type
4134
-    ) {
4135
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4136
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4137
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4138
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4139
-                if ($possible_join_string === '') {
4140
-                    // nothing left to $query_param
4141
-                    // we should actually end in a field name, not a model like this!
4142
-                    throw new EE_Error(
4143
-                        sprintf(
4144
-                            esc_html__(
4145
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4146
-                                "event_espresso"
4147
-                            ),
4148
-                            $possible_join_string,
4149
-                            $query_parameter_type,
4150
-                            get_class($this),
4151
-                            $valid_related_model_name
4152
-                        )
4153
-                    );
4154
-                }
4155
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4156
-                $related_model_obj->_extract_related_model_info_from_query_param(
4157
-                    $possible_join_string,
4158
-                    $query_info_carrier,
4159
-                    $query_parameter_type,
4160
-                    $original_query_param
4161
-                );
4162
-                return true;
4163
-            }
4164
-            if ($possible_join_string === $valid_related_model_name) {
4165
-                $this->_add_join_to_model(
4166
-                    $valid_related_model_name,
4167
-                    $query_info_carrier,
4168
-                    $original_query_param
4169
-                );
4170
-                return true;
4171
-            }
4172
-        }
4173
-        return false;
4174
-    }
4175
-
4176
-
4177
-    /**
4178
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4179
-     *
4180
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4181
-     * @throws EE_Error
4182
-     */
4183
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4184
-    {
4185
-        if (
4186
-            $this->_custom_selections instanceof CustomSelects
4187
-            && (
4188
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4189
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4190
-            )
4191
-        ) {
4192
-            $original_selects = $this->_custom_selections->originalSelects();
4193
-            foreach ($original_selects as $alias => $select_configuration) {
4194
-                $this->extractJoinModelFromQueryParams(
4195
-                    $query_info_carrier,
4196
-                    $select_configuration[0],
4197
-                    $select_configuration[0],
4198
-                    'custom_selects'
4199
-                );
4200
-            }
4201
-        }
4202
-    }
4203
-
4204
-
4205
-    /**
4206
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4207
-     * and store it on $passed_in_query_info
4208
-     *
4209
-     * @param string                      $model_name
4210
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4211
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4212
-     *                                                          model and $model_name. Eg, if we are querying Event,
4213
-     *                                                          and are adding a join to 'Payment' with the original
4214
-     *                                                          query param key
4215
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4216
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4217
-     *                                                          Payment wants to add default query params so that it
4218
-     *                                                          will know what models to prepend onto its default query
4219
-     *                                                          params or in case it wants to rename tables (in case
4220
-     *                                                          there are multiple joins to the same table)
4221
-     * @return void
4222
-     * @throws EE_Error
4223
-     */
4224
-    private function _add_join_to_model(
4225
-        $model_name,
4226
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4227
-        $original_query_param
4228
-    ) {
4229
-        $relation_obj         = $this->related_settings_for($model_name);
4230
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4231
-        // check if the relation is HABTM, because then we're essentially doing two joins
4232
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4233
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4234
-            $join_model_obj = $relation_obj->get_join_model();
4235
-            // replace the model specified with the join model for this relation chain, whi
4236
-            $relation_chain_to_join_model =
4237
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4238
-                    $model_name,
4239
-                    $join_model_obj->get_this_model_name(),
4240
-                    $model_relation_chain
4241
-                );
4242
-            $passed_in_query_info->merge(
4243
-                new EE_Model_Query_Info_Carrier(
4244
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4245
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4246
-                )
4247
-            );
4248
-        }
4249
-        // now just join to the other table pointed to by the relation object, and add its data types
4250
-        $passed_in_query_info->merge(
4251
-            new EE_Model_Query_Info_Carrier(
4252
-                [$model_relation_chain => $model_name],
4253
-                $relation_obj->get_join_statement($model_relation_chain)
4254
-            )
4255
-        );
4256
-    }
4257
-
4258
-
4259
-    /**
4260
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4261
-     *
4262
-     * @param array $where_params @see
4263
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4264
-     * @return string of SQL
4265
-     * @throws EE_Error
4266
-     */
4267
-    private function _construct_where_clause($where_params)
4268
-    {
4269
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4270
-        if ($SQL) {
4271
-            return " WHERE " . $SQL;
4272
-        }
4273
-        return '';
4274
-    }
4275
-
4276
-
4277
-    /**
4278
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4279
-     * and should be passed HAVING parameters, not WHERE parameters
4280
-     *
4281
-     * @param array $having_params
4282
-     * @return string
4283
-     * @throws EE_Error
4284
-     */
4285
-    private function _construct_having_clause($having_params)
4286
-    {
4287
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4288
-        if ($SQL) {
4289
-            return " HAVING " . $SQL;
4290
-        }
4291
-        return '';
4292
-    }
4293
-
4294
-
4295
-    /**
4296
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4297
-     * Event_Meta.meta_value = 'foo'))"
4298
-     *
4299
-     * @param array  $where_params @see
4300
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4301
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4302
-     * @throws EE_Error
4303
-     * @return string of SQL
4304
-     */
4305
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4306
-    {
4307
-        $where_clauses = [];
4308
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4309
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4310
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4311
-                switch ($query_param) {
4312
-                    case 'not':
4313
-                    case 'NOT':
4314
-                        $where_clauses[] = "! ("
4315
-                                           . $this->_construct_condition_clause_recursive(
4316
-                                               $op_and_value_or_sub_condition,
4317
-                                               $glue
4318
-                                           )
4319
-                                           . ")";
4320
-                        break;
4321
-                    case 'and':
4322
-                    case 'AND':
4323
-                        $where_clauses[] = " ("
4324
-                                           . $this->_construct_condition_clause_recursive(
4325
-                                               $op_and_value_or_sub_condition,
4326
-                                               ' AND '
4327
-                                           )
4328
-                                           . ")";
4329
-                        break;
4330
-                    case 'or':
4331
-                    case 'OR':
4332
-                        $where_clauses[] = " ("
4333
-                                           . $this->_construct_condition_clause_recursive(
4334
-                                               $op_and_value_or_sub_condition,
4335
-                                               ' OR '
4336
-                                           )
4337
-                                           . ")";
4338
-                        break;
4339
-                }
4340
-            } else {
4341
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4342
-                // if it's not a normal field, maybe it's a custom selection?
4343
-                if (! $field_obj) {
4344
-                    if ($this->_custom_selections instanceof CustomSelects) {
4345
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4346
-                    } else {
4347
-                        throw new EE_Error(
4348
-                            sprintf(
4349
-                                esc_html__(
4350
-                                    "%s is neither a valid model field name, nor a custom selection",
4351
-                                    "event_espresso"
4352
-                                ),
4353
-                                $query_param
4354
-                            )
4355
-                        );
4356
-                    }
4357
-                }
4358
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4359
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4360
-            }
4361
-        }
4362
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4363
-    }
4364
-
4365
-
4366
-    /**
4367
-     * Takes the input parameter and extract the table name (alias) and column name
4368
-     *
4369
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4370
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4371
-     * @throws EE_Error
4372
-     */
4373
-    private function _deduce_column_name_from_query_param($query_param)
4374
-    {
4375
-        $field = $this->_deduce_field_from_query_param($query_param);
4376
-        if ($field) {
4377
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4378
-                $field->get_model_name(),
4379
-                $query_param
4380
-            );
4381
-            return $table_alias_prefix . $field->get_qualified_column();
4382
-        }
4383
-        if (
4384
-            $this->_custom_selections instanceof CustomSelects
4385
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4386
-        ) {
4387
-            // maybe it's custom selection item?
4388
-            // if so, just use it as the "column name"
4389
-            return $query_param;
4390
-        }
4391
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4392
-            ? implode(',', $this->_custom_selections->columnAliases())
4393
-            : '';
4394
-        throw new EE_Error(
4395
-            sprintf(
4396
-                esc_html__(
4397
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4398
-                    "event_espresso"
4399
-                ),
4400
-                $query_param,
4401
-                $custom_select_aliases
4402
-            )
4403
-        );
4404
-    }
4405
-
4406
-
4407
-    /**
4408
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4409
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4410
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4411
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4412
-     *
4413
-     * @param string $condition_query_param_key
4414
-     * @return string
4415
-     */
4416
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4417
-    {
4418
-        $pos_of_star = strpos($condition_query_param_key, '*');
4419
-        if ($pos_of_star === false) {
4420
-            return $condition_query_param_key;
4421
-        }
4422
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4423
-        return $condition_query_param_sans_star;
4424
-    }
4425
-
4426
-
4427
-    /**
4428
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4429
-     *
4430
-     * @param mixed      array | string    $op_and_value
4431
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4432
-     * @return string
4433
-     * @throws EE_Error
4434
-     */
4435
-    private function _construct_op_and_value($op_and_value, $field_obj)
4436
-    {
4437
-        if (is_array($op_and_value)) {
4438
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4439
-            if (! $operator) {
4440
-                $php_array_like_string = [];
4441
-                foreach ($op_and_value as $key => $value) {
4442
-                    $php_array_like_string[] = "$key=>$value";
4443
-                }
4444
-                throw new EE_Error(
4445
-                    sprintf(
4446
-                        esc_html__(
4447
-                            "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))",
4448
-                            "event_espresso"
4449
-                        ),
4450
-                        implode(",", $php_array_like_string)
4451
-                    )
4452
-                );
4453
-            }
4454
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4455
-        } else {
4456
-            $operator = '=';
4457
-            $value    = $op_and_value;
4458
-        }
4459
-        // check to see if the value is actually another field
4460
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4461
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4462
-        }
4463
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4464
-            // in this case, the value should be an array, or at least a comma-separated list
4465
-            // it will need to handle a little differently
4466
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4467
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4468
-            return $operator . SP . $cleaned_value;
4469
-        }
4470
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4471
-            // the value should be an array with count of two.
4472
-            if (count($value) !== 2) {
4473
-                throw new EE_Error(
4474
-                    sprintf(
4475
-                        esc_html__(
4476
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4477
-                            'event_espresso'
4478
-                        ),
4479
-                        "BETWEEN"
4480
-                    )
4481
-                );
4482
-            }
4483
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4484
-            return $operator . SP . $cleaned_value;
4485
-        }
4486
-        if (in_array($operator, $this->valid_null_style_operators())) {
4487
-            if ($value !== null) {
4488
-                throw new EE_Error(
4489
-                    sprintf(
4490
-                        esc_html__(
4491
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4492
-                            "event_espresso"
4493
-                        ),
4494
-                        $value,
4495
-                        $operator
4496
-                    )
4497
-                );
4498
-            }
4499
-            return $operator;
4500
-        }
4501
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4502
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4503
-            // remove other junk. So just treat it as a string.
4504
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4505
-        }
4506
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4507
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4508
-        }
4509
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4510
-            throw new EE_Error(
4511
-                sprintf(
4512
-                    esc_html__(
4513
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4514
-                        'event_espresso'
4515
-                    ),
4516
-                    $operator,
4517
-                    $operator
4518
-                )
4519
-            );
4520
-        }
4521
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4522
-            throw new EE_Error(
4523
-                sprintf(
4524
-                    esc_html__(
4525
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4526
-                        'event_espresso'
4527
-                    ),
4528
-                    $operator,
4529
-                    $operator
4530
-                )
4531
-            );
4532
-        }
4533
-        throw new EE_Error(
4534
-            sprintf(
4535
-                esc_html__(
4536
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4537
-                    "event_espresso"
4538
-                ),
4539
-                http_build_query($op_and_value)
4540
-            )
4541
-        );
4542
-    }
4543
-
4544
-
4545
-    /**
4546
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4547
-     *
4548
-     * @param array                      $values
4549
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4550
-     *                                              '%s'
4551
-     * @return string
4552
-     * @throws EE_Error
4553
-     */
4554
-    public function _construct_between_value($values, $field_obj)
4555
-    {
4556
-        $cleaned_values = [];
4557
-        foreach ($values as $value) {
4558
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4559
-        }
4560
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4561
-    }
4562
-
4563
-
4564
-    /**
4565
-     * Takes an array or a comma-separated list of $values and cleans them
4566
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4567
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4568
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4569
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4570
-     *
4571
-     * @param mixed                      $values    array or comma-separated string
4572
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4573
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4574
-     * @throws EE_Error
4575
-     */
4576
-    public function _construct_in_value($values, $field_obj)
4577
-    {
4578
-        $prepped = [];
4579
-        // check if the value is a CSV list
4580
-        if (is_string($values)) {
4581
-            // in which case, turn it into an array
4582
-            $values = explode(',', $values);
4583
-        }
4584
-        // make sure we only have one of each value in the list
4585
-        $values = array_unique($values);
4586
-        foreach ($values as $value) {
4587
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4588
-        }
4589
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4590
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4591
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4592
-        if (empty($prepped)) {
4593
-            $all_fields  = $this->field_settings();
4594
-            $first_field = reset($all_fields);
4595
-            $main_table  = $this->_get_main_table();
4596
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4597
-        }
4598
-        return '(' . implode(',', $prepped) . ')';
4599
-    }
4600
-
4601
-
4602
-    /**
4603
-     * @param mixed                      $value
4604
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4605
-     * @return false|null|string
4606
-     * @throws EE_Error
4607
-     */
4608
-    private function _wpdb_prepare_using_field($value, $field_obj)
4609
-    {
4610
-        /** @type WPDB $wpdb */
4611
-        global $wpdb;
4612
-        if ($field_obj instanceof EE_Model_Field_Base) {
4613
-            return $wpdb->prepare(
4614
-                $field_obj->get_wpdb_data_type(),
4615
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4616
-            );
4617
-        } //$field_obj should really just be a data type
4618
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4619
-            throw new EE_Error(
4620
-                sprintf(
4621
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4622
-                    $field_obj,
4623
-                    implode(",", $this->_valid_wpdb_data_types)
4624
-                )
4625
-            );
4626
-        }
4627
-        return $wpdb->prepare($field_obj, $value);
4628
-    }
4629
-
4630
-
4631
-    /**
4632
-     * Takes the input parameter and finds the model field that it indicates.
4633
-     *
4634
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4635
-     * @return EE_Model_Field_Base
4636
-     * @throws EE_Error
4637
-     */
4638
-    protected function _deduce_field_from_query_param($query_param_name)
4639
-    {
4640
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4641
-        // which will help us find the database table and column
4642
-        $query_param_parts = explode(".", $query_param_name);
4643
-        if (empty($query_param_parts)) {
4644
-            throw new EE_Error(
4645
-                sprintf(
4646
-                    esc_html__(
4647
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4648
-                        'event_espresso'
4649
-                    ),
4650
-                    $query_param_name
4651
-                )
4652
-            );
4653
-        }
4654
-        $number_of_parts       = count($query_param_parts);
4655
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4656
-        if ($number_of_parts === 1) {
4657
-            $field_name = $last_query_param_part;
4658
-            $model_obj  = $this;
4659
-        } else {// $number_of_parts >= 2
4660
-            // the last part is the column name, and there are only 2parts. therefore...
4661
-            $field_name = $last_query_param_part;
4662
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4663
-        }
4664
-        try {
4665
-            return $model_obj->field_settings_for($field_name);
4666
-        } catch (EE_Error $e) {
4667
-            return null;
4668
-        }
4669
-    }
4670
-
4671
-
4672
-    /**
4673
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4674
-     * alias and column which corresponds to it
4675
-     *
4676
-     * @param string $field_name
4677
-     * @return string
4678
-     * @throws EE_Error
4679
-     */
4680
-    public function _get_qualified_column_for_field($field_name)
4681
-    {
4682
-        $all_fields = $this->field_settings();
4683
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4684
-        if ($field) {
4685
-            return $field->get_qualified_column();
4686
-        }
4687
-        throw new EE_Error(
4688
-            sprintf(
4689
-                esc_html__(
4690
-                    "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.",
4691
-                    'event_espresso'
4692
-                ),
4693
-                $field_name,
4694
-                get_class($this)
4695
-            )
4696
-        );
4697
-    }
4698
-
4699
-
4700
-    /**
4701
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4702
-     * Example usage:
4703
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4704
-     *      array(),
4705
-     *      ARRAY_A,
4706
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4707
-     *  );
4708
-     * is equivalent to
4709
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4710
-     * and
4711
-     *  EEM_Event::instance()->get_all_wpdb_results(
4712
-     *      array(
4713
-     *          array(
4714
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4715
-     *          ),
4716
-     *          ARRAY_A,
4717
-     *          implode(
4718
-     *              ', ',
4719
-     *              array_merge(
4720
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4721
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4722
-     *              )
4723
-     *          )
4724
-     *      )
4725
-     *  );
4726
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4727
-     *
4728
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4729
-     *                                            and the one whose fields you are selecting for example: when querying
4730
-     *                                            tickets model and selecting fields from the tickets model you would
4731
-     *                                            leave this parameter empty, because no models are needed to join
4732
-     *                                            between the queried model and the selected one. Likewise when
4733
-     *                                            querying the datetime model and selecting fields from the tickets
4734
-     *                                            model, it would also be left empty, because there is a direct
4735
-     *                                            relation from datetimes to tickets, so no model is needed to join
4736
-     *                                            them together. However, when querying from the event model and
4737
-     *                                            selecting fields from the ticket model, you should provide the string
4738
-     *                                            'Datetime', indicating that the event model must first join to the
4739
-     *                                            datetime model in order to find its relation to ticket model.
4740
-     *                                            Also, when querying from the venue model and selecting fields from
4741
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4742
-     *                                            indicating you need to join the venue model to the event model,
4743
-     *                                            to the datetime model, in order to find its relation to the ticket
4744
-     *                                            model. This string is used to deduce the prefix that gets added onto
4745
-     *                                            the models' tables qualified columns
4746
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4747
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4748
-     *                                            qualified column names
4749
-     * @return array|string
4750
-     */
4751
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4752
-    {
4753
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4754
-        $qualified_columns = [];
4755
-        foreach ($this->field_settings() as $field_name => $field) {
4756
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4757
-        }
4758
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4759
-    }
4760
-
4761
-
4762
-    /**
4763
-     * constructs the select use on special limit joins
4764
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4765
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4766
-     * (as that is typically where the limits would be set).
4767
-     *
4768
-     * @param string       $table_alias The table the select is being built for
4769
-     * @param mixed|string $limit       The limit for this select
4770
-     * @return string                The final select join element for the query.
4771
-     * @throws EE_Error
4772
-     * @throws EE_Error
4773
-     */
4774
-    public function _construct_limit_join_select($table_alias, $limit)
4775
-    {
4776
-        $SQL = '';
4777
-        foreach ($this->_tables as $table_obj) {
4778
-            if ($table_obj instanceof EE_Primary_Table) {
4779
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4780
-                    ? $table_obj->get_select_join_limit($limit)
4781
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4782
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4783
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4784
-                    ? $table_obj->get_select_join_limit_join($limit)
4785
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4786
-            }
4787
-        }
4788
-        return $SQL;
4789
-    }
4790
-
4791
-
4792
-    /**
4793
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4794
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4795
-     *
4796
-     * @return string SQL
4797
-     * @throws EE_Error
4798
-     */
4799
-    public function _construct_internal_join()
4800
-    {
4801
-        $SQL = $this->_get_main_table()->get_table_sql();
4802
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4803
-        return $SQL;
4804
-    }
4805
-
4806
-
4807
-    /**
4808
-     * Constructs the SQL for joining all the tables on this model.
4809
-     * Normally $alias should be the primary table's alias, but in cases where
4810
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4811
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4812
-     * alias, this will construct SQL like:
4813
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4814
-     * With $alias being a secondary table's alias, this will construct SQL like:
4815
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4816
-     *
4817
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4818
-     * @return string
4819
-     * @throws EE_Error
4820
-     * @throws EE_Error
4821
-     */
4822
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4823
-    {
4824
-        $SQL               = '';
4825
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4826
-        foreach ($this->_tables as $table_obj) {
4827
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4828
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4829
-                    // so we're joining to this table, meaning the table is already in
4830
-                    // the FROM statement, BUT the primary table isn't. So we want
4831
-                    // to add the inverse join sql
4832
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4833
-                } else {
4834
-                    // just add a regular JOIN to this table from the primary table
4835
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4836
-                }
4837
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4838
-        }
4839
-        return $SQL;
4840
-    }
4841
-
4842
-
4843
-    /**
4844
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4845
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4846
-     * their data type (eg, '%s', '%d', etc)
4847
-     *
4848
-     * @return array
4849
-     */
4850
-    public function _get_data_types()
4851
-    {
4852
-        $data_types = [];
4853
-        foreach ($this->field_settings() as $field_obj) {
4854
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4855
-            /** @var $field_obj EE_Model_Field_Base */
4856
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4857
-        }
4858
-        return $data_types;
4859
-    }
4860
-
4861
-
4862
-    /**
4863
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4864
-     *
4865
-     * @param string $model_name
4866
-     * @return EEM_Base
4867
-     * @throws EE_Error
4868
-     */
4869
-    public function get_related_model_obj($model_name)
4870
-    {
4871
-        $model_classname = "EEM_" . $model_name;
4872
-        if (! class_exists($model_classname)) {
4873
-            throw new EE_Error(
4874
-                sprintf(
4875
-                    esc_html__(
4876
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4877
-                        'event_espresso'
4878
-                    ),
4879
-                    $model_name,
4880
-                    $model_classname
4881
-                )
4882
-            );
4883
-        }
4884
-        return call_user_func($model_classname . "::instance");
4885
-    }
4886
-
4887
-
4888
-    /**
4889
-     * Returns the array of EE_ModelRelations for this model.
4890
-     *
4891
-     * @return EE_Model_Relation_Base[]
4892
-     */
4893
-    public function relation_settings()
4894
-    {
4895
-        return $this->_model_relations;
4896
-    }
4897
-
4898
-
4899
-    /**
4900
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4901
-     * because without THOSE models, this model probably doesn't have much purpose.
4902
-     * (Eg, without an event, datetimes have little purpose.)
4903
-     *
4904
-     * @return EE_Belongs_To_Relation[]
4905
-     */
4906
-    public function belongs_to_relations()
4907
-    {
4908
-        $belongs_to_relations = [];
4909
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4910
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4911
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4912
-            }
4913
-        }
4914
-        return $belongs_to_relations;
4915
-    }
4916
-
4917
-
4918
-    /**
4919
-     * Returns the specified EE_Model_Relation, or throws an exception
4920
-     *
4921
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4922
-     * @return EE_Model_Relation_Base
4923
-     * @throws EE_Error
4924
-     */
4925
-    public function related_settings_for($relation_name)
4926
-    {
4927
-        $relatedModels = $this->relation_settings();
4928
-        if (! array_key_exists($relation_name, $relatedModels)) {
4929
-            throw new EE_Error(
4930
-                sprintf(
4931
-                    esc_html__(
4932
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4933
-                        'event_espresso'
4934
-                    ),
4935
-                    $relation_name,
4936
-                    $this->_get_class_name(),
4937
-                    implode(', ', array_keys($relatedModels))
4938
-                )
4939
-            );
4940
-        }
4941
-        return $relatedModels[ $relation_name ];
4942
-    }
4943
-
4944
-
4945
-    /**
4946
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4947
-     * fields
4948
-     *
4949
-     * @param string  $fieldName
4950
-     * @param boolean $include_db_only_fields
4951
-     * @return EE_Model_Field_Base
4952
-     * @throws EE_Error
4953
-     */
4954
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4955
-    {
4956
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4957
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4958
-            throw new EE_Error(
4959
-                sprintf(
4960
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4961
-                    $fieldName,
4962
-                    get_class($this)
4963
-                )
4964
-            );
4965
-        }
4966
-        return $fieldSettings[ $fieldName ];
4967
-    }
4968
-
4969
-
4970
-    /**
4971
-     * Checks if this field exists on this model
4972
-     *
4973
-     * @param string $fieldName a key in the model's _field_settings array
4974
-     * @return boolean
4975
-     */
4976
-    public function has_field($fieldName)
4977
-    {
4978
-        $fieldSettings = $this->field_settings(true);
4979
-        if (isset($fieldSettings[ $fieldName ])) {
4980
-            return true;
4981
-        }
4982
-        return false;
4983
-    }
4984
-
4985
-
4986
-    /**
4987
-     * Returns whether or not this model has a relation to the specified model
4988
-     *
4989
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4990
-     * @return boolean
4991
-     */
4992
-    public function has_relation($relation_name)
4993
-    {
4994
-        $relations = $this->relation_settings();
4995
-        if (isset($relations[ $relation_name ])) {
4996
-            return true;
4997
-        }
4998
-        return false;
4999
-    }
5000
-
5001
-
5002
-    /**
5003
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5004
-     * Eg, on EE_Answer that would be ANS_ID field object
5005
-     *
5006
-     * @param $field_obj
5007
-     * @return boolean
5008
-     */
5009
-    public function is_primary_key_field($field_obj)
5010
-    {
5011
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : 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
-     * @return EE_Primary_Key_Field_Base
5020
-     * @throws EE_Error
5021
-     */
5022
-    public function get_primary_key_field()
5023
-    {
5024
-        if ($this->_primary_key_field === null) {
5025
-            foreach ($this->field_settings(true) as $field_obj) {
5026
-                if ($this->is_primary_key_field($field_obj)) {
5027
-                    $this->_primary_key_field = $field_obj;
5028
-                    break;
5029
-                }
5030
-            }
5031
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5032
-                throw new EE_Error(
5033
-                    sprintf(
5034
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5035
-                        get_class($this)
5036
-                    )
5037
-                );
5038
-            }
5039
-        }
5040
-        return $this->_primary_key_field;
5041
-    }
5042
-
5043
-
5044
-    /**
5045
-     * Returns whether or not not there is a primary key on this model.
5046
-     * Internally does some caching.
5047
-     *
5048
-     * @return boolean
5049
-     */
5050
-    public function has_primary_key_field()
5051
-    {
5052
-        if ($this->_has_primary_key_field === null) {
5053
-            try {
5054
-                $this->get_primary_key_field();
5055
-                $this->_has_primary_key_field = true;
5056
-            } catch (EE_Error $e) {
5057
-                $this->_has_primary_key_field = false;
5058
-            }
5059
-        }
5060
-        return $this->_has_primary_key_field;
5061
-    }
5062
-
5063
-
5064
-    /**
5065
-     * Finds the first field of type $field_class_name.
5066
-     *
5067
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5068
-     *                                 EE_Foreign_Key_Field, etc
5069
-     * @return EE_Model_Field_Base or null if none is found
5070
-     */
5071
-    public function get_a_field_of_type($field_class_name)
5072
-    {
5073
-        foreach ($this->field_settings() as $field) {
5074
-            if ($field instanceof $field_class_name) {
5075
-                return $field;
5076
-            }
5077
-        }
5078
-        return null;
5079
-    }
5080
-
5081
-
5082
-    /**
5083
-     * Gets a foreign key field pointing to model.
5084
-     *
5085
-     * @param string $model_name eg Event, Registration, not EEM_Event
5086
-     * @return EE_Foreign_Key_Field_Base
5087
-     * @throws EE_Error
5088
-     */
5089
-    public function get_foreign_key_to($model_name)
5090
-    {
5091
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5092
-            foreach ($this->field_settings() as $field) {
5093
-                if (
5094
-                    $field instanceof EE_Foreign_Key_Field_Base
5095
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5096
-                ) {
5097
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5098
-                    break;
5099
-                }
5100
-            }
5101
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5102
-                throw new EE_Error(
5103
-                    sprintf(
5104
-                        esc_html__(
5105
-                            "There is no foreign key field pointing to model %s on model %s",
5106
-                            'event_espresso'
5107
-                        ),
5108
-                        $model_name,
5109
-                        get_class($this)
5110
-                    )
5111
-                );
5112
-            }
5113
-        }
5114
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5115
-    }
5116
-
5117
-
5118
-    /**
5119
-     * Gets the table name (including $wpdb->prefix) for the table alias
5120
-     *
5121
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5122
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5123
-     *                            Either one works
5124
-     * @return string
5125
-     */
5126
-    public function get_table_for_alias($table_alias)
5127
-    {
5128
-        $table_alias_sans_model_relation_chain_prefix =
5129
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5130
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5131
-    }
5132
-
5133
-
5134
-    /**
5135
-     * Returns a flat array of all field son this model, instead of organizing them
5136
-     * by table_alias as they are in the constructor.
5137
-     *
5138
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5139
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5140
-     */
5141
-    public function field_settings($include_db_only_fields = false)
5142
-    {
5143
-        if ($include_db_only_fields) {
5144
-            if ($this->_cached_fields === null) {
5145
-                $this->_cached_fields = [];
5146
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5147
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5149
-                    }
5150
-                }
5151
-            }
5152
-            return $this->_cached_fields;
5153
-        }
5154
-        if ($this->_cached_fields_non_db_only === null) {
5155
-            $this->_cached_fields_non_db_only = [];
5156
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5157
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5158
-                    /** @var $field_obj EE_Model_Field_Base */
5159
-                    if (! $field_obj->is_db_only_field()) {
5160
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5161
-                    }
5162
-                }
5163
-            }
5164
-        }
5165
-        return $this->_cached_fields_non_db_only;
5166
-    }
5167
-
5168
-
5169
-    /**
5170
-     *        cycle though array of attendees and create objects out of each item
5171
-     *
5172
-     * @access        private
5173
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5174
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5175
-     *                           numerically indexed)
5176
-     * @throws EE_Error
5177
-     * @throws ReflectionException
5178
-     */
5179
-    protected function _create_objects($rows = [])
5180
-    {
5181
-        $array_of_objects = [];
5182
-        if (empty($rows)) {
5183
-            return [];
5184
-        }
5185
-        $count_if_model_has_no_primary_key = 0;
5186
-        $has_primary_key                   = $this->has_primary_key_field();
5187
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5188
-        foreach ((array) $rows as $row) {
5189
-            if (empty($row)) {
5190
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5191
-                return [];
5192
-            }
5193
-            // check if we've already set this object in the results array,
5194
-            // in which case there's no need to process it further (again)
5195
-            if ($has_primary_key) {
5196
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5197
-                    $row,
5198
-                    $primary_key_field->get_qualified_column(),
5199
-                    $primary_key_field->get_table_column()
5200
-                );
5201
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5202
-                    continue;
5203
-                }
5204
-            }
5205
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5206
-            if (! $classInstance) {
5207
-                throw new EE_Error(
5208
-                    sprintf(
5209
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5210
-                        $this->get_this_model_name(),
5211
-                        http_build_query($row)
5212
-                    )
5213
-                );
5214
-            }
5215
-            // set the timezone on the instantiated objects
5216
-            $classInstance->set_timezone($this->_timezone);
5217
-            // make sure if there is any timezone setting present that we set the timezone for the object
5218
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5219
-            $array_of_objects[ $key ] = $classInstance;
5220
-            // also, for all the relations of type BelongsTo, see if we can cache
5221
-            // those related models
5222
-            // (we could do this for other relations too, but if there are conditions
5223
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5224
-            // so it requires a little more thought than just caching them immediately...)
5225
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5226
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5227
-                    // check if this model's INFO is present. If so, cache it on the model
5228
-                    $other_model           = $relation_obj->get_other_model();
5229
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5230
-                    // if we managed to make a model object from the results, cache it on the main model object
5231
-                    if ($other_model_obj_maybe) {
5232
-                        // set timezone on these other model objects if they are present
5233
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5234
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5235
-                    }
5236
-                }
5237
-            }
5238
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5239
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5240
-            // the field in the CustomSelects object
5241
-            if ($this->_custom_selections instanceof CustomSelects) {
5242
-                $classInstance->setCustomSelectsValues(
5243
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5244
-                );
5245
-            }
5246
-        }
5247
-        return $array_of_objects;
5248
-    }
5249
-
5250
-
5251
-    /**
5252
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5253
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5254
-     *
5255
-     * @param array $db_results_row
5256
-     * @return array
5257
-     */
5258
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5259
-    {
5260
-        $results = [];
5261
-        if ($this->_custom_selections instanceof CustomSelects) {
5262
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5263
-                if (isset($db_results_row[ $alias ])) {
5264
-                    $results[ $alias ] = $this->convertValueToDataType(
5265
-                        $db_results_row[ $alias ],
5266
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5267
-                    );
5268
-                }
5269
-            }
5270
-        }
5271
-        return $results;
5272
-    }
5273
-
5274
-
5275
-    /**
5276
-     * This will set the value for the given alias
5277
-     *
5278
-     * @param string $value
5279
-     * @param string $datatype (one of %d, %s, %f)
5280
-     * @return int|string|float (int for %d, string for %s, float for %f)
5281
-     */
5282
-    protected function convertValueToDataType($value, $datatype)
5283
-    {
5284
-        switch ($datatype) {
5285
-            case '%f':
5286
-                return (float) $value;
5287
-            case '%d':
5288
-                return (int) $value;
5289
-            default:
5290
-                return (string) $value;
5291
-        }
5292
-    }
5293
-
5294
-
5295
-    /**
5296
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5297
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5298
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5299
-     * object (as set in the model_field!).
5300
-     *
5301
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5302
-     * @throws EE_Error
5303
-     * @throws ReflectionException
5304
-     */
5305
-    public function create_default_object()
5306
-    {
5307
-        $this_model_fields_and_values = [];
5308
-        // setup the row using default values;
5309
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5310
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5311
-        }
5312
-        $className     = $this->_get_class_name();
5313
-        return EE_Registry::instance()->load_class(
5314
-            $className,
5315
-            [$this_model_fields_and_values],
5316
-            false,
5317
-            false
5318
-        );
5319
-    }
5320
-
5321
-
5322
-    /**
5323
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5324
-     *                             or an stdClass where each property is the name of a column,
5325
-     * @return EE_Base_Class
5326
-     * @throws EE_Error
5327
-     * @throws ReflectionException
5328
-     */
5329
-    public function instantiate_class_from_array_or_object($cols_n_values)
5330
-    {
5331
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5332
-            $cols_n_values = get_object_vars($cols_n_values);
5333
-        }
5334
-        $primary_key = null;
5335
-        // make sure the array only has keys that are fields/columns on this model
5336
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5337
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5338
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5339
-        }
5340
-        $className = $this->_get_class_name();
5341
-        // check we actually found results that we can use to build our model object
5342
-        // if not, return null
5343
-        if ($this->has_primary_key_field()) {
5344
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5345
-                return null;
5346
-            }
5347
-        } elseif ($this->unique_indexes()) {
5348
-            $first_column = reset($this_model_fields_n_values);
5349
-            if (empty($first_column)) {
5350
-                return null;
5351
-            }
5352
-        }
5353
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5354
-        if ($primary_key) {
5355
-            $classInstance = $this->get_from_entity_map($primary_key);
5356
-            if (! $classInstance) {
5357
-                $classInstance = EE_Registry::instance()
5358
-                                            ->load_class(
5359
-                                                $className,
5360
-                                                [$this_model_fields_n_values, $this->_timezone],
5361
-                                                true,
5362
-                                                false
5363
-                                            );
5364
-                // add this new object to the entity map
5365
-                $classInstance = $this->add_to_entity_map($classInstance);
5366
-            }
5367
-        } else {
5368
-            $classInstance = EE_Registry::instance()
5369
-                                        ->load_class(
5370
-                                            $className,
5371
-                                            [$this_model_fields_n_values, $this->_timezone],
5372
-                                            true,
5373
-                                            false
5374
-                                        );
5375
-        }
5376
-        return $classInstance;
5377
-    }
5378
-
5379
-
5380
-    /**
5381
-     * Gets the model object from the  entity map if it exists
5382
-     *
5383
-     * @param int|string $id the ID of the model object
5384
-     * @return EE_Base_Class
5385
-     */
5386
-    public function get_from_entity_map($id)
5387
-    {
5388
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5389
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5390
-    }
5391
-
5392
-
5393
-    /**
5394
-     * add_to_entity_map
5395
-     * Adds the object to the model's entity mappings
5396
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5397
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5398
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5399
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5400
-     *        then this method should be called immediately after the update query
5401
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5402
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5403
-     *
5404
-     * @param EE_Base_Class $object
5405
-     * @return EE_Base_Class
5406
-     * @throws EE_Error
5407
-     * @throws ReflectionException
5408
-     */
5409
-    public function add_to_entity_map(EE_Base_Class $object)
5410
-    {
5411
-        $className = $this->_get_class_name();
5412
-        if (! $object instanceof $className) {
5413
-            throw new EE_Error(
5414
-                sprintf(
5415
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5416
-                    is_object($object) ? get_class($object) : $object,
5417
-                    $className
5418
-                )
5419
-            );
5420
-        }
5421
-        /** @var $object EE_Base_Class */
5422
-        if (! $object->ID()) {
5423
-            throw new EE_Error(
5424
-                sprintf(
5425
-                    esc_html__(
5426
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5427
-                        "event_espresso"
5428
-                    ),
5429
-                    get_class($this)
5430
-                )
5431
-            );
5432
-        }
5433
-        // double check it's not already there
5434
-        $classInstance = $this->get_from_entity_map($object->ID());
5435
-        if ($classInstance) {
5436
-            return $classInstance;
5437
-        }
5438
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5439
-        return $object;
5440
-    }
5441
-
5442
-
5443
-    /**
5444
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5445
-     * if no identifier is provided, then the entire entity map is emptied
5446
-     *
5447
-     * @param int|string $id the ID of the model object
5448
-     * @return boolean
5449
-     */
5450
-    public function clear_entity_map($id = null)
5451
-    {
5452
-        if (empty($id)) {
5453
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5454
-            return true;
5455
-        }
5456
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5457
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5458
-            return true;
5459
-        }
5460
-        return false;
5461
-    }
5462
-
5463
-
5464
-    /**
5465
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5466
-     * Given an array where keys are column (or column alias) names and values,
5467
-     * returns an array of their corresponding field names and database values
5468
-     *
5469
-     * @param array $cols_n_values
5470
-     * @return array
5471
-     * @throws EE_Error
5472
-     * @throws ReflectionException
5473
-     */
5474
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5475
-    {
5476
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5477
-    }
5478
-
5479
-
5480
-    /**
5481
-     * _deduce_fields_n_values_from_cols_n_values
5482
-     * Given an array where keys are column (or column alias) names and values,
5483
-     * returns an array of their corresponding field names and database values
5484
-     *
5485
-     * @param array|stdClass $cols_n_values
5486
-     * @return array
5487
-     * @throws EE_Error
5488
-     * @throws ReflectionException
5489
-     */
5490
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5491
-    {
5492
-        if ($cols_n_values instanceof stdClass) {
5493
-            $cols_n_values = get_object_vars($cols_n_values);
5494
-        }
5495
-        $this_model_fields_n_values = [];
5496
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5497
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5498
-                $cols_n_values,
5499
-                $table_obj->get_fully_qualified_pk_column(),
5500
-                $table_obj->get_pk_column()
5501
-            );
5502
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5503
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5504
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5505
-                    if (! $field_obj->is_db_only_field()) {
5506
-                        // prepare field as if its coming from db
5507
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5508
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5509
-                    }
5510
-                }
5511
-            } else {
5512
-                // the table's rows existed. Use their values
5513
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5514
-                    if (! $field_obj->is_db_only_field()) {
5515
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5516
-                            $cols_n_values,
5517
-                            $field_obj->get_qualified_column(),
5518
-                            $field_obj->get_table_column()
5519
-                        );
5520
-                    }
5521
-                }
5522
-            }
5523
-        }
5524
-        return $this_model_fields_n_values;
5525
-    }
5526
-
5527
-
5528
-    /**
5529
-     * @param array|bool $cols_n_values
5530
-     * @param $qualified_column
5531
-     * @param $regular_column
5532
-     * @return null
5533
-     * @throws EE_Error
5534
-     * @throws ReflectionException
5535
-     */
5536
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5537
-    {
5538
-        $value = null;
5539
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5540
-        // does the field on the model relate to this column retrieved from the db?
5541
-        // or is it a db-only field? (not relating to the model)
5542
-        if (isset($cols_n_values[ $qualified_column ])) {
5543
-            $value = $cols_n_values[ $qualified_column ];
5544
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5545
-            $value = $cols_n_values[ $regular_column ];
5546
-        } elseif (! empty($this->foreign_key_aliases)) {
5547
-            // no PK?  ok check if there is a foreign key alias set for this table
5548
-            // then check if that alias exists in the incoming data
5549
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5550
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5551
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5552
-                    $value = $cols_n_values[ $FK_alias ];
5553
-                    [$pk_class] = explode('.', $PK_column);
5554
-                    $pk_model_name = "EEM_{$pk_class}";
5555
-                    /** @var EEM_Base $pk_model */
5556
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5557
-                    if ($pk_model instanceof EEM_Base) {
5558
-                        // make sure object is pulled from db and added to entity map
5559
-                        $pk_model->get_one_by_ID($value);
5560
-                    }
5561
-                    break;
5562
-                }
5563
-            }
5564
-        }
5565
-        return $value;
5566
-    }
5567
-
5568
-
5569
-    /**
5570
-     * refresh_entity_map_from_db
5571
-     * Makes sure the model object in the entity map at $id assumes the values
5572
-     * of the database (opposite of EE_base_Class::save())
5573
-     *
5574
-     * @param int|string $id
5575
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5576
-     * @throws EE_Error
5577
-     * @throws ReflectionException
5578
-     */
5579
-    public function refresh_entity_map_from_db($id)
5580
-    {
5581
-        $obj_in_map = $this->get_from_entity_map($id);
5582
-        if ($obj_in_map) {
5583
-            $wpdb_results = $this->_get_all_wpdb_results(
5584
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5585
-            );
5586
-            if ($wpdb_results && is_array($wpdb_results)) {
5587
-                $one_row = reset($wpdb_results);
5588
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5589
-                    $obj_in_map->set_from_db($field_name, $db_value);
5590
-                }
5591
-                // clear the cache of related model objects
5592
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5593
-                    $obj_in_map->clear_cache($relation_name, null, true);
5594
-                }
5595
-            }
5596
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5597
-            return $obj_in_map;
5598
-        }
5599
-        return $this->get_one_by_ID($id);
5600
-    }
5601
-
5602
-
5603
-    /**
5604
-     * refresh_entity_map_with
5605
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5606
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5607
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5608
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5609
-     *
5610
-     * @param int|string    $id
5611
-     * @param EE_Base_Class $replacing_model_obj
5612
-     * @return EE_Base_Class
5613
-     * @throws EE_Error
5614
-     * @throws ReflectionException
5615
-     */
5616
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5617
-    {
5618
-        $obj_in_map = $this->get_from_entity_map($id);
5619
-        if ($obj_in_map) {
5620
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5621
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5622
-                    $obj_in_map->set($field_name, $value);
5623
-                }
5624
-                // make the model object in the entity map's cache match the $replacing_model_obj
5625
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5626
-                    $obj_in_map->clear_cache($relation_name, null, true);
5627
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5628
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5629
-                    }
5630
-                }
5631
-            }
5632
-            return $obj_in_map;
5633
-        }
5634
-        $this->add_to_entity_map($replacing_model_obj);
5635
-        return $replacing_model_obj;
5636
-    }
5637
-
5638
-
5639
-    /**
5640
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5641
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5642
-     * require_once($this->_getClassName().".class.php");
5643
-     *
5644
-     * @return string
5645
-     */
5646
-    private function _get_class_name()
5647
-    {
5648
-        return "EE_" . $this->get_this_model_name();
5649
-    }
5650
-
5651
-
5652
-    /**
5653
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5654
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5655
-     * it would be 'Events'.
5656
-     *
5657
-     * @param int|float|null $quantity
5658
-     * @return string
5659
-     */
5660
-    public function item_name($quantity = 1): string
5661
-    {
5662
-        $quantity = floor($quantity);
5663
-        return apply_filters(
5664
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5665
-            $quantity > 1 ? $this->plural_item : $this->singular_item,
5666
-            $quantity,
5667
-            $this->plural_item,
5668
-            $this->singular_item
5669
-        );
5670
-    }
5671
-
5672
-
5673
-    /**
5674
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5675
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5676
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5677
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5678
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5679
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5680
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5681
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5682
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5683
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5684
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5685
-     *        return $previousReturnValue.$returnString;
5686
-     * }
5687
-     * require('EEM_Answer.model.php');
5688
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5689
-     * // will output "you called my_callback! and passed args:monkeys,100"
5690
-     *
5691
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5692
-     * @param array  $args       array of original arguments passed to the function
5693
-     * @return mixed whatever the plugin which calls add_filter decides
5694
-     * @throws EE_Error
5695
-     */
5696
-    public function __call($methodName, $args)
5697
-    {
5698
-        $className = get_class($this);
5699
-        $tagName   = "FHEE__{$className}__{$methodName}";
5700
-        if (! has_filter($tagName)) {
5701
-            throw new EE_Error(
5702
-                sprintf(
5703
-                    esc_html__(
5704
-                        '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 );',
5705
-                        'event_espresso'
5706
-                    ),
5707
-                    $methodName,
5708
-                    $className,
5709
-                    $tagName,
5710
-                    '<br />'
5711
-                )
5712
-            );
5713
-        }
5714
-        return apply_filters($tagName, null, $this, $args);
5715
-    }
5716
-
5717
-
5718
-    /**
5719
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5720
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5721
-     *
5722
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5723
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5724
-     *                                                       the object's class name
5725
-     *                                                       or object's ID
5726
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5727
-     *                                                       exists in the database. If it does not, we add it
5728
-     * @return EE_Base_Class
5729
-     * @throws EE_Error
5730
-     * @throws ReflectionException
5731
-     */
5732
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5733
-    {
5734
-        $className = $this->_get_class_name();
5735
-        if ($base_class_obj_or_id instanceof $className) {
5736
-            $model_object = $base_class_obj_or_id;
5737
-        } else {
5738
-            $primary_key_field = $this->get_primary_key_field();
5739
-            if (
5740
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5741
-                && (
5742
-                    is_int($base_class_obj_or_id)
5743
-                    || is_string($base_class_obj_or_id)
5744
-                )
5745
-            ) {
5746
-                // assume it's an ID.
5747
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5748
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5749
-            } elseif (
5750
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5751
-                && is_string($base_class_obj_or_id)
5752
-            ) {
5753
-                // assume its a string representation of the object
5754
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5755
-            } else {
5756
-                throw new EE_Error(
5757
-                    sprintf(
5758
-                        esc_html__(
5759
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5760
-                            'event_espresso'
5761
-                        ),
5762
-                        $base_class_obj_or_id,
5763
-                        $this->_get_class_name(),
5764
-                        print_r($base_class_obj_or_id, true)
5765
-                    )
5766
-                );
5767
-            }
5768
-        }
5769
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5770
-            $model_object->save();
5771
-        }
5772
-        return $model_object;
5773
-    }
5774
-
5775
-
5776
-    /**
5777
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5778
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5779
-     * returns it ID.
5780
-     *
5781
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5782
-     * @return int|string depending on the type of this model object's ID
5783
-     * @throws EE_Error
5784
-     * @throws ReflectionException
5785
-     */
5786
-    public function ensure_is_ID($base_class_obj_or_id)
5787
-    {
5788
-        $className = $this->_get_class_name();
5789
-        if ($base_class_obj_or_id instanceof $className) {
5790
-            /** @var $base_class_obj_or_id EE_Base_Class */
5791
-            $id = $base_class_obj_or_id->ID();
5792
-        } elseif (is_int($base_class_obj_or_id)) {
5793
-            // assume it's an ID
5794
-            $id = $base_class_obj_or_id;
5795
-        } elseif (is_string($base_class_obj_or_id)) {
5796
-            // assume its a string representation of the object
5797
-            $id = $base_class_obj_or_id;
5798
-        } else {
5799
-            throw new EE_Error(
5800
-                sprintf(
5801
-                    esc_html__(
5802
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5803
-                        'event_espresso'
5804
-                    ),
5805
-                    $base_class_obj_or_id,
5806
-                    $this->_get_class_name(),
5807
-                    print_r($base_class_obj_or_id, true)
5808
-                )
5809
-            );
5810
-        }
5811
-        return $id;
5812
-    }
5813
-
5814
-
5815
-    /**
5816
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5817
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5818
-     * been sanitized and converted into the appropriate domain.
5819
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5820
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5821
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5822
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5823
-     * $EVT = EEM_Event::instance(); $old_setting =
5824
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5825
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5826
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5827
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5828
-     *
5829
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5830
-     * @return void
5831
-     */
5832
-    public function assume_values_already_prepared_by_model_object(
5833
-        $values_already_prepared = self::not_prepared_by_model_object
5834
-    ) {
5835
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5836
-    }
5837
-
5838
-
5839
-    /**
5840
-     * Read comments for assume_values_already_prepared_by_model_object()
5841
-     *
5842
-     * @return int
5843
-     */
5844
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5845
-    {
5846
-        return $this->_values_already_prepared_by_model_object;
5847
-    }
5848
-
5849
-
5850
-    /**
5851
-     * Gets all the indexes on this model
5852
-     *
5853
-     * @return EE_Index[]
5854
-     */
5855
-    public function indexes()
5856
-    {
5857
-        return $this->_indexes;
5858
-    }
5859
-
5860
-
5861
-    /**
5862
-     * Gets all the Unique Indexes on this model
5863
-     *
5864
-     * @return EE_Unique_Index[]
5865
-     */
5866
-    public function unique_indexes()
5867
-    {
5868
-        $unique_indexes = [];
5869
-        foreach ($this->_indexes as $name => $index) {
5870
-            if ($index instanceof EE_Unique_Index) {
5871
-                $unique_indexes [ $name ] = $index;
5872
-            }
5873
-        }
5874
-        return $unique_indexes;
5875
-    }
5876
-
5877
-
5878
-    /**
5879
-     * Gets all the fields which, when combined, make the primary key.
5880
-     * This is usually just an array with 1 element (the primary key), but in cases
5881
-     * where there is no primary key, it's a combination of fields as defined
5882
-     * on a primary index
5883
-     *
5884
-     * @return EE_Model_Field_Base[] indexed by the field's name
5885
-     * @throws EE_Error
5886
-     */
5887
-    public function get_combined_primary_key_fields()
5888
-    {
5889
-        foreach ($this->indexes() as $index) {
5890
-            if ($index instanceof EE_Primary_Key_Index) {
5891
-                return $index->fields();
5892
-            }
5893
-        }
5894
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5895
-    }
5896
-
5897
-
5898
-    /**
5899
-     * Used to build a primary key string (when the model has no primary key),
5900
-     * which can be used a unique string to identify this model object.
5901
-     *
5902
-     * @param array $fields_n_values keys are field names, values are their values.
5903
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5904
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5905
-     *                               before passing it to this function (that will convert it from columns-n-values
5906
-     *                               to field-names-n-values).
5907
-     * @return string
5908
-     * @throws EE_Error
5909
-     */
5910
-    public function get_index_primary_key_string($fields_n_values)
5911
-    {
5912
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5913
-            $fields_n_values,
5914
-            $this->get_combined_primary_key_fields()
5915
-        );
5916
-        return http_build_query($cols_n_values_for_primary_key_index);
5917
-    }
5918
-
5919
-
5920
-    /**
5921
-     * Gets the field values from the primary key string
5922
-     *
5923
-     * @param string $index_primary_key_string
5924
-     * @return null|array
5925
-     * @throws EE_Error
5926
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5927
-     */
5928
-    public function parse_index_primary_key_string($index_primary_key_string)
5929
-    {
5930
-        $key_fields = $this->get_combined_primary_key_fields();
5931
-        // check all of them are in the $id
5932
-        $key_vals_in_combined_pk = [];
5933
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5934
-        foreach ($key_fields as $key_field_name => $field_obj) {
5935
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5936
-                return null;
5937
-            }
5938
-        }
5939
-        return $key_vals_in_combined_pk;
5940
-    }
5941
-
5942
-
5943
-    /**
5944
-     * verifies that an array of key-value pairs for model fields has a key
5945
-     * for each field comprising the primary key index
5946
-     *
5947
-     * @param array $key_vals
5948
-     * @return boolean
5949
-     * @throws EE_Error
5950
-     */
5951
-    public function has_all_combined_primary_key_fields($key_vals)
5952
-    {
5953
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5954
-        foreach ($keys_it_should_have as $key) {
5955
-            if (! isset($key_vals[ $key ])) {
5956
-                return false;
5957
-            }
5958
-        }
5959
-        return true;
5960
-    }
5961
-
5962
-
5963
-    /**
5964
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5965
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5966
-     *
5967
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5968
-     * @param array               $query_params                     @see
5969
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5970
-     * @throws EE_Error
5971
-     * @throws ReflectionException
5972
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5973
-     *                                                              indexed)
5974
-     */
5975
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5976
-    {
5977
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5978
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5979
-        } elseif (is_array($model_object_or_attributes_array)) {
5980
-            $attributes_array = $model_object_or_attributes_array;
5981
-        } else {
5982
-            throw new EE_Error(
5983
-                sprintf(
5984
-                    esc_html__(
5985
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5986
-                        "event_espresso"
5987
-                    ),
5988
-                    $model_object_or_attributes_array
5989
-                )
5990
-            );
5991
-        }
5992
-        // even copies obviously won't have the same ID, so remove the primary key
5993
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5994
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5995
-            unset($attributes_array[ $this->primary_key_name() ]);
5996
-        }
5997
-        if (isset($query_params[0])) {
5998
-            $query_params[0] = array_merge($attributes_array, $query_params);
5999
-        } else {
6000
-            $query_params[0] = $attributes_array;
6001
-        }
6002
-        return $this->get_all($query_params);
6003
-    }
6004
-
6005
-
6006
-    /**
6007
-     * Gets the first copy we find. See get_all_copies for more details
6008
-     *
6009
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6010
-     * @param array $query_params
6011
-     * @return EE_Base_Class
6012
-     * @throws EE_Error
6013
-     */
6014
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6015
-    {
6016
-        if (! is_array($query_params)) {
6017
-            EE_Error::doing_it_wrong(
6018
-                'EEM_Base::get_one_copy',
6019
-                sprintf(
6020
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6021
-                    gettype($query_params)
6022
-                ),
6023
-                '4.6.0'
6024
-            );
6025
-            $query_params = [];
6026
-        }
6027
-        $query_params['limit'] = 1;
6028
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6029
-        if (is_array($copies)) {
6030
-            return array_shift($copies);
6031
-        }
6032
-        return null;
6033
-    }
6034
-
6035
-
6036
-    /**
6037
-     * Updates the item with the specified id. Ignores default query parameters because
6038
-     * we have specified the ID, and its assumed we KNOW what we're doing
6039
-     *
6040
-     * @param array      $fields_n_values keys are field names, values are their new values
6041
-     * @param int|string $id              the value of the primary key to update
6042
-     * @return int number of rows updated
6043
-     * @throws EE_Error
6044
-     */
6045
-    public function update_by_ID($fields_n_values, $id)
6046
-    {
6047
-        $query_params = [
6048
-            [
6049
-                $this->get_primary_key_field()->get_name() => $id
6050
-            ],
6051
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6052
-        ];
6053
-        return $this->update($fields_n_values, $query_params);
6054
-    }
6055
-
6056
-
6057
-    /**
6058
-     * Changes an operator which was supplied to the models into one usable in SQL
6059
-     *
6060
-     * @param string $operator_supplied
6061
-     * @return string an operator which can be used in SQL
6062
-     * @throws EE_Error
6063
-     */
6064
-    private function _prepare_operator_for_sql($operator_supplied)
6065
-    {
6066
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6067
-        if ($sql_operator) {
6068
-            return $sql_operator;
6069
-        }
6070
-        throw new EE_Error(
6071
-            sprintf(
6072
-                esc_html__(
6073
-                    "The operator '%s' is not in the list of valid operators: %s",
6074
-                    "event_espresso"
6075
-                ),
6076
-                $operator_supplied,
6077
-                implode(",", array_keys($this->_valid_operators))
6078
-            )
6079
-        );
6080
-    }
6081
-
6082
-
6083
-    /**
6084
-     * Gets the valid operators
6085
-     *
6086
-     * @return array keys are accepted strings, values are the SQL they are converted to
6087
-     */
6088
-    public function valid_operators()
6089
-    {
6090
-        return $this->_valid_operators;
6091
-    }
6092
-
6093
-
6094
-    /**
6095
-     * Gets the between-style operators (take 2 arguments).
6096
-     *
6097
-     * @return array keys are accepted strings, values are the SQL they are converted to
6098
-     */
6099
-    public function valid_between_style_operators()
6100
-    {
6101
-        return array_intersect(
6102
-            $this->valid_operators(),
6103
-            $this->_between_style_operators
6104
-        );
6105
-    }
6106
-
6107
-
6108
-    /**
6109
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6110
-     *
6111
-     * @return array keys are accepted strings, values are the SQL they are converted to
6112
-     */
6113
-    public function valid_like_style_operators()
6114
-    {
6115
-        return array_intersect(
6116
-            $this->valid_operators(),
6117
-            $this->_like_style_operators
6118
-        );
6119
-    }
6120
-
6121
-
6122
-    /**
6123
-     * Gets the "in"-style operators
6124
-     *
6125
-     * @return array keys are accepted strings, values are the SQL they are converted to
6126
-     */
6127
-    public function valid_in_style_operators()
6128
-    {
6129
-        return array_intersect(
6130
-            $this->valid_operators(),
6131
-            $this->_in_style_operators
6132
-        );
6133
-    }
6134
-
6135
-
6136
-    /**
6137
-     * Gets the "null"-style operators (accept no arguments)
6138
-     *
6139
-     * @return array keys are accepted strings, values are the SQL they are converted to
6140
-     */
6141
-    public function valid_null_style_operators()
6142
-    {
6143
-        return array_intersect(
6144
-            $this->valid_operators(),
6145
-            $this->_null_style_operators
6146
-        );
6147
-    }
6148
-
6149
-
6150
-    /**
6151
-     * Gets an array where keys are the primary keys and values are their 'names'
6152
-     * (as determined by the model object's name() function, which is often overridden)
6153
-     *
6154
-     * @param array $query_params like get_all's
6155
-     * @return string[]
6156
-     * @throws EE_Error
6157
-     * @throws ReflectionException
6158
-     */
6159
-    public function get_all_names($query_params = [])
6160
-    {
6161
-        $objs  = $this->get_all($query_params);
6162
-        $names = [];
6163
-        foreach ($objs as $obj) {
6164
-            $names[ $obj->ID() ] = $obj->name();
6165
-        }
6166
-        return $names;
6167
-    }
6168
-
6169
-
6170
-    /**
6171
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6172
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6173
-     * this is duplicated effort and reduces efficiency) you would be better to use
6174
-     * array_keys() on $model_objects.
6175
-     *
6176
-     * @param EE_Base_Class[] $model_objects
6177
-     * @param boolean         $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6178
-     *                                               in the returned array
6179
-     * @return array
6180
-     * @throws EE_Error
6181
-     * @throws ReflectionException
6182
-     */
6183
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6184
-    {
6185
-        if (! $this->has_primary_key_field()) {
6186
-            if (WP_DEBUG) {
6187
-                EE_Error::add_error(
6188
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6189
-                    __FILE__,
6190
-                    __FUNCTION__,
6191
-                    __LINE__
6192
-                );
6193
-            }
6194
-        }
6195
-        $IDs = [];
6196
-        foreach ($model_objects as $model_object) {
6197
-            $id = $model_object->ID();
6198
-            if (! $id) {
6199
-                if ($filter_out_empty_ids) {
6200
-                    continue;
6201
-                }
6202
-                if (WP_DEBUG) {
6203
-                    EE_Error::add_error(
6204
-                        esc_html__(
6205
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6206
-                            'event_espresso'
6207
-                        ),
6208
-                        __FILE__,
6209
-                        __FUNCTION__,
6210
-                        __LINE__
6211
-                    );
6212
-                }
6213
-            }
6214
-            $IDs[] = $id;
6215
-        }
6216
-        return $IDs;
6217
-    }
6218
-
6219
-
6220
-    /**
6221
-     * Returns the string used in capabilities relating to this model. If there
6222
-     * are no capabilities that relate to this model returns false
6223
-     *
6224
-     * @return string|false
6225
-     */
6226
-    public function cap_slug()
6227
-    {
6228
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6229
-    }
6230
-
6231
-
6232
-    /**
6233
-     * Returns the capability-restrictions array (@param string $context
6234
-     *
6235
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6236
-     * @throws EE_Error
6237
-     * @see EEM_Base::_cap_restrictions).
6238
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6239
-     *      only returns the cap restrictions array in that context (ie, the array
6240
-     *      at that key)
6241
-     *
6242
-     */
6243
-    public function cap_restrictions($context = EEM_Base::caps_read)
6244
-    {
6245
-        EEM_Base::verify_is_valid_cap_context($context);
6246
-        // check if we ought to run the restriction generator first
6247
-        if (
6248
-            isset($this->_cap_restriction_generators[ $context ])
6249
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6250
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6251
-        ) {
6252
-            $this->_cap_restrictions[ $context ] = array_merge(
6253
-                $this->_cap_restrictions[ $context ],
6254
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6255
-            );
6256
-        }
6257
-        // and make sure we've finalized the construction of each restriction
6258
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6259
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6260
-                $where_conditions_obj->_finalize_construct($this);
6261
-            }
6262
-        }
6263
-        return $this->_cap_restrictions[ $context ];
6264
-    }
6265
-
6266
-
6267
-    /**
6268
-     * Indicating whether or not this model thinks its a wp core model
6269
-     *
6270
-     * @return boolean
6271
-     */
6272
-    public function is_wp_core_model()
6273
-    {
6274
-        return $this->_wp_core_model;
6275
-    }
6276
-
6277
-
6278
-    /**
6279
-     * Gets all the caps that are missing which impose a restriction on
6280
-     * queries made in this context
6281
-     *
6282
-     * @param string $context one of EEM_Base::caps_ constants
6283
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6284
-     * @throws EE_Error
6285
-     */
6286
-    public function caps_missing($context = EEM_Base::caps_read)
6287
-    {
6288
-        $missing_caps     = [];
6289
-        $cap_restrictions = $this->cap_restrictions($context);
6290
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6291
-            if (
6292
-                ! EE_Capabilities::instance()
6293
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6294
-            ) {
6295
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6296
-            }
6297
-        }
6298
-        return $missing_caps;
6299
-    }
6300
-
6301
-
6302
-    /**
6303
-     * Gets the mapping from capability contexts to action strings used in capability names
6304
-     *
6305
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6306
-     * one of 'read', 'edit', or 'delete'
6307
-     */
6308
-    public function cap_contexts_to_cap_action_map()
6309
-    {
6310
-        return apply_filters(
6311
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6312
-            $this->_cap_contexts_to_cap_action_map,
6313
-            $this
6314
-        );
6315
-    }
6316
-
6317
-
6318
-    /**
6319
-     * Gets the action string for the specified capability context
6320
-     *
6321
-     * @param string $context
6322
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6323
-     * @throws EE_Error
6324
-     */
6325
-    public function cap_action_for_context($context)
6326
-    {
6327
-        $mapping = $this->cap_contexts_to_cap_action_map();
6328
-        if (isset($mapping[ $context ])) {
6329
-            return $mapping[ $context ];
6330
-        }
6331
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6332
-            return $action;
6333
-        }
6334
-        throw new EE_Error(
6335
-            sprintf(
6336
-                esc_html__(
6337
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6338
-                    'event_espresso'
6339
-                ),
6340
-                $context,
6341
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6342
-            )
6343
-        );
6344
-    }
6345
-
6346
-
6347
-    /**
6348
-     * Returns all the capability contexts which are valid when querying models
6349
-     *
6350
-     * @return array
6351
-     */
6352
-    public static function valid_cap_contexts()
6353
-    {
6354
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6355
-            self::caps_read,
6356
-            self::caps_read_admin,
6357
-            self::caps_edit,
6358
-            self::caps_delete,
6359
-        ]);
6360
-    }
6361
-
6362
-
6363
-    /**
6364
-     * Returns all valid options for 'default_where_conditions'
6365
-     *
6366
-     * @return array
6367
-     */
6368
-    public static function valid_default_where_conditions()
6369
-    {
6370
-        return [
6371
-            EEM_Base::default_where_conditions_all,
6372
-            EEM_Base::default_where_conditions_this_only,
6373
-            EEM_Base::default_where_conditions_others_only,
6374
-            EEM_Base::default_where_conditions_minimum_all,
6375
-            EEM_Base::default_where_conditions_minimum_others,
6376
-            EEM_Base::default_where_conditions_none,
6377
-        ];
6378
-    }
6379
-
6380
-    // public static function default_where_conditions_full
6381
-
6382
-
6383
-    /**
6384
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6385
-     *
6386
-     * @param string $context
6387
-     * @return bool
6388
-     * @throws EE_Error
6389
-     */
6390
-    public static function verify_is_valid_cap_context($context)
6391
-    {
6392
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6393
-        if (in_array($context, $valid_cap_contexts)) {
6394
-            return true;
6395
-        }
6396
-        throw new EE_Error(
6397
-            sprintf(
6398
-                esc_html__(
6399
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6400
-                    'event_espresso'
6401
-                ),
6402
-                $context,
6403
-                'EEM_Base',
6404
-                implode(',', $valid_cap_contexts)
6405
-            )
6406
-        );
6407
-    }
6408
-
6409
-
6410
-    /**
6411
-     * Clears all the models field caches. This is only useful when a sub-class
6412
-     * might have added a field or something and these caches might be invalidated
6413
-     */
6414
-    protected function _invalidate_field_caches()
6415
-    {
6416
-        $this->_cache_foreign_key_to_fields = [];
6417
-        $this->_cached_fields               = null;
6418
-        $this->_cached_fields_non_db_only   = null;
6419
-    }
6420
-
6421
-
6422
-    /**
6423
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6424
-     * (eg "and", "or", "not").
6425
-     *
6426
-     * @return array
6427
-     */
6428
-    public function logic_query_param_keys()
6429
-    {
6430
-        return $this->_logic_query_param_keys;
6431
-    }
6432
-
6433
-
6434
-    /**
6435
-     * Determines whether or not the where query param array key is for a logic query param.
6436
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6437
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6438
-     *
6439
-     * @param $query_param_key
6440
-     * @return bool
6441
-     */
6442
-    public function is_logic_query_param_key($query_param_key)
6443
-    {
6444
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6445
-            if (
6446
-                $query_param_key === $logic_query_param_key
6447
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6448
-            ) {
6449
-                return true;
6450
-            }
6451
-        }
6452
-        return false;
6453
-    }
6454
-
6455
-
6456
-    /**
6457
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6458
-     *
6459
-     * @return boolean
6460
-     * @since 4.9.74.p
6461
-     */
6462
-    public function hasPassword()
6463
-    {
6464
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6465
-        if ($this->has_password_field === null) {
6466
-            $password_field           = $this->getPasswordField();
6467
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6468
-        }
6469
-        return $this->has_password_field;
6470
-    }
6471
-
6472
-
6473
-    /**
6474
-     * Returns the password field on this model, if there is one
6475
-     *
6476
-     * @return EE_Password_Field|null
6477
-     * @since 4.9.74.p
6478
-     */
6479
-    public function getPasswordField()
6480
-    {
6481
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6482
-        // there's no need to search for it. If we don't know yet, then find out
6483
-        if ($this->has_password_field === null && $this->password_field === null) {
6484
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6485
-        }
6486
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6487
-        return $this->password_field;
6488
-    }
6489
-
6490
-
6491
-    /**
6492
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6493
-     *
6494
-     * @return EE_Model_Field_Base[]
6495
-     * @throws EE_Error
6496
-     * @since 4.9.74.p
6497
-     */
6498
-    public function getPasswordProtectedFields()
6499
-    {
6500
-        $password_field = $this->getPasswordField();
6501
-        $fields         = [];
6502
-        if ($password_field instanceof EE_Password_Field) {
6503
-            $field_names = $password_field->protectedFields();
6504
-            foreach ($field_names as $field_name) {
6505
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6506
-            }
6507
-        }
6508
-        return $fields;
6509
-    }
6510
-
6511
-
6512
-    /**
6513
-     * Checks if the current user can perform the requested action on this model
6514
-     *
6515
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6516
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6517
-     * @return bool
6518
-     * @throws EE_Error
6519
-     * @throws InvalidArgumentException
6520
-     * @throws InvalidDataTypeException
6521
-     * @throws InvalidInterfaceException
6522
-     * @throws ReflectionException
6523
-     * @throws UnexpectedEntityException
6524
-     * @since 4.9.74.p
6525
-     */
6526
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6527
-    {
6528
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6529
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6530
-        }
6531
-        if (! is_array($model_obj_or_fields_n_values)) {
6532
-            throw new UnexpectedEntityException(
6533
-                $model_obj_or_fields_n_values,
6534
-                'EE_Base_Class',
6535
-                sprintf(
6536
-                    esc_html__(
6537
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6538
-                        'event_espresso'
6539
-                    ),
6540
-                    __FUNCTION__
6541
-                )
6542
-            );
6543
-        }
6544
-        return $this->exists(
6545
-            $this->alter_query_params_to_restrict_by_ID(
6546
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6547
-                [
6548
-                    'default_where_conditions' => 'none',
6549
-                    'caps'                     => $cap_to_check,
6550
-                ]
6551
-            )
6552
-        );
6553
-    }
6554
-
6555
-
6556
-    /**
6557
-     * Returns the query param where conditions key to the password affecting this model.
6558
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6559
-     *
6560
-     * @return null|string
6561
-     * @throws EE_Error
6562
-     * @throws InvalidArgumentException
6563
-     * @throws InvalidDataTypeException
6564
-     * @throws InvalidInterfaceException
6565
-     * @throws ModelConfigurationException
6566
-     * @throws ReflectionException
6567
-     * @since 4.9.74.p
6568
-     */
6569
-    public function modelChainAndPassword()
6570
-    {
6571
-        if ($this->model_chain_to_password === null) {
6572
-            throw new ModelConfigurationException(
6573
-                $this,
6574
-                esc_html_x(
6575
-                // @codingStandardsIgnoreStart
6576
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6577
-                    // @codingStandardsIgnoreEnd
6578
-                    '1: model name',
6579
-                    'event_espresso'
6580
-                )
6581
-            );
6582
-        }
6583
-        if ($this->model_chain_to_password === '') {
6584
-            $model_with_password = $this;
6585
-        } else {
6586
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6587
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6588
-            } else {
6589
-                $last_model_in_chain = $this->model_chain_to_password;
6590
-            }
6591
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6592
-        }
6593
-
6594
-        $password_field = $model_with_password->getPasswordField();
6595
-        if ($password_field instanceof EE_Password_Field) {
6596
-            $password_field_name = $password_field->get_name();
6597
-        } else {
6598
-            throw new ModelConfigurationException(
6599
-                $this,
6600
-                sprintf(
6601
-                    esc_html_x(
6602
-                        '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"',
6603
-                        '1: model name, 2: special string',
6604
-                        'event_espresso'
6605
-                    ),
6606
-                    $model_with_password->get_this_model_name(),
6607
-                    $this->model_chain_to_password
6608
-                )
6609
-            );
6610
-        }
6611
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6612
-    }
6613
-
6614
-
6615
-    /**
6616
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6617
-     * or if this model itself has a password affecting access to some of its other fields.
6618
-     *
6619
-     * @return boolean
6620
-     * @since 4.9.74.p
6621
-     */
6622
-    public function restrictedByRelatedModelPassword()
6623
-    {
6624
-        return $this->model_chain_to_password !== null;
6625
-    }
3878
+		}
3879
+		return $null_friendly_where_conditions;
3880
+	}
3881
+
3882
+
3883
+	/**
3884
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3885
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3886
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3887
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3888
+	 *
3889
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3890
+	 * @return array @see
3891
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3892
+	 * @throws EE_Error
3893
+	 * @throws EE_Error
3894
+	 */
3895
+	private function _get_default_where_conditions($model_relation_path = '')
3896
+	{
3897
+		if ($this->_ignore_where_strategy) {
3898
+			return [];
3899
+		}
3900
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3901
+	}
3902
+
3903
+
3904
+	/**
3905
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3906
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3907
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3908
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3909
+	 * Similar to _get_default_where_conditions
3910
+	 *
3911
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3912
+	 * @return array @see
3913
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3914
+	 * @throws EE_Error
3915
+	 * @throws EE_Error
3916
+	 */
3917
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3918
+	{
3919
+		if ($this->_ignore_where_strategy) {
3920
+			return [];
3921
+		}
3922
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3923
+	}
3924
+
3925
+
3926
+	/**
3927
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3928
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3929
+	 *
3930
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3931
+	 * @return string
3932
+	 * @throws EE_Error
3933
+	 */
3934
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3935
+	{
3936
+		$selects = $this->_get_columns_to_select_for_this_model();
3937
+		foreach (
3938
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3939
+		) {
3940
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3941
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3942
+			foreach ($other_model_selects as $key => $value) {
3943
+				$selects[] = $value;
3944
+			}
3945
+		}
3946
+		return implode(", ", $selects);
3947
+	}
3948
+
3949
+
3950
+	/**
3951
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3952
+	 * So that's going to be the columns for all the fields on the model
3953
+	 *
3954
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3955
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3956
+	 */
3957
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3958
+	{
3959
+		$fields                                       = $this->field_settings();
3960
+		$selects                                      = [];
3961
+		$table_alias_with_model_relation_chain_prefix =
3962
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3963
+				$model_relation_chain,
3964
+				$this->get_this_model_name()
3965
+			);
3966
+		foreach ($fields as $field_obj) {
3967
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3968
+						 . $field_obj->get_table_alias()
3969
+						 . "."
3970
+						 . $field_obj->get_table_column()
3971
+						 . " AS '"
3972
+						 . $table_alias_with_model_relation_chain_prefix
3973
+						 . $field_obj->get_table_alias()
3974
+						 . "."
3975
+						 . $field_obj->get_table_column()
3976
+						 . "'";
3977
+		}
3978
+		// make sure we are also getting the PKs of each table
3979
+		$tables = $this->get_tables();
3980
+		if (count($tables) > 1) {
3981
+			foreach ($tables as $table_obj) {
3982
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3983
+									   . $table_obj->get_fully_qualified_pk_column();
3984
+				if (! in_array($qualified_pk_column, $selects)) {
3985
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3986
+				}
3987
+			}
3988
+		}
3989
+		return $selects;
3990
+	}
3991
+
3992
+
3993
+	/**
3994
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3995
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3996
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3997
+	 * SQL for joining, and the data types
3998
+	 *
3999
+	 * @param null|string                 $original_query_param
4000
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4001
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4002
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4003
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4004
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4005
+	 *                                                          or 'Registration's
4006
+	 * @param string                      $original_query_param what it originally was (eg
4007
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4008
+	 *                                                          matches $query_param
4009
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4010
+	 * @throws EE_Error
4011
+	 */
4012
+	private function _extract_related_model_info_from_query_param(
4013
+		$query_param,
4014
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4015
+		$query_param_type,
4016
+		$original_query_param = null
4017
+	) {
4018
+		if ($original_query_param === null) {
4019
+			$original_query_param = $query_param;
4020
+		}
4021
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4022
+		// check to see if we have a field on this model
4023
+		$this_model_fields = $this->field_settings(true);
4024
+		if (array_key_exists($query_param, $this_model_fields)) {
4025
+			$field_is_allowed = in_array(
4026
+				$query_param_type,
4027
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4028
+				true
4029
+			);
4030
+			if ($field_is_allowed) {
4031
+				return;
4032
+			}
4033
+			throw new EE_Error(
4034
+				sprintf(
4035
+					esc_html__(
4036
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4037
+						"event_espresso"
4038
+					),
4039
+					$query_param,
4040
+					get_class($this),
4041
+					$query_param_type,
4042
+					$original_query_param
4043
+				)
4044
+			);
4045
+		}
4046
+		// check if this is a special logic query param
4047
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4048
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4049
+			if ($operator_is_allowed) {
4050
+				return;
4051
+			}
4052
+			throw new EE_Error(
4053
+				sprintf(
4054
+					esc_html__(
4055
+						'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',
4056
+						'event_espresso'
4057
+					),
4058
+					implode('", "', $this->_logic_query_param_keys),
4059
+					$query_param,
4060
+					get_class($this),
4061
+					'<br />',
4062
+					"\t"
4063
+					. ' $passed_in_query_info = <pre>'
4064
+					. print_r($passed_in_query_info, true)
4065
+					. '</pre>'
4066
+					. "\n\t"
4067
+					. ' $query_param_type = '
4068
+					. $query_param_type
4069
+					. "\n\t"
4070
+					. ' $original_query_param = '
4071
+					. $original_query_param
4072
+				)
4073
+			);
4074
+		}
4075
+		// check if it's a custom selection
4076
+		if (
4077
+			$this->_custom_selections instanceof CustomSelects
4078
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4079
+		) {
4080
+			return;
4081
+		}
4082
+		// check if has a model name at the beginning
4083
+		// and
4084
+		// check if it's a field on a related model
4085
+		if (
4086
+			$this->extractJoinModelFromQueryParams(
4087
+				$passed_in_query_info,
4088
+				$query_param,
4089
+				$original_query_param,
4090
+				$query_param_type
4091
+			)
4092
+		) {
4093
+			return;
4094
+		}
4095
+
4096
+		// ok so $query_param didn't start with a model name
4097
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4098
+		// it's wack, that's what it is
4099
+		throw new EE_Error(
4100
+			sprintf(
4101
+				esc_html__(
4102
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4103
+					"event_espresso"
4104
+				),
4105
+				$query_param,
4106
+				get_class($this),
4107
+				$query_param_type,
4108
+				$original_query_param
4109
+			)
4110
+		);
4111
+	}
4112
+
4113
+
4114
+	/**
4115
+	 * Extracts any possible join model information from the provided possible_join_string.
4116
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4117
+	 * join
4118
+	 * parts that should be added to the query.
4119
+	 *
4120
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4121
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4122
+	 * @param null|string                 $original_query_param
4123
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4124
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4125
+	 *                                                           etc.)
4126
+	 * @return bool  returns true if a join was added and false if not.
4127
+	 * @throws EE_Error
4128
+	 */
4129
+	private function extractJoinModelFromQueryParams(
4130
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4131
+		$possible_join_string,
4132
+		$original_query_param,
4133
+		$query_parameter_type
4134
+	) {
4135
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4136
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4137
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4138
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4139
+				if ($possible_join_string === '') {
4140
+					// nothing left to $query_param
4141
+					// we should actually end in a field name, not a model like this!
4142
+					throw new EE_Error(
4143
+						sprintf(
4144
+							esc_html__(
4145
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4146
+								"event_espresso"
4147
+							),
4148
+							$possible_join_string,
4149
+							$query_parameter_type,
4150
+							get_class($this),
4151
+							$valid_related_model_name
4152
+						)
4153
+					);
4154
+				}
4155
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4156
+				$related_model_obj->_extract_related_model_info_from_query_param(
4157
+					$possible_join_string,
4158
+					$query_info_carrier,
4159
+					$query_parameter_type,
4160
+					$original_query_param
4161
+				);
4162
+				return true;
4163
+			}
4164
+			if ($possible_join_string === $valid_related_model_name) {
4165
+				$this->_add_join_to_model(
4166
+					$valid_related_model_name,
4167
+					$query_info_carrier,
4168
+					$original_query_param
4169
+				);
4170
+				return true;
4171
+			}
4172
+		}
4173
+		return false;
4174
+	}
4175
+
4176
+
4177
+	/**
4178
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4179
+	 *
4180
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4181
+	 * @throws EE_Error
4182
+	 */
4183
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4184
+	{
4185
+		if (
4186
+			$this->_custom_selections instanceof CustomSelects
4187
+			&& (
4188
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4189
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4190
+			)
4191
+		) {
4192
+			$original_selects = $this->_custom_selections->originalSelects();
4193
+			foreach ($original_selects as $alias => $select_configuration) {
4194
+				$this->extractJoinModelFromQueryParams(
4195
+					$query_info_carrier,
4196
+					$select_configuration[0],
4197
+					$select_configuration[0],
4198
+					'custom_selects'
4199
+				);
4200
+			}
4201
+		}
4202
+	}
4203
+
4204
+
4205
+	/**
4206
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4207
+	 * and store it on $passed_in_query_info
4208
+	 *
4209
+	 * @param string                      $model_name
4210
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4211
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4212
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4213
+	 *                                                          and are adding a join to 'Payment' with the original
4214
+	 *                                                          query param key
4215
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4216
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4217
+	 *                                                          Payment wants to add default query params so that it
4218
+	 *                                                          will know what models to prepend onto its default query
4219
+	 *                                                          params or in case it wants to rename tables (in case
4220
+	 *                                                          there are multiple joins to the same table)
4221
+	 * @return void
4222
+	 * @throws EE_Error
4223
+	 */
4224
+	private function _add_join_to_model(
4225
+		$model_name,
4226
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4227
+		$original_query_param
4228
+	) {
4229
+		$relation_obj         = $this->related_settings_for($model_name);
4230
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4231
+		// check if the relation is HABTM, because then we're essentially doing two joins
4232
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4233
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4234
+			$join_model_obj = $relation_obj->get_join_model();
4235
+			// replace the model specified with the join model for this relation chain, whi
4236
+			$relation_chain_to_join_model =
4237
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4238
+					$model_name,
4239
+					$join_model_obj->get_this_model_name(),
4240
+					$model_relation_chain
4241
+				);
4242
+			$passed_in_query_info->merge(
4243
+				new EE_Model_Query_Info_Carrier(
4244
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4245
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4246
+				)
4247
+			);
4248
+		}
4249
+		// now just join to the other table pointed to by the relation object, and add its data types
4250
+		$passed_in_query_info->merge(
4251
+			new EE_Model_Query_Info_Carrier(
4252
+				[$model_relation_chain => $model_name],
4253
+				$relation_obj->get_join_statement($model_relation_chain)
4254
+			)
4255
+		);
4256
+	}
4257
+
4258
+
4259
+	/**
4260
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4261
+	 *
4262
+	 * @param array $where_params @see
4263
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4264
+	 * @return string of SQL
4265
+	 * @throws EE_Error
4266
+	 */
4267
+	private function _construct_where_clause($where_params)
4268
+	{
4269
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4270
+		if ($SQL) {
4271
+			return " WHERE " . $SQL;
4272
+		}
4273
+		return '';
4274
+	}
4275
+
4276
+
4277
+	/**
4278
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4279
+	 * and should be passed HAVING parameters, not WHERE parameters
4280
+	 *
4281
+	 * @param array $having_params
4282
+	 * @return string
4283
+	 * @throws EE_Error
4284
+	 */
4285
+	private function _construct_having_clause($having_params)
4286
+	{
4287
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4288
+		if ($SQL) {
4289
+			return " HAVING " . $SQL;
4290
+		}
4291
+		return '';
4292
+	}
4293
+
4294
+
4295
+	/**
4296
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4297
+	 * Event_Meta.meta_value = 'foo'))"
4298
+	 *
4299
+	 * @param array  $where_params @see
4300
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4301
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4302
+	 * @throws EE_Error
4303
+	 * @return string of SQL
4304
+	 */
4305
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4306
+	{
4307
+		$where_clauses = [];
4308
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4309
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4310
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4311
+				switch ($query_param) {
4312
+					case 'not':
4313
+					case 'NOT':
4314
+						$where_clauses[] = "! ("
4315
+										   . $this->_construct_condition_clause_recursive(
4316
+											   $op_and_value_or_sub_condition,
4317
+											   $glue
4318
+										   )
4319
+										   . ")";
4320
+						break;
4321
+					case 'and':
4322
+					case 'AND':
4323
+						$where_clauses[] = " ("
4324
+										   . $this->_construct_condition_clause_recursive(
4325
+											   $op_and_value_or_sub_condition,
4326
+											   ' AND '
4327
+										   )
4328
+										   . ")";
4329
+						break;
4330
+					case 'or':
4331
+					case 'OR':
4332
+						$where_clauses[] = " ("
4333
+										   . $this->_construct_condition_clause_recursive(
4334
+											   $op_and_value_or_sub_condition,
4335
+											   ' OR '
4336
+										   )
4337
+										   . ")";
4338
+						break;
4339
+				}
4340
+			} else {
4341
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4342
+				// if it's not a normal field, maybe it's a custom selection?
4343
+				if (! $field_obj) {
4344
+					if ($this->_custom_selections instanceof CustomSelects) {
4345
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4346
+					} else {
4347
+						throw new EE_Error(
4348
+							sprintf(
4349
+								esc_html__(
4350
+									"%s is neither a valid model field name, nor a custom selection",
4351
+									"event_espresso"
4352
+								),
4353
+								$query_param
4354
+							)
4355
+						);
4356
+					}
4357
+				}
4358
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4359
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4360
+			}
4361
+		}
4362
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4363
+	}
4364
+
4365
+
4366
+	/**
4367
+	 * Takes the input parameter and extract the table name (alias) and column name
4368
+	 *
4369
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4370
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4371
+	 * @throws EE_Error
4372
+	 */
4373
+	private function _deduce_column_name_from_query_param($query_param)
4374
+	{
4375
+		$field = $this->_deduce_field_from_query_param($query_param);
4376
+		if ($field) {
4377
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4378
+				$field->get_model_name(),
4379
+				$query_param
4380
+			);
4381
+			return $table_alias_prefix . $field->get_qualified_column();
4382
+		}
4383
+		if (
4384
+			$this->_custom_selections instanceof CustomSelects
4385
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4386
+		) {
4387
+			// maybe it's custom selection item?
4388
+			// if so, just use it as the "column name"
4389
+			return $query_param;
4390
+		}
4391
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4392
+			? implode(',', $this->_custom_selections->columnAliases())
4393
+			: '';
4394
+		throw new EE_Error(
4395
+			sprintf(
4396
+				esc_html__(
4397
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4398
+					"event_espresso"
4399
+				),
4400
+				$query_param,
4401
+				$custom_select_aliases
4402
+			)
4403
+		);
4404
+	}
4405
+
4406
+
4407
+	/**
4408
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4409
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4410
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4411
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4412
+	 *
4413
+	 * @param string $condition_query_param_key
4414
+	 * @return string
4415
+	 */
4416
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4417
+	{
4418
+		$pos_of_star = strpos($condition_query_param_key, '*');
4419
+		if ($pos_of_star === false) {
4420
+			return $condition_query_param_key;
4421
+		}
4422
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4423
+		return $condition_query_param_sans_star;
4424
+	}
4425
+
4426
+
4427
+	/**
4428
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4429
+	 *
4430
+	 * @param mixed      array | string    $op_and_value
4431
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4432
+	 * @return string
4433
+	 * @throws EE_Error
4434
+	 */
4435
+	private function _construct_op_and_value($op_and_value, $field_obj)
4436
+	{
4437
+		if (is_array($op_and_value)) {
4438
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4439
+			if (! $operator) {
4440
+				$php_array_like_string = [];
4441
+				foreach ($op_and_value as $key => $value) {
4442
+					$php_array_like_string[] = "$key=>$value";
4443
+				}
4444
+				throw new EE_Error(
4445
+					sprintf(
4446
+						esc_html__(
4447
+							"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))",
4448
+							"event_espresso"
4449
+						),
4450
+						implode(",", $php_array_like_string)
4451
+					)
4452
+				);
4453
+			}
4454
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4455
+		} else {
4456
+			$operator = '=';
4457
+			$value    = $op_and_value;
4458
+		}
4459
+		// check to see if the value is actually another field
4460
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4461
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4462
+		}
4463
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4464
+			// in this case, the value should be an array, or at least a comma-separated list
4465
+			// it will need to handle a little differently
4466
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4467
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4468
+			return $operator . SP . $cleaned_value;
4469
+		}
4470
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4471
+			// the value should be an array with count of two.
4472
+			if (count($value) !== 2) {
4473
+				throw new EE_Error(
4474
+					sprintf(
4475
+						esc_html__(
4476
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4477
+							'event_espresso'
4478
+						),
4479
+						"BETWEEN"
4480
+					)
4481
+				);
4482
+			}
4483
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4484
+			return $operator . SP . $cleaned_value;
4485
+		}
4486
+		if (in_array($operator, $this->valid_null_style_operators())) {
4487
+			if ($value !== null) {
4488
+				throw new EE_Error(
4489
+					sprintf(
4490
+						esc_html__(
4491
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4492
+							"event_espresso"
4493
+						),
4494
+						$value,
4495
+						$operator
4496
+					)
4497
+				);
4498
+			}
4499
+			return $operator;
4500
+		}
4501
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4502
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4503
+			// remove other junk. So just treat it as a string.
4504
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4505
+		}
4506
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4507
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4508
+		}
4509
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4510
+			throw new EE_Error(
4511
+				sprintf(
4512
+					esc_html__(
4513
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4514
+						'event_espresso'
4515
+					),
4516
+					$operator,
4517
+					$operator
4518
+				)
4519
+			);
4520
+		}
4521
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4522
+			throw new EE_Error(
4523
+				sprintf(
4524
+					esc_html__(
4525
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4526
+						'event_espresso'
4527
+					),
4528
+					$operator,
4529
+					$operator
4530
+				)
4531
+			);
4532
+		}
4533
+		throw new EE_Error(
4534
+			sprintf(
4535
+				esc_html__(
4536
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4537
+					"event_espresso"
4538
+				),
4539
+				http_build_query($op_and_value)
4540
+			)
4541
+		);
4542
+	}
4543
+
4544
+
4545
+	/**
4546
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4547
+	 *
4548
+	 * @param array                      $values
4549
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4550
+	 *                                              '%s'
4551
+	 * @return string
4552
+	 * @throws EE_Error
4553
+	 */
4554
+	public function _construct_between_value($values, $field_obj)
4555
+	{
4556
+		$cleaned_values = [];
4557
+		foreach ($values as $value) {
4558
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4559
+		}
4560
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4561
+	}
4562
+
4563
+
4564
+	/**
4565
+	 * Takes an array or a comma-separated list of $values and cleans them
4566
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4567
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4568
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4569
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4570
+	 *
4571
+	 * @param mixed                      $values    array or comma-separated string
4572
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4573
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4574
+	 * @throws EE_Error
4575
+	 */
4576
+	public function _construct_in_value($values, $field_obj)
4577
+	{
4578
+		$prepped = [];
4579
+		// check if the value is a CSV list
4580
+		if (is_string($values)) {
4581
+			// in which case, turn it into an array
4582
+			$values = explode(',', $values);
4583
+		}
4584
+		// make sure we only have one of each value in the list
4585
+		$values = array_unique($values);
4586
+		foreach ($values as $value) {
4587
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4588
+		}
4589
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4590
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4591
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4592
+		if (empty($prepped)) {
4593
+			$all_fields  = $this->field_settings();
4594
+			$first_field = reset($all_fields);
4595
+			$main_table  = $this->_get_main_table();
4596
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4597
+		}
4598
+		return '(' . implode(',', $prepped) . ')';
4599
+	}
4600
+
4601
+
4602
+	/**
4603
+	 * @param mixed                      $value
4604
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4605
+	 * @return false|null|string
4606
+	 * @throws EE_Error
4607
+	 */
4608
+	private function _wpdb_prepare_using_field($value, $field_obj)
4609
+	{
4610
+		/** @type WPDB $wpdb */
4611
+		global $wpdb;
4612
+		if ($field_obj instanceof EE_Model_Field_Base) {
4613
+			return $wpdb->prepare(
4614
+				$field_obj->get_wpdb_data_type(),
4615
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4616
+			);
4617
+		} //$field_obj should really just be a data type
4618
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4619
+			throw new EE_Error(
4620
+				sprintf(
4621
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4622
+					$field_obj,
4623
+					implode(",", $this->_valid_wpdb_data_types)
4624
+				)
4625
+			);
4626
+		}
4627
+		return $wpdb->prepare($field_obj, $value);
4628
+	}
4629
+
4630
+
4631
+	/**
4632
+	 * Takes the input parameter and finds the model field that it indicates.
4633
+	 *
4634
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4635
+	 * @return EE_Model_Field_Base
4636
+	 * @throws EE_Error
4637
+	 */
4638
+	protected function _deduce_field_from_query_param($query_param_name)
4639
+	{
4640
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4641
+		// which will help us find the database table and column
4642
+		$query_param_parts = explode(".", $query_param_name);
4643
+		if (empty($query_param_parts)) {
4644
+			throw new EE_Error(
4645
+				sprintf(
4646
+					esc_html__(
4647
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4648
+						'event_espresso'
4649
+					),
4650
+					$query_param_name
4651
+				)
4652
+			);
4653
+		}
4654
+		$number_of_parts       = count($query_param_parts);
4655
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4656
+		if ($number_of_parts === 1) {
4657
+			$field_name = $last_query_param_part;
4658
+			$model_obj  = $this;
4659
+		} else {// $number_of_parts >= 2
4660
+			// the last part is the column name, and there are only 2parts. therefore...
4661
+			$field_name = $last_query_param_part;
4662
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4663
+		}
4664
+		try {
4665
+			return $model_obj->field_settings_for($field_name);
4666
+		} catch (EE_Error $e) {
4667
+			return null;
4668
+		}
4669
+	}
4670
+
4671
+
4672
+	/**
4673
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4674
+	 * alias and column which corresponds to it
4675
+	 *
4676
+	 * @param string $field_name
4677
+	 * @return string
4678
+	 * @throws EE_Error
4679
+	 */
4680
+	public function _get_qualified_column_for_field($field_name)
4681
+	{
4682
+		$all_fields = $this->field_settings();
4683
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4684
+		if ($field) {
4685
+			return $field->get_qualified_column();
4686
+		}
4687
+		throw new EE_Error(
4688
+			sprintf(
4689
+				esc_html__(
4690
+					"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.",
4691
+					'event_espresso'
4692
+				),
4693
+				$field_name,
4694
+				get_class($this)
4695
+			)
4696
+		);
4697
+	}
4698
+
4699
+
4700
+	/**
4701
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4702
+	 * Example usage:
4703
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4704
+	 *      array(),
4705
+	 *      ARRAY_A,
4706
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4707
+	 *  );
4708
+	 * is equivalent to
4709
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4710
+	 * and
4711
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4712
+	 *      array(
4713
+	 *          array(
4714
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4715
+	 *          ),
4716
+	 *          ARRAY_A,
4717
+	 *          implode(
4718
+	 *              ', ',
4719
+	 *              array_merge(
4720
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4721
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4722
+	 *              )
4723
+	 *          )
4724
+	 *      )
4725
+	 *  );
4726
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4727
+	 *
4728
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4729
+	 *                                            and the one whose fields you are selecting for example: when querying
4730
+	 *                                            tickets model and selecting fields from the tickets model you would
4731
+	 *                                            leave this parameter empty, because no models are needed to join
4732
+	 *                                            between the queried model and the selected one. Likewise when
4733
+	 *                                            querying the datetime model and selecting fields from the tickets
4734
+	 *                                            model, it would also be left empty, because there is a direct
4735
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4736
+	 *                                            them together. However, when querying from the event model and
4737
+	 *                                            selecting fields from the ticket model, you should provide the string
4738
+	 *                                            'Datetime', indicating that the event model must first join to the
4739
+	 *                                            datetime model in order to find its relation to ticket model.
4740
+	 *                                            Also, when querying from the venue model and selecting fields from
4741
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4742
+	 *                                            indicating you need to join the venue model to the event model,
4743
+	 *                                            to the datetime model, in order to find its relation to the ticket
4744
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4745
+	 *                                            the models' tables qualified columns
4746
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4747
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4748
+	 *                                            qualified column names
4749
+	 * @return array|string
4750
+	 */
4751
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4752
+	{
4753
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4754
+		$qualified_columns = [];
4755
+		foreach ($this->field_settings() as $field_name => $field) {
4756
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4757
+		}
4758
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4759
+	}
4760
+
4761
+
4762
+	/**
4763
+	 * constructs the select use on special limit joins
4764
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4765
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4766
+	 * (as that is typically where the limits would be set).
4767
+	 *
4768
+	 * @param string       $table_alias The table the select is being built for
4769
+	 * @param mixed|string $limit       The limit for this select
4770
+	 * @return string                The final select join element for the query.
4771
+	 * @throws EE_Error
4772
+	 * @throws EE_Error
4773
+	 */
4774
+	public function _construct_limit_join_select($table_alias, $limit)
4775
+	{
4776
+		$SQL = '';
4777
+		foreach ($this->_tables as $table_obj) {
4778
+			if ($table_obj instanceof EE_Primary_Table) {
4779
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4780
+					? $table_obj->get_select_join_limit($limit)
4781
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4782
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4783
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4784
+					? $table_obj->get_select_join_limit_join($limit)
4785
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4786
+			}
4787
+		}
4788
+		return $SQL;
4789
+	}
4790
+
4791
+
4792
+	/**
4793
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4794
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4795
+	 *
4796
+	 * @return string SQL
4797
+	 * @throws EE_Error
4798
+	 */
4799
+	public function _construct_internal_join()
4800
+	{
4801
+		$SQL = $this->_get_main_table()->get_table_sql();
4802
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4803
+		return $SQL;
4804
+	}
4805
+
4806
+
4807
+	/**
4808
+	 * Constructs the SQL for joining all the tables on this model.
4809
+	 * Normally $alias should be the primary table's alias, but in cases where
4810
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4811
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4812
+	 * alias, this will construct SQL like:
4813
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4814
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4815
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4816
+	 *
4817
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4818
+	 * @return string
4819
+	 * @throws EE_Error
4820
+	 * @throws EE_Error
4821
+	 */
4822
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4823
+	{
4824
+		$SQL               = '';
4825
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4826
+		foreach ($this->_tables as $table_obj) {
4827
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4828
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4829
+					// so we're joining to this table, meaning the table is already in
4830
+					// the FROM statement, BUT the primary table isn't. So we want
4831
+					// to add the inverse join sql
4832
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4833
+				} else {
4834
+					// just add a regular JOIN to this table from the primary table
4835
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4836
+				}
4837
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4838
+		}
4839
+		return $SQL;
4840
+	}
4841
+
4842
+
4843
+	/**
4844
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4845
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4846
+	 * their data type (eg, '%s', '%d', etc)
4847
+	 *
4848
+	 * @return array
4849
+	 */
4850
+	public function _get_data_types()
4851
+	{
4852
+		$data_types = [];
4853
+		foreach ($this->field_settings() as $field_obj) {
4854
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4855
+			/** @var $field_obj EE_Model_Field_Base */
4856
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4857
+		}
4858
+		return $data_types;
4859
+	}
4860
+
4861
+
4862
+	/**
4863
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4864
+	 *
4865
+	 * @param string $model_name
4866
+	 * @return EEM_Base
4867
+	 * @throws EE_Error
4868
+	 */
4869
+	public function get_related_model_obj($model_name)
4870
+	{
4871
+		$model_classname = "EEM_" . $model_name;
4872
+		if (! class_exists($model_classname)) {
4873
+			throw new EE_Error(
4874
+				sprintf(
4875
+					esc_html__(
4876
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4877
+						'event_espresso'
4878
+					),
4879
+					$model_name,
4880
+					$model_classname
4881
+				)
4882
+			);
4883
+		}
4884
+		return call_user_func($model_classname . "::instance");
4885
+	}
4886
+
4887
+
4888
+	/**
4889
+	 * Returns the array of EE_ModelRelations for this model.
4890
+	 *
4891
+	 * @return EE_Model_Relation_Base[]
4892
+	 */
4893
+	public function relation_settings()
4894
+	{
4895
+		return $this->_model_relations;
4896
+	}
4897
+
4898
+
4899
+	/**
4900
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4901
+	 * because without THOSE models, this model probably doesn't have much purpose.
4902
+	 * (Eg, without an event, datetimes have little purpose.)
4903
+	 *
4904
+	 * @return EE_Belongs_To_Relation[]
4905
+	 */
4906
+	public function belongs_to_relations()
4907
+	{
4908
+		$belongs_to_relations = [];
4909
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4910
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4911
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4912
+			}
4913
+		}
4914
+		return $belongs_to_relations;
4915
+	}
4916
+
4917
+
4918
+	/**
4919
+	 * Returns the specified EE_Model_Relation, or throws an exception
4920
+	 *
4921
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4922
+	 * @return EE_Model_Relation_Base
4923
+	 * @throws EE_Error
4924
+	 */
4925
+	public function related_settings_for($relation_name)
4926
+	{
4927
+		$relatedModels = $this->relation_settings();
4928
+		if (! array_key_exists($relation_name, $relatedModels)) {
4929
+			throw new EE_Error(
4930
+				sprintf(
4931
+					esc_html__(
4932
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4933
+						'event_espresso'
4934
+					),
4935
+					$relation_name,
4936
+					$this->_get_class_name(),
4937
+					implode(', ', array_keys($relatedModels))
4938
+				)
4939
+			);
4940
+		}
4941
+		return $relatedModels[ $relation_name ];
4942
+	}
4943
+
4944
+
4945
+	/**
4946
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4947
+	 * fields
4948
+	 *
4949
+	 * @param string  $fieldName
4950
+	 * @param boolean $include_db_only_fields
4951
+	 * @return EE_Model_Field_Base
4952
+	 * @throws EE_Error
4953
+	 */
4954
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4955
+	{
4956
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4957
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4958
+			throw new EE_Error(
4959
+				sprintf(
4960
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4961
+					$fieldName,
4962
+					get_class($this)
4963
+				)
4964
+			);
4965
+		}
4966
+		return $fieldSettings[ $fieldName ];
4967
+	}
4968
+
4969
+
4970
+	/**
4971
+	 * Checks if this field exists on this model
4972
+	 *
4973
+	 * @param string $fieldName a key in the model's _field_settings array
4974
+	 * @return boolean
4975
+	 */
4976
+	public function has_field($fieldName)
4977
+	{
4978
+		$fieldSettings = $this->field_settings(true);
4979
+		if (isset($fieldSettings[ $fieldName ])) {
4980
+			return true;
4981
+		}
4982
+		return false;
4983
+	}
4984
+
4985
+
4986
+	/**
4987
+	 * Returns whether or not this model has a relation to the specified model
4988
+	 *
4989
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4990
+	 * @return boolean
4991
+	 */
4992
+	public function has_relation($relation_name)
4993
+	{
4994
+		$relations = $this->relation_settings();
4995
+		if (isset($relations[ $relation_name ])) {
4996
+			return true;
4997
+		}
4998
+		return false;
4999
+	}
5000
+
5001
+
5002
+	/**
5003
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5004
+	 * Eg, on EE_Answer that would be ANS_ID field object
5005
+	 *
5006
+	 * @param $field_obj
5007
+	 * @return boolean
5008
+	 */
5009
+	public function is_primary_key_field($field_obj)
5010
+	{
5011
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : 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
+	 * @return EE_Primary_Key_Field_Base
5020
+	 * @throws EE_Error
5021
+	 */
5022
+	public function get_primary_key_field()
5023
+	{
5024
+		if ($this->_primary_key_field === null) {
5025
+			foreach ($this->field_settings(true) as $field_obj) {
5026
+				if ($this->is_primary_key_field($field_obj)) {
5027
+					$this->_primary_key_field = $field_obj;
5028
+					break;
5029
+				}
5030
+			}
5031
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5032
+				throw new EE_Error(
5033
+					sprintf(
5034
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5035
+						get_class($this)
5036
+					)
5037
+				);
5038
+			}
5039
+		}
5040
+		return $this->_primary_key_field;
5041
+	}
5042
+
5043
+
5044
+	/**
5045
+	 * Returns whether or not not there is a primary key on this model.
5046
+	 * Internally does some caching.
5047
+	 *
5048
+	 * @return boolean
5049
+	 */
5050
+	public function has_primary_key_field()
5051
+	{
5052
+		if ($this->_has_primary_key_field === null) {
5053
+			try {
5054
+				$this->get_primary_key_field();
5055
+				$this->_has_primary_key_field = true;
5056
+			} catch (EE_Error $e) {
5057
+				$this->_has_primary_key_field = false;
5058
+			}
5059
+		}
5060
+		return $this->_has_primary_key_field;
5061
+	}
5062
+
5063
+
5064
+	/**
5065
+	 * Finds the first field of type $field_class_name.
5066
+	 *
5067
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5068
+	 *                                 EE_Foreign_Key_Field, etc
5069
+	 * @return EE_Model_Field_Base or null if none is found
5070
+	 */
5071
+	public function get_a_field_of_type($field_class_name)
5072
+	{
5073
+		foreach ($this->field_settings() as $field) {
5074
+			if ($field instanceof $field_class_name) {
5075
+				return $field;
5076
+			}
5077
+		}
5078
+		return null;
5079
+	}
5080
+
5081
+
5082
+	/**
5083
+	 * Gets a foreign key field pointing to model.
5084
+	 *
5085
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5086
+	 * @return EE_Foreign_Key_Field_Base
5087
+	 * @throws EE_Error
5088
+	 */
5089
+	public function get_foreign_key_to($model_name)
5090
+	{
5091
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5092
+			foreach ($this->field_settings() as $field) {
5093
+				if (
5094
+					$field instanceof EE_Foreign_Key_Field_Base
5095
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5096
+				) {
5097
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5098
+					break;
5099
+				}
5100
+			}
5101
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5102
+				throw new EE_Error(
5103
+					sprintf(
5104
+						esc_html__(
5105
+							"There is no foreign key field pointing to model %s on model %s",
5106
+							'event_espresso'
5107
+						),
5108
+						$model_name,
5109
+						get_class($this)
5110
+					)
5111
+				);
5112
+			}
5113
+		}
5114
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5115
+	}
5116
+
5117
+
5118
+	/**
5119
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5120
+	 *
5121
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5122
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5123
+	 *                            Either one works
5124
+	 * @return string
5125
+	 */
5126
+	public function get_table_for_alias($table_alias)
5127
+	{
5128
+		$table_alias_sans_model_relation_chain_prefix =
5129
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5130
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5131
+	}
5132
+
5133
+
5134
+	/**
5135
+	 * Returns a flat array of all field son this model, instead of organizing them
5136
+	 * by table_alias as they are in the constructor.
5137
+	 *
5138
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5139
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5140
+	 */
5141
+	public function field_settings($include_db_only_fields = false)
5142
+	{
5143
+		if ($include_db_only_fields) {
5144
+			if ($this->_cached_fields === null) {
5145
+				$this->_cached_fields = [];
5146
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5147
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5148
+						$this->_cached_fields[ $field_name ] = $field_obj;
5149
+					}
5150
+				}
5151
+			}
5152
+			return $this->_cached_fields;
5153
+		}
5154
+		if ($this->_cached_fields_non_db_only === null) {
5155
+			$this->_cached_fields_non_db_only = [];
5156
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5157
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5158
+					/** @var $field_obj EE_Model_Field_Base */
5159
+					if (! $field_obj->is_db_only_field()) {
5160
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5161
+					}
5162
+				}
5163
+			}
5164
+		}
5165
+		return $this->_cached_fields_non_db_only;
5166
+	}
5167
+
5168
+
5169
+	/**
5170
+	 *        cycle though array of attendees and create objects out of each item
5171
+	 *
5172
+	 * @access        private
5173
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5174
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5175
+	 *                           numerically indexed)
5176
+	 * @throws EE_Error
5177
+	 * @throws ReflectionException
5178
+	 */
5179
+	protected function _create_objects($rows = [])
5180
+	{
5181
+		$array_of_objects = [];
5182
+		if (empty($rows)) {
5183
+			return [];
5184
+		}
5185
+		$count_if_model_has_no_primary_key = 0;
5186
+		$has_primary_key                   = $this->has_primary_key_field();
5187
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5188
+		foreach ((array) $rows as $row) {
5189
+			if (empty($row)) {
5190
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5191
+				return [];
5192
+			}
5193
+			// check if we've already set this object in the results array,
5194
+			// in which case there's no need to process it further (again)
5195
+			if ($has_primary_key) {
5196
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5197
+					$row,
5198
+					$primary_key_field->get_qualified_column(),
5199
+					$primary_key_field->get_table_column()
5200
+				);
5201
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5202
+					continue;
5203
+				}
5204
+			}
5205
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5206
+			if (! $classInstance) {
5207
+				throw new EE_Error(
5208
+					sprintf(
5209
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5210
+						$this->get_this_model_name(),
5211
+						http_build_query($row)
5212
+					)
5213
+				);
5214
+			}
5215
+			// set the timezone on the instantiated objects
5216
+			$classInstance->set_timezone($this->_timezone);
5217
+			// make sure if there is any timezone setting present that we set the timezone for the object
5218
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5219
+			$array_of_objects[ $key ] = $classInstance;
5220
+			// also, for all the relations of type BelongsTo, see if we can cache
5221
+			// those related models
5222
+			// (we could do this for other relations too, but if there are conditions
5223
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5224
+			// so it requires a little more thought than just caching them immediately...)
5225
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5226
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5227
+					// check if this model's INFO is present. If so, cache it on the model
5228
+					$other_model           = $relation_obj->get_other_model();
5229
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5230
+					// if we managed to make a model object from the results, cache it on the main model object
5231
+					if ($other_model_obj_maybe) {
5232
+						// set timezone on these other model objects if they are present
5233
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5234
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5235
+					}
5236
+				}
5237
+			}
5238
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5239
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5240
+			// the field in the CustomSelects object
5241
+			if ($this->_custom_selections instanceof CustomSelects) {
5242
+				$classInstance->setCustomSelectsValues(
5243
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5244
+				);
5245
+			}
5246
+		}
5247
+		return $array_of_objects;
5248
+	}
5249
+
5250
+
5251
+	/**
5252
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5253
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5254
+	 *
5255
+	 * @param array $db_results_row
5256
+	 * @return array
5257
+	 */
5258
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5259
+	{
5260
+		$results = [];
5261
+		if ($this->_custom_selections instanceof CustomSelects) {
5262
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5263
+				if (isset($db_results_row[ $alias ])) {
5264
+					$results[ $alias ] = $this->convertValueToDataType(
5265
+						$db_results_row[ $alias ],
5266
+						$this->_custom_selections->getDataTypeForAlias($alias)
5267
+					);
5268
+				}
5269
+			}
5270
+		}
5271
+		return $results;
5272
+	}
5273
+
5274
+
5275
+	/**
5276
+	 * This will set the value for the given alias
5277
+	 *
5278
+	 * @param string $value
5279
+	 * @param string $datatype (one of %d, %s, %f)
5280
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5281
+	 */
5282
+	protected function convertValueToDataType($value, $datatype)
5283
+	{
5284
+		switch ($datatype) {
5285
+			case '%f':
5286
+				return (float) $value;
5287
+			case '%d':
5288
+				return (int) $value;
5289
+			default:
5290
+				return (string) $value;
5291
+		}
5292
+	}
5293
+
5294
+
5295
+	/**
5296
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5297
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5298
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5299
+	 * object (as set in the model_field!).
5300
+	 *
5301
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5302
+	 * @throws EE_Error
5303
+	 * @throws ReflectionException
5304
+	 */
5305
+	public function create_default_object()
5306
+	{
5307
+		$this_model_fields_and_values = [];
5308
+		// setup the row using default values;
5309
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5310
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5311
+		}
5312
+		$className     = $this->_get_class_name();
5313
+		return EE_Registry::instance()->load_class(
5314
+			$className,
5315
+			[$this_model_fields_and_values],
5316
+			false,
5317
+			false
5318
+		);
5319
+	}
5320
+
5321
+
5322
+	/**
5323
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5324
+	 *                             or an stdClass where each property is the name of a column,
5325
+	 * @return EE_Base_Class
5326
+	 * @throws EE_Error
5327
+	 * @throws ReflectionException
5328
+	 */
5329
+	public function instantiate_class_from_array_or_object($cols_n_values)
5330
+	{
5331
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5332
+			$cols_n_values = get_object_vars($cols_n_values);
5333
+		}
5334
+		$primary_key = null;
5335
+		// make sure the array only has keys that are fields/columns on this model
5336
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5337
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5338
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5339
+		}
5340
+		$className = $this->_get_class_name();
5341
+		// check we actually found results that we can use to build our model object
5342
+		// if not, return null
5343
+		if ($this->has_primary_key_field()) {
5344
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5345
+				return null;
5346
+			}
5347
+		} elseif ($this->unique_indexes()) {
5348
+			$first_column = reset($this_model_fields_n_values);
5349
+			if (empty($first_column)) {
5350
+				return null;
5351
+			}
5352
+		}
5353
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5354
+		if ($primary_key) {
5355
+			$classInstance = $this->get_from_entity_map($primary_key);
5356
+			if (! $classInstance) {
5357
+				$classInstance = EE_Registry::instance()
5358
+											->load_class(
5359
+												$className,
5360
+												[$this_model_fields_n_values, $this->_timezone],
5361
+												true,
5362
+												false
5363
+											);
5364
+				// add this new object to the entity map
5365
+				$classInstance = $this->add_to_entity_map($classInstance);
5366
+			}
5367
+		} else {
5368
+			$classInstance = EE_Registry::instance()
5369
+										->load_class(
5370
+											$className,
5371
+											[$this_model_fields_n_values, $this->_timezone],
5372
+											true,
5373
+											false
5374
+										);
5375
+		}
5376
+		return $classInstance;
5377
+	}
5378
+
5379
+
5380
+	/**
5381
+	 * Gets the model object from the  entity map if it exists
5382
+	 *
5383
+	 * @param int|string $id the ID of the model object
5384
+	 * @return EE_Base_Class
5385
+	 */
5386
+	public function get_from_entity_map($id)
5387
+	{
5388
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5389
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5390
+	}
5391
+
5392
+
5393
+	/**
5394
+	 * add_to_entity_map
5395
+	 * Adds the object to the model's entity mappings
5396
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5397
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5398
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5399
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5400
+	 *        then this method should be called immediately after the update query
5401
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5402
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5403
+	 *
5404
+	 * @param EE_Base_Class $object
5405
+	 * @return EE_Base_Class
5406
+	 * @throws EE_Error
5407
+	 * @throws ReflectionException
5408
+	 */
5409
+	public function add_to_entity_map(EE_Base_Class $object)
5410
+	{
5411
+		$className = $this->_get_class_name();
5412
+		if (! $object instanceof $className) {
5413
+			throw new EE_Error(
5414
+				sprintf(
5415
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5416
+					is_object($object) ? get_class($object) : $object,
5417
+					$className
5418
+				)
5419
+			);
5420
+		}
5421
+		/** @var $object EE_Base_Class */
5422
+		if (! $object->ID()) {
5423
+			throw new EE_Error(
5424
+				sprintf(
5425
+					esc_html__(
5426
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5427
+						"event_espresso"
5428
+					),
5429
+					get_class($this)
5430
+				)
5431
+			);
5432
+		}
5433
+		// double check it's not already there
5434
+		$classInstance = $this->get_from_entity_map($object->ID());
5435
+		if ($classInstance) {
5436
+			return $classInstance;
5437
+		}
5438
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5439
+		return $object;
5440
+	}
5441
+
5442
+
5443
+	/**
5444
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5445
+	 * if no identifier is provided, then the entire entity map is emptied
5446
+	 *
5447
+	 * @param int|string $id the ID of the model object
5448
+	 * @return boolean
5449
+	 */
5450
+	public function clear_entity_map($id = null)
5451
+	{
5452
+		if (empty($id)) {
5453
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5454
+			return true;
5455
+		}
5456
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5457
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5458
+			return true;
5459
+		}
5460
+		return false;
5461
+	}
5462
+
5463
+
5464
+	/**
5465
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5466
+	 * Given an array where keys are column (or column alias) names and values,
5467
+	 * returns an array of their corresponding field names and database values
5468
+	 *
5469
+	 * @param array $cols_n_values
5470
+	 * @return array
5471
+	 * @throws EE_Error
5472
+	 * @throws ReflectionException
5473
+	 */
5474
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5475
+	{
5476
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5477
+	}
5478
+
5479
+
5480
+	/**
5481
+	 * _deduce_fields_n_values_from_cols_n_values
5482
+	 * Given an array where keys are column (or column alias) names and values,
5483
+	 * returns an array of their corresponding field names and database values
5484
+	 *
5485
+	 * @param array|stdClass $cols_n_values
5486
+	 * @return array
5487
+	 * @throws EE_Error
5488
+	 * @throws ReflectionException
5489
+	 */
5490
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5491
+	{
5492
+		if ($cols_n_values instanceof stdClass) {
5493
+			$cols_n_values = get_object_vars($cols_n_values);
5494
+		}
5495
+		$this_model_fields_n_values = [];
5496
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5497
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5498
+				$cols_n_values,
5499
+				$table_obj->get_fully_qualified_pk_column(),
5500
+				$table_obj->get_pk_column()
5501
+			);
5502
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5503
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5504
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5505
+					if (! $field_obj->is_db_only_field()) {
5506
+						// prepare field as if its coming from db
5507
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5508
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5509
+					}
5510
+				}
5511
+			} else {
5512
+				// the table's rows existed. Use their values
5513
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5514
+					if (! $field_obj->is_db_only_field()) {
5515
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5516
+							$cols_n_values,
5517
+							$field_obj->get_qualified_column(),
5518
+							$field_obj->get_table_column()
5519
+						);
5520
+					}
5521
+				}
5522
+			}
5523
+		}
5524
+		return $this_model_fields_n_values;
5525
+	}
5526
+
5527
+
5528
+	/**
5529
+	 * @param array|bool $cols_n_values
5530
+	 * @param $qualified_column
5531
+	 * @param $regular_column
5532
+	 * @return null
5533
+	 * @throws EE_Error
5534
+	 * @throws ReflectionException
5535
+	 */
5536
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5537
+	{
5538
+		$value = null;
5539
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5540
+		// does the field on the model relate to this column retrieved from the db?
5541
+		// or is it a db-only field? (not relating to the model)
5542
+		if (isset($cols_n_values[ $qualified_column ])) {
5543
+			$value = $cols_n_values[ $qualified_column ];
5544
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5545
+			$value = $cols_n_values[ $regular_column ];
5546
+		} elseif (! empty($this->foreign_key_aliases)) {
5547
+			// no PK?  ok check if there is a foreign key alias set for this table
5548
+			// then check if that alias exists in the incoming data
5549
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5550
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5551
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5552
+					$value = $cols_n_values[ $FK_alias ];
5553
+					[$pk_class] = explode('.', $PK_column);
5554
+					$pk_model_name = "EEM_{$pk_class}";
5555
+					/** @var EEM_Base $pk_model */
5556
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5557
+					if ($pk_model instanceof EEM_Base) {
5558
+						// make sure object is pulled from db and added to entity map
5559
+						$pk_model->get_one_by_ID($value);
5560
+					}
5561
+					break;
5562
+				}
5563
+			}
5564
+		}
5565
+		return $value;
5566
+	}
5567
+
5568
+
5569
+	/**
5570
+	 * refresh_entity_map_from_db
5571
+	 * Makes sure the model object in the entity map at $id assumes the values
5572
+	 * of the database (opposite of EE_base_Class::save())
5573
+	 *
5574
+	 * @param int|string $id
5575
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5576
+	 * @throws EE_Error
5577
+	 * @throws ReflectionException
5578
+	 */
5579
+	public function refresh_entity_map_from_db($id)
5580
+	{
5581
+		$obj_in_map = $this->get_from_entity_map($id);
5582
+		if ($obj_in_map) {
5583
+			$wpdb_results = $this->_get_all_wpdb_results(
5584
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5585
+			);
5586
+			if ($wpdb_results && is_array($wpdb_results)) {
5587
+				$one_row = reset($wpdb_results);
5588
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5589
+					$obj_in_map->set_from_db($field_name, $db_value);
5590
+				}
5591
+				// clear the cache of related model objects
5592
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5593
+					$obj_in_map->clear_cache($relation_name, null, true);
5594
+				}
5595
+			}
5596
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5597
+			return $obj_in_map;
5598
+		}
5599
+		return $this->get_one_by_ID($id);
5600
+	}
5601
+
5602
+
5603
+	/**
5604
+	 * refresh_entity_map_with
5605
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5606
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5607
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5608
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5609
+	 *
5610
+	 * @param int|string    $id
5611
+	 * @param EE_Base_Class $replacing_model_obj
5612
+	 * @return EE_Base_Class
5613
+	 * @throws EE_Error
5614
+	 * @throws ReflectionException
5615
+	 */
5616
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5617
+	{
5618
+		$obj_in_map = $this->get_from_entity_map($id);
5619
+		if ($obj_in_map) {
5620
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5621
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5622
+					$obj_in_map->set($field_name, $value);
5623
+				}
5624
+				// make the model object in the entity map's cache match the $replacing_model_obj
5625
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5626
+					$obj_in_map->clear_cache($relation_name, null, true);
5627
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5628
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5629
+					}
5630
+				}
5631
+			}
5632
+			return $obj_in_map;
5633
+		}
5634
+		$this->add_to_entity_map($replacing_model_obj);
5635
+		return $replacing_model_obj;
5636
+	}
5637
+
5638
+
5639
+	/**
5640
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5641
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5642
+	 * require_once($this->_getClassName().".class.php");
5643
+	 *
5644
+	 * @return string
5645
+	 */
5646
+	private function _get_class_name()
5647
+	{
5648
+		return "EE_" . $this->get_this_model_name();
5649
+	}
5650
+
5651
+
5652
+	/**
5653
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5654
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5655
+	 * it would be 'Events'.
5656
+	 *
5657
+	 * @param int|float|null $quantity
5658
+	 * @return string
5659
+	 */
5660
+	public function item_name($quantity = 1): string
5661
+	{
5662
+		$quantity = floor($quantity);
5663
+		return apply_filters(
5664
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5665
+			$quantity > 1 ? $this->plural_item : $this->singular_item,
5666
+			$quantity,
5667
+			$this->plural_item,
5668
+			$this->singular_item
5669
+		);
5670
+	}
5671
+
5672
+
5673
+	/**
5674
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5675
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5676
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5677
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5678
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5679
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5680
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5681
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5682
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5683
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5684
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5685
+	 *        return $previousReturnValue.$returnString;
5686
+	 * }
5687
+	 * require('EEM_Answer.model.php');
5688
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5689
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5690
+	 *
5691
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5692
+	 * @param array  $args       array of original arguments passed to the function
5693
+	 * @return mixed whatever the plugin which calls add_filter decides
5694
+	 * @throws EE_Error
5695
+	 */
5696
+	public function __call($methodName, $args)
5697
+	{
5698
+		$className = get_class($this);
5699
+		$tagName   = "FHEE__{$className}__{$methodName}";
5700
+		if (! has_filter($tagName)) {
5701
+			throw new EE_Error(
5702
+				sprintf(
5703
+					esc_html__(
5704
+						'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 );',
5705
+						'event_espresso'
5706
+					),
5707
+					$methodName,
5708
+					$className,
5709
+					$tagName,
5710
+					'<br />'
5711
+				)
5712
+			);
5713
+		}
5714
+		return apply_filters($tagName, null, $this, $args);
5715
+	}
5716
+
5717
+
5718
+	/**
5719
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5720
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5721
+	 *
5722
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5723
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5724
+	 *                                                       the object's class name
5725
+	 *                                                       or object's ID
5726
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5727
+	 *                                                       exists in the database. If it does not, we add it
5728
+	 * @return EE_Base_Class
5729
+	 * @throws EE_Error
5730
+	 * @throws ReflectionException
5731
+	 */
5732
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5733
+	{
5734
+		$className = $this->_get_class_name();
5735
+		if ($base_class_obj_or_id instanceof $className) {
5736
+			$model_object = $base_class_obj_or_id;
5737
+		} else {
5738
+			$primary_key_field = $this->get_primary_key_field();
5739
+			if (
5740
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5741
+				&& (
5742
+					is_int($base_class_obj_or_id)
5743
+					|| is_string($base_class_obj_or_id)
5744
+				)
5745
+			) {
5746
+				// assume it's an ID.
5747
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5748
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5749
+			} elseif (
5750
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5751
+				&& is_string($base_class_obj_or_id)
5752
+			) {
5753
+				// assume its a string representation of the object
5754
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5755
+			} else {
5756
+				throw new EE_Error(
5757
+					sprintf(
5758
+						esc_html__(
5759
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5760
+							'event_espresso'
5761
+						),
5762
+						$base_class_obj_or_id,
5763
+						$this->_get_class_name(),
5764
+						print_r($base_class_obj_or_id, true)
5765
+					)
5766
+				);
5767
+			}
5768
+		}
5769
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5770
+			$model_object->save();
5771
+		}
5772
+		return $model_object;
5773
+	}
5774
+
5775
+
5776
+	/**
5777
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5778
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5779
+	 * returns it ID.
5780
+	 *
5781
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5782
+	 * @return int|string depending on the type of this model object's ID
5783
+	 * @throws EE_Error
5784
+	 * @throws ReflectionException
5785
+	 */
5786
+	public function ensure_is_ID($base_class_obj_or_id)
5787
+	{
5788
+		$className = $this->_get_class_name();
5789
+		if ($base_class_obj_or_id instanceof $className) {
5790
+			/** @var $base_class_obj_or_id EE_Base_Class */
5791
+			$id = $base_class_obj_or_id->ID();
5792
+		} elseif (is_int($base_class_obj_or_id)) {
5793
+			// assume it's an ID
5794
+			$id = $base_class_obj_or_id;
5795
+		} elseif (is_string($base_class_obj_or_id)) {
5796
+			// assume its a string representation of the object
5797
+			$id = $base_class_obj_or_id;
5798
+		} else {
5799
+			throw new EE_Error(
5800
+				sprintf(
5801
+					esc_html__(
5802
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5803
+						'event_espresso'
5804
+					),
5805
+					$base_class_obj_or_id,
5806
+					$this->_get_class_name(),
5807
+					print_r($base_class_obj_or_id, true)
5808
+				)
5809
+			);
5810
+		}
5811
+		return $id;
5812
+	}
5813
+
5814
+
5815
+	/**
5816
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5817
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5818
+	 * been sanitized and converted into the appropriate domain.
5819
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5820
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5821
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5822
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5823
+	 * $EVT = EEM_Event::instance(); $old_setting =
5824
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5825
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5826
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5827
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5828
+	 *
5829
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5830
+	 * @return void
5831
+	 */
5832
+	public function assume_values_already_prepared_by_model_object(
5833
+		$values_already_prepared = self::not_prepared_by_model_object
5834
+	) {
5835
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5836
+	}
5837
+
5838
+
5839
+	/**
5840
+	 * Read comments for assume_values_already_prepared_by_model_object()
5841
+	 *
5842
+	 * @return int
5843
+	 */
5844
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5845
+	{
5846
+		return $this->_values_already_prepared_by_model_object;
5847
+	}
5848
+
5849
+
5850
+	/**
5851
+	 * Gets all the indexes on this model
5852
+	 *
5853
+	 * @return EE_Index[]
5854
+	 */
5855
+	public function indexes()
5856
+	{
5857
+		return $this->_indexes;
5858
+	}
5859
+
5860
+
5861
+	/**
5862
+	 * Gets all the Unique Indexes on this model
5863
+	 *
5864
+	 * @return EE_Unique_Index[]
5865
+	 */
5866
+	public function unique_indexes()
5867
+	{
5868
+		$unique_indexes = [];
5869
+		foreach ($this->_indexes as $name => $index) {
5870
+			if ($index instanceof EE_Unique_Index) {
5871
+				$unique_indexes [ $name ] = $index;
5872
+			}
5873
+		}
5874
+		return $unique_indexes;
5875
+	}
5876
+
5877
+
5878
+	/**
5879
+	 * Gets all the fields which, when combined, make the primary key.
5880
+	 * This is usually just an array with 1 element (the primary key), but in cases
5881
+	 * where there is no primary key, it's a combination of fields as defined
5882
+	 * on a primary index
5883
+	 *
5884
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5885
+	 * @throws EE_Error
5886
+	 */
5887
+	public function get_combined_primary_key_fields()
5888
+	{
5889
+		foreach ($this->indexes() as $index) {
5890
+			if ($index instanceof EE_Primary_Key_Index) {
5891
+				return $index->fields();
5892
+			}
5893
+		}
5894
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5895
+	}
5896
+
5897
+
5898
+	/**
5899
+	 * Used to build a primary key string (when the model has no primary key),
5900
+	 * which can be used a unique string to identify this model object.
5901
+	 *
5902
+	 * @param array $fields_n_values keys are field names, values are their values.
5903
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5904
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5905
+	 *                               before passing it to this function (that will convert it from columns-n-values
5906
+	 *                               to field-names-n-values).
5907
+	 * @return string
5908
+	 * @throws EE_Error
5909
+	 */
5910
+	public function get_index_primary_key_string($fields_n_values)
5911
+	{
5912
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5913
+			$fields_n_values,
5914
+			$this->get_combined_primary_key_fields()
5915
+		);
5916
+		return http_build_query($cols_n_values_for_primary_key_index);
5917
+	}
5918
+
5919
+
5920
+	/**
5921
+	 * Gets the field values from the primary key string
5922
+	 *
5923
+	 * @param string $index_primary_key_string
5924
+	 * @return null|array
5925
+	 * @throws EE_Error
5926
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5927
+	 */
5928
+	public function parse_index_primary_key_string($index_primary_key_string)
5929
+	{
5930
+		$key_fields = $this->get_combined_primary_key_fields();
5931
+		// check all of them are in the $id
5932
+		$key_vals_in_combined_pk = [];
5933
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5934
+		foreach ($key_fields as $key_field_name => $field_obj) {
5935
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5936
+				return null;
5937
+			}
5938
+		}
5939
+		return $key_vals_in_combined_pk;
5940
+	}
5941
+
5942
+
5943
+	/**
5944
+	 * verifies that an array of key-value pairs for model fields has a key
5945
+	 * for each field comprising the primary key index
5946
+	 *
5947
+	 * @param array $key_vals
5948
+	 * @return boolean
5949
+	 * @throws EE_Error
5950
+	 */
5951
+	public function has_all_combined_primary_key_fields($key_vals)
5952
+	{
5953
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5954
+		foreach ($keys_it_should_have as $key) {
5955
+			if (! isset($key_vals[ $key ])) {
5956
+				return false;
5957
+			}
5958
+		}
5959
+		return true;
5960
+	}
5961
+
5962
+
5963
+	/**
5964
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5965
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5966
+	 *
5967
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5968
+	 * @param array               $query_params                     @see
5969
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5970
+	 * @throws EE_Error
5971
+	 * @throws ReflectionException
5972
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5973
+	 *                                                              indexed)
5974
+	 */
5975
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5976
+	{
5977
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5978
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5979
+		} elseif (is_array($model_object_or_attributes_array)) {
5980
+			$attributes_array = $model_object_or_attributes_array;
5981
+		} else {
5982
+			throw new EE_Error(
5983
+				sprintf(
5984
+					esc_html__(
5985
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5986
+						"event_espresso"
5987
+					),
5988
+					$model_object_or_attributes_array
5989
+				)
5990
+			);
5991
+		}
5992
+		// even copies obviously won't have the same ID, so remove the primary key
5993
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5994
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5995
+			unset($attributes_array[ $this->primary_key_name() ]);
5996
+		}
5997
+		if (isset($query_params[0])) {
5998
+			$query_params[0] = array_merge($attributes_array, $query_params);
5999
+		} else {
6000
+			$query_params[0] = $attributes_array;
6001
+		}
6002
+		return $this->get_all($query_params);
6003
+	}
6004
+
6005
+
6006
+	/**
6007
+	 * Gets the first copy we find. See get_all_copies for more details
6008
+	 *
6009
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6010
+	 * @param array $query_params
6011
+	 * @return EE_Base_Class
6012
+	 * @throws EE_Error
6013
+	 */
6014
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6015
+	{
6016
+		if (! is_array($query_params)) {
6017
+			EE_Error::doing_it_wrong(
6018
+				'EEM_Base::get_one_copy',
6019
+				sprintf(
6020
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6021
+					gettype($query_params)
6022
+				),
6023
+				'4.6.0'
6024
+			);
6025
+			$query_params = [];
6026
+		}
6027
+		$query_params['limit'] = 1;
6028
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6029
+		if (is_array($copies)) {
6030
+			return array_shift($copies);
6031
+		}
6032
+		return null;
6033
+	}
6034
+
6035
+
6036
+	/**
6037
+	 * Updates the item with the specified id. Ignores default query parameters because
6038
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6039
+	 *
6040
+	 * @param array      $fields_n_values keys are field names, values are their new values
6041
+	 * @param int|string $id              the value of the primary key to update
6042
+	 * @return int number of rows updated
6043
+	 * @throws EE_Error
6044
+	 */
6045
+	public function update_by_ID($fields_n_values, $id)
6046
+	{
6047
+		$query_params = [
6048
+			[
6049
+				$this->get_primary_key_field()->get_name() => $id
6050
+			],
6051
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6052
+		];
6053
+		return $this->update($fields_n_values, $query_params);
6054
+	}
6055
+
6056
+
6057
+	/**
6058
+	 * Changes an operator which was supplied to the models into one usable in SQL
6059
+	 *
6060
+	 * @param string $operator_supplied
6061
+	 * @return string an operator which can be used in SQL
6062
+	 * @throws EE_Error
6063
+	 */
6064
+	private function _prepare_operator_for_sql($operator_supplied)
6065
+	{
6066
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6067
+		if ($sql_operator) {
6068
+			return $sql_operator;
6069
+		}
6070
+		throw new EE_Error(
6071
+			sprintf(
6072
+				esc_html__(
6073
+					"The operator '%s' is not in the list of valid operators: %s",
6074
+					"event_espresso"
6075
+				),
6076
+				$operator_supplied,
6077
+				implode(",", array_keys($this->_valid_operators))
6078
+			)
6079
+		);
6080
+	}
6081
+
6082
+
6083
+	/**
6084
+	 * Gets the valid operators
6085
+	 *
6086
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6087
+	 */
6088
+	public function valid_operators()
6089
+	{
6090
+		return $this->_valid_operators;
6091
+	}
6092
+
6093
+
6094
+	/**
6095
+	 * Gets the between-style operators (take 2 arguments).
6096
+	 *
6097
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6098
+	 */
6099
+	public function valid_between_style_operators()
6100
+	{
6101
+		return array_intersect(
6102
+			$this->valid_operators(),
6103
+			$this->_between_style_operators
6104
+		);
6105
+	}
6106
+
6107
+
6108
+	/**
6109
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6110
+	 *
6111
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6112
+	 */
6113
+	public function valid_like_style_operators()
6114
+	{
6115
+		return array_intersect(
6116
+			$this->valid_operators(),
6117
+			$this->_like_style_operators
6118
+		);
6119
+	}
6120
+
6121
+
6122
+	/**
6123
+	 * Gets the "in"-style operators
6124
+	 *
6125
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6126
+	 */
6127
+	public function valid_in_style_operators()
6128
+	{
6129
+		return array_intersect(
6130
+			$this->valid_operators(),
6131
+			$this->_in_style_operators
6132
+		);
6133
+	}
6134
+
6135
+
6136
+	/**
6137
+	 * Gets the "null"-style operators (accept no arguments)
6138
+	 *
6139
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6140
+	 */
6141
+	public function valid_null_style_operators()
6142
+	{
6143
+		return array_intersect(
6144
+			$this->valid_operators(),
6145
+			$this->_null_style_operators
6146
+		);
6147
+	}
6148
+
6149
+
6150
+	/**
6151
+	 * Gets an array where keys are the primary keys and values are their 'names'
6152
+	 * (as determined by the model object's name() function, which is often overridden)
6153
+	 *
6154
+	 * @param array $query_params like get_all's
6155
+	 * @return string[]
6156
+	 * @throws EE_Error
6157
+	 * @throws ReflectionException
6158
+	 */
6159
+	public function get_all_names($query_params = [])
6160
+	{
6161
+		$objs  = $this->get_all($query_params);
6162
+		$names = [];
6163
+		foreach ($objs as $obj) {
6164
+			$names[ $obj->ID() ] = $obj->name();
6165
+		}
6166
+		return $names;
6167
+	}
6168
+
6169
+
6170
+	/**
6171
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6172
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6173
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6174
+	 * array_keys() on $model_objects.
6175
+	 *
6176
+	 * @param EE_Base_Class[] $model_objects
6177
+	 * @param boolean         $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6178
+	 *                                               in the returned array
6179
+	 * @return array
6180
+	 * @throws EE_Error
6181
+	 * @throws ReflectionException
6182
+	 */
6183
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6184
+	{
6185
+		if (! $this->has_primary_key_field()) {
6186
+			if (WP_DEBUG) {
6187
+				EE_Error::add_error(
6188
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6189
+					__FILE__,
6190
+					__FUNCTION__,
6191
+					__LINE__
6192
+				);
6193
+			}
6194
+		}
6195
+		$IDs = [];
6196
+		foreach ($model_objects as $model_object) {
6197
+			$id = $model_object->ID();
6198
+			if (! $id) {
6199
+				if ($filter_out_empty_ids) {
6200
+					continue;
6201
+				}
6202
+				if (WP_DEBUG) {
6203
+					EE_Error::add_error(
6204
+						esc_html__(
6205
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6206
+							'event_espresso'
6207
+						),
6208
+						__FILE__,
6209
+						__FUNCTION__,
6210
+						__LINE__
6211
+					);
6212
+				}
6213
+			}
6214
+			$IDs[] = $id;
6215
+		}
6216
+		return $IDs;
6217
+	}
6218
+
6219
+
6220
+	/**
6221
+	 * Returns the string used in capabilities relating to this model. If there
6222
+	 * are no capabilities that relate to this model returns false
6223
+	 *
6224
+	 * @return string|false
6225
+	 */
6226
+	public function cap_slug()
6227
+	{
6228
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6229
+	}
6230
+
6231
+
6232
+	/**
6233
+	 * Returns the capability-restrictions array (@param string $context
6234
+	 *
6235
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6236
+	 * @throws EE_Error
6237
+	 * @see EEM_Base::_cap_restrictions).
6238
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6239
+	 *      only returns the cap restrictions array in that context (ie, the array
6240
+	 *      at that key)
6241
+	 *
6242
+	 */
6243
+	public function cap_restrictions($context = EEM_Base::caps_read)
6244
+	{
6245
+		EEM_Base::verify_is_valid_cap_context($context);
6246
+		// check if we ought to run the restriction generator first
6247
+		if (
6248
+			isset($this->_cap_restriction_generators[ $context ])
6249
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6250
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6251
+		) {
6252
+			$this->_cap_restrictions[ $context ] = array_merge(
6253
+				$this->_cap_restrictions[ $context ],
6254
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6255
+			);
6256
+		}
6257
+		// and make sure we've finalized the construction of each restriction
6258
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6259
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6260
+				$where_conditions_obj->_finalize_construct($this);
6261
+			}
6262
+		}
6263
+		return $this->_cap_restrictions[ $context ];
6264
+	}
6265
+
6266
+
6267
+	/**
6268
+	 * Indicating whether or not this model thinks its a wp core model
6269
+	 *
6270
+	 * @return boolean
6271
+	 */
6272
+	public function is_wp_core_model()
6273
+	{
6274
+		return $this->_wp_core_model;
6275
+	}
6276
+
6277
+
6278
+	/**
6279
+	 * Gets all the caps that are missing which impose a restriction on
6280
+	 * queries made in this context
6281
+	 *
6282
+	 * @param string $context one of EEM_Base::caps_ constants
6283
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6284
+	 * @throws EE_Error
6285
+	 */
6286
+	public function caps_missing($context = EEM_Base::caps_read)
6287
+	{
6288
+		$missing_caps     = [];
6289
+		$cap_restrictions = $this->cap_restrictions($context);
6290
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6291
+			if (
6292
+				! EE_Capabilities::instance()
6293
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6294
+			) {
6295
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6296
+			}
6297
+		}
6298
+		return $missing_caps;
6299
+	}
6300
+
6301
+
6302
+	/**
6303
+	 * Gets the mapping from capability contexts to action strings used in capability names
6304
+	 *
6305
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6306
+	 * one of 'read', 'edit', or 'delete'
6307
+	 */
6308
+	public function cap_contexts_to_cap_action_map()
6309
+	{
6310
+		return apply_filters(
6311
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6312
+			$this->_cap_contexts_to_cap_action_map,
6313
+			$this
6314
+		);
6315
+	}
6316
+
6317
+
6318
+	/**
6319
+	 * Gets the action string for the specified capability context
6320
+	 *
6321
+	 * @param string $context
6322
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6323
+	 * @throws EE_Error
6324
+	 */
6325
+	public function cap_action_for_context($context)
6326
+	{
6327
+		$mapping = $this->cap_contexts_to_cap_action_map();
6328
+		if (isset($mapping[ $context ])) {
6329
+			return $mapping[ $context ];
6330
+		}
6331
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6332
+			return $action;
6333
+		}
6334
+		throw new EE_Error(
6335
+			sprintf(
6336
+				esc_html__(
6337
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6338
+					'event_espresso'
6339
+				),
6340
+				$context,
6341
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6342
+			)
6343
+		);
6344
+	}
6345
+
6346
+
6347
+	/**
6348
+	 * Returns all the capability contexts which are valid when querying models
6349
+	 *
6350
+	 * @return array
6351
+	 */
6352
+	public static function valid_cap_contexts()
6353
+	{
6354
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6355
+			self::caps_read,
6356
+			self::caps_read_admin,
6357
+			self::caps_edit,
6358
+			self::caps_delete,
6359
+		]);
6360
+	}
6361
+
6362
+
6363
+	/**
6364
+	 * Returns all valid options for 'default_where_conditions'
6365
+	 *
6366
+	 * @return array
6367
+	 */
6368
+	public static function valid_default_where_conditions()
6369
+	{
6370
+		return [
6371
+			EEM_Base::default_where_conditions_all,
6372
+			EEM_Base::default_where_conditions_this_only,
6373
+			EEM_Base::default_where_conditions_others_only,
6374
+			EEM_Base::default_where_conditions_minimum_all,
6375
+			EEM_Base::default_where_conditions_minimum_others,
6376
+			EEM_Base::default_where_conditions_none,
6377
+		];
6378
+	}
6379
+
6380
+	// public static function default_where_conditions_full
6381
+
6382
+
6383
+	/**
6384
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6385
+	 *
6386
+	 * @param string $context
6387
+	 * @return bool
6388
+	 * @throws EE_Error
6389
+	 */
6390
+	public static function verify_is_valid_cap_context($context)
6391
+	{
6392
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6393
+		if (in_array($context, $valid_cap_contexts)) {
6394
+			return true;
6395
+		}
6396
+		throw new EE_Error(
6397
+			sprintf(
6398
+				esc_html__(
6399
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6400
+					'event_espresso'
6401
+				),
6402
+				$context,
6403
+				'EEM_Base',
6404
+				implode(',', $valid_cap_contexts)
6405
+			)
6406
+		);
6407
+	}
6408
+
6409
+
6410
+	/**
6411
+	 * Clears all the models field caches. This is only useful when a sub-class
6412
+	 * might have added a field or something and these caches might be invalidated
6413
+	 */
6414
+	protected function _invalidate_field_caches()
6415
+	{
6416
+		$this->_cache_foreign_key_to_fields = [];
6417
+		$this->_cached_fields               = null;
6418
+		$this->_cached_fields_non_db_only   = null;
6419
+	}
6420
+
6421
+
6422
+	/**
6423
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6424
+	 * (eg "and", "or", "not").
6425
+	 *
6426
+	 * @return array
6427
+	 */
6428
+	public function logic_query_param_keys()
6429
+	{
6430
+		return $this->_logic_query_param_keys;
6431
+	}
6432
+
6433
+
6434
+	/**
6435
+	 * Determines whether or not the where query param array key is for a logic query param.
6436
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6437
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6438
+	 *
6439
+	 * @param $query_param_key
6440
+	 * @return bool
6441
+	 */
6442
+	public function is_logic_query_param_key($query_param_key)
6443
+	{
6444
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6445
+			if (
6446
+				$query_param_key === $logic_query_param_key
6447
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6448
+			) {
6449
+				return true;
6450
+			}
6451
+		}
6452
+		return false;
6453
+	}
6454
+
6455
+
6456
+	/**
6457
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6458
+	 *
6459
+	 * @return boolean
6460
+	 * @since 4.9.74.p
6461
+	 */
6462
+	public function hasPassword()
6463
+	{
6464
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6465
+		if ($this->has_password_field === null) {
6466
+			$password_field           = $this->getPasswordField();
6467
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6468
+		}
6469
+		return $this->has_password_field;
6470
+	}
6471
+
6472
+
6473
+	/**
6474
+	 * Returns the password field on this model, if there is one
6475
+	 *
6476
+	 * @return EE_Password_Field|null
6477
+	 * @since 4.9.74.p
6478
+	 */
6479
+	public function getPasswordField()
6480
+	{
6481
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6482
+		// there's no need to search for it. If we don't know yet, then find out
6483
+		if ($this->has_password_field === null && $this->password_field === null) {
6484
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6485
+		}
6486
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6487
+		return $this->password_field;
6488
+	}
6489
+
6490
+
6491
+	/**
6492
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6493
+	 *
6494
+	 * @return EE_Model_Field_Base[]
6495
+	 * @throws EE_Error
6496
+	 * @since 4.9.74.p
6497
+	 */
6498
+	public function getPasswordProtectedFields()
6499
+	{
6500
+		$password_field = $this->getPasswordField();
6501
+		$fields         = [];
6502
+		if ($password_field instanceof EE_Password_Field) {
6503
+			$field_names = $password_field->protectedFields();
6504
+			foreach ($field_names as $field_name) {
6505
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6506
+			}
6507
+		}
6508
+		return $fields;
6509
+	}
6510
+
6511
+
6512
+	/**
6513
+	 * Checks if the current user can perform the requested action on this model
6514
+	 *
6515
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6516
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6517
+	 * @return bool
6518
+	 * @throws EE_Error
6519
+	 * @throws InvalidArgumentException
6520
+	 * @throws InvalidDataTypeException
6521
+	 * @throws InvalidInterfaceException
6522
+	 * @throws ReflectionException
6523
+	 * @throws UnexpectedEntityException
6524
+	 * @since 4.9.74.p
6525
+	 */
6526
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6527
+	{
6528
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6529
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6530
+		}
6531
+		if (! is_array($model_obj_or_fields_n_values)) {
6532
+			throw new UnexpectedEntityException(
6533
+				$model_obj_or_fields_n_values,
6534
+				'EE_Base_Class',
6535
+				sprintf(
6536
+					esc_html__(
6537
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6538
+						'event_espresso'
6539
+					),
6540
+					__FUNCTION__
6541
+				)
6542
+			);
6543
+		}
6544
+		return $this->exists(
6545
+			$this->alter_query_params_to_restrict_by_ID(
6546
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6547
+				[
6548
+					'default_where_conditions' => 'none',
6549
+					'caps'                     => $cap_to_check,
6550
+				]
6551
+			)
6552
+		);
6553
+	}
6554
+
6555
+
6556
+	/**
6557
+	 * Returns the query param where conditions key to the password affecting this model.
6558
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6559
+	 *
6560
+	 * @return null|string
6561
+	 * @throws EE_Error
6562
+	 * @throws InvalidArgumentException
6563
+	 * @throws InvalidDataTypeException
6564
+	 * @throws InvalidInterfaceException
6565
+	 * @throws ModelConfigurationException
6566
+	 * @throws ReflectionException
6567
+	 * @since 4.9.74.p
6568
+	 */
6569
+	public function modelChainAndPassword()
6570
+	{
6571
+		if ($this->model_chain_to_password === null) {
6572
+			throw new ModelConfigurationException(
6573
+				$this,
6574
+				esc_html_x(
6575
+				// @codingStandardsIgnoreStart
6576
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6577
+					// @codingStandardsIgnoreEnd
6578
+					'1: model name',
6579
+					'event_espresso'
6580
+				)
6581
+			);
6582
+		}
6583
+		if ($this->model_chain_to_password === '') {
6584
+			$model_with_password = $this;
6585
+		} else {
6586
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6587
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6588
+			} else {
6589
+				$last_model_in_chain = $this->model_chain_to_password;
6590
+			}
6591
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6592
+		}
6593
+
6594
+		$password_field = $model_with_password->getPasswordField();
6595
+		if ($password_field instanceof EE_Password_Field) {
6596
+			$password_field_name = $password_field->get_name();
6597
+		} else {
6598
+			throw new ModelConfigurationException(
6599
+				$this,
6600
+				sprintf(
6601
+					esc_html_x(
6602
+						'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"',
6603
+						'1: model name, 2: special string',
6604
+						'event_espresso'
6605
+					),
6606
+					$model_with_password->get_this_model_name(),
6607
+					$this->model_chain_to_password
6608
+				)
6609
+			);
6610
+		}
6611
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6612
+	}
6613
+
6614
+
6615
+	/**
6616
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6617
+	 * or if this model itself has a password affecting access to some of its other fields.
6618
+	 *
6619
+	 * @return boolean
6620
+	 * @since 4.9.74.p
6621
+	 */
6622
+	public function restrictedByRelatedModelPassword()
6623
+	{
6624
+		return $this->model_chain_to_password !== null;
6625
+	}
6626 6626
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Country_Select_Input.php 2 patches
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -14,80 +14,80 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Country_Select_Input extends EE_Select_Input
16 16
 {
17
-    /**
18
-     * $input_settings key used for detecting the "get" option
19
-     */
20
-    const OPTION_GET_KEY = 'get';
17
+	/**
18
+	 * $input_settings key used for detecting the "get" option
19
+	 */
20
+	const OPTION_GET_KEY = 'get';
21 21
 
22
-    /**
23
-     * indicates that ALL countries should be retrieved from the db for the input
24
-     */
25
-    const OPTION_GET_ALL = 'all';
22
+	/**
23
+	 * indicates that ALL countries should be retrieved from the db for the input
24
+	 */
25
+	const OPTION_GET_ALL = 'all';
26 26
 
27
-    /**
28
-     * indicates that only ACTIVE countries should be retrieved from the db for the input
29
-     */
30
-    const OPTION_GET_ACTIVE = 'active';
27
+	/**
28
+	 * indicates that only ACTIVE countries should be retrieved from the db for the input
29
+	 */
30
+	const OPTION_GET_ACTIVE = 'active';
31 31
 
32 32
 
33
-    /**
34
-     * @param array $country_options
35
-     * @param array $input_settings
36
-     * @throws EE_Error
37
-     * @throws InvalidArgumentException
38
-     * @throws InvalidDataTypeException
39
-     * @throws InvalidInterfaceException
40
-     * @throws ReflectionException
41
-     */
42
-    public function __construct($country_options = null, $input_settings = [])
43
-    {
44
-        $get                          = $input_settings[ self::OPTION_GET_KEY ] ?? self::OPTION_GET_ACTIVE;
45
-        $country_options              = apply_filters(
46
-            'FHEE__EE_Country_Select_Input____construct__country_options',
47
-            $this->get_country_answer_options($country_options, $get),
48
-            $this,
49
-            $get
50
-        );
51
-        $input_settings['html_class'] = isset($input_settings['html_class'])
52
-            ? $input_settings['html_class'] . ' ee-country-select-js'
53
-            : 'ee-country-select-js';
54
-        parent::__construct($country_options, $input_settings);
55
-    }
33
+	/**
34
+	 * @param array $country_options
35
+	 * @param array $input_settings
36
+	 * @throws EE_Error
37
+	 * @throws InvalidArgumentException
38
+	 * @throws InvalidDataTypeException
39
+	 * @throws InvalidInterfaceException
40
+	 * @throws ReflectionException
41
+	 */
42
+	public function __construct($country_options = null, $input_settings = [])
43
+	{
44
+		$get                          = $input_settings[ self::OPTION_GET_KEY ] ?? self::OPTION_GET_ACTIVE;
45
+		$country_options              = apply_filters(
46
+			'FHEE__EE_Country_Select_Input____construct__country_options',
47
+			$this->get_country_answer_options($country_options, $get),
48
+			$this,
49
+			$get
50
+		);
51
+		$input_settings['html_class'] = isset($input_settings['html_class'])
52
+			? $input_settings['html_class'] . ' ee-country-select-js'
53
+			: 'ee-country-select-js';
54
+		parent::__construct($country_options, $input_settings);
55
+	}
56 56
 
57 57
 
58
-    /**
59
-     * get_country_answer_options
60
-     *
61
-     * @param array|null $country_options
62
-     * @param string     $get
63
-     * @return array
64
-     * @throws EE_Error
65
-     * @throws InvalidArgumentException
66
-     * @throws ReflectionException
67
-     * @throws InvalidDataTypeException
68
-     * @throws InvalidInterfaceException
69
-     */
70
-    public function get_country_answer_options(
71
-        array $country_options = null,
72
-        string $get = self::OPTION_GET_ACTIVE
73
-    ): ?array {
74
-        // if passed something that is NOT an array
75
-        if (! is_array($country_options)) {
76
-            // get possibly cached list of countries
77
-            $countries = $get === self::OPTION_GET_ALL
78
-                ? EEM_Country::instance()->get_all_countries()
79
-                : EEM_Country::instance()->get_all_active_countries();
80
-            if (! empty($countries)) {
81
-                $country_options[''] = '';
82
-                foreach ($countries as $country) {
83
-                    if ($country instanceof EE_Country) {
84
-                        $country_options[ $country->ID() ] = $country->name();
85
-                    }
86
-                }
87
-            } else {
88
-                $country_options = [];
89
-            }
90
-        }
91
-        return $country_options;
92
-    }
58
+	/**
59
+	 * get_country_answer_options
60
+	 *
61
+	 * @param array|null $country_options
62
+	 * @param string     $get
63
+	 * @return array
64
+	 * @throws EE_Error
65
+	 * @throws InvalidArgumentException
66
+	 * @throws ReflectionException
67
+	 * @throws InvalidDataTypeException
68
+	 * @throws InvalidInterfaceException
69
+	 */
70
+	public function get_country_answer_options(
71
+		array $country_options = null,
72
+		string $get = self::OPTION_GET_ACTIVE
73
+	): ?array {
74
+		// if passed something that is NOT an array
75
+		if (! is_array($country_options)) {
76
+			// get possibly cached list of countries
77
+			$countries = $get === self::OPTION_GET_ALL
78
+				? EEM_Country::instance()->get_all_countries()
79
+				: EEM_Country::instance()->get_all_active_countries();
80
+			if (! empty($countries)) {
81
+				$country_options[''] = '';
82
+				foreach ($countries as $country) {
83
+					if ($country instanceof EE_Country) {
84
+						$country_options[ $country->ID() ] = $country->name();
85
+					}
86
+				}
87
+			} else {
88
+				$country_options = [];
89
+			}
90
+		}
91
+		return $country_options;
92
+	}
93 93
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
      */
42 42
     public function __construct($country_options = null, $input_settings = [])
43 43
     {
44
-        $get                          = $input_settings[ self::OPTION_GET_KEY ] ?? self::OPTION_GET_ACTIVE;
44
+        $get                          = $input_settings[self::OPTION_GET_KEY] ?? self::OPTION_GET_ACTIVE;
45 45
         $country_options              = apply_filters(
46 46
             'FHEE__EE_Country_Select_Input____construct__country_options',
47 47
             $this->get_country_answer_options($country_options, $get),
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
             $get
50 50
         );
51 51
         $input_settings['html_class'] = isset($input_settings['html_class'])
52
-            ? $input_settings['html_class'] . ' ee-country-select-js'
52
+            ? $input_settings['html_class'].' ee-country-select-js'
53 53
             : 'ee-country-select-js';
54 54
         parent::__construct($country_options, $input_settings);
55 55
     }
@@ -72,16 +72,16 @@  discard block
 block discarded – undo
72 72
         string $get = self::OPTION_GET_ACTIVE
73 73
     ): ?array {
74 74
         // if passed something that is NOT an array
75
-        if (! is_array($country_options)) {
75
+        if ( ! is_array($country_options)) {
76 76
             // get possibly cached list of countries
77 77
             $countries = $get === self::OPTION_GET_ALL
78 78
                 ? EEM_Country::instance()->get_all_countries()
79 79
                 : EEM_Country::instance()->get_all_active_countries();
80
-            if (! empty($countries)) {
80
+            if ( ! empty($countries)) {
81 81
                 $country_options[''] = '';
82 82
                 foreach ($countries as $country) {
83 83
                     if ($country instanceof EE_Country) {
84
-                        $country_options[ $country->ID() ] = $country->name();
84
+                        $country_options[$country->ID()] = $country->name();
85 85
                     }
86 86
                 }
87 87
             } else {
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 1 patch
Indentation   +2134 added lines, -2134 removed lines patch added patch discarded remove patch
@@ -14,2142 +14,2142 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Ticket extends EE_Soft_Delete_Base_Class implements EEI_Line_Item_Object, EEI_Event_Relation, EEI_Has_Icon
16 16
 {
17
-    /**
18
-     * TicKet Archived:
19
-     * constant used by ticket_status() to indicate that a ticket is archived
20
-     * and no longer available for purchase
21
-     */
22
-    const archived = 'TKA';
23
-
24
-    /**
25
-     * TicKet Expired:
26
-     * constant used by ticket_status() to indicate that a ticket is expired
27
-     * and no longer available for purchase
28
-     */
29
-    const expired = 'TKE';
30
-
31
-    /**
32
-     * TicKet On sale:
33
-     * constant used by ticket_status() to indicate that a ticket is On Sale
34
-     * and IS available for purchase
35
-     */
36
-    const onsale = 'TKO';
37
-
38
-    /**
39
-     * TicKet Pending:
40
-     * constant used by ticket_status() to indicate that a ticket is pending
41
-     * and is NOT YET available for purchase
42
-     */
43
-    const pending = 'TKP';
44
-
45
-    /**
46
-     * TicKet Sold out:
47
-     * constant used by ticket_status() to indicate that a ticket is sold out
48
-     * and no longer available for purchases
49
-     */
50
-    const sold_out = 'TKS';
51
-
52
-    /**
53
-     * extra meta key for tracking ticket reservations
54
-     *
55
-     * @type string
56
-     */
57
-    const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
-
59
-    /**
60
-     * override of parent property
61
-     *
62
-     * @var EEM_Ticket
63
-     */
64
-    protected $_model;
65
-
66
-    /**
67
-     * cached result from method of the same name
68
-     *
69
-     * @var float $_ticket_total_with_taxes
70
-     */
71
-    private $_ticket_total_with_taxes;
72
-
73
-    /**
74
-     * @var TicketPriceModifiers
75
-     */
76
-    protected $ticket_price_modifiers;
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values          incoming values
81
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
82
-     *                                        used.)
83
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
84
-     *                                        date_format and the second value is the time format
85
-     * @return EE_Ticket
86
-     * @throws EE_Error
87
-     * @throws ReflectionException
88
-     */
89
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
90
-    {
91
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
92
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param array  $props_n_values  incoming values from the database
98
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
99
-     *                                the website will be used.
100
-     * @return EE_Ticket
101
-     * @throws EE_Error
102
-     * @throws ReflectionException
103
-     */
104
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
105
-    {
106
-        return new self($props_n_values, true, $timezone);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param array  $fieldValues
112
-     * @param false  $bydb
113
-     * @param string $timezone
114
-     * @param array  $date_formats
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
119
-    {
120
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
121
-        $this->ticket_price_modifiers = new TicketPriceModifiers($this);
122
-    }
123
-
124
-
125
-    /**
126
-     * @return bool
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function parent()
131
-    {
132
-        return $this->get('TKT_parent');
133
-    }
134
-
135
-
136
-    /**
137
-     * return if a ticket has quantities available for purchase
138
-     *
139
-     * @param int $DTT_ID the primary key for a particular datetime
140
-     * @return boolean
141
-     * @throws EE_Error
142
-     * @throws ReflectionException
143
-     */
144
-    public function available($DTT_ID = 0)
145
-    {
146
-        // are we checking availability for a particular datetime ?
147
-        if ($DTT_ID) {
148
-            // get that datetime object
149
-            $datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
150
-            // if  ticket sales for this datetime have exceeded the reg limit...
151
-            if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
152
-                return false;
153
-            }
154
-        }
155
-        // datetime is still open for registration, but is this ticket sold out ?
156
-        return $this->qty() < 1 || $this->qty() > $this->sold();
157
-    }
158
-
159
-
160
-    /**
161
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
162
-     *
163
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
164
-     *                               relevant status const
165
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
166
-     *                               further processing
167
-     * @return mixed status int if the display string isn't requested
168
-     * @throws EE_Error
169
-     * @throws ReflectionException
170
-     */
171
-    public function ticket_status($display = false, $remaining = null)
172
-    {
173
-        $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
174
-        if (! $remaining) {
175
-            return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
176
-        }
177
-        if ($this->get('TKT_deleted')) {
178
-            return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
179
-        }
180
-        if ($this->is_expired()) {
181
-            return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
182
-        }
183
-        if ($this->is_pending()) {
184
-            return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
185
-        }
186
-        if ($this->is_on_sale()) {
187
-            return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
188
-        }
189
-        return '';
190
-    }
191
-
192
-
193
-    /**
194
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
195
-     * considering ALL the factors used for figuring that out.
196
-     *
197
-     * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
198
-     * @return boolean         true = tickets remaining, false not.
199
-     * @throws EE_Error
200
-     * @throws ReflectionException
201
-     */
202
-    public function is_remaining($DTT_ID = 0)
203
-    {
204
-        $num_remaining = $this->remaining($DTT_ID);
205
-        if ($num_remaining === 0) {
206
-            return false;
207
-        }
208
-        if ($num_remaining > 0 && $num_remaining < $this->min()) {
209
-            return false;
210
-        }
211
-        return true;
212
-    }
213
-
214
-
215
-    /**
216
-     * return the total number of tickets available for purchase
217
-     *
218
-     * @param int $DTT_ID  the primary key for a particular datetime.
219
-     *                     set to 0 for all related datetimes
220
-     * @return int
221
-     * @throws EE_Error
222
-     * @throws ReflectionException
223
-     */
224
-    public function remaining($DTT_ID = 0)
225
-    {
226
-        return $this->real_quantity_on_ticket('saleable', $DTT_ID);
227
-    }
228
-
229
-
230
-    /**
231
-     * Gets min
232
-     *
233
-     * @return int
234
-     * @throws EE_Error
235
-     * @throws ReflectionException
236
-     */
237
-    public function min()
238
-    {
239
-        return $this->get('TKT_min');
240
-    }
241
-
242
-
243
-    /**
244
-     * return if a ticket is no longer available cause its available dates have expired.
245
-     *
246
-     * @return boolean
247
-     * @throws EE_Error
248
-     * @throws ReflectionException
249
-     */
250
-    public function is_expired()
251
-    {
252
-        return ($this->get_raw('TKT_end_date') < time());
253
-    }
254
-
255
-
256
-    /**
257
-     * Return if a ticket is yet to go on sale or not
258
-     *
259
-     * @return boolean
260
-     * @throws EE_Error
261
-     * @throws ReflectionException
262
-     */
263
-    public function is_pending()
264
-    {
265
-        return ($this->get_raw('TKT_start_date') >= time());
266
-    }
267
-
268
-
269
-    /**
270
-     * Return if a ticket is on sale or not
271
-     *
272
-     * @return boolean
273
-     * @throws EE_Error
274
-     * @throws ReflectionException
275
-     */
276
-    public function is_on_sale()
277
-    {
278
-        return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
279
-    }
280
-
281
-
282
-    /**
283
-     * This returns the chronologically last datetime that this ticket is associated with
284
-     *
285
-     * @param string $date_format
286
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
287
-     *                            the end date ie: Jan 01 "to" Dec 31
288
-     * @return string
289
-     * @throws EE_Error
290
-     * @throws ReflectionException
291
-     */
292
-    public function date_range($date_format = '', $conjunction = ' - ')
293
-    {
294
-        $date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
295
-        $first_date  = $this->first_datetime() instanceof EE_Datetime
296
-            ? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
297
-            : '';
298
-        $last_date   = $this->last_datetime() instanceof EE_Datetime
299
-            ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
300
-            : '';
301
-
302
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
-    }
304
-
305
-
306
-    /**
307
-     * This returns the chronologically first datetime that this ticket is associated with
308
-     *
309
-     * @return EE_Datetime
310
-     * @throws EE_Error
311
-     * @throws ReflectionException
312
-     */
313
-    public function first_datetime()
314
-    {
315
-        $datetimes = $this->datetimes(['limit' => 1]);
316
-        return reset($datetimes);
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets all the datetimes this ticket can be used for attending.
322
-     * Unless otherwise specified, orders datetimes by start date.
323
-     *
324
-     * @param array $query_params
325
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
-     * @return EE_Datetime[]|EE_Base_Class[]
327
-     * @throws EE_Error
328
-     * @throws ReflectionException
329
-     */
330
-    public function datetimes($query_params = [])
331
-    {
332
-        if (! isset($query_params['order_by'])) {
333
-            $query_params['order_by']['DTT_order'] = 'ASC';
334
-        }
335
-        return $this->get_many_related('Datetime', $query_params);
336
-    }
337
-
338
-
339
-    /**
340
-     * This returns the chronologically last datetime that this ticket is associated with
341
-     *
342
-     * @return EE_Datetime
343
-     * @throws EE_Error
344
-     * @throws ReflectionException
345
-     */
346
-    public function last_datetime()
347
-    {
348
-        $datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
349
-        return end($datetimes);
350
-    }
351
-
352
-
353
-    /**
354
-     * This returns the total tickets sold depending on the given parameters.
355
-     *
356
-     * @param string $what    Can be one of two options: 'ticket', 'datetime'.
357
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
358
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
359
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
360
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
361
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
362
-     * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
363
-     * @return mixed (array|int)          how many tickets have sold
364
-     * @throws EE_Error
365
-     * @throws ReflectionException
366
-     */
367
-    public function tickets_sold($what = 'ticket', $dtt_id = null)
368
-    {
369
-        $total        = 0;
370
-        $tickets_sold = $this->_all_tickets_sold();
371
-        switch ($what) {
372
-            case 'ticket':
373
-                return $tickets_sold['ticket'];
374
-
375
-            case 'datetime':
376
-                if (empty($tickets_sold['datetime'])) {
377
-                    return $total;
378
-                }
379
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
-                    EE_Error::add_error(
381
-                        esc_html__(
382
-                            'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
383
-                            'event_espresso'
384
-                        ),
385
-                        __FILE__,
386
-                        __FUNCTION__,
387
-                        __LINE__
388
-                    );
389
-                    return $total;
390
-                }
391
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
-
393
-            default:
394
-                return $total;
395
-        }
396
-    }
397
-
398
-
399
-    /**
400
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
401
-     *
402
-     * @return EE_Ticket[]
403
-     * @throws EE_Error
404
-     * @throws ReflectionException
405
-     */
406
-    protected function _all_tickets_sold()
407
-    {
408
-        $datetimes    = $this->get_many_related('Datetime');
409
-        $tickets_sold = [];
410
-        if (! empty($datetimes)) {
411
-            foreach ($datetimes as $datetime) {
412
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
-            }
414
-        }
415
-        // Tickets sold
416
-        $tickets_sold['ticket'] = $this->sold();
417
-        return $tickets_sold;
418
-    }
419
-
420
-
421
-    /**
422
-     * This returns the base price object for the ticket.
423
-     *
424
-     * @param bool $return_array whether to return as an array indexed by price id or just the object.
425
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function base_price(bool $return_array = false)
430
-    {
431
-        $base_price = $this->ticket_price_modifiers->getBasePrice();
432
-        if (! empty($base_price)) {
433
-            return $return_array ? $base_price : reset($base_price);
434
-        }
435
-        $_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
436
-        return $return_array
437
-            ? $this->get_many_related('Price', [$_where])
438
-            : $this->get_first_related('Price', [$_where]);
439
-    }
440
-
441
-
442
-    /**
443
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
444
-     *
445
-     * @return EE_Price[]
446
-     * @throws EE_Error
447
-     * @throws ReflectionException
448
-     */
449
-    public function price_modifiers(): array
450
-    {
451
-        $price_modifiers = $this->usesGlobalTaxes()
452
-            ? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
453
-            : $this->ticket_price_modifiers ->getAllModifiersForTicket();
454
-        if (! empty($price_modifiers)) {
455
-            return $price_modifiers;
456
-        }
457
-        return $this->prices(
458
-            [
459
-                [
460
-                    'Price_Type.PBT_ID' => [
461
-                        'NOT IN',
462
-                        [EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
463
-                    ]
464
-                ]
465
-            ]
466
-        );
467
-    }
468
-
469
-
470
-    /**
471
-     * This returns ONLY the TAX price modifiers for the ticket
472
-     *
473
-     * @return EE_Price[]
474
-     * @throws EE_Error
475
-     * @throws ReflectionException
476
-     */
477
-    public function tax_price_modifiers(): array
478
-    {
479
-        $tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
480
-        if (! empty($tax_price_modifiers)) {
481
-            return $tax_price_modifiers;
482
-        }
483
-        return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
484
-    }
485
-
486
-
487
-    /**
488
-     * Gets all the prices that combine to form the final price of this ticket
489
-     *
490
-     * @param array $query_params
491
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
492
-     * @return EE_Price[]|EE_Base_Class[]
493
-     * @throws EE_Error
494
-     * @throws ReflectionException
495
-     */
496
-    public function prices(array $query_params = []): array
497
-    {
498
-        if (! isset($query_params['order_by'])) {
499
-            $query_params['order_by']['PRC_order'] = 'ASC';
500
-        }
501
-        return $this->get_many_related('Price', $query_params);
502
-    }
503
-
504
-
505
-    /**
506
-     * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
507
-     *
508
-     * @param array $query_params
509
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
510
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     */
514
-    public function datetime_tickets($query_params = [])
515
-    {
516
-        return $this->get_many_related('Datetime_Ticket', $query_params);
517
-    }
518
-
519
-
520
-    /**
521
-     * Gets all the datetimes from the db ordered by DTT_order
522
-     *
523
-     * @param boolean $show_expired
524
-     * @param boolean $show_deleted
525
-     * @return EE_Datetime[]
526
-     * @throws EE_Error
527
-     * @throws ReflectionException
528
-     */
529
-    public function datetimes_ordered($show_expired = true, $show_deleted = false)
530
-    {
531
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
532
-            $this->ID(),
533
-            $show_expired,
534
-            $show_deleted
535
-        );
536
-    }
537
-
538
-
539
-    /**
540
-     * Gets ID
541
-     *
542
-     * @return int
543
-     * @throws EE_Error
544
-     * @throws ReflectionException
545
-     */
546
-    public function ID()
547
-    {
548
-        return (int) $this->get('TKT_ID');
549
-    }
550
-
551
-
552
-    /**
553
-     * get the author of the ticket.
554
-     *
555
-     * @return int
556
-     * @throws EE_Error
557
-     * @throws ReflectionException
558
-     * @since 4.5.0
559
-     */
560
-    public function wp_user()
561
-    {
562
-        return $this->get('TKT_wp_user');
563
-    }
564
-
565
-
566
-    /**
567
-     * Gets the template for the ticket
568
-     *
569
-     * @return EE_Ticket_Template|EE_Base_Class
570
-     * @throws EE_Error
571
-     * @throws ReflectionException
572
-     */
573
-    public function template()
574
-    {
575
-        return $this->get_first_related('Ticket_Template');
576
-    }
577
-
578
-
579
-    /**
580
-     * Simply returns an array of EE_Price objects that are taxes.
581
-     *
582
-     * @return EE_Price[]
583
-     * @throws EE_Error
584
-     * @throws ReflectionException
585
-     */
586
-    public function get_ticket_taxes_for_admin(): array
587
-    {
588
-        return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
589
-    }
590
-
591
-
592
-    /**
593
-     * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
594
-     * as opposed to having tax price modifiers added directly to each ticket
595
-     *
596
-     * @return bool
597
-     * @throws EE_Error
598
-     * @throws ReflectionException
599
-     * @since   $VID:$
600
-     */
601
-    public function usesGlobalTaxes(): bool
602
-    {
603
-        return $this->taxable();
604
-    }
605
-
606
-
607
-    /**
608
-     * @return float
609
-     * @throws EE_Error
610
-     * @throws ReflectionException
611
-     */
612
-    public function ticket_price()
613
-    {
614
-        return $this->get('TKT_price');
615
-    }
616
-
617
-
618
-    /**
619
-     * @return mixed
620
-     * @throws EE_Error
621
-     * @throws ReflectionException
622
-     */
623
-    public function pretty_price()
624
-    {
625
-        return $this->get_pretty('TKT_price');
626
-    }
627
-
628
-
629
-    /**
630
-     * @return bool
631
-     * @throws EE_Error
632
-     * @throws ReflectionException
633
-     */
634
-    public function is_free()
635
-    {
636
-        return $this->get_ticket_total_with_taxes() === (float) 0;
637
-    }
638
-
639
-
640
-    /**
641
-     * get_ticket_total_with_taxes
642
-     *
643
-     * @param bool $no_cache
644
-     * @return float
645
-     * @throws EE_Error
646
-     * @throws ReflectionException
647
-     */
648
-    public function get_ticket_total_with_taxes($no_cache = false)
649
-    {
650
-        if ($this->_ticket_total_with_taxes === null || $no_cache) {
651
-            $this->_ticket_total_with_taxes = $this->usesGlobalTaxes()
652
-                ? $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin()
653
-                : $this->ticket_price();
654
-        }
655
-        return (float) $this->_ticket_total_with_taxes;
656
-    }
657
-
658
-
659
-    /**
660
-     * @throws EE_Error
661
-     * @throws ReflectionException
662
-     */
663
-    public function ensure_TKT_Price_correct()
664
-    {
665
-        $this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
666
-        $this->save();
667
-    }
668
-
669
-
670
-    /**
671
-     * @return float
672
-     * @throws EE_Error
673
-     * @throws ReflectionException
674
-     */
675
-    public function get_ticket_subtotal()
676
-    {
677
-        return EE_Taxes::get_subtotal_for_admin($this);
678
-    }
679
-
680
-
681
-    /**
682
-     * Returns the total taxes applied to this ticket
683
-     *
684
-     * @return float
685
-     * @throws EE_Error
686
-     * @throws ReflectionException
687
-     */
688
-    public function get_ticket_taxes_total_for_admin()
689
-    {
690
-        return EE_Taxes::get_total_taxes_for_admin($this);
691
-    }
692
-
693
-
694
-    /**
695
-     * Sets name
696
-     *
697
-     * @param string $name
698
-     * @throws EE_Error
699
-     * @throws ReflectionException
700
-     */
701
-    public function set_name($name)
702
-    {
703
-        $this->set('TKT_name', $name);
704
-    }
705
-
706
-
707
-    /**
708
-     * Gets description
709
-     *
710
-     * @return string
711
-     * @throws EE_Error
712
-     * @throws ReflectionException
713
-     */
714
-    public function description()
715
-    {
716
-        return $this->get('TKT_description');
717
-    }
718
-
719
-
720
-    /**
721
-     * Sets description
722
-     *
723
-     * @param string $description
724
-     * @throws EE_Error
725
-     * @throws ReflectionException
726
-     */
727
-    public function set_description($description)
728
-    {
729
-        $this->set('TKT_description', $description);
730
-    }
731
-
732
-
733
-    /**
734
-     * Gets start_date
735
-     *
736
-     * @param string|null $date_format
737
-     * @param string|null $time_format
738
-     * @return string
739
-     * @throws EE_Error
740
-     * @throws ReflectionException
741
-     */
742
-    public function start_date(?string $date_format = '', ?string $time_format = ''): string
743
-    {
744
-        return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
745
-    }
746
-
747
-
748
-    /**
749
-     * Sets start_date
750
-     *
751
-     * @param string $start_date
752
-     * @return void
753
-     * @throws EE_Error
754
-     * @throws ReflectionException
755
-     */
756
-    public function set_start_date($start_date)
757
-    {
758
-        $this->_set_date_time('B', $start_date, 'TKT_start_date');
759
-    }
760
-
761
-
762
-    /**
763
-     * Gets end_date
764
-     *
765
-     * @param string|null $date_format
766
-     * @param string|null $time_format
767
-     * @return string
768
-     * @throws EE_Error
769
-     * @throws ReflectionException
770
-     */
771
-    public function end_date(?string $date_format = '', ?string $time_format = ''): string
772
-    {
773
-        return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
774
-    }
775
-
776
-
777
-    /**
778
-     * Sets end_date
779
-     *
780
-     * @param string $end_date
781
-     * @return void
782
-     * @throws EE_Error
783
-     * @throws ReflectionException
784
-     */
785
-    public function set_end_date($end_date)
786
-    {
787
-        $this->_set_date_time('B', $end_date, 'TKT_end_date');
788
-    }
789
-
790
-
791
-    /**
792
-     * Sets sell until time
793
-     *
794
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
795
-     * @throws EE_Error
796
-     * @throws ReflectionException
797
-     * @since 4.5.0
798
-     */
799
-    public function set_end_time($time)
800
-    {
801
-        $this->_set_time_for($time, 'TKT_end_date');
802
-    }
803
-
804
-
805
-    /**
806
-     * Sets min
807
-     *
808
-     * @param int $min
809
-     * @return void
810
-     * @throws EE_Error
811
-     * @throws ReflectionException
812
-     */
813
-    public function set_min($min)
814
-    {
815
-        $this->set('TKT_min', $min);
816
-    }
817
-
818
-
819
-    /**
820
-     * Gets max
821
-     *
822
-     * @return int
823
-     * @throws EE_Error
824
-     * @throws ReflectionException
825
-     */
826
-    public function max()
827
-    {
828
-        return $this->get('TKT_max');
829
-    }
830
-
831
-
832
-    /**
833
-     * Sets max
834
-     *
835
-     * @param int $max
836
-     * @return void
837
-     * @throws EE_Error
838
-     * @throws ReflectionException
839
-     */
840
-    public function set_max($max)
841
-    {
842
-        $this->set('TKT_max', $max);
843
-    }
844
-
845
-
846
-    /**
847
-     * Sets price
848
-     *
849
-     * @param float $price
850
-     * @return void
851
-     * @throws EE_Error
852
-     * @throws ReflectionException
853
-     */
854
-    public function set_price($price)
855
-    {
856
-        $this->set('TKT_price', $price);
857
-    }
858
-
859
-
860
-    /**
861
-     * Gets sold
862
-     *
863
-     * @return int
864
-     * @throws EE_Error
865
-     * @throws ReflectionException
866
-     */
867
-    public function sold(): int
868
-    {
869
-        return (int) $this->get_raw('TKT_sold');
870
-    }
871
-
872
-
873
-    /**
874
-     * Sets sold
875
-     *
876
-     * @param int $sold
877
-     * @return void
878
-     * @throws EE_Error
879
-     * @throws ReflectionException
880
-     */
881
-    public function set_sold($sold)
882
-    {
883
-        // sold can not go below zero
884
-        $sold = max(0, $sold);
885
-        $this->set('TKT_sold', $sold);
886
-    }
887
-
888
-
889
-    /**
890
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
891
-     * associated datetimes.
892
-     *
893
-     * @param int $qty
894
-     * @return boolean
895
-     * @throws EE_Error
896
-     * @throws InvalidArgumentException
897
-     * @throws InvalidDataTypeException
898
-     * @throws InvalidInterfaceException
899
-     * @throws ReflectionException
900
-     * @since 4.9.80.p
901
-     */
902
-    public function increaseSold($qty = 1)
903
-    {
904
-        $qty = absint($qty);
905
-        // increment sold and decrement reserved datetime quantities simultaneously
906
-        // don't worry about failures, because they must have already had a spot reserved
907
-        $this->increaseSoldForDatetimes($qty);
908
-        // Increment and decrement ticket quantities simultaneously
909
-        $success = $this->adjustNumericFieldsInDb(
910
-            [
911
-                'TKT_reserved' => $qty * -1,
912
-                'TKT_sold'     => $qty,
913
-            ]
914
-        );
915
-        do_action(
916
-            'AHEE__EE_Ticket__increase_sold',
917
-            $this,
918
-            $qty,
919
-            $this->sold(),
920
-            $success
921
-        );
922
-        return $success;
923
-    }
924
-
925
-
926
-    /**
927
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
928
-     *
929
-     * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
930
-     *                           counts), Negative means to decreases old counts (and increase reserved counts).
931
-     * @param EE_Datetime[] $datetimes
932
-     * @throws EE_Error
933
-     * @throws InvalidArgumentException
934
-     * @throws InvalidDataTypeException
935
-     * @throws InvalidInterfaceException
936
-     * @throws ReflectionException
937
-     * @since 4.9.80.p
938
-     */
939
-    protected function increaseSoldForDatetimes($qty, array $datetimes = [])
940
-    {
941
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
942
-        foreach ($datetimes as $datetime) {
943
-            $datetime->increaseSold($qty);
944
-        }
945
-    }
946
-
947
-
948
-    /**
949
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
950
-     * DB and then updates the model objects.
951
-     * Does not affect the reserved counts.
952
-     *
953
-     * @param int $qty
954
-     * @return boolean
955
-     * @throws EE_Error
956
-     * @throws InvalidArgumentException
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws ReflectionException
960
-     * @since 4.9.80.p
961
-     */
962
-    public function decreaseSold($qty = 1)
963
-    {
964
-        $qty = absint($qty);
965
-        $this->decreaseSoldForDatetimes($qty);
966
-        $success = $this->adjustNumericFieldsInDb(
967
-            [
968
-                'TKT_sold' => $qty * -1,
969
-            ]
970
-        );
971
-        do_action(
972
-            'AHEE__EE_Ticket__decrease_sold',
973
-            $this,
974
-            $qty,
975
-            $this->sold(),
976
-            $success
977
-        );
978
-        return $success;
979
-    }
980
-
981
-
982
-    /**
983
-     * Decreases sold on related datetimes
984
-     *
985
-     * @param int           $qty
986
-     * @param EE_Datetime[] $datetimes
987
-     * @return void
988
-     * @throws EE_Error
989
-     * @throws InvalidArgumentException
990
-     * @throws InvalidDataTypeException
991
-     * @throws InvalidInterfaceException
992
-     * @throws ReflectionException
993
-     * @since 4.9.80.p
994
-     */
995
-    protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
996
-    {
997
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
998
-        if (is_array($datetimes)) {
999
-            foreach ($datetimes as $datetime) {
1000
-                if ($datetime instanceof EE_Datetime) {
1001
-                    $datetime->decreaseSold($qty);
1002
-                }
1003
-            }
1004
-        }
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Gets qty of reserved tickets
1010
-     *
1011
-     * @return int
1012
-     * @throws EE_Error
1013
-     * @throws ReflectionException
1014
-     */
1015
-    public function reserved(): int
1016
-    {
1017
-        return (int) $this->get_raw('TKT_reserved');
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * Sets reserved
1023
-     *
1024
-     * @param int $reserved
1025
-     * @return void
1026
-     * @throws EE_Error
1027
-     * @throws ReflectionException
1028
-     */
1029
-    public function set_reserved($reserved)
1030
-    {
1031
-        // reserved can not go below zero
1032
-        $reserved = max(0, (int) $reserved);
1033
-        $this->set('TKT_reserved', $reserved);
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1039
-     *
1040
-     * @param int    $qty
1041
-     * @param string $source
1042
-     * @return bool whether we successfully reserved the ticket or not.
1043
-     * @throws EE_Error
1044
-     * @throws InvalidArgumentException
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws InvalidInterfaceException
1048
-     * @since 4.9.80.p
1049
-     */
1050
-    public function increaseReserved($qty = 1, $source = 'unknown')
1051
-    {
1052
-        $qty = absint($qty);
1053
-        do_action(
1054
-            'AHEE__EE_Ticket__increase_reserved__begin',
1055
-            $this,
1056
-            $qty,
1057
-            $source
1058
-        );
1059
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1060
-        $success                         = false;
1061
-        $datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1062
-        if ($datetimes_adjusted_successfully) {
1063
-            $success = $this->incrementFieldConditionallyInDb(
1064
-                'TKT_reserved',
1065
-                'TKT_sold',
1066
-                'TKT_qty',
1067
-                $qty
1068
-            );
1069
-            if (! $success) {
1070
-                // The datetimes were successfully bumped, but not the
1071
-                // ticket. So we need to manually rollback the datetimes.
1072
-                $this->decreaseReservedForDatetimes($qty);
1073
-            }
1074
-        }
1075
-        do_action(
1076
-            'AHEE__EE_Ticket__increase_reserved',
1077
-            $this,
1078
-            $qty,
1079
-            $this->reserved(),
1080
-            $success
1081
-        );
1082
-        return $success;
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     * Increases reserved counts on related datetimes
1088
-     *
1089
-     * @param int           $qty
1090
-     * @param EE_Datetime[] $datetimes
1091
-     * @return boolean indicating success
1092
-     * @throws EE_Error
1093
-     * @throws InvalidArgumentException
1094
-     * @throws InvalidDataTypeException
1095
-     * @throws InvalidInterfaceException
1096
-     * @throws ReflectionException
1097
-     * @since 4.9.80.p
1098
-     */
1099
-    protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1100
-    {
1101
-        $datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1102
-        $datetimes_updated = [];
1103
-        $limit_exceeded    = false;
1104
-        if (is_array($datetimes)) {
1105
-            foreach ($datetimes as $datetime) {
1106
-                if ($datetime instanceof EE_Datetime) {
1107
-                    if ($datetime->increaseReserved($qty)) {
1108
-                        $datetimes_updated[] = $datetime;
1109
-                    } else {
1110
-                        $limit_exceeded = true;
1111
-                        break;
1112
-                    }
1113
-                }
1114
-            }
1115
-            // If somewhere along the way we detected a datetime whose
1116
-            // limit was exceeded, do a manual rollback.
1117
-            if ($limit_exceeded) {
1118
-                $this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1119
-                return false;
1120
-            }
1121
-        }
1122
-        return true;
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1128
-     *
1129
-     * @param int    $qty
1130
-     * @param bool   $adjust_datetimes
1131
-     * @param string $source
1132
-     * @return boolean
1133
-     * @throws EE_Error
1134
-     * @throws InvalidArgumentException
1135
-     * @throws ReflectionException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws InvalidInterfaceException
1138
-     * @since 4.9.80.p
1139
-     */
1140
-    public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1141
-    {
1142
-        $qty = absint($qty);
1143
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1144
-        if ($adjust_datetimes) {
1145
-            $this->decreaseReservedForDatetimes($qty);
1146
-        }
1147
-        $success = $this->adjustNumericFieldsInDb(
1148
-            [
1149
-                'TKT_reserved' => $qty * -1,
1150
-            ]
1151
-        );
1152
-        do_action(
1153
-            'AHEE__EE_Ticket__decrease_reserved',
1154
-            $this,
1155
-            $qty,
1156
-            $this->reserved(),
1157
-            $success
1158
-        );
1159
-        return $success;
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * Decreases the reserved count on the specified datetimes.
1165
-     *
1166
-     * @param int           $qty
1167
-     * @param EE_Datetime[] $datetimes
1168
-     * @throws EE_Error
1169
-     * @throws InvalidArgumentException
1170
-     * @throws ReflectionException
1171
-     * @throws InvalidDataTypeException
1172
-     * @throws InvalidInterfaceException
1173
-     * @since 4.9.80.p
1174
-     */
1175
-    protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1176
-    {
1177
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1178
-        foreach ($datetimes as $datetime) {
1179
-            if ($datetime instanceof EE_Datetime) {
1180
-                $datetime->decreaseReserved($qty);
1181
-            }
1182
-        }
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Gets ticket quantity
1188
-     *
1189
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1190
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1191
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1192
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1193
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1194
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1195
-     * @return int
1196
-     * @throws EE_Error
1197
-     * @throws ReflectionException
1198
-     */
1199
-    public function qty($context = '')
1200
-    {
1201
-        switch ($context) {
1202
-            case 'reg_limit':
1203
-                return $this->real_quantity_on_ticket();
1204
-            case 'saleable':
1205
-                return $this->real_quantity_on_ticket('saleable');
1206
-            default:
1207
-                return $this->get_raw('TKT_qty');
1208
-        }
1209
-    }
1210
-
1211
-
1212
-    /**
1213
-     * Gets ticket quantity
1214
-     *
1215
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1216
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1217
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1218
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1219
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1220
-     * @param int    $DTT_ID      the primary key for a particular datetime.
1221
-     *                            set to 0 for all related datetimes
1222
-     * @return int
1223
-     * @throws EE_Error
1224
-     * @throws ReflectionException
1225
-     */
1226
-    public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1227
-    {
1228
-        $raw = $this->get_raw('TKT_qty');
1229
-        // return immediately if it's zero
1230
-        if ($raw === 0) {
1231
-            return $raw;
1232
-        }
1233
-        // echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1234
-        // ensure qty doesn't exceed raw value for THIS ticket
1235
-        $qty = min(EE_INF, $raw);
1236
-        // echo "\n . qty: " . $qty . '<br />';
1237
-        // calculate this ticket's total sales and reservations
1238
-        $sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1239
-        // echo "\n . sold: " . $this->sold() . '<br />';
1240
-        // echo "\n . reserved: " . $this->reserved() . '<br />';
1241
-        // echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1242
-        // first we need to calculate the maximum number of tickets available for the datetime
1243
-        // do we want data for one datetime or all of them ?
1244
-        $query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1245
-        $datetimes    = $this->datetimes($query_params);
1246
-        if (is_array($datetimes) && ! empty($datetimes)) {
1247
-            foreach ($datetimes as $datetime) {
1248
-                if ($datetime instanceof EE_Datetime) {
1249
-                    $datetime->refresh_from_db();
1250
-                    // echo "\n . . datetime name: " . $datetime->name() . '<br />';
1251
-                    // echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1252
-                    // initialize with no restrictions for each datetime
1253
-                    // but adjust datetime qty based on datetime reg limit
1254
-                    $datetime_qty = min(EE_INF, $datetime->reg_limit());
1255
-                    // echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1256
-                    // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1257
-                    // if we want the actual saleable amount, then we need to consider OTHER ticket sales
1258
-                    // and reservations for this datetime, that do NOT include sales and reservations
1259
-                    // for this ticket (so we add $this->sold() and $this->reserved() back in)
1260
-                    if ($context === 'saleable') {
1261
-                        $datetime_qty = max(
1262
-                            $datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1263
-                            0
1264
-                        );
1265
-                        // echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1266
-                        // echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1267
-                        // echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1268
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1269
-                        $datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1270
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1271
-                    }
1272
-                    $qty = min($datetime_qty, $qty);
1273
-                    // echo "\n . . qty: " . $qty . '<br />';
1274
-                }
1275
-            }
1276
-        }
1277
-        // NOW that we know the  maximum number of tickets available for the datetime
1278
-        // we can finally factor in the details for this specific ticket
1279
-        if ($qty > 0 && $context === 'saleable') {
1280
-            // and subtract the sales for THIS ticket
1281
-            $qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1282
-            // echo "\n . qty: " . $qty . '<br />';
1283
-        }
1284
-        // echo "\nFINAL QTY: " . $qty . "<br /><br />";
1285
-        return (int) $qty;
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1291
-     *
1292
-     * @param int $qty
1293
-     * @return void
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function set_qty($qty)
1298
-    {
1299
-        $datetimes = $this->datetimes();
1300
-        foreach ($datetimes as $datetime) {
1301
-            if ($datetime instanceof EE_Datetime) {
1302
-                $qty = min($qty, $datetime->reg_limit());
1303
-            }
1304
-        }
1305
-        $this->set('TKT_qty', $qty);
1306
-    }
1307
-
1308
-
1309
-    /**
1310
-     * Gets uses
1311
-     *
1312
-     * @return int
1313
-     * @throws EE_Error
1314
-     * @throws ReflectionException
1315
-     */
1316
-    public function uses()
1317
-    {
1318
-        return $this->get('TKT_uses');
1319
-    }
1320
-
1321
-
1322
-    /**
1323
-     * Sets uses
1324
-     *
1325
-     * @param int $uses
1326
-     * @return void
1327
-     * @throws EE_Error
1328
-     * @throws ReflectionException
1329
-     */
1330
-    public function set_uses($uses)
1331
-    {
1332
-        $this->set('TKT_uses', $uses);
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * returns whether ticket is required or not.
1338
-     *
1339
-     * @return boolean
1340
-     * @throws EE_Error
1341
-     * @throws ReflectionException
1342
-     */
1343
-    public function required()
1344
-    {
1345
-        return $this->get('TKT_required');
1346
-    }
1347
-
1348
-
1349
-    /**
1350
-     * sets the TKT_required property
1351
-     *
1352
-     * @param boolean $required
1353
-     * @return void
1354
-     * @throws EE_Error
1355
-     * @throws ReflectionException
1356
-     */
1357
-    public function set_required($required)
1358
-    {
1359
-        $this->set('TKT_required', $required);
1360
-    }
1361
-
1362
-
1363
-    /**
1364
-     * Gets taxable
1365
-     *
1366
-     * @return boolean
1367
-     * @throws EE_Error
1368
-     * @throws ReflectionException
1369
-     */
1370
-    public function taxable()
1371
-    {
1372
-        return $this->get('TKT_taxable');
1373
-    }
1374
-
1375
-
1376
-    /**
1377
-     * Sets taxable
1378
-     *
1379
-     * @param boolean $taxable
1380
-     * @return void
1381
-     * @throws EE_Error
1382
-     * @throws ReflectionException
1383
-     */
1384
-    public function set_taxable($taxable)
1385
-    {
1386
-        $this->set('TKT_taxable', $taxable);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * Gets is_default
1392
-     *
1393
-     * @return boolean
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function is_default()
1398
-    {
1399
-        return $this->get('TKT_is_default');
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * Sets is_default
1405
-     *
1406
-     * @param boolean $is_default
1407
-     * @return void
1408
-     * @throws EE_Error
1409
-     * @throws ReflectionException
1410
-     */
1411
-    public function set_is_default($is_default)
1412
-    {
1413
-        $this->set('TKT_is_default', $is_default);
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Gets order
1419
-     *
1420
-     * @return int
1421
-     * @throws EE_Error
1422
-     * @throws ReflectionException
1423
-     */
1424
-    public function order()
1425
-    {
1426
-        return $this->get('TKT_order');
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * Sets order
1432
-     *
1433
-     * @param int $order
1434
-     * @return void
1435
-     * @throws EE_Error
1436
-     * @throws ReflectionException
1437
-     */
1438
-    public function set_order($order)
1439
-    {
1440
-        $this->set('TKT_order', $order);
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Gets row
1446
-     *
1447
-     * @return int
1448
-     * @throws EE_Error
1449
-     * @throws ReflectionException
1450
-     */
1451
-    public function row()
1452
-    {
1453
-        return $this->get('TKT_row');
1454
-    }
1455
-
1456
-
1457
-    /**
1458
-     * Sets row
1459
-     *
1460
-     * @param int $row
1461
-     * @return void
1462
-     * @throws EE_Error
1463
-     * @throws ReflectionException
1464
-     */
1465
-    public function set_row($row)
1466
-    {
1467
-        $this->set('TKT_row', $row);
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Gets deleted
1473
-     *
1474
-     * @return boolean
1475
-     * @throws EE_Error
1476
-     * @throws ReflectionException
1477
-     */
1478
-    public function deleted()
1479
-    {
1480
-        return $this->get('TKT_deleted');
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * Sets deleted
1486
-     *
1487
-     * @param boolean $deleted
1488
-     * @return void
1489
-     * @throws EE_Error
1490
-     * @throws ReflectionException
1491
-     */
1492
-    public function set_deleted($deleted)
1493
-    {
1494
-        $this->set('TKT_deleted', $deleted);
1495
-    }
1496
-
1497
-
1498
-    /**
1499
-     * Gets parent
1500
-     *
1501
-     * @return int
1502
-     * @throws EE_Error
1503
-     * @throws ReflectionException
1504
-     */
1505
-    public function parent_ID()
1506
-    {
1507
-        return $this->get('TKT_parent');
1508
-    }
1509
-
1510
-
1511
-    /**
1512
-     * Sets parent
1513
-     *
1514
-     * @param int $parent
1515
-     * @return void
1516
-     * @throws EE_Error
1517
-     * @throws ReflectionException
1518
-     */
1519
-    public function set_parent_ID($parent)
1520
-    {
1521
-        $this->set('TKT_parent', $parent);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * @return boolean
1527
-     * @throws EE_Error
1528
-     * @throws InvalidArgumentException
1529
-     * @throws InvalidDataTypeException
1530
-     * @throws InvalidInterfaceException
1531
-     * @throws ReflectionException
1532
-     */
1533
-    public function reverse_calculate()
1534
-    {
1535
-        return $this->get('TKT_reverse_calculate');
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * @param boolean $reverse_calculate
1541
-     * @throws EE_Error
1542
-     * @throws InvalidArgumentException
1543
-     * @throws InvalidDataTypeException
1544
-     * @throws InvalidInterfaceException
1545
-     * @throws ReflectionException
1546
-     */
1547
-    public function set_reverse_calculate($reverse_calculate)
1548
-    {
1549
-        $this->set('TKT_reverse_calculate', $reverse_calculate);
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1555
-     *
1556
-     * @return string
1557
-     * @throws EE_Error
1558
-     * @throws ReflectionException
1559
-     */
1560
-    public function name_and_info()
1561
-    {
1562
-        $times = [];
1563
-        foreach ($this->datetimes() as $datetime) {
1564
-            $times[] = $datetime->start_date_and_time();
1565
-        }
1566
-        return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1567
-    }
1568
-
1569
-
1570
-    /**
1571
-     * Gets name
1572
-     *
1573
-     * @return string
1574
-     * @throws EE_Error
1575
-     * @throws ReflectionException
1576
-     */
1577
-    public function name()
1578
-    {
1579
-        return $this->get('TKT_name');
1580
-    }
1581
-
1582
-
1583
-    /**
1584
-     * Gets price
1585
-     *
1586
-     * @return float
1587
-     * @throws EE_Error
1588
-     * @throws ReflectionException
1589
-     */
1590
-    public function price()
1591
-    {
1592
-        return $this->get('TKT_price');
1593
-    }
1594
-
1595
-
1596
-    /**
1597
-     * Gets all the registrations for this ticket
1598
-     *
1599
-     * @param array $query_params
1600
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1601
-     * @return EE_Registration[]|EE_Base_Class[]
1602
-     * @throws EE_Error
1603
-     * @throws ReflectionException
1604
-     */
1605
-    public function registrations($query_params = [])
1606
-    {
1607
-        return $this->get_many_related('Registration', $query_params);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1613
-     *
1614
-     * @return int
1615
-     * @throws EE_Error
1616
-     * @throws ReflectionException
1617
-     */
1618
-    public function update_tickets_sold()
1619
-    {
1620
-        $count_regs_for_this_ticket = $this->count_registrations(
1621
-            [
1622
-                [
1623
-                    'STS_ID'      => EEM_Registration::status_id_approved,
1624
-                    'REG_deleted' => 0,
1625
-                ],
1626
-            ]
1627
-        );
1628
-        $this->set_sold($count_regs_for_this_ticket);
1629
-        $this->save();
1630
-        return $count_regs_for_this_ticket;
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * Counts the registrations for this ticket
1636
-     *
1637
-     * @param array $query_params
1638
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1639
-     * @return int
1640
-     * @throws EE_Error
1641
-     * @throws ReflectionException
1642
-     */
1643
-    public function count_registrations($query_params = [])
1644
-    {
1645
-        return $this->count_related('Registration', $query_params);
1646
-    }
1647
-
1648
-
1649
-    /**
1650
-     * Implementation for EEI_Has_Icon interface method.
1651
-     *
1652
-     * @return string
1653
-     * @see EEI_Visual_Representation for comments
1654
-     */
1655
-    public function get_icon()
1656
-    {
1657
-        return '<span class="dashicons dashicons-tickets-alt"></span>';
1658
-    }
1659
-
1660
-
1661
-    /**
1662
-     * Implementation of the EEI_Event_Relation interface method
1663
-     *
1664
-     * @return EE_Event
1665
-     * @throws EE_Error
1666
-     * @throws UnexpectedEntityException
1667
-     * @throws ReflectionException
1668
-     * @see EEI_Event_Relation for comments
1669
-     */
1670
-    public function get_related_event()
1671
-    {
1672
-        // get one datetime to use for getting the event
1673
-        $datetime = $this->first_datetime();
1674
-        if (! $datetime instanceof EE_Datetime) {
1675
-            throw new UnexpectedEntityException(
1676
-                $datetime,
1677
-                'EE_Datetime',
1678
-                sprintf(
1679
-                    esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1680
-                    $this->name()
1681
-                )
1682
-            );
1683
-        }
1684
-        $event = $datetime->event();
1685
-        if (! $event instanceof EE_Event) {
1686
-            throw new UnexpectedEntityException(
1687
-                $event,
1688
-                'EE_Event',
1689
-                sprintf(
1690
-                    esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1691
-                    $this->name()
1692
-                )
1693
-            );
1694
-        }
1695
-        return $event;
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * Implementation of the EEI_Event_Relation interface method
1701
-     *
1702
-     * @return string
1703
-     * @throws UnexpectedEntityException
1704
-     * @throws EE_Error
1705
-     * @throws ReflectionException
1706
-     * @see EEI_Event_Relation for comments
1707
-     */
1708
-    public function get_event_name()
1709
-    {
1710
-        $event = $this->get_related_event();
1711
-        return $event instanceof EE_Event ? $event->name() : '';
1712
-    }
1713
-
1714
-
1715
-    /**
1716
-     * Implementation of the EEI_Event_Relation interface method
1717
-     *
1718
-     * @return int
1719
-     * @throws UnexpectedEntityException
1720
-     * @throws EE_Error
1721
-     * @throws ReflectionException
1722
-     * @see EEI_Event_Relation for comments
1723
-     */
1724
-    public function get_event_ID()
1725
-    {
1726
-        $event = $this->get_related_event();
1727
-        return $event instanceof EE_Event ? $event->ID() : 0;
1728
-    }
1729
-
1730
-
1731
-    /**
1732
-     * This simply returns whether a ticket can be permanently deleted or not.
1733
-     * The criteria for determining this is whether the ticket has any related registrations.
1734
-     * If there are none then it can be permanently deleted.
1735
-     *
1736
-     * @return bool
1737
-     * @throws EE_Error
1738
-     * @throws ReflectionException
1739
-     */
1740
-    public function is_permanently_deleteable()
1741
-    {
1742
-        return $this->count_registrations() === 0;
1743
-    }
1744
-
1745
-
1746
-    /**
1747
-     * @return int
1748
-     * @throws EE_Error
1749
-     * @throws ReflectionException
1750
-     * @since   $VID:$
1751
-     */
1752
-    public function visibility(): int
1753
-    {
1754
-        return $this->get('TKT_visibility');
1755
-    }
1756
-
1757
-
1758
-    /**
1759
-     * @return int
1760
-     * @throws EE_Error
1761
-     * @throws ReflectionException
1762
-     * @since   $VID:$
1763
-     */
1764
-    public function isHidden(): int
1765
-    {
1766
-        return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1767
-    }
1768
-
1769
-
1770
-    /**
1771
-     * @return int
1772
-     * @throws EE_Error
1773
-     * @throws ReflectionException
1774
-     * @since   $VID:$
1775
-     */
1776
-    public function isNotHidden(): int
1777
-    {
1778
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1779
-    }
1780
-
1781
-
1782
-    /**
1783
-     * @return int
1784
-     * @throws EE_Error
1785
-     * @throws ReflectionException
1786
-     * @since   $VID:$
1787
-     */
1788
-    public function isPublicOnly(): int
1789
-    {
1790
-        return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     * @return int
1796
-     * @throws EE_Error
1797
-     * @throws ReflectionException
1798
-     * @since   $VID:$
1799
-     */
1800
-    public function isMembersOnly(): int
1801
-    {
1802
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1803
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1804
-    }
1805
-
1806
-
1807
-    /**
1808
-     * @return int
1809
-     * @throws EE_Error
1810
-     * @throws ReflectionException
1811
-     * @since   $VID:$
1812
-     */
1813
-    public function isAdminsOnly(): int
1814
-    {
1815
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1816
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1817
-    }
1818
-
1819
-
1820
-    /**
1821
-     * @return int
1822
-     * @throws EE_Error
1823
-     * @throws ReflectionException
1824
-     * @since   $VID:$
1825
-     */
1826
-    public function isAdminUiOnly(): int
1827
-    {
1828
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1829
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1830
-    }
1831
-
1832
-
1833
-    /**
1834
-     * @param int $visibility
1835
-     * @throws EE_Error
1836
-     * @throws ReflectionException
1837
-     * @since   $VID:$
1838
-     */
1839
-    public function set_visibility(int $visibility)
1840
-    {
1841
-
1842
-        $ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1843
-        $ticket_visibility         = -1;
1844
-        foreach ($ticket_visibility_options as $ticket_visibility_option) {
1845
-            if ($visibility === $ticket_visibility_option) {
1846
-                $ticket_visibility = $visibility;
1847
-            }
1848
-        }
1849
-        if ($ticket_visibility === -1) {
1850
-            throw new DomainException(
1851
-                sprintf(
1852
-                    esc_html__(
1853
-                        'The supplied ticket visibility setting of "%1$s" is not valid. It needs to match one of the keys in the following array:%2$s %3$s ',
1854
-                        'event_espresso'
1855
-                    ),
1856
-                    $visibility,
1857
-                    '<br />',
1858
-                    var_export($ticket_visibility_options, true)
1859
-                )
1860
-            );
1861
-        }
1862
-        $this->set('TKT_visibility', $ticket_visibility);
1863
-    }
1864
-
1865
-
1866
-    /**
1867
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1868
-     * @param string                   $relationName
1869
-     * @param array                    $extra_join_model_fields_n_values
1870
-     * @param string|null              $cache_id
1871
-     * @return EE_Base_Class
1872
-     * @throws EE_Error
1873
-     * @throws ReflectionException
1874
-     * @since   $VID:$
1875
-     */
1876
-    public function _add_relation_to(
1877
-        $otherObjectModelObjectOrID,
1878
-        $relationName,
1879
-        $extra_join_model_fields_n_values = [],
1880
-        $cache_id = null
1881
-    ) {
1882
-        if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1883
-            /** @var EE_Datetime $datetime */
1884
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1885
-            $datetime->increaseSold($this->sold(), false);
1886
-            $datetime->increaseReserved($this->reserved());
1887
-            $datetime->save();
1888
-            $otherObjectModelObjectOrID = $datetime;
1889
-        }
1890
-        return parent::_add_relation_to(
1891
-            $otherObjectModelObjectOrID,
1892
-            $relationName,
1893
-            $extra_join_model_fields_n_values,
1894
-            $cache_id
1895
-        );
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1901
-     * @param string                   $relationName
1902
-     * @param array                    $where_query
1903
-     * @return bool|EE_Base_Class|null
1904
-     * @throws EE_Error
1905
-     * @throws ReflectionException
1906
-     * @since   $VID:$
1907
-     */
1908
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1909
-    {
1910
-        // if we're adding a new relation to a datetime
1911
-        if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1912
-            /** @var EE_Datetime $datetime */
1913
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1914
-            $datetime->decreaseSold($this->sold());
1915
-            $datetime->decreaseReserved($this->reserved());
1916
-            $datetime->save();
1917
-            $otherObjectModelObjectOrID = $datetime;
1918
-        }
1919
-        return parent::_remove_relation_to(
1920
-            $otherObjectModelObjectOrID,
1921
-            $relationName,
1922
-            $where_query
1923
-        );
1924
-    }
1925
-
1926
-
1927
-    /**
1928
-     * Removes ALL the related things for the $relationName.
1929
-     *
1930
-     * @param string $relationName
1931
-     * @param array  $where_query_params
1932
-     * @return EE_Base_Class
1933
-     * @throws ReflectionException
1934
-     * @throws InvalidArgumentException
1935
-     * @throws InvalidInterfaceException
1936
-     * @throws InvalidDataTypeException
1937
-     * @throws EE_Error
1938
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1939
-     */
1940
-    public function _remove_relations($relationName, $where_query_params = [])
1941
-    {
1942
-        if ($relationName === 'Datetime') {
1943
-            $datetimes = $this->datetimes();
1944
-            foreach ($datetimes as $datetime) {
1945
-                $datetime->decreaseSold($this->sold());
1946
-                $datetime->decreaseReserved($this->reserved());
1947
-                $datetime->save();
1948
-            }
1949
-        }
1950
-        return parent::_remove_relations($relationName, $where_query_params);
1951
-    }
1952
-
1953
-
1954
-    /*******************************************************************
17
+	/**
18
+	 * TicKet Archived:
19
+	 * constant used by ticket_status() to indicate that a ticket is archived
20
+	 * and no longer available for purchase
21
+	 */
22
+	const archived = 'TKA';
23
+
24
+	/**
25
+	 * TicKet Expired:
26
+	 * constant used by ticket_status() to indicate that a ticket is expired
27
+	 * and no longer available for purchase
28
+	 */
29
+	const expired = 'TKE';
30
+
31
+	/**
32
+	 * TicKet On sale:
33
+	 * constant used by ticket_status() to indicate that a ticket is On Sale
34
+	 * and IS available for purchase
35
+	 */
36
+	const onsale = 'TKO';
37
+
38
+	/**
39
+	 * TicKet Pending:
40
+	 * constant used by ticket_status() to indicate that a ticket is pending
41
+	 * and is NOT YET available for purchase
42
+	 */
43
+	const pending = 'TKP';
44
+
45
+	/**
46
+	 * TicKet Sold out:
47
+	 * constant used by ticket_status() to indicate that a ticket is sold out
48
+	 * and no longer available for purchases
49
+	 */
50
+	const sold_out = 'TKS';
51
+
52
+	/**
53
+	 * extra meta key for tracking ticket reservations
54
+	 *
55
+	 * @type string
56
+	 */
57
+	const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
+
59
+	/**
60
+	 * override of parent property
61
+	 *
62
+	 * @var EEM_Ticket
63
+	 */
64
+	protected $_model;
65
+
66
+	/**
67
+	 * cached result from method of the same name
68
+	 *
69
+	 * @var float $_ticket_total_with_taxes
70
+	 */
71
+	private $_ticket_total_with_taxes;
72
+
73
+	/**
74
+	 * @var TicketPriceModifiers
75
+	 */
76
+	protected $ticket_price_modifiers;
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values          incoming values
81
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
82
+	 *                                        used.)
83
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
84
+	 *                                        date_format and the second value is the time format
85
+	 * @return EE_Ticket
86
+	 * @throws EE_Error
87
+	 * @throws ReflectionException
88
+	 */
89
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
90
+	{
91
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
92
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param array  $props_n_values  incoming values from the database
98
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
99
+	 *                                the website will be used.
100
+	 * @return EE_Ticket
101
+	 * @throws EE_Error
102
+	 * @throws ReflectionException
103
+	 */
104
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
105
+	{
106
+		return new self($props_n_values, true, $timezone);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param array  $fieldValues
112
+	 * @param false  $bydb
113
+	 * @param string $timezone
114
+	 * @param array  $date_formats
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
119
+	{
120
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
121
+		$this->ticket_price_modifiers = new TicketPriceModifiers($this);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @return bool
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function parent()
131
+	{
132
+		return $this->get('TKT_parent');
133
+	}
134
+
135
+
136
+	/**
137
+	 * return if a ticket has quantities available for purchase
138
+	 *
139
+	 * @param int $DTT_ID the primary key for a particular datetime
140
+	 * @return boolean
141
+	 * @throws EE_Error
142
+	 * @throws ReflectionException
143
+	 */
144
+	public function available($DTT_ID = 0)
145
+	{
146
+		// are we checking availability for a particular datetime ?
147
+		if ($DTT_ID) {
148
+			// get that datetime object
149
+			$datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
150
+			// if  ticket sales for this datetime have exceeded the reg limit...
151
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
152
+				return false;
153
+			}
154
+		}
155
+		// datetime is still open for registration, but is this ticket sold out ?
156
+		return $this->qty() < 1 || $this->qty() > $this->sold();
157
+	}
158
+
159
+
160
+	/**
161
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
162
+	 *
163
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
164
+	 *                               relevant status const
165
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
166
+	 *                               further processing
167
+	 * @return mixed status int if the display string isn't requested
168
+	 * @throws EE_Error
169
+	 * @throws ReflectionException
170
+	 */
171
+	public function ticket_status($display = false, $remaining = null)
172
+	{
173
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
174
+		if (! $remaining) {
175
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
176
+		}
177
+		if ($this->get('TKT_deleted')) {
178
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
179
+		}
180
+		if ($this->is_expired()) {
181
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
182
+		}
183
+		if ($this->is_pending()) {
184
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
185
+		}
186
+		if ($this->is_on_sale()) {
187
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
188
+		}
189
+		return '';
190
+	}
191
+
192
+
193
+	/**
194
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
195
+	 * considering ALL the factors used for figuring that out.
196
+	 *
197
+	 * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
198
+	 * @return boolean         true = tickets remaining, false not.
199
+	 * @throws EE_Error
200
+	 * @throws ReflectionException
201
+	 */
202
+	public function is_remaining($DTT_ID = 0)
203
+	{
204
+		$num_remaining = $this->remaining($DTT_ID);
205
+		if ($num_remaining === 0) {
206
+			return false;
207
+		}
208
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
209
+			return false;
210
+		}
211
+		return true;
212
+	}
213
+
214
+
215
+	/**
216
+	 * return the total number of tickets available for purchase
217
+	 *
218
+	 * @param int $DTT_ID  the primary key for a particular datetime.
219
+	 *                     set to 0 for all related datetimes
220
+	 * @return int
221
+	 * @throws EE_Error
222
+	 * @throws ReflectionException
223
+	 */
224
+	public function remaining($DTT_ID = 0)
225
+	{
226
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
227
+	}
228
+
229
+
230
+	/**
231
+	 * Gets min
232
+	 *
233
+	 * @return int
234
+	 * @throws EE_Error
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function min()
238
+	{
239
+		return $this->get('TKT_min');
240
+	}
241
+
242
+
243
+	/**
244
+	 * return if a ticket is no longer available cause its available dates have expired.
245
+	 *
246
+	 * @return boolean
247
+	 * @throws EE_Error
248
+	 * @throws ReflectionException
249
+	 */
250
+	public function is_expired()
251
+	{
252
+		return ($this->get_raw('TKT_end_date') < time());
253
+	}
254
+
255
+
256
+	/**
257
+	 * Return if a ticket is yet to go on sale or not
258
+	 *
259
+	 * @return boolean
260
+	 * @throws EE_Error
261
+	 * @throws ReflectionException
262
+	 */
263
+	public function is_pending()
264
+	{
265
+		return ($this->get_raw('TKT_start_date') >= time());
266
+	}
267
+
268
+
269
+	/**
270
+	 * Return if a ticket is on sale or not
271
+	 *
272
+	 * @return boolean
273
+	 * @throws EE_Error
274
+	 * @throws ReflectionException
275
+	 */
276
+	public function is_on_sale()
277
+	{
278
+		return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
279
+	}
280
+
281
+
282
+	/**
283
+	 * This returns the chronologically last datetime that this ticket is associated with
284
+	 *
285
+	 * @param string $date_format
286
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
287
+	 *                            the end date ie: Jan 01 "to" Dec 31
288
+	 * @return string
289
+	 * @throws EE_Error
290
+	 * @throws ReflectionException
291
+	 */
292
+	public function date_range($date_format = '', $conjunction = ' - ')
293
+	{
294
+		$date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
295
+		$first_date  = $this->first_datetime() instanceof EE_Datetime
296
+			? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
297
+			: '';
298
+		$last_date   = $this->last_datetime() instanceof EE_Datetime
299
+			? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
300
+			: '';
301
+
302
+		return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
+	}
304
+
305
+
306
+	/**
307
+	 * This returns the chronologically first datetime that this ticket is associated with
308
+	 *
309
+	 * @return EE_Datetime
310
+	 * @throws EE_Error
311
+	 * @throws ReflectionException
312
+	 */
313
+	public function first_datetime()
314
+	{
315
+		$datetimes = $this->datetimes(['limit' => 1]);
316
+		return reset($datetimes);
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets all the datetimes this ticket can be used for attending.
322
+	 * Unless otherwise specified, orders datetimes by start date.
323
+	 *
324
+	 * @param array $query_params
325
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
+	 * @return EE_Datetime[]|EE_Base_Class[]
327
+	 * @throws EE_Error
328
+	 * @throws ReflectionException
329
+	 */
330
+	public function datetimes($query_params = [])
331
+	{
332
+		if (! isset($query_params['order_by'])) {
333
+			$query_params['order_by']['DTT_order'] = 'ASC';
334
+		}
335
+		return $this->get_many_related('Datetime', $query_params);
336
+	}
337
+
338
+
339
+	/**
340
+	 * This returns the chronologically last datetime that this ticket is associated with
341
+	 *
342
+	 * @return EE_Datetime
343
+	 * @throws EE_Error
344
+	 * @throws ReflectionException
345
+	 */
346
+	public function last_datetime()
347
+	{
348
+		$datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
349
+		return end($datetimes);
350
+	}
351
+
352
+
353
+	/**
354
+	 * This returns the total tickets sold depending on the given parameters.
355
+	 *
356
+	 * @param string $what    Can be one of two options: 'ticket', 'datetime'.
357
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
358
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
359
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
360
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
361
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
362
+	 * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
363
+	 * @return mixed (array|int)          how many tickets have sold
364
+	 * @throws EE_Error
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function tickets_sold($what = 'ticket', $dtt_id = null)
368
+	{
369
+		$total        = 0;
370
+		$tickets_sold = $this->_all_tickets_sold();
371
+		switch ($what) {
372
+			case 'ticket':
373
+				return $tickets_sold['ticket'];
374
+
375
+			case 'datetime':
376
+				if (empty($tickets_sold['datetime'])) {
377
+					return $total;
378
+				}
379
+				if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
+					EE_Error::add_error(
381
+						esc_html__(
382
+							'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
383
+							'event_espresso'
384
+						),
385
+						__FILE__,
386
+						__FUNCTION__,
387
+						__LINE__
388
+					);
389
+					return $total;
390
+				}
391
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
+
393
+			default:
394
+				return $total;
395
+		}
396
+	}
397
+
398
+
399
+	/**
400
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
401
+	 *
402
+	 * @return EE_Ticket[]
403
+	 * @throws EE_Error
404
+	 * @throws ReflectionException
405
+	 */
406
+	protected function _all_tickets_sold()
407
+	{
408
+		$datetimes    = $this->get_many_related('Datetime');
409
+		$tickets_sold = [];
410
+		if (! empty($datetimes)) {
411
+			foreach ($datetimes as $datetime) {
412
+				$tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
+			}
414
+		}
415
+		// Tickets sold
416
+		$tickets_sold['ticket'] = $this->sold();
417
+		return $tickets_sold;
418
+	}
419
+
420
+
421
+	/**
422
+	 * This returns the base price object for the ticket.
423
+	 *
424
+	 * @param bool $return_array whether to return as an array indexed by price id or just the object.
425
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function base_price(bool $return_array = false)
430
+	{
431
+		$base_price = $this->ticket_price_modifiers->getBasePrice();
432
+		if (! empty($base_price)) {
433
+			return $return_array ? $base_price : reset($base_price);
434
+		}
435
+		$_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
436
+		return $return_array
437
+			? $this->get_many_related('Price', [$_where])
438
+			: $this->get_first_related('Price', [$_where]);
439
+	}
440
+
441
+
442
+	/**
443
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
444
+	 *
445
+	 * @return EE_Price[]
446
+	 * @throws EE_Error
447
+	 * @throws ReflectionException
448
+	 */
449
+	public function price_modifiers(): array
450
+	{
451
+		$price_modifiers = $this->usesGlobalTaxes()
452
+			? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
453
+			: $this->ticket_price_modifiers ->getAllModifiersForTicket();
454
+		if (! empty($price_modifiers)) {
455
+			return $price_modifiers;
456
+		}
457
+		return $this->prices(
458
+			[
459
+				[
460
+					'Price_Type.PBT_ID' => [
461
+						'NOT IN',
462
+						[EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
463
+					]
464
+				]
465
+			]
466
+		);
467
+	}
468
+
469
+
470
+	/**
471
+	 * This returns ONLY the TAX price modifiers for the ticket
472
+	 *
473
+	 * @return EE_Price[]
474
+	 * @throws EE_Error
475
+	 * @throws ReflectionException
476
+	 */
477
+	public function tax_price_modifiers(): array
478
+	{
479
+		$tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
480
+		if (! empty($tax_price_modifiers)) {
481
+			return $tax_price_modifiers;
482
+		}
483
+		return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
484
+	}
485
+
486
+
487
+	/**
488
+	 * Gets all the prices that combine to form the final price of this ticket
489
+	 *
490
+	 * @param array $query_params
491
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
492
+	 * @return EE_Price[]|EE_Base_Class[]
493
+	 * @throws EE_Error
494
+	 * @throws ReflectionException
495
+	 */
496
+	public function prices(array $query_params = []): array
497
+	{
498
+		if (! isset($query_params['order_by'])) {
499
+			$query_params['order_by']['PRC_order'] = 'ASC';
500
+		}
501
+		return $this->get_many_related('Price', $query_params);
502
+	}
503
+
504
+
505
+	/**
506
+	 * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
507
+	 *
508
+	 * @param array $query_params
509
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
510
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 */
514
+	public function datetime_tickets($query_params = [])
515
+	{
516
+		return $this->get_many_related('Datetime_Ticket', $query_params);
517
+	}
518
+
519
+
520
+	/**
521
+	 * Gets all the datetimes from the db ordered by DTT_order
522
+	 *
523
+	 * @param boolean $show_expired
524
+	 * @param boolean $show_deleted
525
+	 * @return EE_Datetime[]
526
+	 * @throws EE_Error
527
+	 * @throws ReflectionException
528
+	 */
529
+	public function datetimes_ordered($show_expired = true, $show_deleted = false)
530
+	{
531
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
532
+			$this->ID(),
533
+			$show_expired,
534
+			$show_deleted
535
+		);
536
+	}
537
+
538
+
539
+	/**
540
+	 * Gets ID
541
+	 *
542
+	 * @return int
543
+	 * @throws EE_Error
544
+	 * @throws ReflectionException
545
+	 */
546
+	public function ID()
547
+	{
548
+		return (int) $this->get('TKT_ID');
549
+	}
550
+
551
+
552
+	/**
553
+	 * get the author of the ticket.
554
+	 *
555
+	 * @return int
556
+	 * @throws EE_Error
557
+	 * @throws ReflectionException
558
+	 * @since 4.5.0
559
+	 */
560
+	public function wp_user()
561
+	{
562
+		return $this->get('TKT_wp_user');
563
+	}
564
+
565
+
566
+	/**
567
+	 * Gets the template for the ticket
568
+	 *
569
+	 * @return EE_Ticket_Template|EE_Base_Class
570
+	 * @throws EE_Error
571
+	 * @throws ReflectionException
572
+	 */
573
+	public function template()
574
+	{
575
+		return $this->get_first_related('Ticket_Template');
576
+	}
577
+
578
+
579
+	/**
580
+	 * Simply returns an array of EE_Price objects that are taxes.
581
+	 *
582
+	 * @return EE_Price[]
583
+	 * @throws EE_Error
584
+	 * @throws ReflectionException
585
+	 */
586
+	public function get_ticket_taxes_for_admin(): array
587
+	{
588
+		return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
589
+	}
590
+
591
+
592
+	/**
593
+	 * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
594
+	 * as opposed to having tax price modifiers added directly to each ticket
595
+	 *
596
+	 * @return bool
597
+	 * @throws EE_Error
598
+	 * @throws ReflectionException
599
+	 * @since   $VID:$
600
+	 */
601
+	public function usesGlobalTaxes(): bool
602
+	{
603
+		return $this->taxable();
604
+	}
605
+
606
+
607
+	/**
608
+	 * @return float
609
+	 * @throws EE_Error
610
+	 * @throws ReflectionException
611
+	 */
612
+	public function ticket_price()
613
+	{
614
+		return $this->get('TKT_price');
615
+	}
616
+
617
+
618
+	/**
619
+	 * @return mixed
620
+	 * @throws EE_Error
621
+	 * @throws ReflectionException
622
+	 */
623
+	public function pretty_price()
624
+	{
625
+		return $this->get_pretty('TKT_price');
626
+	}
627
+
628
+
629
+	/**
630
+	 * @return bool
631
+	 * @throws EE_Error
632
+	 * @throws ReflectionException
633
+	 */
634
+	public function is_free()
635
+	{
636
+		return $this->get_ticket_total_with_taxes() === (float) 0;
637
+	}
638
+
639
+
640
+	/**
641
+	 * get_ticket_total_with_taxes
642
+	 *
643
+	 * @param bool $no_cache
644
+	 * @return float
645
+	 * @throws EE_Error
646
+	 * @throws ReflectionException
647
+	 */
648
+	public function get_ticket_total_with_taxes($no_cache = false)
649
+	{
650
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
651
+			$this->_ticket_total_with_taxes = $this->usesGlobalTaxes()
652
+				? $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin()
653
+				: $this->ticket_price();
654
+		}
655
+		return (float) $this->_ticket_total_with_taxes;
656
+	}
657
+
658
+
659
+	/**
660
+	 * @throws EE_Error
661
+	 * @throws ReflectionException
662
+	 */
663
+	public function ensure_TKT_Price_correct()
664
+	{
665
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
666
+		$this->save();
667
+	}
668
+
669
+
670
+	/**
671
+	 * @return float
672
+	 * @throws EE_Error
673
+	 * @throws ReflectionException
674
+	 */
675
+	public function get_ticket_subtotal()
676
+	{
677
+		return EE_Taxes::get_subtotal_for_admin($this);
678
+	}
679
+
680
+
681
+	/**
682
+	 * Returns the total taxes applied to this ticket
683
+	 *
684
+	 * @return float
685
+	 * @throws EE_Error
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function get_ticket_taxes_total_for_admin()
689
+	{
690
+		return EE_Taxes::get_total_taxes_for_admin($this);
691
+	}
692
+
693
+
694
+	/**
695
+	 * Sets name
696
+	 *
697
+	 * @param string $name
698
+	 * @throws EE_Error
699
+	 * @throws ReflectionException
700
+	 */
701
+	public function set_name($name)
702
+	{
703
+		$this->set('TKT_name', $name);
704
+	}
705
+
706
+
707
+	/**
708
+	 * Gets description
709
+	 *
710
+	 * @return string
711
+	 * @throws EE_Error
712
+	 * @throws ReflectionException
713
+	 */
714
+	public function description()
715
+	{
716
+		return $this->get('TKT_description');
717
+	}
718
+
719
+
720
+	/**
721
+	 * Sets description
722
+	 *
723
+	 * @param string $description
724
+	 * @throws EE_Error
725
+	 * @throws ReflectionException
726
+	 */
727
+	public function set_description($description)
728
+	{
729
+		$this->set('TKT_description', $description);
730
+	}
731
+
732
+
733
+	/**
734
+	 * Gets start_date
735
+	 *
736
+	 * @param string|null $date_format
737
+	 * @param string|null $time_format
738
+	 * @return string
739
+	 * @throws EE_Error
740
+	 * @throws ReflectionException
741
+	 */
742
+	public function start_date(?string $date_format = '', ?string $time_format = ''): string
743
+	{
744
+		return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
745
+	}
746
+
747
+
748
+	/**
749
+	 * Sets start_date
750
+	 *
751
+	 * @param string $start_date
752
+	 * @return void
753
+	 * @throws EE_Error
754
+	 * @throws ReflectionException
755
+	 */
756
+	public function set_start_date($start_date)
757
+	{
758
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
759
+	}
760
+
761
+
762
+	/**
763
+	 * Gets end_date
764
+	 *
765
+	 * @param string|null $date_format
766
+	 * @param string|null $time_format
767
+	 * @return string
768
+	 * @throws EE_Error
769
+	 * @throws ReflectionException
770
+	 */
771
+	public function end_date(?string $date_format = '', ?string $time_format = ''): string
772
+	{
773
+		return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
774
+	}
775
+
776
+
777
+	/**
778
+	 * Sets end_date
779
+	 *
780
+	 * @param string $end_date
781
+	 * @return void
782
+	 * @throws EE_Error
783
+	 * @throws ReflectionException
784
+	 */
785
+	public function set_end_date($end_date)
786
+	{
787
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
788
+	}
789
+
790
+
791
+	/**
792
+	 * Sets sell until time
793
+	 *
794
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
795
+	 * @throws EE_Error
796
+	 * @throws ReflectionException
797
+	 * @since 4.5.0
798
+	 */
799
+	public function set_end_time($time)
800
+	{
801
+		$this->_set_time_for($time, 'TKT_end_date');
802
+	}
803
+
804
+
805
+	/**
806
+	 * Sets min
807
+	 *
808
+	 * @param int $min
809
+	 * @return void
810
+	 * @throws EE_Error
811
+	 * @throws ReflectionException
812
+	 */
813
+	public function set_min($min)
814
+	{
815
+		$this->set('TKT_min', $min);
816
+	}
817
+
818
+
819
+	/**
820
+	 * Gets max
821
+	 *
822
+	 * @return int
823
+	 * @throws EE_Error
824
+	 * @throws ReflectionException
825
+	 */
826
+	public function max()
827
+	{
828
+		return $this->get('TKT_max');
829
+	}
830
+
831
+
832
+	/**
833
+	 * Sets max
834
+	 *
835
+	 * @param int $max
836
+	 * @return void
837
+	 * @throws EE_Error
838
+	 * @throws ReflectionException
839
+	 */
840
+	public function set_max($max)
841
+	{
842
+		$this->set('TKT_max', $max);
843
+	}
844
+
845
+
846
+	/**
847
+	 * Sets price
848
+	 *
849
+	 * @param float $price
850
+	 * @return void
851
+	 * @throws EE_Error
852
+	 * @throws ReflectionException
853
+	 */
854
+	public function set_price($price)
855
+	{
856
+		$this->set('TKT_price', $price);
857
+	}
858
+
859
+
860
+	/**
861
+	 * Gets sold
862
+	 *
863
+	 * @return int
864
+	 * @throws EE_Error
865
+	 * @throws ReflectionException
866
+	 */
867
+	public function sold(): int
868
+	{
869
+		return (int) $this->get_raw('TKT_sold');
870
+	}
871
+
872
+
873
+	/**
874
+	 * Sets sold
875
+	 *
876
+	 * @param int $sold
877
+	 * @return void
878
+	 * @throws EE_Error
879
+	 * @throws ReflectionException
880
+	 */
881
+	public function set_sold($sold)
882
+	{
883
+		// sold can not go below zero
884
+		$sold = max(0, $sold);
885
+		$this->set('TKT_sold', $sold);
886
+	}
887
+
888
+
889
+	/**
890
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
891
+	 * associated datetimes.
892
+	 *
893
+	 * @param int $qty
894
+	 * @return boolean
895
+	 * @throws EE_Error
896
+	 * @throws InvalidArgumentException
897
+	 * @throws InvalidDataTypeException
898
+	 * @throws InvalidInterfaceException
899
+	 * @throws ReflectionException
900
+	 * @since 4.9.80.p
901
+	 */
902
+	public function increaseSold($qty = 1)
903
+	{
904
+		$qty = absint($qty);
905
+		// increment sold and decrement reserved datetime quantities simultaneously
906
+		// don't worry about failures, because they must have already had a spot reserved
907
+		$this->increaseSoldForDatetimes($qty);
908
+		// Increment and decrement ticket quantities simultaneously
909
+		$success = $this->adjustNumericFieldsInDb(
910
+			[
911
+				'TKT_reserved' => $qty * -1,
912
+				'TKT_sold'     => $qty,
913
+			]
914
+		);
915
+		do_action(
916
+			'AHEE__EE_Ticket__increase_sold',
917
+			$this,
918
+			$qty,
919
+			$this->sold(),
920
+			$success
921
+		);
922
+		return $success;
923
+	}
924
+
925
+
926
+	/**
927
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
928
+	 *
929
+	 * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
930
+	 *                           counts), Negative means to decreases old counts (and increase reserved counts).
931
+	 * @param EE_Datetime[] $datetimes
932
+	 * @throws EE_Error
933
+	 * @throws InvalidArgumentException
934
+	 * @throws InvalidDataTypeException
935
+	 * @throws InvalidInterfaceException
936
+	 * @throws ReflectionException
937
+	 * @since 4.9.80.p
938
+	 */
939
+	protected function increaseSoldForDatetimes($qty, array $datetimes = [])
940
+	{
941
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
942
+		foreach ($datetimes as $datetime) {
943
+			$datetime->increaseSold($qty);
944
+		}
945
+	}
946
+
947
+
948
+	/**
949
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
950
+	 * DB and then updates the model objects.
951
+	 * Does not affect the reserved counts.
952
+	 *
953
+	 * @param int $qty
954
+	 * @return boolean
955
+	 * @throws EE_Error
956
+	 * @throws InvalidArgumentException
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws ReflectionException
960
+	 * @since 4.9.80.p
961
+	 */
962
+	public function decreaseSold($qty = 1)
963
+	{
964
+		$qty = absint($qty);
965
+		$this->decreaseSoldForDatetimes($qty);
966
+		$success = $this->adjustNumericFieldsInDb(
967
+			[
968
+				'TKT_sold' => $qty * -1,
969
+			]
970
+		);
971
+		do_action(
972
+			'AHEE__EE_Ticket__decrease_sold',
973
+			$this,
974
+			$qty,
975
+			$this->sold(),
976
+			$success
977
+		);
978
+		return $success;
979
+	}
980
+
981
+
982
+	/**
983
+	 * Decreases sold on related datetimes
984
+	 *
985
+	 * @param int           $qty
986
+	 * @param EE_Datetime[] $datetimes
987
+	 * @return void
988
+	 * @throws EE_Error
989
+	 * @throws InvalidArgumentException
990
+	 * @throws InvalidDataTypeException
991
+	 * @throws InvalidInterfaceException
992
+	 * @throws ReflectionException
993
+	 * @since 4.9.80.p
994
+	 */
995
+	protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
996
+	{
997
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
998
+		if (is_array($datetimes)) {
999
+			foreach ($datetimes as $datetime) {
1000
+				if ($datetime instanceof EE_Datetime) {
1001
+					$datetime->decreaseSold($qty);
1002
+				}
1003
+			}
1004
+		}
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Gets qty of reserved tickets
1010
+	 *
1011
+	 * @return int
1012
+	 * @throws EE_Error
1013
+	 * @throws ReflectionException
1014
+	 */
1015
+	public function reserved(): int
1016
+	{
1017
+		return (int) $this->get_raw('TKT_reserved');
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * Sets reserved
1023
+	 *
1024
+	 * @param int $reserved
1025
+	 * @return void
1026
+	 * @throws EE_Error
1027
+	 * @throws ReflectionException
1028
+	 */
1029
+	public function set_reserved($reserved)
1030
+	{
1031
+		// reserved can not go below zero
1032
+		$reserved = max(0, (int) $reserved);
1033
+		$this->set('TKT_reserved', $reserved);
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1039
+	 *
1040
+	 * @param int    $qty
1041
+	 * @param string $source
1042
+	 * @return bool whether we successfully reserved the ticket or not.
1043
+	 * @throws EE_Error
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @since 4.9.80.p
1049
+	 */
1050
+	public function increaseReserved($qty = 1, $source = 'unknown')
1051
+	{
1052
+		$qty = absint($qty);
1053
+		do_action(
1054
+			'AHEE__EE_Ticket__increase_reserved__begin',
1055
+			$this,
1056
+			$qty,
1057
+			$source
1058
+		);
1059
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1060
+		$success                         = false;
1061
+		$datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1062
+		if ($datetimes_adjusted_successfully) {
1063
+			$success = $this->incrementFieldConditionallyInDb(
1064
+				'TKT_reserved',
1065
+				'TKT_sold',
1066
+				'TKT_qty',
1067
+				$qty
1068
+			);
1069
+			if (! $success) {
1070
+				// The datetimes were successfully bumped, but not the
1071
+				// ticket. So we need to manually rollback the datetimes.
1072
+				$this->decreaseReservedForDatetimes($qty);
1073
+			}
1074
+		}
1075
+		do_action(
1076
+			'AHEE__EE_Ticket__increase_reserved',
1077
+			$this,
1078
+			$qty,
1079
+			$this->reserved(),
1080
+			$success
1081
+		);
1082
+		return $success;
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 * Increases reserved counts on related datetimes
1088
+	 *
1089
+	 * @param int           $qty
1090
+	 * @param EE_Datetime[] $datetimes
1091
+	 * @return boolean indicating success
1092
+	 * @throws EE_Error
1093
+	 * @throws InvalidArgumentException
1094
+	 * @throws InvalidDataTypeException
1095
+	 * @throws InvalidInterfaceException
1096
+	 * @throws ReflectionException
1097
+	 * @since 4.9.80.p
1098
+	 */
1099
+	protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1100
+	{
1101
+		$datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1102
+		$datetimes_updated = [];
1103
+		$limit_exceeded    = false;
1104
+		if (is_array($datetimes)) {
1105
+			foreach ($datetimes as $datetime) {
1106
+				if ($datetime instanceof EE_Datetime) {
1107
+					if ($datetime->increaseReserved($qty)) {
1108
+						$datetimes_updated[] = $datetime;
1109
+					} else {
1110
+						$limit_exceeded = true;
1111
+						break;
1112
+					}
1113
+				}
1114
+			}
1115
+			// If somewhere along the way we detected a datetime whose
1116
+			// limit was exceeded, do a manual rollback.
1117
+			if ($limit_exceeded) {
1118
+				$this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1119
+				return false;
1120
+			}
1121
+		}
1122
+		return true;
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1128
+	 *
1129
+	 * @param int    $qty
1130
+	 * @param bool   $adjust_datetimes
1131
+	 * @param string $source
1132
+	 * @return boolean
1133
+	 * @throws EE_Error
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws ReflectionException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws InvalidInterfaceException
1138
+	 * @since 4.9.80.p
1139
+	 */
1140
+	public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1141
+	{
1142
+		$qty = absint($qty);
1143
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1144
+		if ($adjust_datetimes) {
1145
+			$this->decreaseReservedForDatetimes($qty);
1146
+		}
1147
+		$success = $this->adjustNumericFieldsInDb(
1148
+			[
1149
+				'TKT_reserved' => $qty * -1,
1150
+			]
1151
+		);
1152
+		do_action(
1153
+			'AHEE__EE_Ticket__decrease_reserved',
1154
+			$this,
1155
+			$qty,
1156
+			$this->reserved(),
1157
+			$success
1158
+		);
1159
+		return $success;
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * Decreases the reserved count on the specified datetimes.
1165
+	 *
1166
+	 * @param int           $qty
1167
+	 * @param EE_Datetime[] $datetimes
1168
+	 * @throws EE_Error
1169
+	 * @throws InvalidArgumentException
1170
+	 * @throws ReflectionException
1171
+	 * @throws InvalidDataTypeException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @since 4.9.80.p
1174
+	 */
1175
+	protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1176
+	{
1177
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1178
+		foreach ($datetimes as $datetime) {
1179
+			if ($datetime instanceof EE_Datetime) {
1180
+				$datetime->decreaseReserved($qty);
1181
+			}
1182
+		}
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Gets ticket quantity
1188
+	 *
1189
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1190
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1191
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1192
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1193
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1194
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1195
+	 * @return int
1196
+	 * @throws EE_Error
1197
+	 * @throws ReflectionException
1198
+	 */
1199
+	public function qty($context = '')
1200
+	{
1201
+		switch ($context) {
1202
+			case 'reg_limit':
1203
+				return $this->real_quantity_on_ticket();
1204
+			case 'saleable':
1205
+				return $this->real_quantity_on_ticket('saleable');
1206
+			default:
1207
+				return $this->get_raw('TKT_qty');
1208
+		}
1209
+	}
1210
+
1211
+
1212
+	/**
1213
+	 * Gets ticket quantity
1214
+	 *
1215
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1216
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1217
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1218
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1219
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1220
+	 * @param int    $DTT_ID      the primary key for a particular datetime.
1221
+	 *                            set to 0 for all related datetimes
1222
+	 * @return int
1223
+	 * @throws EE_Error
1224
+	 * @throws ReflectionException
1225
+	 */
1226
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1227
+	{
1228
+		$raw = $this->get_raw('TKT_qty');
1229
+		// return immediately if it's zero
1230
+		if ($raw === 0) {
1231
+			return $raw;
1232
+		}
1233
+		// echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1234
+		// ensure qty doesn't exceed raw value for THIS ticket
1235
+		$qty = min(EE_INF, $raw);
1236
+		// echo "\n . qty: " . $qty . '<br />';
1237
+		// calculate this ticket's total sales and reservations
1238
+		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1239
+		// echo "\n . sold: " . $this->sold() . '<br />';
1240
+		// echo "\n . reserved: " . $this->reserved() . '<br />';
1241
+		// echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1242
+		// first we need to calculate the maximum number of tickets available for the datetime
1243
+		// do we want data for one datetime or all of them ?
1244
+		$query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1245
+		$datetimes    = $this->datetimes($query_params);
1246
+		if (is_array($datetimes) && ! empty($datetimes)) {
1247
+			foreach ($datetimes as $datetime) {
1248
+				if ($datetime instanceof EE_Datetime) {
1249
+					$datetime->refresh_from_db();
1250
+					// echo "\n . . datetime name: " . $datetime->name() . '<br />';
1251
+					// echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1252
+					// initialize with no restrictions for each datetime
1253
+					// but adjust datetime qty based on datetime reg limit
1254
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
1255
+					// echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1256
+					// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1257
+					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
1258
+					// and reservations for this datetime, that do NOT include sales and reservations
1259
+					// for this ticket (so we add $this->sold() and $this->reserved() back in)
1260
+					if ($context === 'saleable') {
1261
+						$datetime_qty = max(
1262
+							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1263
+							0
1264
+						);
1265
+						// echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1266
+						// echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1267
+						// echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1268
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1269
+						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1270
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1271
+					}
1272
+					$qty = min($datetime_qty, $qty);
1273
+					// echo "\n . . qty: " . $qty . '<br />';
1274
+				}
1275
+			}
1276
+		}
1277
+		// NOW that we know the  maximum number of tickets available for the datetime
1278
+		// we can finally factor in the details for this specific ticket
1279
+		if ($qty > 0 && $context === 'saleable') {
1280
+			// and subtract the sales for THIS ticket
1281
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1282
+			// echo "\n . qty: " . $qty . '<br />';
1283
+		}
1284
+		// echo "\nFINAL QTY: " . $qty . "<br /><br />";
1285
+		return (int) $qty;
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1291
+	 *
1292
+	 * @param int $qty
1293
+	 * @return void
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function set_qty($qty)
1298
+	{
1299
+		$datetimes = $this->datetimes();
1300
+		foreach ($datetimes as $datetime) {
1301
+			if ($datetime instanceof EE_Datetime) {
1302
+				$qty = min($qty, $datetime->reg_limit());
1303
+			}
1304
+		}
1305
+		$this->set('TKT_qty', $qty);
1306
+	}
1307
+
1308
+
1309
+	/**
1310
+	 * Gets uses
1311
+	 *
1312
+	 * @return int
1313
+	 * @throws EE_Error
1314
+	 * @throws ReflectionException
1315
+	 */
1316
+	public function uses()
1317
+	{
1318
+		return $this->get('TKT_uses');
1319
+	}
1320
+
1321
+
1322
+	/**
1323
+	 * Sets uses
1324
+	 *
1325
+	 * @param int $uses
1326
+	 * @return void
1327
+	 * @throws EE_Error
1328
+	 * @throws ReflectionException
1329
+	 */
1330
+	public function set_uses($uses)
1331
+	{
1332
+		$this->set('TKT_uses', $uses);
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * returns whether ticket is required or not.
1338
+	 *
1339
+	 * @return boolean
1340
+	 * @throws EE_Error
1341
+	 * @throws ReflectionException
1342
+	 */
1343
+	public function required()
1344
+	{
1345
+		return $this->get('TKT_required');
1346
+	}
1347
+
1348
+
1349
+	/**
1350
+	 * sets the TKT_required property
1351
+	 *
1352
+	 * @param boolean $required
1353
+	 * @return void
1354
+	 * @throws EE_Error
1355
+	 * @throws ReflectionException
1356
+	 */
1357
+	public function set_required($required)
1358
+	{
1359
+		$this->set('TKT_required', $required);
1360
+	}
1361
+
1362
+
1363
+	/**
1364
+	 * Gets taxable
1365
+	 *
1366
+	 * @return boolean
1367
+	 * @throws EE_Error
1368
+	 * @throws ReflectionException
1369
+	 */
1370
+	public function taxable()
1371
+	{
1372
+		return $this->get('TKT_taxable');
1373
+	}
1374
+
1375
+
1376
+	/**
1377
+	 * Sets taxable
1378
+	 *
1379
+	 * @param boolean $taxable
1380
+	 * @return void
1381
+	 * @throws EE_Error
1382
+	 * @throws ReflectionException
1383
+	 */
1384
+	public function set_taxable($taxable)
1385
+	{
1386
+		$this->set('TKT_taxable', $taxable);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * Gets is_default
1392
+	 *
1393
+	 * @return boolean
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function is_default()
1398
+	{
1399
+		return $this->get('TKT_is_default');
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * Sets is_default
1405
+	 *
1406
+	 * @param boolean $is_default
1407
+	 * @return void
1408
+	 * @throws EE_Error
1409
+	 * @throws ReflectionException
1410
+	 */
1411
+	public function set_is_default($is_default)
1412
+	{
1413
+		$this->set('TKT_is_default', $is_default);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Gets order
1419
+	 *
1420
+	 * @return int
1421
+	 * @throws EE_Error
1422
+	 * @throws ReflectionException
1423
+	 */
1424
+	public function order()
1425
+	{
1426
+		return $this->get('TKT_order');
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * Sets order
1432
+	 *
1433
+	 * @param int $order
1434
+	 * @return void
1435
+	 * @throws EE_Error
1436
+	 * @throws ReflectionException
1437
+	 */
1438
+	public function set_order($order)
1439
+	{
1440
+		$this->set('TKT_order', $order);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Gets row
1446
+	 *
1447
+	 * @return int
1448
+	 * @throws EE_Error
1449
+	 * @throws ReflectionException
1450
+	 */
1451
+	public function row()
1452
+	{
1453
+		return $this->get('TKT_row');
1454
+	}
1455
+
1456
+
1457
+	/**
1458
+	 * Sets row
1459
+	 *
1460
+	 * @param int $row
1461
+	 * @return void
1462
+	 * @throws EE_Error
1463
+	 * @throws ReflectionException
1464
+	 */
1465
+	public function set_row($row)
1466
+	{
1467
+		$this->set('TKT_row', $row);
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Gets deleted
1473
+	 *
1474
+	 * @return boolean
1475
+	 * @throws EE_Error
1476
+	 * @throws ReflectionException
1477
+	 */
1478
+	public function deleted()
1479
+	{
1480
+		return $this->get('TKT_deleted');
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * Sets deleted
1486
+	 *
1487
+	 * @param boolean $deleted
1488
+	 * @return void
1489
+	 * @throws EE_Error
1490
+	 * @throws ReflectionException
1491
+	 */
1492
+	public function set_deleted($deleted)
1493
+	{
1494
+		$this->set('TKT_deleted', $deleted);
1495
+	}
1496
+
1497
+
1498
+	/**
1499
+	 * Gets parent
1500
+	 *
1501
+	 * @return int
1502
+	 * @throws EE_Error
1503
+	 * @throws ReflectionException
1504
+	 */
1505
+	public function parent_ID()
1506
+	{
1507
+		return $this->get('TKT_parent');
1508
+	}
1509
+
1510
+
1511
+	/**
1512
+	 * Sets parent
1513
+	 *
1514
+	 * @param int $parent
1515
+	 * @return void
1516
+	 * @throws EE_Error
1517
+	 * @throws ReflectionException
1518
+	 */
1519
+	public function set_parent_ID($parent)
1520
+	{
1521
+		$this->set('TKT_parent', $parent);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * @return boolean
1527
+	 * @throws EE_Error
1528
+	 * @throws InvalidArgumentException
1529
+	 * @throws InvalidDataTypeException
1530
+	 * @throws InvalidInterfaceException
1531
+	 * @throws ReflectionException
1532
+	 */
1533
+	public function reverse_calculate()
1534
+	{
1535
+		return $this->get('TKT_reverse_calculate');
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * @param boolean $reverse_calculate
1541
+	 * @throws EE_Error
1542
+	 * @throws InvalidArgumentException
1543
+	 * @throws InvalidDataTypeException
1544
+	 * @throws InvalidInterfaceException
1545
+	 * @throws ReflectionException
1546
+	 */
1547
+	public function set_reverse_calculate($reverse_calculate)
1548
+	{
1549
+		$this->set('TKT_reverse_calculate', $reverse_calculate);
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1555
+	 *
1556
+	 * @return string
1557
+	 * @throws EE_Error
1558
+	 * @throws ReflectionException
1559
+	 */
1560
+	public function name_and_info()
1561
+	{
1562
+		$times = [];
1563
+		foreach ($this->datetimes() as $datetime) {
1564
+			$times[] = $datetime->start_date_and_time();
1565
+		}
1566
+		return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1567
+	}
1568
+
1569
+
1570
+	/**
1571
+	 * Gets name
1572
+	 *
1573
+	 * @return string
1574
+	 * @throws EE_Error
1575
+	 * @throws ReflectionException
1576
+	 */
1577
+	public function name()
1578
+	{
1579
+		return $this->get('TKT_name');
1580
+	}
1581
+
1582
+
1583
+	/**
1584
+	 * Gets price
1585
+	 *
1586
+	 * @return float
1587
+	 * @throws EE_Error
1588
+	 * @throws ReflectionException
1589
+	 */
1590
+	public function price()
1591
+	{
1592
+		return $this->get('TKT_price');
1593
+	}
1594
+
1595
+
1596
+	/**
1597
+	 * Gets all the registrations for this ticket
1598
+	 *
1599
+	 * @param array $query_params
1600
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1601
+	 * @return EE_Registration[]|EE_Base_Class[]
1602
+	 * @throws EE_Error
1603
+	 * @throws ReflectionException
1604
+	 */
1605
+	public function registrations($query_params = [])
1606
+	{
1607
+		return $this->get_many_related('Registration', $query_params);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1613
+	 *
1614
+	 * @return int
1615
+	 * @throws EE_Error
1616
+	 * @throws ReflectionException
1617
+	 */
1618
+	public function update_tickets_sold()
1619
+	{
1620
+		$count_regs_for_this_ticket = $this->count_registrations(
1621
+			[
1622
+				[
1623
+					'STS_ID'      => EEM_Registration::status_id_approved,
1624
+					'REG_deleted' => 0,
1625
+				],
1626
+			]
1627
+		);
1628
+		$this->set_sold($count_regs_for_this_ticket);
1629
+		$this->save();
1630
+		return $count_regs_for_this_ticket;
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * Counts the registrations for this ticket
1636
+	 *
1637
+	 * @param array $query_params
1638
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1639
+	 * @return int
1640
+	 * @throws EE_Error
1641
+	 * @throws ReflectionException
1642
+	 */
1643
+	public function count_registrations($query_params = [])
1644
+	{
1645
+		return $this->count_related('Registration', $query_params);
1646
+	}
1647
+
1648
+
1649
+	/**
1650
+	 * Implementation for EEI_Has_Icon interface method.
1651
+	 *
1652
+	 * @return string
1653
+	 * @see EEI_Visual_Representation for comments
1654
+	 */
1655
+	public function get_icon()
1656
+	{
1657
+		return '<span class="dashicons dashicons-tickets-alt"></span>';
1658
+	}
1659
+
1660
+
1661
+	/**
1662
+	 * Implementation of the EEI_Event_Relation interface method
1663
+	 *
1664
+	 * @return EE_Event
1665
+	 * @throws EE_Error
1666
+	 * @throws UnexpectedEntityException
1667
+	 * @throws ReflectionException
1668
+	 * @see EEI_Event_Relation for comments
1669
+	 */
1670
+	public function get_related_event()
1671
+	{
1672
+		// get one datetime to use for getting the event
1673
+		$datetime = $this->first_datetime();
1674
+		if (! $datetime instanceof EE_Datetime) {
1675
+			throw new UnexpectedEntityException(
1676
+				$datetime,
1677
+				'EE_Datetime',
1678
+				sprintf(
1679
+					esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1680
+					$this->name()
1681
+				)
1682
+			);
1683
+		}
1684
+		$event = $datetime->event();
1685
+		if (! $event instanceof EE_Event) {
1686
+			throw new UnexpectedEntityException(
1687
+				$event,
1688
+				'EE_Event',
1689
+				sprintf(
1690
+					esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1691
+					$this->name()
1692
+				)
1693
+			);
1694
+		}
1695
+		return $event;
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * Implementation of the EEI_Event_Relation interface method
1701
+	 *
1702
+	 * @return string
1703
+	 * @throws UnexpectedEntityException
1704
+	 * @throws EE_Error
1705
+	 * @throws ReflectionException
1706
+	 * @see EEI_Event_Relation for comments
1707
+	 */
1708
+	public function get_event_name()
1709
+	{
1710
+		$event = $this->get_related_event();
1711
+		return $event instanceof EE_Event ? $event->name() : '';
1712
+	}
1713
+
1714
+
1715
+	/**
1716
+	 * Implementation of the EEI_Event_Relation interface method
1717
+	 *
1718
+	 * @return int
1719
+	 * @throws UnexpectedEntityException
1720
+	 * @throws EE_Error
1721
+	 * @throws ReflectionException
1722
+	 * @see EEI_Event_Relation for comments
1723
+	 */
1724
+	public function get_event_ID()
1725
+	{
1726
+		$event = $this->get_related_event();
1727
+		return $event instanceof EE_Event ? $event->ID() : 0;
1728
+	}
1729
+
1730
+
1731
+	/**
1732
+	 * This simply returns whether a ticket can be permanently deleted or not.
1733
+	 * The criteria for determining this is whether the ticket has any related registrations.
1734
+	 * If there are none then it can be permanently deleted.
1735
+	 *
1736
+	 * @return bool
1737
+	 * @throws EE_Error
1738
+	 * @throws ReflectionException
1739
+	 */
1740
+	public function is_permanently_deleteable()
1741
+	{
1742
+		return $this->count_registrations() === 0;
1743
+	}
1744
+
1745
+
1746
+	/**
1747
+	 * @return int
1748
+	 * @throws EE_Error
1749
+	 * @throws ReflectionException
1750
+	 * @since   $VID:$
1751
+	 */
1752
+	public function visibility(): int
1753
+	{
1754
+		return $this->get('TKT_visibility');
1755
+	}
1756
+
1757
+
1758
+	/**
1759
+	 * @return int
1760
+	 * @throws EE_Error
1761
+	 * @throws ReflectionException
1762
+	 * @since   $VID:$
1763
+	 */
1764
+	public function isHidden(): int
1765
+	{
1766
+		return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1767
+	}
1768
+
1769
+
1770
+	/**
1771
+	 * @return int
1772
+	 * @throws EE_Error
1773
+	 * @throws ReflectionException
1774
+	 * @since   $VID:$
1775
+	 */
1776
+	public function isNotHidden(): int
1777
+	{
1778
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1779
+	}
1780
+
1781
+
1782
+	/**
1783
+	 * @return int
1784
+	 * @throws EE_Error
1785
+	 * @throws ReflectionException
1786
+	 * @since   $VID:$
1787
+	 */
1788
+	public function isPublicOnly(): int
1789
+	{
1790
+		return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 * @return int
1796
+	 * @throws EE_Error
1797
+	 * @throws ReflectionException
1798
+	 * @since   $VID:$
1799
+	 */
1800
+	public function isMembersOnly(): int
1801
+	{
1802
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1803
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1804
+	}
1805
+
1806
+
1807
+	/**
1808
+	 * @return int
1809
+	 * @throws EE_Error
1810
+	 * @throws ReflectionException
1811
+	 * @since   $VID:$
1812
+	 */
1813
+	public function isAdminsOnly(): int
1814
+	{
1815
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1816
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1817
+	}
1818
+
1819
+
1820
+	/**
1821
+	 * @return int
1822
+	 * @throws EE_Error
1823
+	 * @throws ReflectionException
1824
+	 * @since   $VID:$
1825
+	 */
1826
+	public function isAdminUiOnly(): int
1827
+	{
1828
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1829
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1830
+	}
1831
+
1832
+
1833
+	/**
1834
+	 * @param int $visibility
1835
+	 * @throws EE_Error
1836
+	 * @throws ReflectionException
1837
+	 * @since   $VID:$
1838
+	 */
1839
+	public function set_visibility(int $visibility)
1840
+	{
1841
+
1842
+		$ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1843
+		$ticket_visibility         = -1;
1844
+		foreach ($ticket_visibility_options as $ticket_visibility_option) {
1845
+			if ($visibility === $ticket_visibility_option) {
1846
+				$ticket_visibility = $visibility;
1847
+			}
1848
+		}
1849
+		if ($ticket_visibility === -1) {
1850
+			throw new DomainException(
1851
+				sprintf(
1852
+					esc_html__(
1853
+						'The supplied ticket visibility setting of "%1$s" is not valid. It needs to match one of the keys in the following array:%2$s %3$s ',
1854
+						'event_espresso'
1855
+					),
1856
+					$visibility,
1857
+					'<br />',
1858
+					var_export($ticket_visibility_options, true)
1859
+				)
1860
+			);
1861
+		}
1862
+		$this->set('TKT_visibility', $ticket_visibility);
1863
+	}
1864
+
1865
+
1866
+	/**
1867
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1868
+	 * @param string                   $relationName
1869
+	 * @param array                    $extra_join_model_fields_n_values
1870
+	 * @param string|null              $cache_id
1871
+	 * @return EE_Base_Class
1872
+	 * @throws EE_Error
1873
+	 * @throws ReflectionException
1874
+	 * @since   $VID:$
1875
+	 */
1876
+	public function _add_relation_to(
1877
+		$otherObjectModelObjectOrID,
1878
+		$relationName,
1879
+		$extra_join_model_fields_n_values = [],
1880
+		$cache_id = null
1881
+	) {
1882
+		if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1883
+			/** @var EE_Datetime $datetime */
1884
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1885
+			$datetime->increaseSold($this->sold(), false);
1886
+			$datetime->increaseReserved($this->reserved());
1887
+			$datetime->save();
1888
+			$otherObjectModelObjectOrID = $datetime;
1889
+		}
1890
+		return parent::_add_relation_to(
1891
+			$otherObjectModelObjectOrID,
1892
+			$relationName,
1893
+			$extra_join_model_fields_n_values,
1894
+			$cache_id
1895
+		);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1901
+	 * @param string                   $relationName
1902
+	 * @param array                    $where_query
1903
+	 * @return bool|EE_Base_Class|null
1904
+	 * @throws EE_Error
1905
+	 * @throws ReflectionException
1906
+	 * @since   $VID:$
1907
+	 */
1908
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1909
+	{
1910
+		// if we're adding a new relation to a datetime
1911
+		if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1912
+			/** @var EE_Datetime $datetime */
1913
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1914
+			$datetime->decreaseSold($this->sold());
1915
+			$datetime->decreaseReserved($this->reserved());
1916
+			$datetime->save();
1917
+			$otherObjectModelObjectOrID = $datetime;
1918
+		}
1919
+		return parent::_remove_relation_to(
1920
+			$otherObjectModelObjectOrID,
1921
+			$relationName,
1922
+			$where_query
1923
+		);
1924
+	}
1925
+
1926
+
1927
+	/**
1928
+	 * Removes ALL the related things for the $relationName.
1929
+	 *
1930
+	 * @param string $relationName
1931
+	 * @param array  $where_query_params
1932
+	 * @return EE_Base_Class
1933
+	 * @throws ReflectionException
1934
+	 * @throws InvalidArgumentException
1935
+	 * @throws InvalidInterfaceException
1936
+	 * @throws InvalidDataTypeException
1937
+	 * @throws EE_Error
1938
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1939
+	 */
1940
+	public function _remove_relations($relationName, $where_query_params = [])
1941
+	{
1942
+		if ($relationName === 'Datetime') {
1943
+			$datetimes = $this->datetimes();
1944
+			foreach ($datetimes as $datetime) {
1945
+				$datetime->decreaseSold($this->sold());
1946
+				$datetime->decreaseReserved($this->reserved());
1947
+				$datetime->save();
1948
+			}
1949
+		}
1950
+		return parent::_remove_relations($relationName, $where_query_params);
1951
+	}
1952
+
1953
+
1954
+	/*******************************************************************
1955 1955
      ***********************  DEPRECATED METHODS  **********************
1956 1956
      *******************************************************************/
1957 1957
 
1958 1958
 
1959
-    /**
1960
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1961
-     * associated datetimes.
1962
-     *
1963
-     * @param int $qty
1964
-     * @return void
1965
-     * @throws EE_Error
1966
-     * @throws InvalidArgumentException
1967
-     * @throws InvalidDataTypeException
1968
-     * @throws InvalidInterfaceException
1969
-     * @throws ReflectionException
1970
-     * @deprecated 4.9.80.p
1971
-     */
1972
-    public function increase_sold($qty = 1)
1973
-    {
1974
-        EE_Error::doing_it_wrong(
1975
-            __FUNCTION__,
1976
-            esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1977
-            '4.9.80.p',
1978
-            '5.0.0.p'
1979
-        );
1980
-        $this->increaseSold($qty);
1981
-    }
1982
-
1983
-
1984
-    /**
1985
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1986
-     *
1987
-     * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1988
-     *                 Negative means to decreases old counts (and increase reserved counts).
1989
-     * @throws EE_Error
1990
-     * @throws InvalidArgumentException
1991
-     * @throws InvalidDataTypeException
1992
-     * @throws InvalidInterfaceException
1993
-     * @throws ReflectionException
1994
-     * @deprecated 4.9.80.p
1995
-     */
1996
-    protected function _increase_sold_for_datetimes($qty)
1997
-    {
1998
-        EE_Error::doing_it_wrong(
1999
-            __FUNCTION__,
2000
-            esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2001
-            '4.9.80.p',
2002
-            '5.0.0.p'
2003
-        );
2004
-        $this->increaseSoldForDatetimes($qty);
2005
-    }
2006
-
2007
-
2008
-    /**
2009
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2010
-     * DB and then updates the model objects.
2011
-     * Does not affect the reserved counts.
2012
-     *
2013
-     * @param int $qty
2014
-     * @return void
2015
-     * @throws EE_Error
2016
-     * @throws InvalidArgumentException
2017
-     * @throws InvalidDataTypeException
2018
-     * @throws InvalidInterfaceException
2019
-     * @throws ReflectionException
2020
-     * @deprecated 4.9.80.p
2021
-     */
2022
-    public function decrease_sold($qty = 1)
2023
-    {
2024
-        EE_Error::doing_it_wrong(
2025
-            __FUNCTION__,
2026
-            esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2027
-            '4.9.80.p',
2028
-            '5.0.0.p'
2029
-        );
2030
-        $this->decreaseSold($qty);
2031
-    }
2032
-
2033
-
2034
-    /**
2035
-     * Decreases sold on related datetimes
2036
-     *
2037
-     * @param int $qty
2038
-     * @return void
2039
-     * @throws EE_Error
2040
-     * @throws InvalidArgumentException
2041
-     * @throws InvalidDataTypeException
2042
-     * @throws InvalidInterfaceException
2043
-     * @throws ReflectionException
2044
-     * @deprecated 4.9.80.p
2045
-     */
2046
-    protected function _decrease_sold_for_datetimes($qty = 1)
2047
-    {
2048
-        EE_Error::doing_it_wrong(
2049
-            __FUNCTION__,
2050
-            esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2051
-            '4.9.80.p',
2052
-            '5.0.0.p'
2053
-        );
2054
-        $this->decreaseSoldForDatetimes($qty);
2055
-    }
2056
-
2057
-
2058
-    /**
2059
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2060
-     *
2061
-     * @param int    $qty
2062
-     * @param string $source
2063
-     * @return bool whether we successfully reserved the ticket or not.
2064
-     * @throws EE_Error
2065
-     * @throws InvalidArgumentException
2066
-     * @throws ReflectionException
2067
-     * @throws InvalidDataTypeException
2068
-     * @throws InvalidInterfaceException
2069
-     * @deprecated 4.9.80.p
2070
-     */
2071
-    public function increase_reserved($qty = 1, $source = 'unknown')
2072
-    {
2073
-        EE_Error::doing_it_wrong(
2074
-            __FUNCTION__,
2075
-            esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2076
-            '4.9.80.p',
2077
-            '5.0.0.p'
2078
-        );
2079
-        return $this->increaseReserved($qty);
2080
-    }
2081
-
2082
-
2083
-    /**
2084
-     * Increases sold on related datetimes
2085
-     *
2086
-     * @param int $qty
2087
-     * @return boolean indicating success
2088
-     * @throws EE_Error
2089
-     * @throws InvalidArgumentException
2090
-     * @throws InvalidDataTypeException
2091
-     * @throws InvalidInterfaceException
2092
-     * @throws ReflectionException
2093
-     * @deprecated 4.9.80.p
2094
-     */
2095
-    protected function _increase_reserved_for_datetimes($qty = 1)
2096
-    {
2097
-        EE_Error::doing_it_wrong(
2098
-            __FUNCTION__,
2099
-            esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2100
-            '4.9.80.p',
2101
-            '5.0.0.p'
2102
-        );
2103
-        return $this->increaseReservedForDatetimes($qty);
2104
-    }
2105
-
2106
-
2107
-    /**
2108
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2109
-     *
2110
-     * @param int    $qty
2111
-     * @param bool   $adjust_datetimes
2112
-     * @param string $source
2113
-     * @return void
2114
-     * @throws EE_Error
2115
-     * @throws InvalidArgumentException
2116
-     * @throws ReflectionException
2117
-     * @throws InvalidDataTypeException
2118
-     * @throws InvalidInterfaceException
2119
-     * @deprecated 4.9.80.p
2120
-     */
2121
-    public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2122
-    {
2123
-        EE_Error::doing_it_wrong(
2124
-            __FUNCTION__,
2125
-            esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2126
-            '4.9.80.p',
2127
-            '5.0.0.p'
2128
-        );
2129
-        $this->decreaseReserved($qty);
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Decreases reserved on related datetimes
2135
-     *
2136
-     * @param int $qty
2137
-     * @return void
2138
-     * @throws EE_Error
2139
-     * @throws InvalidArgumentException
2140
-     * @throws ReflectionException
2141
-     * @throws InvalidDataTypeException
2142
-     * @throws InvalidInterfaceException
2143
-     * @deprecated 4.9.80.p
2144
-     */
2145
-    protected function _decrease_reserved_for_datetimes($qty = 1)
2146
-    {
2147
-        EE_Error::doing_it_wrong(
2148
-            __FUNCTION__,
2149
-            esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2150
-            '4.9.80.p',
2151
-            '5.0.0.p'
2152
-        );
2153
-        $this->decreaseReservedForDatetimes($qty);
2154
-    }
1959
+	/**
1960
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1961
+	 * associated datetimes.
1962
+	 *
1963
+	 * @param int $qty
1964
+	 * @return void
1965
+	 * @throws EE_Error
1966
+	 * @throws InvalidArgumentException
1967
+	 * @throws InvalidDataTypeException
1968
+	 * @throws InvalidInterfaceException
1969
+	 * @throws ReflectionException
1970
+	 * @deprecated 4.9.80.p
1971
+	 */
1972
+	public function increase_sold($qty = 1)
1973
+	{
1974
+		EE_Error::doing_it_wrong(
1975
+			__FUNCTION__,
1976
+			esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1977
+			'4.9.80.p',
1978
+			'5.0.0.p'
1979
+		);
1980
+		$this->increaseSold($qty);
1981
+	}
1982
+
1983
+
1984
+	/**
1985
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1986
+	 *
1987
+	 * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1988
+	 *                 Negative means to decreases old counts (and increase reserved counts).
1989
+	 * @throws EE_Error
1990
+	 * @throws InvalidArgumentException
1991
+	 * @throws InvalidDataTypeException
1992
+	 * @throws InvalidInterfaceException
1993
+	 * @throws ReflectionException
1994
+	 * @deprecated 4.9.80.p
1995
+	 */
1996
+	protected function _increase_sold_for_datetimes($qty)
1997
+	{
1998
+		EE_Error::doing_it_wrong(
1999
+			__FUNCTION__,
2000
+			esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2001
+			'4.9.80.p',
2002
+			'5.0.0.p'
2003
+		);
2004
+		$this->increaseSoldForDatetimes($qty);
2005
+	}
2006
+
2007
+
2008
+	/**
2009
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2010
+	 * DB and then updates the model objects.
2011
+	 * Does not affect the reserved counts.
2012
+	 *
2013
+	 * @param int $qty
2014
+	 * @return void
2015
+	 * @throws EE_Error
2016
+	 * @throws InvalidArgumentException
2017
+	 * @throws InvalidDataTypeException
2018
+	 * @throws InvalidInterfaceException
2019
+	 * @throws ReflectionException
2020
+	 * @deprecated 4.9.80.p
2021
+	 */
2022
+	public function decrease_sold($qty = 1)
2023
+	{
2024
+		EE_Error::doing_it_wrong(
2025
+			__FUNCTION__,
2026
+			esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2027
+			'4.9.80.p',
2028
+			'5.0.0.p'
2029
+		);
2030
+		$this->decreaseSold($qty);
2031
+	}
2032
+
2033
+
2034
+	/**
2035
+	 * Decreases sold on related datetimes
2036
+	 *
2037
+	 * @param int $qty
2038
+	 * @return void
2039
+	 * @throws EE_Error
2040
+	 * @throws InvalidArgumentException
2041
+	 * @throws InvalidDataTypeException
2042
+	 * @throws InvalidInterfaceException
2043
+	 * @throws ReflectionException
2044
+	 * @deprecated 4.9.80.p
2045
+	 */
2046
+	protected function _decrease_sold_for_datetimes($qty = 1)
2047
+	{
2048
+		EE_Error::doing_it_wrong(
2049
+			__FUNCTION__,
2050
+			esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2051
+			'4.9.80.p',
2052
+			'5.0.0.p'
2053
+		);
2054
+		$this->decreaseSoldForDatetimes($qty);
2055
+	}
2056
+
2057
+
2058
+	/**
2059
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2060
+	 *
2061
+	 * @param int    $qty
2062
+	 * @param string $source
2063
+	 * @return bool whether we successfully reserved the ticket or not.
2064
+	 * @throws EE_Error
2065
+	 * @throws InvalidArgumentException
2066
+	 * @throws ReflectionException
2067
+	 * @throws InvalidDataTypeException
2068
+	 * @throws InvalidInterfaceException
2069
+	 * @deprecated 4.9.80.p
2070
+	 */
2071
+	public function increase_reserved($qty = 1, $source = 'unknown')
2072
+	{
2073
+		EE_Error::doing_it_wrong(
2074
+			__FUNCTION__,
2075
+			esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2076
+			'4.9.80.p',
2077
+			'5.0.0.p'
2078
+		);
2079
+		return $this->increaseReserved($qty);
2080
+	}
2081
+
2082
+
2083
+	/**
2084
+	 * Increases sold on related datetimes
2085
+	 *
2086
+	 * @param int $qty
2087
+	 * @return boolean indicating success
2088
+	 * @throws EE_Error
2089
+	 * @throws InvalidArgumentException
2090
+	 * @throws InvalidDataTypeException
2091
+	 * @throws InvalidInterfaceException
2092
+	 * @throws ReflectionException
2093
+	 * @deprecated 4.9.80.p
2094
+	 */
2095
+	protected function _increase_reserved_for_datetimes($qty = 1)
2096
+	{
2097
+		EE_Error::doing_it_wrong(
2098
+			__FUNCTION__,
2099
+			esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2100
+			'4.9.80.p',
2101
+			'5.0.0.p'
2102
+		);
2103
+		return $this->increaseReservedForDatetimes($qty);
2104
+	}
2105
+
2106
+
2107
+	/**
2108
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2109
+	 *
2110
+	 * @param int    $qty
2111
+	 * @param bool   $adjust_datetimes
2112
+	 * @param string $source
2113
+	 * @return void
2114
+	 * @throws EE_Error
2115
+	 * @throws InvalidArgumentException
2116
+	 * @throws ReflectionException
2117
+	 * @throws InvalidDataTypeException
2118
+	 * @throws InvalidInterfaceException
2119
+	 * @deprecated 4.9.80.p
2120
+	 */
2121
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2122
+	{
2123
+		EE_Error::doing_it_wrong(
2124
+			__FUNCTION__,
2125
+			esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2126
+			'4.9.80.p',
2127
+			'5.0.0.p'
2128
+		);
2129
+		$this->decreaseReserved($qty);
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Decreases reserved on related datetimes
2135
+	 *
2136
+	 * @param int $qty
2137
+	 * @return void
2138
+	 * @throws EE_Error
2139
+	 * @throws InvalidArgumentException
2140
+	 * @throws ReflectionException
2141
+	 * @throws InvalidDataTypeException
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @deprecated 4.9.80.p
2144
+	 */
2145
+	protected function _decrease_reserved_for_datetimes($qty = 1)
2146
+	{
2147
+		EE_Error::doing_it_wrong(
2148
+			__FUNCTION__,
2149
+			esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2150
+			'4.9.80.p',
2151
+			'5.0.0.p'
2152
+		);
2153
+		$this->decreaseReservedForDatetimes($qty);
2154
+	}
2155 2155
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3368 added lines, -3368 removed lines patch added patch discarded remove patch
@@ -13,3384 +13,3384 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_Base_Class
15 15
 {
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_tm_frmt;
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            [$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            // should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            // if we're not in the constructor...
334
-            // now check if what we set was a primary key
335
-            if (
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_tm_frmt;
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			[$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (
254
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			// should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			// if we're not in the constructor...
334
+			// now check if what we set was a primary key
335
+			if (
336 336
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                // if so, we want all this object's fields to be filled either with
342
-                // what we've explicitly set on this model
343
-                // or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (
349
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
-                        && $field_obj->get_name() !== $field_name
351
-                    ) {
352
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
-                    }
354
-                }
355
-                // oh this model object has an ID? well make sure its in the entity mapper
356
-                $model->add_to_entity_map($this);
357
-            }
358
-            // let's unset any cache for this field_name from the $_cached_properties property.
359
-            $this->_clear_cached_property($field_name);
360
-        } else {
361
-            throw new EE_Error(
362
-                sprintf(
363
-                    esc_html__(
364
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
-                        'event_espresso'
366
-                    ),
367
-                    $field_name
368
-                )
369
-            );
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Set custom select values for model.
376
-     *
377
-     * @param array $custom_select_values
378
-     */
379
-    public function setCustomSelectsValues(array $custom_select_values)
380
-    {
381
-        $this->custom_selection_results = $custom_select_values;
382
-    }
383
-
384
-
385
-    /**
386
-     * Returns the custom select value for the provided alias if its set.
387
-     * If not set, returns null.
388
-     *
389
-     * @param string $alias
390
-     * @return string|int|float|null
391
-     */
392
-    public function getCustomSelect($alias)
393
-    {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
396
-            : null;
397
-    }
398
-
399
-
400
-    /**
401
-     * This sets the field value on the db column if it exists for the given $column_name or
402
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
-     *
404
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     */
414
-    public function set_field_or_extra_meta($field_name, $field_value)
415
-    {
416
-        if ($this->get_model()->has_field($field_name)) {
417
-            $this->set($field_name, $field_value);
418
-            return true;
419
-        }
420
-        // ensure this object is saved first so that extra meta can be properly related.
421
-        $this->save();
422
-        return $this->update_extra_meta($field_name, $field_value);
423
-    }
424
-
425
-
426
-    /**
427
-     * This retrieves the value of the db column set on this class or if that's not present
428
-     * it will attempt to retrieve from extra_meta if found.
429
-     * Example Usage:
430
-     * Via EE_Message child class:
431
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
434
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
-     * value for those extra fields dynamically via the EE_message object.
436
-     *
437
-     * @param  string $field_name expecting the fully qualified field name.
438
-     * @return mixed|null  value for the field if found.  null if not found.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function get_field_or_extra_meta($field_name)
446
-    {
447
-        if ($this->get_model()->has_field($field_name)) {
448
-            $column_value = $this->get($field_name);
449
-        } else {
450
-            // This isn't a column in the main table, let's see if it is in the extra meta.
451
-            $column_value = $this->get_extra_meta($field_name, true, null);
452
-        }
453
-        return $column_value;
454
-    }
455
-
456
-
457
-    /**
458
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
-     *
463
-     * @access public
464
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
-     * @return void
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidInterfaceException
468
-     * @throws InvalidDataTypeException
469
-     * @throws EE_Error
470
-     * @throws ReflectionException
471
-     */
472
-    public function set_timezone($timezone = '')
473
-    {
474
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
-        // make sure we clear all cached properties because they won't be relevant now
476
-        $this->_clear_cached_properties();
477
-        // make sure we update field settings and the date for all EE_Datetime_Fields
478
-        $model_fields = $this->get_model()->field_settings(false);
479
-        foreach ($model_fields as $field_name => $field_obj) {
480
-            if ($field_obj instanceof EE_Datetime_Field) {
481
-                $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
-                }
485
-            }
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     * This just returns whatever is set for the current timezone.
492
-     *
493
-     * @access public
494
-     * @return string timezone string
495
-     */
496
-    public function get_timezone()
497
-    {
498
-        return $this->_timezone;
499
-    }
500
-
501
-
502
-    /**
503
-     * This sets the internal date format to what is sent in to be used as the new default for the class
504
-     * internally instead of wp set date format options
505
-     *
506
-     * @since 4.6
507
-     * @param string $format should be a format recognizable by PHP date() functions.
508
-     */
509
-    public function set_date_format($format)
510
-    {
511
-        $this->_dt_frmt = $format;
512
-        // clear cached_properties because they won't be relevant now.
513
-        $this->_clear_cached_properties();
514
-    }
515
-
516
-
517
-    /**
518
-     * This sets the internal time format string to what is sent in to be used as the new default for the
519
-     * class internally instead of wp set time format options.
520
-     *
521
-     * @since 4.6
522
-     * @param string $format should be a format recognizable by PHP date() functions.
523
-     */
524
-    public function set_time_format($format)
525
-    {
526
-        $this->_tm_frmt = $format;
527
-        // clear cached_properties because they won't be relevant now.
528
-        $this->_clear_cached_properties();
529
-    }
530
-
531
-
532
-    /**
533
-     * This returns the current internal set format for the date and time formats.
534
-     *
535
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
-     *                             where the first value is the date format and the second value is the time format.
537
-     * @return mixed string|array
538
-     */
539
-    public function get_format($full = true)
540
-    {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
-    }
543
-
544
-
545
-    /**
546
-     * cache
547
-     * stores the passed model object on the current model object.
548
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
-     *
550
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
-     *                                       'Registration' associated with this model object
552
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
-     *                                       that could be a payment or a registration)
554
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
-     *                                       items which will be stored in an array on this object
556
-     * @throws ReflectionException
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
-     *                                       related thing, no array)
563
-     */
564
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
-    {
566
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
568
-            return false;
569
-        }
570
-        // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
-            throw new EE_Error(
573
-                sprintf(
574
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
-                    $relationName,
576
-                    get_class($this)
577
-                )
578
-            );
579
-        }
580
-        // how many things are related ?
581
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
-            // if it's a "belongs to" relationship, then there's only one related model object
583
-            // eg, if this is a registration, there's only 1 attendee for it
584
-            // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
586
-            $return = true;
587
-        } else {
588
-            // otherwise, this is the "many" side of a one to many relationship,
589
-            // so we'll add the object to the array of related objects for that type.
590
-            // eg: if this is an event, there are many registrations for that event,
591
-            // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
593
-                // if for some reason, the cached item is a model object,
594
-                // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
-                                                           instanceof
597
-                                                           EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
599
-            }
600
-            // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
602
-                // if the cache_id exists, then it means we are purposely trying to cache this
603
-                // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
-                $return = $cache_id;
606
-            } elseif ($object_to_cache->ID()) {
607
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
-                $return = $object_to_cache->ID();
610
-            } else {
611
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
613
-                // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
615
-                // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
617
-            }
618
-        }
619
-        return $return;
620
-    }
621
-
622
-
623
-    /**
624
-     * For adding an item to the cached_properties property.
625
-     *
626
-     * @access protected
627
-     * @param string      $fieldname the property item the corresponding value is for.
628
-     * @param mixed       $value     The value we are caching.
629
-     * @param string|null $cache_type
630
-     * @return void
631
-     * @throws ReflectionException
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     */
637
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
-    {
639
-        // first make sure this property exists
640
-        $this->get_model()->field_settings_for($fieldname);
641
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
-    }
644
-
645
-
646
-    /**
647
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
-     * This also SETS the cache if we return the actual property!
649
-     *
650
-     * @param string $fieldname        the name of the property we're trying to retrieve
651
-     * @param bool   $pretty
652
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
-     *                                 (in cases where the same property may be used for different outputs
654
-     *                                 - i.e. datetime, money etc.)
655
-     *                                 It can also accept certain pre-defined "schema" strings
656
-     *                                 to define how to output the property.
657
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
-     * @return mixed                   whatever the value for the property is we're retrieving
659
-     * @throws ReflectionException
660
-     * @throws InvalidArgumentException
661
-     * @throws InvalidInterfaceException
662
-     * @throws InvalidDataTypeException
663
-     * @throws EE_Error
664
-     */
665
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
-    {
667
-        // verify the field exists
668
-        $model = $this->get_model();
669
-        $model->field_settings_for($fieldname);
670
-        $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
-        }
675
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
-        $this->_set_cached_property($fieldname, $value, $cache_type);
677
-        return $value;
678
-    }
679
-
680
-
681
-    /**
682
-     * If the cache didn't fetch the needed item, this fetches it.
683
-     *
684
-     * @param string $fieldname
685
-     * @param bool   $pretty
686
-     * @param string $extra_cache_ref
687
-     * @return mixed
688
-     * @throws InvalidArgumentException
689
-     * @throws InvalidInterfaceException
690
-     * @throws InvalidDataTypeException
691
-     * @throws EE_Error
692
-     * @throws ReflectionException
693
-     */
694
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
-    {
696
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
697
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
-        if ($field_obj instanceof EE_Datetime_Field) {
699
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
-        }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
703
-        }
704
-        return $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
-    }
708
-
709
-
710
-    /**
711
-     * set timezone, formats, and output for EE_Datetime_Field objects
712
-     *
713
-     * @param EE_Datetime_Field $datetime_field
714
-     * @param bool              $pretty
715
-     * @param null              $date_or_time
716
-     * @return void
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidInterfaceException
719
-     * @throws InvalidDataTypeException
720
-     */
721
-    protected function _prepare_datetime_field(
722
-        EE_Datetime_Field $datetime_field,
723
-        $pretty = false,
724
-        $date_or_time = null
725
-    ) {
726
-        $datetime_field->set_timezone($this->_timezone);
727
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
728
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
729
-        // set the output returned
730
-        switch ($date_or_time) {
731
-            case 'D':
732
-                $datetime_field->set_date_time_output('date');
733
-                break;
734
-            case 'T':
735
-                $datetime_field->set_date_time_output('time');
736
-                break;
737
-            default:
738
-                $datetime_field->set_date_time_output();
739
-        }
740
-    }
741
-
742
-
743
-    /**
744
-     * This just takes care of clearing out the cached_properties
745
-     *
746
-     * @return void
747
-     */
748
-    protected function _clear_cached_properties()
749
-    {
750
-        $this->_cached_properties = array();
751
-    }
752
-
753
-
754
-    /**
755
-     * This just clears out ONE property if it exists in the cache
756
-     *
757
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
758
-     * @return void
759
-     */
760
-    protected function _clear_cached_property($property_name)
761
-    {
762
-        if (isset($this->_cached_properties[ $property_name ])) {
763
-            unset($this->_cached_properties[ $property_name ]);
764
-        }
765
-    }
766
-
767
-
768
-    /**
769
-     * Ensures that this related thing is a model object.
770
-     *
771
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
772
-     * @param string $model_name   name of the related thing, eg 'Attendee',
773
-     * @return EE_Base_Class
774
-     * @throws ReflectionException
775
-     * @throws InvalidArgumentException
776
-     * @throws InvalidInterfaceException
777
-     * @throws InvalidDataTypeException
778
-     * @throws EE_Error
779
-     */
780
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
781
-    {
782
-        $other_model_instance = self::_get_model_instance_with_name(
783
-            self::_get_model_classname($model_name),
784
-            $this->_timezone
785
-        );
786
-        return $other_model_instance->ensure_is_obj($object_or_id);
787
-    }
788
-
789
-
790
-    /**
791
-     * Forgets the cached model of the given relation Name. So the next time we request it,
792
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
793
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
794
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
795
-     *
796
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
797
-     *                                                     Eg 'Registration'
798
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
799
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
800
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
801
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
802
-     *                                                     this is HasMany or HABTM.
803
-     * @throws ReflectionException
804
-     * @throws InvalidArgumentException
805
-     * @throws InvalidInterfaceException
806
-     * @throws InvalidDataTypeException
807
-     * @throws EE_Error
808
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
809
-     *                                                     relation from all
810
-     */
811
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
812
-    {
813
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
814
-        $index_in_cache = '';
815
-        if (! $relationship_to_model) {
816
-            throw new EE_Error(
817
-                sprintf(
818
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
819
-                    $relationName,
820
-                    get_class($this)
821
-                )
822
-            );
823
-        }
824
-        if ($clear_all) {
825
-            $obj_removed = true;
826
-            $this->_model_relations[ $relationName ] = null;
827
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
-            $obj_removed = $this->_model_relations[ $relationName ];
829
-            $this->_model_relations[ $relationName ] = null;
830
-        } else {
831
-            if (
832
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
833
-                && $object_to_remove_or_index_into_array->ID()
834
-            ) {
835
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
836
-                if (
837
-                    is_array($this->_model_relations[ $relationName ])
838
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
-                ) {
840
-                    $index_found_at = null;
841
-                    // find this object in the array even though it has a different key
842
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
843
-                        /** @noinspection TypeUnsafeComparisonInspection */
844
-                        if (
845
-                            $obj instanceof EE_Base_Class
846
-                            && (
847
-                                $obj == $object_to_remove_or_index_into_array
848
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
849
-                            )
850
-                        ) {
851
-                            $index_found_at = $index;
852
-                            break;
853
-                        }
854
-                    }
855
-                    if ($index_found_at) {
856
-                        $index_in_cache = $index_found_at;
857
-                    } else {
858
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
859
-                        // if it wasn't in it to begin with. So we're done
860
-                        return $object_to_remove_or_index_into_array;
861
-                    }
862
-                }
863
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
864
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
865
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
866
-                    /** @noinspection TypeUnsafeComparisonInspection */
867
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
868
-                        $index_in_cache = $index;
869
-                    }
870
-                }
871
-            } else {
872
-                $index_in_cache = $object_to_remove_or_index_into_array;
873
-            }
874
-            // supposedly we've found it. But it could just be that the client code
875
-            // provided a bad index/object
876
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
879
-            } else {
880
-                // that thing was never cached anyways.
881
-                $obj_removed = null;
882
-            }
883
-        }
884
-        return $obj_removed;
885
-    }
886
-
887
-
888
-    /**
889
-     * update_cache_after_object_save
890
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
891
-     * obtained after being saved to the db
892
-     *
893
-     * @param string        $relationName       - the type of object that is cached
894
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
895
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
896
-     * @return boolean TRUE on success, FALSE on fail
897
-     * @throws ReflectionException
898
-     * @throws InvalidArgumentException
899
-     * @throws InvalidInterfaceException
900
-     * @throws InvalidDataTypeException
901
-     * @throws EE_Error
902
-     */
903
-    public function update_cache_after_object_save(
904
-        $relationName,
905
-        EE_Base_Class $newly_saved_object,
906
-        $current_cache_id = ''
907
-    ) {
908
-        // verify that incoming object is of the correct type
909
-        $obj_class = 'EE_' . $relationName;
910
-        if ($newly_saved_object instanceof $obj_class) {
911
-            /* @type EE_Base_Class $newly_saved_object */
912
-            // now get the type of relation
913
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
914
-            // if this is a 1:1 relationship
915
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916
-                // then just replace the cached object with the newly saved object
917
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
918
-                return true;
919
-                // or if it's some kind of sordid feral polyamorous relationship...
920
-            }
921
-            if (
922
-                is_array($this->_model_relations[ $relationName ])
923
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
-            ) {
925
-                // then remove the current cached item
926
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
-                // and cache the newly saved object using it's new ID
928
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
-                return true;
930
-            }
931
-        }
932
-        return false;
933
-    }
934
-
935
-
936
-    /**
937
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
938
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
939
-     *
940
-     * @param string $relationName
941
-     * @return EE_Base_Class
942
-     */
943
-    public function get_one_from_cache($relationName)
944
-    {
945
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
-            ? $this->_model_relations[ $relationName ]
947
-            : null;
948
-        if (is_array($cached_array_or_object)) {
949
-            return array_shift($cached_array_or_object);
950
-        }
951
-        return $cached_array_or_object;
952
-    }
953
-
954
-
955
-    /**
956
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
957
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
958
-     *
959
-     * @param string $relationName
960
-     * @throws ReflectionException
961
-     * @throws InvalidArgumentException
962
-     * @throws InvalidInterfaceException
963
-     * @throws InvalidDataTypeException
964
-     * @throws EE_Error
965
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
966
-     */
967
-    public function get_all_from_cache($relationName)
968
-    {
969
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
-        // if the result is not an array, but exists, make it an array
971
-        $objects = is_array($objects) ? $objects : array($objects);
972
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
973
-        // basically, if this model object was stored in the session, and these cached model objects
974
-        // already have IDs, let's make sure they're in their model's entity mapper
975
-        // otherwise we will have duplicates next time we call
976
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
977
-        $model = EE_Registry::instance()->load_model($relationName);
978
-        foreach ($objects as $model_object) {
979
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
980
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
981
-                if ($model_object->ID()) {
982
-                    $model->add_to_entity_map($model_object);
983
-                }
984
-            } else {
985
-                throw new EE_Error(
986
-                    sprintf(
987
-                        esc_html__(
988
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
989
-                            'event_espresso'
990
-                        ),
991
-                        $relationName,
992
-                        gettype($model_object)
993
-                    )
994
-                );
995
-            }
996
-        }
997
-        return $objects;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1003
-     * matching the given query conditions.
1004
-     *
1005
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1006
-     * @param int   $limit              How many objects to return.
1007
-     * @param array $query_params       Any additional conditions on the query.
1008
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1009
-     *                                  you can indicate just the columns you want returned
1010
-     * @return array|EE_Base_Class[]
1011
-     * @throws ReflectionException
1012
-     * @throws InvalidArgumentException
1013
-     * @throws InvalidInterfaceException
1014
-     * @throws InvalidDataTypeException
1015
-     * @throws EE_Error
1016
-     */
1017
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1018
-    {
1019
-        $model = $this->get_model();
1020
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1021
-            ? $model->get_primary_key_field()->get_name()
1022
-            : $field_to_order_by;
1023
-        $current_value = ! empty($field) ? $this->get($field) : null;
1024
-        if (empty($field) || empty($current_value)) {
1025
-            return array();
1026
-        }
1027
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1028
-    }
1029
-
1030
-
1031
-    /**
1032
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1033
-     * matching the given query conditions.
1034
-     *
1035
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1036
-     * @param int   $limit              How many objects to return.
1037
-     * @param array $query_params       Any additional conditions on the query.
1038
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1039
-     *                                  you can indicate just the columns you want returned
1040
-     * @return array|EE_Base_Class[]
1041
-     * @throws ReflectionException
1042
-     * @throws InvalidArgumentException
1043
-     * @throws InvalidInterfaceException
1044
-     * @throws InvalidDataTypeException
1045
-     * @throws EE_Error
1046
-     */
1047
-    public function previous_x(
1048
-        $field_to_order_by = null,
1049
-        $limit = 1,
1050
-        $query_params = array(),
1051
-        $columns_to_select = null
1052
-    ) {
1053
-        $model = $this->get_model();
1054
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1055
-            ? $model->get_primary_key_field()->get_name()
1056
-            : $field_to_order_by;
1057
-        $current_value = ! empty($field) ? $this->get($field) : null;
1058
-        if (empty($field) || empty($current_value)) {
1059
-            return array();
1060
-        }
1061
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1062
-    }
1063
-
1064
-
1065
-    /**
1066
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1067
-     * matching the given query conditions.
1068
-     *
1069
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1070
-     * @param array $query_params       Any additional conditions on the query.
1071
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1072
-     *                                  you can indicate just the columns you want returned
1073
-     * @return array|EE_Base_Class
1074
-     * @throws ReflectionException
1075
-     * @throws InvalidArgumentException
1076
-     * @throws InvalidInterfaceException
1077
-     * @throws InvalidDataTypeException
1078
-     * @throws EE_Error
1079
-     */
1080
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1081
-    {
1082
-        $model = $this->get_model();
1083
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1084
-            ? $model->get_primary_key_field()->get_name()
1085
-            : $field_to_order_by;
1086
-        $current_value = ! empty($field) ? $this->get($field) : null;
1087
-        if (empty($field) || empty($current_value)) {
1088
-            return array();
1089
-        }
1090
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1096
-     * matching the given query conditions.
1097
-     *
1098
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1099
-     * @param array $query_params       Any additional conditions on the query.
1100
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1101
-     *                                  you can indicate just the column you want returned
1102
-     * @return array|EE_Base_Class
1103
-     * @throws ReflectionException
1104
-     * @throws InvalidArgumentException
1105
-     * @throws InvalidInterfaceException
1106
-     * @throws InvalidDataTypeException
1107
-     * @throws EE_Error
1108
-     */
1109
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1110
-    {
1111
-        $model = $this->get_model();
1112
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1113
-            ? $model->get_primary_key_field()->get_name()
1114
-            : $field_to_order_by;
1115
-        $current_value = ! empty($field) ? $this->get($field) : null;
1116
-        if (empty($field) || empty($current_value)) {
1117
-            return array();
1118
-        }
1119
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1120
-    }
1121
-
1122
-
1123
-    /**
1124
-     * Overrides parent because parent expects old models.
1125
-     * This also doesn't do any validation, and won't work for serialized arrays
1126
-     *
1127
-     * @param string $field_name
1128
-     * @param mixed  $field_value_from_db
1129
-     * @throws ReflectionException
1130
-     * @throws InvalidArgumentException
1131
-     * @throws InvalidInterfaceException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws EE_Error
1134
-     */
1135
-    public function set_from_db($field_name, $field_value_from_db)
1136
-    {
1137
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1138
-        if ($field_obj instanceof EE_Model_Field_Base) {
1139
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1140
-            // eg, a CPT model object could have an entry in the posts table, but no
1141
-            // entry in the meta table. Meaning that all its columns in the meta table
1142
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1143
-            if ($field_value_from_db === null) {
1144
-                if ($field_obj->is_nullable()) {
1145
-                    // if the field allows nulls, then let it be null
1146
-                    $field_value = null;
1147
-                } else {
1148
-                    $field_value = $field_obj->get_default_value();
1149
-                }
1150
-            } else {
1151
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152
-            }
1153
-            $this->_fields[ $field_name ] = $field_value;
1154
-            $this->_clear_cached_property($field_name);
1155
-        }
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * verifies that the specified field is of the correct type
1161
-     *
1162
-     * @param string $field_name
1163
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
-     *                                (in cases where the same property may be used for different outputs
1165
-     *                                - i.e. datetime, money etc.)
1166
-     * @return mixed
1167
-     * @throws ReflectionException
1168
-     * @throws InvalidArgumentException
1169
-     * @throws InvalidInterfaceException
1170
-     * @throws InvalidDataTypeException
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function get($field_name, $extra_cache_ref = null)
1174
-    {
1175
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * This method simply returns the RAW unprocessed value for the given property in this class
1181
-     *
1182
-     * @param  string $field_name A valid fieldname
1183
-     * @return mixed              Whatever the raw value stored on the property is.
1184
-     * @throws ReflectionException
1185
-     * @throws InvalidArgumentException
1186
-     * @throws InvalidInterfaceException
1187
-     * @throws InvalidDataTypeException
1188
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1189
-     */
1190
-    public function get_raw($field_name)
1191
-    {
1192
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1193
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
-            ? $this->_fields[ $field_name ]->format('U')
1195
-            : $this->_fields[ $field_name ];
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * This is used to return the internal DateTime object used for a field that is a
1201
-     * EE_Datetime_Field.
1202
-     *
1203
-     * @param string $field_name               The field name retrieving the DateTime object.
1204
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1205
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1206
-     *                                         EE_Datetime_Field and but the field value is null, then
1207
-     *                                         just null is returned (because that indicates that likely
1208
-     *                                         this field is nullable).
1209
-     * @throws InvalidArgumentException
1210
-     * @throws InvalidDataTypeException
1211
-     * @throws InvalidInterfaceException
1212
-     * @throws ReflectionException
1213
-     */
1214
-    public function get_DateTime_object($field_name)
1215
-    {
1216
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1217
-        if (! $field_settings instanceof EE_Datetime_Field) {
1218
-            EE_Error::add_error(
1219
-                sprintf(
1220
-                    esc_html__(
1221
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1222
-                        'event_espresso'
1223
-                    ),
1224
-                    $field_name
1225
-                ),
1226
-                __FILE__,
1227
-                __FUNCTION__,
1228
-                __LINE__
1229
-            );
1230
-            return false;
1231
-        }
1232
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
-            ? clone $this->_fields[ $field_name ]
1234
-            : null;
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * To be used in template to immediately echo out the value, and format it for output.
1240
-     * Eg, should call stripslashes and whatnot before echoing
1241
-     *
1242
-     * @param string $field_name      the name of the field as it appears in the DB
1243
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1244
-     *                                (in cases where the same property may be used for different outputs
1245
-     *                                - i.e. datetime, money etc.)
1246
-     * @return void
1247
-     * @throws ReflectionException
1248
-     * @throws InvalidArgumentException
1249
-     * @throws InvalidInterfaceException
1250
-     * @throws InvalidDataTypeException
1251
-     * @throws EE_Error
1252
-     */
1253
-    public function e($field_name, $extra_cache_ref = null)
1254
-    {
1255
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1256
-    }
1257
-
1258
-
1259
-    /**
1260
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1261
-     * can be easily used as the value of form input.
1262
-     *
1263
-     * @param string $field_name
1264
-     * @return void
1265
-     * @throws ReflectionException
1266
-     * @throws InvalidArgumentException
1267
-     * @throws InvalidInterfaceException
1268
-     * @throws InvalidDataTypeException
1269
-     * @throws EE_Error
1270
-     */
1271
-    public function f($field_name)
1272
-    {
1273
-        $this->e($field_name, 'form_input');
1274
-    }
1275
-
1276
-
1277
-    /**
1278
-     * Same as `f()` but just returns the value instead of echoing it
1279
-     *
1280
-     * @param string $field_name
1281
-     * @return string
1282
-     * @throws ReflectionException
1283
-     * @throws InvalidArgumentException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws InvalidDataTypeException
1286
-     * @throws EE_Error
1287
-     */
1288
-    public function get_f($field_name)
1289
-    {
1290
-        return (string) $this->get_pretty($field_name, 'form_input');
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1296
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1297
-     * to see what options are available.
1298
-     *
1299
-     * @param string $field_name
1300
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1301
-     *                                (in cases where the same property may be used for different outputs
1302
-     *                                - i.e. datetime, money etc.)
1303
-     * @return mixed
1304
-     * @throws ReflectionException
1305
-     * @throws InvalidArgumentException
1306
-     * @throws InvalidInterfaceException
1307
-     * @throws InvalidDataTypeException
1308
-     * @throws EE_Error
1309
-     */
1310
-    public function get_pretty($field_name, $extra_cache_ref = null)
1311
-    {
1312
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * This simply returns the datetime for the given field name
1318
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1319
-     * (and the equivalent e_date, e_time, e_datetime).
1320
-     *
1321
-     * @access   protected
1322
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1323
-     * @param string|null $date_format  valid datetime format used for date
1324
-     *                                  (if '' then we just use the default on the field,
1325
-     *                                  if NULL we use the last-used format)
1326
-     * @param string|null $time_format  Same as above except this is for time format
1327
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1328
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1329
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1330
-     *                                  if field is not a valid dtt field, or void if echoing
1331
-     * @throws EE_Error
1332
-     * @throws ReflectionException
1333
-     */
1334
-    protected function _get_datetime(
1335
-        string $field_name,
1336
-        ?string $date_format = '',
1337
-        ?string $time_format = '',
1338
-        ?string $date_or_time = '',
1339
-        ?bool $echo = false
1340
-    ) {
1341
-        // clear cached property
1342
-        $this->_clear_cached_property($field_name);
1343
-        // reset format properties because they are used in get()
1344
-        $this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1345
-        $this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1346
-        if ($echo) {
1347
-            $this->e($field_name, $date_or_time);
1348
-            return '';
1349
-        }
1350
-        return $this->get($field_name, $date_or_time);
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
-     * other echoes the pretty value for dtt)
1358
-     *
1359
-     * @param  string $field_name name of model object datetime field holding the value
1360
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
-     * @return string            datetime value formatted
1362
-     * @throws ReflectionException
1363
-     * @throws InvalidArgumentException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws InvalidDataTypeException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_date($field_name, $format = '')
1369
-    {
1370
-        return $this->_get_datetime($field_name, $format, null, 'D');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @param        $field_name
1376
-     * @param string $format
1377
-     * @throws ReflectionException
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws InvalidDataTypeException
1381
-     * @throws EE_Error
1382
-     */
1383
-    public function e_date($field_name, $format = '')
1384
-    {
1385
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
-     * other echoes the pretty value for dtt)
1393
-     *
1394
-     * @param  string $field_name name of model object datetime field holding the value
1395
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
-     * @return string             datetime value formatted
1397
-     * @throws ReflectionException
1398
-     * @throws InvalidArgumentException
1399
-     * @throws InvalidInterfaceException
1400
-     * @throws InvalidDataTypeException
1401
-     * @throws EE_Error
1402
-     */
1403
-    public function get_time($field_name, $format = '')
1404
-    {
1405
-        return $this->_get_datetime($field_name, null, $format, 'T');
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * @param        $field_name
1411
-     * @param string $format
1412
-     * @throws ReflectionException
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws InvalidDataTypeException
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function e_time($field_name, $format = '')
1419
-    {
1420
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
-     * other echoes the pretty value for dtt)
1428
-     *
1429
-     * @param  string $field_name name of model object datetime field holding the value
1430
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
-     * @return string             datetime value formatted
1433
-     * @throws ReflectionException
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidInterfaceException
1436
-     * @throws InvalidDataTypeException
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
-    {
1441
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * @param string $field_name
1447
-     * @param string $dt_frmt
1448
-     * @param string $tm_frmt
1449
-     * @throws ReflectionException
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidInterfaceException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
-    {
1457
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
-    }
1459
-
1460
-
1461
-    /**
1462
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
-     *
1464
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
-     *                           on the object will be used.
1467
-     * @return string Date and time string in set locale or false if no field exists for the given
1468
-     * @throws ReflectionException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidInterfaceException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws EE_Error
1473
-     *                           field name.
1474
-     */
1475
-    public function get_i18n_datetime($field_name, $format = '')
1476
-    {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
-        return date_i18n(
1479
-            $format,
1480
-            EEH_DTT_Helper::get_timestamp_with_offset(
1481
-                $this->get_raw($field_name),
1482
-                $this->_timezone
1483
-            )
1484
-        );
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
-     * thrown.
1492
-     *
1493
-     * @param  string $field_name The field name being checked
1494
-     * @throws ReflectionException
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidInterfaceException
1497
-     * @throws InvalidDataTypeException
1498
-     * @throws EE_Error
1499
-     * @return EE_Datetime_Field
1500
-     */
1501
-    protected function _get_dtt_field_settings($field_name)
1502
-    {
1503
-        $field = $this->get_model()->field_settings_for($field_name);
1504
-        // check if field is dtt
1505
-        if ($field instanceof EE_Datetime_Field) {
1506
-            return $field;
1507
-        }
1508
-        throw new EE_Error(
1509
-            sprintf(
1510
-                esc_html__(
1511
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
-                    'event_espresso'
1513
-                ),
1514
-                $field_name,
1515
-                self::_get_model_classname(get_class($this))
1516
-            )
1517
-        );
1518
-    }
1519
-
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * NOTE ABOUT BELOW:
1525
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
-     * method and make sure you send the entire datetime value for setting.
1529
-     */
1530
-    /**
1531
-     * sets the time on a datetime property
1532
-     *
1533
-     * @access protected
1534
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
-     * @throws ReflectionException
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidInterfaceException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws EE_Error
1541
-     */
1542
-    protected function _set_time_for($time, $fieldname)
1543
-    {
1544
-        $this->_set_date_time('T', $time, $fieldname);
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * sets the date on a datetime property
1550
-     *
1551
-     * @access protected
1552
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
-     * @throws ReflectionException
1555
-     * @throws InvalidArgumentException
1556
-     * @throws InvalidInterfaceException
1557
-     * @throws InvalidDataTypeException
1558
-     * @throws EE_Error
1559
-     */
1560
-    protected function _set_date_for($date, $fieldname)
1561
-    {
1562
-        $this->_set_date_time('D', $date, $fieldname);
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * This takes care of setting a date or time independently on a given model object property. This method also
1568
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1569
-     *
1570
-     * @access protected
1571
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1574
-     *                                        EE_Datetime_Field property)
1575
-     * @throws ReflectionException
1576
-     * @throws InvalidArgumentException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws EE_Error
1580
-     */
1581
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1582
-    {
1583
-        $field = $this->_get_dtt_field_settings($field_name);
1584
-        $field->set_timezone($this->_timezone);
1585
-        $field->set_date_format($this->_dt_frmt);
1586
-        $field->set_time_format($this->_tm_frmt);
1587
-        switch ($what) {
1588
-            case 'T':
1589
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1590
-                    $datetime_value,
1591
-                    $this->_fields[ $field_name ]
1592
-                );
1593
-                $this->_has_changes = true;
1594
-                break;
1595
-            case 'D':
1596
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1597
-                    $datetime_value,
1598
-                    $this->_fields[ $field_name ]
1599
-                );
1600
-                $this->_has_changes = true;
1601
-                break;
1602
-            case 'B':
1603
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1604
-                $this->_has_changes = true;
1605
-                break;
1606
-        }
1607
-        $this->_clear_cached_property($field_name);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
-     * that could lead to some unexpected results!
1616
-     *
1617
-     * @access public
1618
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
-     *                                         value being returned.
1620
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
-     * @param string $prepend                  You can include something to prepend on the timestamp
1623
-     * @param string $append                   You can include something to append on the timestamp
1624
-     * @throws ReflectionException
1625
-     * @throws InvalidArgumentException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws InvalidDataTypeException
1628
-     * @throws EE_Error
1629
-     * @return string timestamp
1630
-     */
1631
-    public function display_in_my_timezone(
1632
-        $field_name,
1633
-        $callback = 'get_datetime',
1634
-        $args = null,
1635
-        $prepend = '',
1636
-        $append = ''
1637
-    ) {
1638
-        $timezone = EEH_DTT_Helper::get_timezone();
1639
-        if ($timezone === $this->_timezone) {
1640
-            return '';
1641
-        }
1642
-        $original_timezone = $this->_timezone;
1643
-        $this->set_timezone($timezone);
1644
-        $fn = (array) $field_name;
1645
-        $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1647
-            throw new EE_Error(
1648
-                sprintf(
1649
-                    esc_html__(
1650
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
-                        'event_espresso'
1652
-                    ),
1653
-                    $callback
1654
-                )
1655
-            );
1656
-        }
1657
-        $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
-        $this->set_timezone($original_timezone);
1660
-        return $return;
1661
-    }
1662
-
1663
-
1664
-    /**
1665
-     * Deletes this model object.
1666
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
-     * override
1668
-     * `EE_Base_Class::_delete` NOT this class.
1669
-     *
1670
-     * @return boolean | int
1671
-     * @throws ReflectionException
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidInterfaceException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws EE_Error
1676
-     */
1677
-    public function delete()
1678
-    {
1679
-        /**
1680
-         * Called just before the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object about to be 'deleted'
1688
-         */
1689
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
-        $result = $this->_delete();
1691
-        /**
1692
-         * Called just after the `EE_Base_Class::_delete` method call.
1693
-         * Note:
1694
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
-         * should be aware that `_delete` may not always result in a permanent delete.
1696
-         * For example `EE_Soft_Base_Class::_delete`
1697
-         * soft deletes (trash) the object and does not permanently delete it.
1698
-         *
1699
-         * @param EE_Base_Class $model_object that was just 'deleted'
1700
-         * @param boolean       $result
1701
-         */
1702
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
-        return $result;
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Calls the specific delete method for the instantiated class.
1709
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
-     * `EE_Base_Class::delete`
1712
-     *
1713
-     * @return bool|int
1714
-     * @throws ReflectionException
1715
-     * @throws InvalidArgumentException
1716
-     * @throws InvalidInterfaceException
1717
-     * @throws InvalidDataTypeException
1718
-     * @throws EE_Error
1719
-     */
1720
-    protected function _delete()
1721
-    {
1722
-        return $this->delete_permanently();
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * Deletes this model object permanently from db
1728
-     * (but keep in mind related models may block the delete and return an error)
1729
-     *
1730
-     * @return bool | int
1731
-     * @throws ReflectionException
1732
-     * @throws InvalidArgumentException
1733
-     * @throws InvalidInterfaceException
1734
-     * @throws InvalidDataTypeException
1735
-     * @throws EE_Error
1736
-     */
1737
-    public function delete_permanently()
1738
-    {
1739
-        /**
1740
-         * Called just before HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object about to be 'deleted'
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
-        $model = $this->get_model();
1746
-        $result = $model->delete_permanently_by_ID($this->ID());
1747
-        $this->refresh_cache_of_related_objects();
1748
-        /**
1749
-         * Called just after HARD deleting a model object
1750
-         *
1751
-         * @param EE_Base_Class $model_object that was just 'deleted'
1752
-         * @param boolean       $result
1753
-         */
1754
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
-        return $result;
1756
-    }
1757
-
1758
-
1759
-    /**
1760
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
-     * related model objects
1762
-     *
1763
-     * @throws ReflectionException
1764
-     * @throws InvalidArgumentException
1765
-     * @throws InvalidInterfaceException
1766
-     * @throws InvalidDataTypeException
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function refresh_cache_of_related_objects()
1770
-    {
1771
-        $model = $this->get_model();
1772
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
-                    // this relation only stores a single model object, not an array
1777
-                    // but let's make it consistent
1778
-                    $related_objects = array($related_objects);
1779
-                }
1780
-                foreach ($related_objects as $related_object) {
1781
-                    // only refresh their cache if they're in memory
1782
-                    if ($related_object instanceof EE_Base_Class) {
1783
-                        $related_object->clear_cache(
1784
-                            $model->get_this_model_name(),
1785
-                            $this
1786
-                        );
1787
-                    }
1788
-                }
1789
-            }
1790
-        }
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     *        Saves this object to the database. An array may be supplied to set some values on this
1796
-     * object just before saving.
1797
-     *
1798
-     * @access public
1799
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1800
-     *                                 if provided during the save() method (often client code will change the fields'
1801
-     *                                 values before calling save)
1802
-     * @return bool|int|string         1 on a successful update
1803
-     *                                 the ID of the new entry on insert
1804
-     *                                 0 on failure or if the model object isn't allowed to persist
1805
-     *                                 (as determined by EE_Base_Class::allow_persist())
1806
-     * @throws InvalidInterfaceException
1807
-     * @throws InvalidDataTypeException
1808
-     * @throws EE_Error
1809
-     * @throws InvalidArgumentException
1810
-     * @throws ReflectionException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     */
1814
-    public function save($set_cols_n_values = array())
1815
-    {
1816
-        $model = $this->get_model();
1817
-        /**
1818
-         * Filters the fields we're about to save on the model object
1819
-         *
1820
-         * @param array         $set_cols_n_values
1821
-         * @param EE_Base_Class $model_object
1822
-         */
1823
-        $set_cols_n_values = (array) apply_filters(
1824
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
-            $set_cols_n_values,
1826
-            $this
1827
-        );
1828
-        // set attributes as provided in $set_cols_n_values
1829
-        foreach ($set_cols_n_values as $column => $value) {
1830
-            $this->set($column, $value);
1831
-        }
1832
-        // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
-            return 0;
1835
-        }
1836
-        /**
1837
-         * Saving a model object.
1838
-         * Before we perform a save, this action is fired.
1839
-         *
1840
-         * @param EE_Base_Class $model_object the model object about to be saved.
1841
-         */
1842
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1844
-            return 0;
1845
-        }
1846
-        // now get current attribute values
1847
-        $save_cols_n_values = $this->_fields;
1848
-        // if the object already has an ID, update it. Otherwise, insert it
1849
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
-        // They have been
1851
-        $old_assumption_concerning_value_preparation = $model
1852
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1853
-        $model->assume_values_already_prepared_by_model_object(true);
1854
-        // does this model have an autoincrement PK?
1855
-        if ($model->has_primary_key_field()) {
1856
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1857
-                // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
-                } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
-                    $results = $model->insert($save_cols_n_values);
1863
-                    if ($results) {
1864
-                        // if successful, set the primary key
1865
-                        // but don't use the normal SET method, because it will check if
1866
-                        // an item with the same ID exists in the mapper & db, then
1867
-                        // will find it in the db (because we just added it) and THAT object
1868
-                        // will get added to the mapper before we can add this one!
1869
-                        // but if we just avoid using the SET method, all that headache can be avoided
1870
-                        $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1872
-                        $this->_clear_cached_property($pk_field_name);
1873
-                        $model->add_to_entity_map($this);
1874
-                        $this->_update_cached_related_model_objs_fks();
1875
-                    }
1876
-                }
1877
-            } else {// PK is NOT auto-increment
1878
-                // so check if one like it already exists in the db
1879
-                if ($model->exists_by_ID($this->ID())) {
1880
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1881
-                        throw new EE_Error(
1882
-                            sprintf(
1883
-                                esc_html__(
1884
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
-                                    'event_espresso'
1886
-                                ),
1887
-                                get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
-                                '<br />'
1891
-                            )
1892
-                        );
1893
-                    }
1894
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
-                } else {
1896
-                    $results = $model->insert($save_cols_n_values);
1897
-                    $this->_update_cached_related_model_objs_fks();
1898
-                }
1899
-            }
1900
-        } else {// there is NO primary key
1901
-            $already_in_db = false;
1902
-            foreach ($model->unique_indexes() as $index) {
1903
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
-                if ($model->exists(array($uniqueness_where_params))) {
1905
-                    $already_in_db = true;
1906
-                }
1907
-            }
1908
-            if ($already_in_db) {
1909
-                $combined_pk_fields_n_values = array_intersect_key(
1910
-                    $save_cols_n_values,
1911
-                    $model->get_combined_primary_key_fields()
1912
-                );
1913
-                $results = $model->update(
1914
-                    $save_cols_n_values,
1915
-                    $combined_pk_fields_n_values
1916
-                );
1917
-            } else {
1918
-                $results = $model->insert($save_cols_n_values);
1919
-            }
1920
-        }
1921
-        // restore the old assumption about values being prepared by the model object
1922
-        $model->assume_values_already_prepared_by_model_object(
1923
-            $old_assumption_concerning_value_preparation
1924
-        );
1925
-        /**
1926
-         * After saving the model object this action is called
1927
-         *
1928
-         * @param EE_Base_Class $model_object which was just saved
1929
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
-         */
1932
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
-        $this->_has_changes = false;
1934
-        return $results;
1935
-    }
1936
-
1937
-
1938
-    /**
1939
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
-     *
1947
-     * @return void
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     */
1954
-    protected function _update_cached_related_model_objs_fks()
1955
-    {
1956
-        $model = $this->get_model();
1957
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
-                        $model->get_this_model_name()
1962
-                    );
1963
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
-                    if ($related_model_obj_in_cache->ID()) {
1965
-                        $related_model_obj_in_cache->save();
1966
-                    }
1967
-                }
1968
-            }
1969
-        }
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Saves this model object and its NEW cached relations to the database.
1975
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1977
-     * because otherwise, there's a potential for infinite looping of saving
1978
-     * Saves the cached related model objects, and ensures the relation between them
1979
-     * and this object and properly setup
1980
-     *
1981
-     * @return int ID of new model object on save; 0 on failure+
1982
-     * @throws ReflectionException
1983
-     * @throws InvalidArgumentException
1984
-     * @throws InvalidInterfaceException
1985
-     * @throws InvalidDataTypeException
1986
-     * @throws EE_Error
1987
-     */
1988
-    public function save_new_cached_related_model_objs()
1989
-    {
1990
-        // make sure this has been saved
1991
-        if (! $this->ID()) {
1992
-            $id = $this->save();
1993
-        } else {
1994
-            $id = $this->ID();
1995
-        }
1996
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1999
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
-                /* @var $related_model_obj EE_Base_Class */
2002
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2004
-                    // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2006
-                    // if( ! $related_model_obj->ID()){
2007
-                    $this->_add_relation_to($related_model_obj, $relationName);
2008
-                    $related_model_obj->save_new_cached_related_model_objs();
2009
-                    // }
2010
-                } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2013
-                        // but ONLY if it DOES NOT exist in the DB
2014
-                        // if( ! $related_model_obj->ID()){
2015
-                        $this->_add_relation_to($related_model_obj, $relationName);
2016
-                        $related_model_obj->save_new_cached_related_model_objs();
2017
-                        // }
2018
-                    }
2019
-                }
2020
-            }
2021
-        }
2022
-        return $id;
2023
-    }
2024
-
2025
-
2026
-    /**
2027
-     * for getting a model while instantiated.
2028
-     *
2029
-     * @return EEM_Base | EEM_CPT_Base
2030
-     * @throws ReflectionException
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidInterfaceException
2033
-     * @throws InvalidDataTypeException
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function get_model()
2037
-    {
2038
-        if (! $this->_model) {
2039
-            $modelName = self::_get_model_classname(get_class($this));
2040
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
-        } else {
2042
-            $this->_model->set_timezone($this->_timezone);
2043
-        }
2044
-        return $this->_model;
2045
-    }
2046
-
2047
-
2048
-    /**
2049
-     * @param $props_n_values
2050
-     * @param $classname
2051
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
-     * @throws ReflectionException
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     */
2058
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
-    {
2060
-        // TODO: will not work for Term_Relationships because they have no PK!
2061
-        $primary_id_ref = self::_get_primary_key_name($classname);
2062
-        if (
2063
-            array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2065
-        ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2067
-            return self::_get_model($classname)->get_from_entity_map($id);
2068
-        }
2069
-        return false;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
-     * we return false.
2078
-     *
2079
-     * @param  array  $props_n_values   incoming array of properties and their values
2080
-     * @param  string $classname        the classname of the child class
2081
-     * @param null    $timezone
2082
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
-     *                                  date_format and the second value is the time format
2084
-     * @return mixed (EE_Base_Class|bool)
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidInterfaceException
2087
-     * @throws InvalidDataTypeException
2088
-     * @throws EE_Error
2089
-     * @throws ReflectionException
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     */
2093
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
-    {
2095
-        $existing = null;
2096
-        $model = self::_get_model($classname, $timezone);
2097
-        if ($model->has_primary_key_field()) {
2098
-            $primary_id_ref = self::_get_primary_key_name($classname);
2099
-            if (
2100
-                array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2102
-            ) {
2103
-                $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2105
-                );
2106
-            }
2107
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
-            // no primary key on this model, but there's still a matching item in the DB
2109
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
-                self::_get_model($classname, $timezone)
2111
-                    ->get_index_primary_key_string($props_n_values)
2112
-            );
2113
-        }
2114
-        if ($existing) {
2115
-            // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2117
-                $existing->set_date_format($date_formats[0]);
2118
-                $existing->set_time_format($date_formats[1]);
2119
-            } else {
2120
-                // set default formats for date and time
2121
-                $existing->set_date_format(get_option('date_format'));
2122
-                $existing->set_time_format(get_option('time_format'));
2123
-            }
2124
-            foreach ($props_n_values as $property => $field_value) {
2125
-                $existing->set($property, $field_value);
2126
-            }
2127
-            return $existing;
2128
-        }
2129
-        return false;
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Gets the EEM_*_Model for this class
2135
-     *
2136
-     * @access public now, as this is more convenient
2137
-     * @param      $classname
2138
-     * @param null $timezone
2139
-     * @throws ReflectionException
2140
-     * @throws InvalidArgumentException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws InvalidDataTypeException
2143
-     * @throws EE_Error
2144
-     * @return EEM_Base
2145
-     */
2146
-    protected static function _get_model($classname, $timezone = null)
2147
-    {
2148
-        // find model for this class
2149
-        if (! $classname) {
2150
-            throw new EE_Error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    $classname
2157
-                )
2158
-            );
2159
-        }
2160
-        $modelName = self::_get_model_classname($classname);
2161
-        return self::_get_model_instance_with_name($modelName, $timezone);
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
-     *
2168
-     * @param string $model_classname
2169
-     * @param null   $timezone
2170
-     * @return EEM_Base
2171
-     * @throws ReflectionException
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     */
2177
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
-    {
2179
-        $model_classname = str_replace('EEM_', '', $model_classname);
2180
-        $model = EE_Registry::instance()->load_model($model_classname);
2181
-        $model->set_timezone($timezone);
2182
-        return $model;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2188
-     * Also works if a model class's classname is provided (eg EE_Registration).
2189
-     *
2190
-     * @param null $model_name
2191
-     * @return string like EEM_Attendee
2192
-     */
2193
-    private static function _get_model_classname($model_name = null)
2194
-    {
2195
-        if (strpos($model_name, 'EE_') === 0) {
2196
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
-        } else {
2198
-            $model_classname = 'EEM_' . $model_name;
2199
-        }
2200
-        return $model_classname;
2201
-    }
2202
-
2203
-
2204
-    /**
2205
-     * returns the name of the primary key attribute
2206
-     *
2207
-     * @param null $classname
2208
-     * @throws ReflectionException
2209
-     * @throws InvalidArgumentException
2210
-     * @throws InvalidInterfaceException
2211
-     * @throws InvalidDataTypeException
2212
-     * @throws EE_Error
2213
-     * @return string
2214
-     */
2215
-    protected static function _get_primary_key_name($classname = null)
2216
-    {
2217
-        if (! $classname) {
2218
-            throw new EE_Error(
2219
-                sprintf(
2220
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
-                    $classname
2222
-                )
2223
-            );
2224
-        }
2225
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
-    }
2227
-
2228
-
2229
-    /**
2230
-     * Gets the value of the primary key.
2231
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
-     *
2235
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
-     * @throws ReflectionException
2237
-     * @throws InvalidArgumentException
2238
-     * @throws InvalidInterfaceException
2239
-     * @throws InvalidDataTypeException
2240
-     * @throws EE_Error
2241
-     */
2242
-    public function ID()
2243
-    {
2244
-        $model = $this->get_model();
2245
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2246
-        if ($model->has_primary_key_field()) {
2247
-            return $this->_fields[ $model->primary_key_name() ];
2248
-        }
2249
-        return $model->get_index_primary_key_string($this->_fields);
2250
-    }
2251
-
2252
-
2253
-    /**
2254
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2255
-     * @param string                   $relationName
2256
-     * @return bool
2257
-     * @throws EE_Error
2258
-     * @throws ReflectionException
2259
-     * @since   $VID:$
2260
-     */
2261
-    public function hasRelation($otherModelObjectOrID, string $relationName): bool
2262
-    {
2263
-        $other_model = self::_get_model_instance_with_name(
2264
-            self::_get_model_classname($relationName),
2265
-            $this->_timezone
2266
-        );
2267
-        $primary_key = $other_model->primary_key_name();
2268
-        /** @var EE_Base_Class $otherModelObject */
2269
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2270
-        return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2271
-    }
2272
-
2273
-
2274
-    /**
2275
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2276
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2277
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2278
-     *
2279
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2280
-     * @param string $relationName                     eg 'Events','Question',etc.
2281
-     *                                                 an attendee to a group, you also want to specify which role they
2282
-     *                                                 will have in that group. So you would use this parameter to
2283
-     *                                                 specify array('role-column-name'=>'role-id')
2284
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2285
-     *                                                 allow you to further constrict the relation to being added.
2286
-     *                                                 However, keep in mind that the columns (keys) given must match a
2287
-     *                                                 column on the JOIN table and currently only the HABTM models
2288
-     *                                                 accept these additional conditions.  Also remember that if an
2289
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2290
-     *                                                 NEW row is created in the join table.
2291
-     * @param null   $cache_id
2292
-     * @throws ReflectionException
2293
-     * @throws InvalidArgumentException
2294
-     * @throws InvalidInterfaceException
2295
-     * @throws InvalidDataTypeException
2296
-     * @throws EE_Error
2297
-     * @return EE_Base_Class the object the relation was added to
2298
-     */
2299
-    public function _add_relation_to(
2300
-        $otherObjectModelObjectOrID,
2301
-        $relationName,
2302
-        $extra_join_model_fields_n_values = array(),
2303
-        $cache_id = null
2304
-    ) {
2305
-        $model = $this->get_model();
2306
-        // if this thing exists in the DB, save the relation to the DB
2307
-        if ($this->ID()) {
2308
-            $otherObject = $model->add_relationship_to(
2309
-                $this,
2310
-                $otherObjectModelObjectOrID,
2311
-                $relationName,
2312
-                $extra_join_model_fields_n_values
2313
-            );
2314
-            // clear cache so future get_many_related and get_first_related() return new results.
2315
-            $this->clear_cache($relationName, $otherObject, true);
2316
-            if ($otherObject instanceof EE_Base_Class) {
2317
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2318
-            }
2319
-        } else {
2320
-            // this thing doesn't exist in the DB,  so just cache it
2321
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2322
-                throw new EE_Error(
2323
-                    sprintf(
2324
-                        esc_html__(
2325
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2326
-                            'event_espresso'
2327
-                        ),
2328
-                        $otherObjectModelObjectOrID,
2329
-                        get_class($this)
2330
-                    )
2331
-                );
2332
-            }
2333
-            $otherObject = $otherObjectModelObjectOrID;
2334
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2335
-        }
2336
-        if ($otherObject instanceof EE_Base_Class) {
2337
-            // fix the reciprocal relation too
2338
-            if ($otherObject->ID()) {
2339
-                // its saved so assumed relations exist in the DB, so we can just
2340
-                // clear the cache so future queries use the updated info in the DB
2341
-                $otherObject->clear_cache(
2342
-                    $model->get_this_model_name(),
2343
-                    null,
2344
-                    true
2345
-                );
2346
-            } else {
2347
-                // it's not saved, so it caches relations like this
2348
-                $otherObject->cache($model->get_this_model_name(), $this);
2349
-            }
2350
-        }
2351
-        return $otherObject;
2352
-    }
2353
-
2354
-
2355
-    /**
2356
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2357
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2358
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2359
-     * from the cache
2360
-     *
2361
-     * @param mixed  $otherObjectModelObjectOrID
2362
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2363
-     *                to the DB yet
2364
-     * @param string $relationName
2365
-     * @param array  $where_query
2366
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2367
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2368
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2369
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2370
-     *                deleted.
2371
-     * @return EE_Base_Class the relation was removed from
2372
-     * @throws ReflectionException
2373
-     * @throws InvalidArgumentException
2374
-     * @throws InvalidInterfaceException
2375
-     * @throws InvalidDataTypeException
2376
-     * @throws EE_Error
2377
-     */
2378
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2379
-    {
2380
-        if ($this->ID()) {
2381
-            // if this exists in the DB, save the relation change to the DB too
2382
-            $otherObject = $this->get_model()->remove_relationship_to(
2383
-                $this,
2384
-                $otherObjectModelObjectOrID,
2385
-                $relationName,
2386
-                $where_query
2387
-            );
2388
-            $this->clear_cache(
2389
-                $relationName,
2390
-                $otherObject
2391
-            );
2392
-        } else {
2393
-            // this doesn't exist in the DB, just remove it from the cache
2394
-            $otherObject = $this->clear_cache(
2395
-                $relationName,
2396
-                $otherObjectModelObjectOrID
2397
-            );
2398
-        }
2399
-        if ($otherObject instanceof EE_Base_Class) {
2400
-            $otherObject->clear_cache(
2401
-                $this->get_model()->get_this_model_name(),
2402
-                $this
2403
-            );
2404
-        }
2405
-        return $otherObject;
2406
-    }
2407
-
2408
-
2409
-    /**
2410
-     * Removes ALL the related things for the $relationName.
2411
-     *
2412
-     * @param string $relationName
2413
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2414
-     * @return EE_Base_Class
2415
-     * @throws ReflectionException
2416
-     * @throws InvalidArgumentException
2417
-     * @throws InvalidInterfaceException
2418
-     * @throws InvalidDataTypeException
2419
-     * @throws EE_Error
2420
-     */
2421
-    public function _remove_relations($relationName, $where_query_params = array())
2422
-    {
2423
-        if ($this->ID()) {
2424
-            // if this exists in the DB, save the relation change to the DB too
2425
-            $otherObjects = $this->get_model()->remove_relations(
2426
-                $this,
2427
-                $relationName,
2428
-                $where_query_params
2429
-            );
2430
-            $this->clear_cache(
2431
-                $relationName,
2432
-                null,
2433
-                true
2434
-            );
2435
-        } else {
2436
-            // this doesn't exist in the DB, just remove it from the cache
2437
-            $otherObjects = $this->clear_cache(
2438
-                $relationName,
2439
-                null,
2440
-                true
2441
-            );
2442
-        }
2443
-        if (is_array($otherObjects)) {
2444
-            foreach ($otherObjects as $otherObject) {
2445
-                $otherObject->clear_cache(
2446
-                    $this->get_model()->get_this_model_name(),
2447
-                    $this
2448
-                );
2449
-            }
2450
-        }
2451
-        return $otherObjects;
2452
-    }
2453
-
2454
-
2455
-    /**
2456
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2457
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2458
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2459
-     * because we want to get even deleted items etc.
2460
-     *
2461
-     * @param string $relationName key in the model's _model_relations array
2462
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2463
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2464
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2465
-     *                             results if you want IDs
2466
-     * @throws ReflectionException
2467
-     * @throws InvalidArgumentException
2468
-     * @throws InvalidInterfaceException
2469
-     * @throws InvalidDataTypeException
2470
-     * @throws EE_Error
2471
-     */
2472
-    public function get_many_related($relationName, $query_params = array())
2473
-    {
2474
-        if ($this->ID()) {
2475
-            // this exists in the DB, so get the related things from either the cache or the DB
2476
-            // if there are query parameters, forget about caching the related model objects.
2477
-            if ($query_params) {
2478
-                $related_model_objects = $this->get_model()->get_all_related(
2479
-                    $this,
2480
-                    $relationName,
2481
-                    $query_params
2482
-                );
2483
-            } else {
2484
-                // did we already cache the result of this query?
2485
-                $cached_results = $this->get_all_from_cache($relationName);
2486
-                if (! $cached_results) {
2487
-                    $related_model_objects = $this->get_model()->get_all_related(
2488
-                        $this,
2489
-                        $relationName,
2490
-                        $query_params
2491
-                    );
2492
-                    // if no query parameters were passed, then we got all the related model objects
2493
-                    // for that relation. We can cache them then.
2494
-                    foreach ($related_model_objects as $related_model_object) {
2495
-                        $this->cache($relationName, $related_model_object);
2496
-                    }
2497
-                } else {
2498
-                    $related_model_objects = $cached_results;
2499
-                }
2500
-            }
2501
-        } else {
2502
-            // this doesn't exist in the DB, so just get the related things from the cache
2503
-            $related_model_objects = $this->get_all_from_cache($relationName);
2504
-        }
2505
-        return $related_model_objects;
2506
-    }
2507
-
2508
-
2509
-    /**
2510
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2511
-     * unless otherwise specified in the $query_params
2512
-     *
2513
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2514
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2515
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2516
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2517
-     *                               that by the setting $distinct to TRUE;
2518
-     * @return int
2519
-     * @throws ReflectionException
2520
-     * @throws InvalidArgumentException
2521
-     * @throws InvalidInterfaceException
2522
-     * @throws InvalidDataTypeException
2523
-     * @throws EE_Error
2524
-     */
2525
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2526
-    {
2527
-        return $this->get_model()->count_related(
2528
-            $this,
2529
-            $relation_name,
2530
-            $query_params,
2531
-            $field_to_count,
2532
-            $distinct
2533
-        );
2534
-    }
2535
-
2536
-
2537
-    /**
2538
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2539
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2540
-     *
2541
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2542
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2543
-     * @param string $field_to_sum  name of field to count by.
2544
-     *                              By default, uses primary key
2545
-     *                              (which doesn't make much sense, so you should probably change it)
2546
-     * @return int
2547
-     * @throws ReflectionException
2548
-     * @throws InvalidArgumentException
2549
-     * @throws InvalidInterfaceException
2550
-     * @throws InvalidDataTypeException
2551
-     * @throws EE_Error
2552
-     */
2553
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2554
-    {
2555
-        return $this->get_model()->sum_related(
2556
-            $this,
2557
-            $relation_name,
2558
-            $query_params,
2559
-            $field_to_sum
2560
-        );
2561
-    }
2562
-
2563
-
2564
-    /**
2565
-     * Gets the first (ie, one) related model object of the specified type.
2566
-     *
2567
-     * @param string $relationName key in the model's _model_relations array
2568
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2569
-     * @return EE_Base_Class (not an array, a single object)
2570
-     * @throws ReflectionException
2571
-     * @throws InvalidArgumentException
2572
-     * @throws InvalidInterfaceException
2573
-     * @throws InvalidDataTypeException
2574
-     * @throws EE_Error
2575
-     */
2576
-    public function get_first_related($relationName, $query_params = array())
2577
-    {
2578
-        $model = $this->get_model();
2579
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2580
-            // if they've provided some query parameters, don't bother trying to cache the result
2581
-            // also make sure we're not caching the result of get_first_related
2582
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2583
-            if (
2584
-                $query_params
2585
-                || ! $model->related_settings_for($relationName)
2586
-                     instanceof
2587
-                     EE_Belongs_To_Relation
2588
-            ) {
2589
-                $related_model_object = $model->get_first_related(
2590
-                    $this,
2591
-                    $relationName,
2592
-                    $query_params
2593
-                );
2594
-            } else {
2595
-                // first, check if we've already cached the result of this query
2596
-                $cached_result = $this->get_one_from_cache($relationName);
2597
-                if (! $cached_result) {
2598
-                    $related_model_object = $model->get_first_related(
2599
-                        $this,
2600
-                        $relationName,
2601
-                        $query_params
2602
-                    );
2603
-                    $this->cache($relationName, $related_model_object);
2604
-                } else {
2605
-                    $related_model_object = $cached_result;
2606
-                }
2607
-            }
2608
-        } else {
2609
-            $related_model_object = null;
2610
-            // this doesn't exist in the Db,
2611
-            // but maybe the relation is of type belongs to, and so the related thing might
2612
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2613
-                $related_model_object = $model->get_first_related(
2614
-                    $this,
2615
-                    $relationName,
2616
-                    $query_params
2617
-                );
2618
-            }
2619
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2620
-            // just get what's cached on this object
2621
-            if (! $related_model_object) {
2622
-                $related_model_object = $this->get_one_from_cache($relationName);
2623
-            }
2624
-        }
2625
-        return $related_model_object;
2626
-    }
2627
-
2628
-
2629
-    /**
2630
-     * Does a delete on all related objects of type $relationName and removes
2631
-     * the current model object's relation to them. If they can't be deleted (because
2632
-     * of blocking related model objects) does nothing. If the related model objects are
2633
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2634
-     * If this model object doesn't exist yet in the DB, just removes its related things
2635
-     *
2636
-     * @param string $relationName
2637
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
-     * @return int how many deleted
2639
-     * @throws ReflectionException
2640
-     * @throws InvalidArgumentException
2641
-     * @throws InvalidInterfaceException
2642
-     * @throws InvalidDataTypeException
2643
-     * @throws EE_Error
2644
-     */
2645
-    public function delete_related($relationName, $query_params = array())
2646
-    {
2647
-        if ($this->ID()) {
2648
-            $count = $this->get_model()->delete_related(
2649
-                $this,
2650
-                $relationName,
2651
-                $query_params
2652
-            );
2653
-        } else {
2654
-            $count = count($this->get_all_from_cache($relationName));
2655
-            $this->clear_cache($relationName, null, true);
2656
-        }
2657
-        return $count;
2658
-    }
2659
-
2660
-
2661
-    /**
2662
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2663
-     * the current model object's relation to them. If they can't be deleted (because
2664
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2665
-     * If the related thing isn't a soft-deletable model object, this function is identical
2666
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2667
-     *
2668
-     * @param string $relationName
2669
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
-     * @return int how many deleted (including those soft deleted)
2671
-     * @throws ReflectionException
2672
-     * @throws InvalidArgumentException
2673
-     * @throws InvalidInterfaceException
2674
-     * @throws InvalidDataTypeException
2675
-     * @throws EE_Error
2676
-     */
2677
-    public function delete_related_permanently($relationName, $query_params = array())
2678
-    {
2679
-        if ($this->ID()) {
2680
-            $count = $this->get_model()->delete_related_permanently(
2681
-                $this,
2682
-                $relationName,
2683
-                $query_params
2684
-            );
2685
-        } else {
2686
-            $count = count($this->get_all_from_cache($relationName));
2687
-        }
2688
-        $this->clear_cache($relationName, null, true);
2689
-        return $count;
2690
-    }
2691
-
2692
-
2693
-    /**
2694
-     * is_set
2695
-     * Just a simple utility function children can use for checking if property exists
2696
-     *
2697
-     * @access  public
2698
-     * @param  string $field_name property to check
2699
-     * @return bool                              TRUE if existing,FALSE if not.
2700
-     */
2701
-    public function is_set($field_name)
2702
-    {
2703
-        return isset($this->_fields[ $field_name ]);
2704
-    }
2705
-
2706
-
2707
-    /**
2708
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2709
-     * EE_Error exception if they don't
2710
-     *
2711
-     * @param  mixed (string|array) $properties properties to check
2712
-     * @throws EE_Error
2713
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2714
-     */
2715
-    protected function _property_exists($properties)
2716
-    {
2717
-        foreach ((array) $properties as $property_name) {
2718
-            // first make sure this property exists
2719
-            if (! $this->_fields[ $property_name ]) {
2720
-                throw new EE_Error(
2721
-                    sprintf(
2722
-                        esc_html__(
2723
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2724
-                            'event_espresso'
2725
-                        ),
2726
-                        $property_name
2727
-                    )
2728
-                );
2729
-            }
2730
-        }
2731
-        return true;
2732
-    }
2733
-
2734
-
2735
-    /**
2736
-     * This simply returns an array of model fields for this object
2737
-     *
2738
-     * @return array
2739
-     * @throws ReflectionException
2740
-     * @throws InvalidArgumentException
2741
-     * @throws InvalidInterfaceException
2742
-     * @throws InvalidDataTypeException
2743
-     * @throws EE_Error
2744
-     */
2745
-    public function model_field_array()
2746
-    {
2747
-        $fields = $this->get_model()->field_settings(false);
2748
-        $properties = array();
2749
-        // remove prepended underscore
2750
-        foreach ($fields as $field_name => $settings) {
2751
-            $properties[ $field_name ] = $this->get($field_name);
2752
-        }
2753
-        return $properties;
2754
-    }
2755
-
2756
-
2757
-    /**
2758
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2759
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2760
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2761
-     * Instead of requiring a plugin to extend the EE_Base_Class
2762
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2763
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2764
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2765
-     * and accepts 2 arguments: the object on which the function was called,
2766
-     * and an array of the original arguments passed to the function.
2767
-     * Whatever their callback function returns will be returned by this function.
2768
-     * Example: in functions.php (or in a plugin):
2769
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2770
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2771
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2772
-     *          return $previousReturnValue.$returnString;
2773
-     *      }
2774
-     * require('EE_Answer.class.php');
2775
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2776
-     *      ->my_callback('monkeys',100);
2777
-     * // will output "you called my_callback! and passed args:monkeys,100"
2778
-     *
2779
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2780
-     * @param array  $args       array of original arguments passed to the function
2781
-     * @throws EE_Error
2782
-     * @return mixed whatever the plugin which calls add_filter decides
2783
-     */
2784
-    public function __call($methodName, $args)
2785
-    {
2786
-        $className = get_class($this);
2787
-        $tagName = "FHEE__{$className}__{$methodName}";
2788
-        if (! has_filter($tagName)) {
2789
-            throw new EE_Error(
2790
-                sprintf(
2791
-                    esc_html__(
2792
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2793
-                        'event_espresso'
2794
-                    ),
2795
-                    $methodName,
2796
-                    $className,
2797
-                    $tagName
2798
-                )
2799
-            );
2800
-        }
2801
-        return apply_filters($tagName, null, $this, $args);
2802
-    }
2803
-
2804
-
2805
-    /**
2806
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2807
-     * A $previous_value can be specified in case there are many meta rows with the same key
2808
-     *
2809
-     * @param string $meta_key
2810
-     * @param mixed  $meta_value
2811
-     * @param mixed  $previous_value
2812
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2813
-     *                  NOTE: if the values haven't changed, returns 0
2814
-     * @throws InvalidArgumentException
2815
-     * @throws InvalidInterfaceException
2816
-     * @throws InvalidDataTypeException
2817
-     * @throws EE_Error
2818
-     * @throws ReflectionException
2819
-     */
2820
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2821
-    {
2822
-        $query_params = array(
2823
-            array(
2824
-                'EXM_key'  => $meta_key,
2825
-                'OBJ_ID'   => $this->ID(),
2826
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2827
-            ),
2828
-        );
2829
-        if ($previous_value !== null) {
2830
-            $query_params[0]['EXM_value'] = $meta_value;
2831
-        }
2832
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2833
-        if (! $existing_rows_like_that) {
2834
-            return $this->add_extra_meta($meta_key, $meta_value);
2835
-        }
2836
-        foreach ($existing_rows_like_that as $existing_row) {
2837
-            $existing_row->save(array('EXM_value' => $meta_value));
2838
-        }
2839
-        return count($existing_rows_like_that);
2840
-    }
2841
-
2842
-
2843
-    /**
2844
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2845
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2846
-     * extra meta row was entered, false if not
2847
-     *
2848
-     * @param string  $meta_key
2849
-     * @param mixed   $meta_value
2850
-     * @param boolean $unique
2851
-     * @return boolean
2852
-     * @throws InvalidArgumentException
2853
-     * @throws InvalidInterfaceException
2854
-     * @throws InvalidDataTypeException
2855
-     * @throws EE_Error
2856
-     * @throws ReflectionException
2857
-     * @throws ReflectionException
2858
-     */
2859
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2860
-    {
2861
-        if ($unique) {
2862
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2863
-                array(
2864
-                    array(
2865
-                        'EXM_key'  => $meta_key,
2866
-                        'OBJ_ID'   => $this->ID(),
2867
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2868
-                    ),
2869
-                )
2870
-            );
2871
-            if ($existing_extra_meta) {
2872
-                return false;
2873
-            }
2874
-        }
2875
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2876
-            array(
2877
-                'EXM_key'   => $meta_key,
2878
-                'EXM_value' => $meta_value,
2879
-                'OBJ_ID'    => $this->ID(),
2880
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2881
-            )
2882
-        );
2883
-        $new_extra_meta->save();
2884
-        return true;
2885
-    }
2886
-
2887
-
2888
-    /**
2889
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2890
-     * is specified, only deletes extra meta records with that value.
2891
-     *
2892
-     * @param string $meta_key
2893
-     * @param mixed  $meta_value
2894
-     * @return int number of extra meta rows deleted
2895
-     * @throws InvalidArgumentException
2896
-     * @throws InvalidInterfaceException
2897
-     * @throws InvalidDataTypeException
2898
-     * @throws EE_Error
2899
-     * @throws ReflectionException
2900
-     */
2901
-    public function delete_extra_meta($meta_key, $meta_value = null)
2902
-    {
2903
-        $query_params = array(
2904
-            array(
2905
-                'EXM_key'  => $meta_key,
2906
-                'OBJ_ID'   => $this->ID(),
2907
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2908
-            ),
2909
-        );
2910
-        if ($meta_value !== null) {
2911
-            $query_params[0]['EXM_value'] = $meta_value;
2912
-        }
2913
-        return EEM_Extra_Meta::instance()->delete($query_params);
2914
-    }
2915
-
2916
-
2917
-    /**
2918
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2919
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2920
-     * You can specify $default is case you haven't found the extra meta
2921
-     *
2922
-     * @param string  $meta_key
2923
-     * @param boolean $single
2924
-     * @param mixed   $default if we don't find anything, what should we return?
2925
-     * @return mixed single value if $single; array if ! $single
2926
-     * @throws ReflectionException
2927
-     * @throws InvalidArgumentException
2928
-     * @throws InvalidInterfaceException
2929
-     * @throws InvalidDataTypeException
2930
-     * @throws EE_Error
2931
-     */
2932
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2933
-    {
2934
-        if ($single) {
2935
-            $result = $this->get_first_related(
2936
-                'Extra_Meta',
2937
-                array(array('EXM_key' => $meta_key))
2938
-            );
2939
-            if ($result instanceof EE_Extra_Meta) {
2940
-                return $result->value();
2941
-            }
2942
-        } else {
2943
-            $results = $this->get_many_related(
2944
-                'Extra_Meta',
2945
-                array(array('EXM_key' => $meta_key))
2946
-            );
2947
-            if ($results) {
2948
-                $values = array();
2949
-                foreach ($results as $result) {
2950
-                    if ($result instanceof EE_Extra_Meta) {
2951
-                        $values[ $result->ID() ] = $result->value();
2952
-                    }
2953
-                }
2954
-                return $values;
2955
-            }
2956
-        }
2957
-        // if nothing discovered yet return default.
2958
-        return apply_filters(
2959
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2960
-            $default,
2961
-            $meta_key,
2962
-            $single,
2963
-            $this
2964
-        );
2965
-    }
2966
-
2967
-
2968
-    /**
2969
-     * Returns a simple array of all the extra meta associated with this model object.
2970
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2971
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2972
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2973
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2974
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2975
-     * finally the extra meta's value as each sub-value. (eg
2976
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2977
-     *
2978
-     * @param boolean $one_of_each_key
2979
-     * @return array
2980
-     * @throws ReflectionException
2981
-     * @throws InvalidArgumentException
2982
-     * @throws InvalidInterfaceException
2983
-     * @throws InvalidDataTypeException
2984
-     * @throws EE_Error
2985
-     */
2986
-    public function all_extra_meta_array($one_of_each_key = true)
2987
-    {
2988
-        $return_array = array();
2989
-        if ($one_of_each_key) {
2990
-            $extra_meta_objs = $this->get_many_related(
2991
-                'Extra_Meta',
2992
-                array('group_by' => 'EXM_key')
2993
-            );
2994
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2995
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2996
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2997
-                }
2998
-            }
2999
-        } else {
3000
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
3001
-            foreach ($extra_meta_objs as $extra_meta_obj) {
3002
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
3003
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
3004
-                        $return_array[ $extra_meta_obj->key() ] = array();
3005
-                    }
3006
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
3007
-                }
3008
-            }
3009
-        }
3010
-        return $return_array;
3011
-    }
3012
-
3013
-
3014
-    /**
3015
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3016
-     *
3017
-     * @return string
3018
-     * @throws ReflectionException
3019
-     * @throws InvalidArgumentException
3020
-     * @throws InvalidInterfaceException
3021
-     * @throws InvalidDataTypeException
3022
-     * @throws EE_Error
3023
-     */
3024
-    public function name()
3025
-    {
3026
-        // find a field that's not a text field
3027
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3028
-        if ($field_we_can_use) {
3029
-            return $this->get($field_we_can_use->get_name());
3030
-        }
3031
-        $first_few_properties = $this->model_field_array();
3032
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3033
-        $name_parts = array();
3034
-        foreach ($first_few_properties as $name => $value) {
3035
-            $name_parts[] = "$name:$value";
3036
-        }
3037
-        return implode(',', $name_parts);
3038
-    }
3039
-
3040
-
3041
-    /**
3042
-     * in_entity_map
3043
-     * Checks if this model object has been proven to already be in the entity map
3044
-     *
3045
-     * @return boolean
3046
-     * @throws ReflectionException
3047
-     * @throws InvalidArgumentException
3048
-     * @throws InvalidInterfaceException
3049
-     * @throws InvalidDataTypeException
3050
-     * @throws EE_Error
3051
-     */
3052
-    public function in_entity_map()
3053
-    {
3054
-        // well, if we looked, did we find it in the entity map?
3055
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3056
-    }
3057
-
3058
-
3059
-    /**
3060
-     * refresh_from_db
3061
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3062
-     *
3063
-     * @throws ReflectionException
3064
-     * @throws InvalidArgumentException
3065
-     * @throws InvalidInterfaceException
3066
-     * @throws InvalidDataTypeException
3067
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3068
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3069
-     */
3070
-    public function refresh_from_db()
3071
-    {
3072
-        if ($this->ID() && $this->in_entity_map()) {
3073
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3074
-        } else {
3075
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3076
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3077
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3078
-            // absolutely nothing in it for this ID
3079
-            if (WP_DEBUG) {
3080
-                throw new EE_Error(
3081
-                    sprintf(
3082
-                        esc_html__(
3083
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3084
-                            'event_espresso'
3085
-                        ),
3086
-                        $this->ID(),
3087
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3088
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3089
-                    )
3090
-                );
3091
-            }
3092
-        }
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3098
-     *
3099
-     * @since 4.9.80.p
3100
-     * @param EE_Model_Field_Base[] $fields
3101
-     * @param string $new_value_sql
3102
-     *      example: 'column_name=123',
3103
-     *      or 'column_name=column_name+1',
3104
-     *      or 'column_name= CASE
3105
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3106
-     *          THEN `column_name` + 5
3107
-     *          ELSE `column_name`
3108
-     *      END'
3109
-     *      Also updates $field on this model object with the latest value from the database.
3110
-     * @return bool
3111
-     * @throws EE_Error
3112
-     * @throws InvalidArgumentException
3113
-     * @throws InvalidDataTypeException
3114
-     * @throws InvalidInterfaceException
3115
-     * @throws ReflectionException
3116
-     */
3117
-    protected function updateFieldsInDB($fields, $new_value_sql)
3118
-    {
3119
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3120
-        // if it wasn't even there to start off.
3121
-        if (! $this->ID()) {
3122
-            $this->save();
3123
-        }
3124
-        global $wpdb;
3125
-        if (empty($fields)) {
3126
-            throw new InvalidArgumentException(
3127
-                esc_html__(
3128
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3129
-                    'event_espresso'
3130
-                )
3131
-            );
3132
-        }
3133
-        $first_field = reset($fields);
3134
-        $table_alias = $first_field->get_table_alias();
3135
-        foreach ($fields as $field) {
3136
-            if ($table_alias !== $field->get_table_alias()) {
3137
-                throw new InvalidArgumentException(
3138
-                    sprintf(
3139
-                        esc_html__(
3140
-                            // @codingStandardsIgnoreStart
3141
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3142
-                            // @codingStandardsIgnoreEnd
3143
-                            'event_espresso'
3144
-                        ),
3145
-                        $table_alias,
3146
-                        $field->get_table_alias()
3147
-                    )
3148
-                );
3149
-            }
3150
-        }
3151
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3152
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3153
-        $table_pk_value = $this->ID();
3154
-        $table_name = $table_obj->get_table_name();
3155
-        if ($table_obj instanceof EE_Secondary_Table) {
3156
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3157
-        } else {
3158
-            $table_pk_field_name = $table_obj->get_pk_column();
3159
-        }
3160
-
3161
-        $query =
3162
-            "UPDATE `{$table_name}`
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				// if so, we want all this object's fields to be filled either with
342
+				// what we've explicitly set on this model
343
+				// or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (
349
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
+						&& $field_obj->get_name() !== $field_name
351
+					) {
352
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
+					}
354
+				}
355
+				// oh this model object has an ID? well make sure its in the entity mapper
356
+				$model->add_to_entity_map($this);
357
+			}
358
+			// let's unset any cache for this field_name from the $_cached_properties property.
359
+			$this->_clear_cached_property($field_name);
360
+		} else {
361
+			throw new EE_Error(
362
+				sprintf(
363
+					esc_html__(
364
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
+						'event_espresso'
366
+					),
367
+					$field_name
368
+				)
369
+			);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Set custom select values for model.
376
+	 *
377
+	 * @param array $custom_select_values
378
+	 */
379
+	public function setCustomSelectsValues(array $custom_select_values)
380
+	{
381
+		$this->custom_selection_results = $custom_select_values;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Returns the custom select value for the provided alias if its set.
387
+	 * If not set, returns null.
388
+	 *
389
+	 * @param string $alias
390
+	 * @return string|int|float|null
391
+	 */
392
+	public function getCustomSelect($alias)
393
+	{
394
+		return isset($this->custom_selection_results[ $alias ])
395
+			? $this->custom_selection_results[ $alias ]
396
+			: null;
397
+	}
398
+
399
+
400
+	/**
401
+	 * This sets the field value on the db column if it exists for the given $column_name or
402
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
+	 *
404
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function set_field_or_extra_meta($field_name, $field_value)
415
+	{
416
+		if ($this->get_model()->has_field($field_name)) {
417
+			$this->set($field_name, $field_value);
418
+			return true;
419
+		}
420
+		// ensure this object is saved first so that extra meta can be properly related.
421
+		$this->save();
422
+		return $this->update_extra_meta($field_name, $field_value);
423
+	}
424
+
425
+
426
+	/**
427
+	 * This retrieves the value of the db column set on this class or if that's not present
428
+	 * it will attempt to retrieve from extra_meta if found.
429
+	 * Example Usage:
430
+	 * Via EE_Message child class:
431
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
434
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
+	 * value for those extra fields dynamically via the EE_message object.
436
+	 *
437
+	 * @param  string $field_name expecting the fully qualified field name.
438
+	 * @return mixed|null  value for the field if found.  null if not found.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function get_field_or_extra_meta($field_name)
446
+	{
447
+		if ($this->get_model()->has_field($field_name)) {
448
+			$column_value = $this->get($field_name);
449
+		} else {
450
+			// This isn't a column in the main table, let's see if it is in the extra meta.
451
+			$column_value = $this->get_extra_meta($field_name, true, null);
452
+		}
453
+		return $column_value;
454
+	}
455
+
456
+
457
+	/**
458
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
+	 *
463
+	 * @access public
464
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
+	 * @return void
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws EE_Error
470
+	 * @throws ReflectionException
471
+	 */
472
+	public function set_timezone($timezone = '')
473
+	{
474
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
+		// make sure we clear all cached properties because they won't be relevant now
476
+		$this->_clear_cached_properties();
477
+		// make sure we update field settings and the date for all EE_Datetime_Fields
478
+		$model_fields = $this->get_model()->field_settings(false);
479
+		foreach ($model_fields as $field_name => $field_obj) {
480
+			if ($field_obj instanceof EE_Datetime_Field) {
481
+				$field_obj->set_timezone($this->_timezone);
482
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+				}
485
+			}
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 * This just returns whatever is set for the current timezone.
492
+	 *
493
+	 * @access public
494
+	 * @return string timezone string
495
+	 */
496
+	public function get_timezone()
497
+	{
498
+		return $this->_timezone;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
504
+	 * internally instead of wp set date format options
505
+	 *
506
+	 * @since 4.6
507
+	 * @param string $format should be a format recognizable by PHP date() functions.
508
+	 */
509
+	public function set_date_format($format)
510
+	{
511
+		$this->_dt_frmt = $format;
512
+		// clear cached_properties because they won't be relevant now.
513
+		$this->_clear_cached_properties();
514
+	}
515
+
516
+
517
+	/**
518
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
519
+	 * class internally instead of wp set time format options.
520
+	 *
521
+	 * @since 4.6
522
+	 * @param string $format should be a format recognizable by PHP date() functions.
523
+	 */
524
+	public function set_time_format($format)
525
+	{
526
+		$this->_tm_frmt = $format;
527
+		// clear cached_properties because they won't be relevant now.
528
+		$this->_clear_cached_properties();
529
+	}
530
+
531
+
532
+	/**
533
+	 * This returns the current internal set format for the date and time formats.
534
+	 *
535
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
+	 *                             where the first value is the date format and the second value is the time format.
537
+	 * @return mixed string|array
538
+	 */
539
+	public function get_format($full = true)
540
+	{
541
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
+	}
543
+
544
+
545
+	/**
546
+	 * cache
547
+	 * stores the passed model object on the current model object.
548
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
+	 *
550
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
+	 *                                       'Registration' associated with this model object
552
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
+	 *                                       that could be a payment or a registration)
554
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
+	 *                                       items which will be stored in an array on this object
556
+	 * @throws ReflectionException
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
+	 *                                       related thing, no array)
563
+	 */
564
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
+	{
566
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
+		if (! $object_to_cache instanceof EE_Base_Class) {
568
+			return false;
569
+		}
570
+		// also get "how" the object is related, or throw an error
571
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
+			throw new EE_Error(
573
+				sprintf(
574
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
+					$relationName,
576
+					get_class($this)
577
+				)
578
+			);
579
+		}
580
+		// how many things are related ?
581
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
+			// if it's a "belongs to" relationship, then there's only one related model object
583
+			// eg, if this is a registration, there's only 1 attendee for it
584
+			// so for these model objects just set it to be cached
585
+			$this->_model_relations[ $relationName ] = $object_to_cache;
586
+			$return = true;
587
+		} else {
588
+			// otherwise, this is the "many" side of a one to many relationship,
589
+			// so we'll add the object to the array of related objects for that type.
590
+			// eg: if this is an event, there are many registrations for that event,
591
+			// so we cache the registrations in an array
592
+			if (! is_array($this->_model_relations[ $relationName ])) {
593
+				// if for some reason, the cached item is a model object,
594
+				// then stick that in the array, otherwise start with an empty array
595
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
+														   instanceof
597
+														   EE_Base_Class
598
+					? array($this->_model_relations[ $relationName ]) : array();
599
+			}
600
+			// first check for a cache_id which is normally empty
601
+			if (! empty($cache_id)) {
602
+				// if the cache_id exists, then it means we are purposely trying to cache this
603
+				// with a known key that can then be used to retrieve the object later on
604
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
+				$return = $cache_id;
606
+			} elseif ($object_to_cache->ID()) {
607
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
608
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
+				$return = $object_to_cache->ID();
610
+			} else {
611
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
613
+				// move the internal pointer to the end of the array
614
+				end($this->_model_relations[ $relationName ]);
615
+				// and grab the key so that we can return it
616
+				$return = key($this->_model_relations[ $relationName ]);
617
+			}
618
+		}
619
+		return $return;
620
+	}
621
+
622
+
623
+	/**
624
+	 * For adding an item to the cached_properties property.
625
+	 *
626
+	 * @access protected
627
+	 * @param string      $fieldname the property item the corresponding value is for.
628
+	 * @param mixed       $value     The value we are caching.
629
+	 * @param string|null $cache_type
630
+	 * @return void
631
+	 * @throws ReflectionException
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 */
637
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
+	{
639
+		// first make sure this property exists
640
+		$this->get_model()->field_settings_for($fieldname);
641
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
+	}
644
+
645
+
646
+	/**
647
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
+	 * This also SETS the cache if we return the actual property!
649
+	 *
650
+	 * @param string $fieldname        the name of the property we're trying to retrieve
651
+	 * @param bool   $pretty
652
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
+	 *                                 (in cases where the same property may be used for different outputs
654
+	 *                                 - i.e. datetime, money etc.)
655
+	 *                                 It can also accept certain pre-defined "schema" strings
656
+	 *                                 to define how to output the property.
657
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
+	 * @return mixed                   whatever the value for the property is we're retrieving
659
+	 * @throws ReflectionException
660
+	 * @throws InvalidArgumentException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws InvalidDataTypeException
663
+	 * @throws EE_Error
664
+	 */
665
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
+	{
667
+		// verify the field exists
668
+		$model = $this->get_model();
669
+		$model->field_settings_for($fieldname);
670
+		$cache_type = $pretty ? 'pretty' : 'standard';
671
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+		}
675
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
+		$this->_set_cached_property($fieldname, $value, $cache_type);
677
+		return $value;
678
+	}
679
+
680
+
681
+	/**
682
+	 * If the cache didn't fetch the needed item, this fetches it.
683
+	 *
684
+	 * @param string $fieldname
685
+	 * @param bool   $pretty
686
+	 * @param string $extra_cache_ref
687
+	 * @return mixed
688
+	 * @throws InvalidArgumentException
689
+	 * @throws InvalidInterfaceException
690
+	 * @throws InvalidDataTypeException
691
+	 * @throws EE_Error
692
+	 * @throws ReflectionException
693
+	 */
694
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
+	{
696
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
697
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
+		if ($field_obj instanceof EE_Datetime_Field) {
699
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
+		}
701
+		if (! isset($this->_fields[ $fieldname ])) {
702
+			$this->_fields[ $fieldname ] = null;
703
+		}
704
+		return $pretty
705
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+	}
708
+
709
+
710
+	/**
711
+	 * set timezone, formats, and output for EE_Datetime_Field objects
712
+	 *
713
+	 * @param EE_Datetime_Field $datetime_field
714
+	 * @param bool              $pretty
715
+	 * @param null              $date_or_time
716
+	 * @return void
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidInterfaceException
719
+	 * @throws InvalidDataTypeException
720
+	 */
721
+	protected function _prepare_datetime_field(
722
+		EE_Datetime_Field $datetime_field,
723
+		$pretty = false,
724
+		$date_or_time = null
725
+	) {
726
+		$datetime_field->set_timezone($this->_timezone);
727
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
728
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
729
+		// set the output returned
730
+		switch ($date_or_time) {
731
+			case 'D':
732
+				$datetime_field->set_date_time_output('date');
733
+				break;
734
+			case 'T':
735
+				$datetime_field->set_date_time_output('time');
736
+				break;
737
+			default:
738
+				$datetime_field->set_date_time_output();
739
+		}
740
+	}
741
+
742
+
743
+	/**
744
+	 * This just takes care of clearing out the cached_properties
745
+	 *
746
+	 * @return void
747
+	 */
748
+	protected function _clear_cached_properties()
749
+	{
750
+		$this->_cached_properties = array();
751
+	}
752
+
753
+
754
+	/**
755
+	 * This just clears out ONE property if it exists in the cache
756
+	 *
757
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
758
+	 * @return void
759
+	 */
760
+	protected function _clear_cached_property($property_name)
761
+	{
762
+		if (isset($this->_cached_properties[ $property_name ])) {
763
+			unset($this->_cached_properties[ $property_name ]);
764
+		}
765
+	}
766
+
767
+
768
+	/**
769
+	 * Ensures that this related thing is a model object.
770
+	 *
771
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
772
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
773
+	 * @return EE_Base_Class
774
+	 * @throws ReflectionException
775
+	 * @throws InvalidArgumentException
776
+	 * @throws InvalidInterfaceException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws EE_Error
779
+	 */
780
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
781
+	{
782
+		$other_model_instance = self::_get_model_instance_with_name(
783
+			self::_get_model_classname($model_name),
784
+			$this->_timezone
785
+		);
786
+		return $other_model_instance->ensure_is_obj($object_or_id);
787
+	}
788
+
789
+
790
+	/**
791
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
792
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
793
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
794
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
795
+	 *
796
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
797
+	 *                                                     Eg 'Registration'
798
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
799
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
800
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
801
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
802
+	 *                                                     this is HasMany or HABTM.
803
+	 * @throws ReflectionException
804
+	 * @throws InvalidArgumentException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws InvalidDataTypeException
807
+	 * @throws EE_Error
808
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
809
+	 *                                                     relation from all
810
+	 */
811
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
812
+	{
813
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
814
+		$index_in_cache = '';
815
+		if (! $relationship_to_model) {
816
+			throw new EE_Error(
817
+				sprintf(
818
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
819
+					$relationName,
820
+					get_class($this)
821
+				)
822
+			);
823
+		}
824
+		if ($clear_all) {
825
+			$obj_removed = true;
826
+			$this->_model_relations[ $relationName ] = null;
827
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
+			$obj_removed = $this->_model_relations[ $relationName ];
829
+			$this->_model_relations[ $relationName ] = null;
830
+		} else {
831
+			if (
832
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
833
+				&& $object_to_remove_or_index_into_array->ID()
834
+			) {
835
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
836
+				if (
837
+					is_array($this->_model_relations[ $relationName ])
838
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+				) {
840
+					$index_found_at = null;
841
+					// find this object in the array even though it has a different key
842
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
843
+						/** @noinspection TypeUnsafeComparisonInspection */
844
+						if (
845
+							$obj instanceof EE_Base_Class
846
+							&& (
847
+								$obj == $object_to_remove_or_index_into_array
848
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
849
+							)
850
+						) {
851
+							$index_found_at = $index;
852
+							break;
853
+						}
854
+					}
855
+					if ($index_found_at) {
856
+						$index_in_cache = $index_found_at;
857
+					} else {
858
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
859
+						// if it wasn't in it to begin with. So we're done
860
+						return $object_to_remove_or_index_into_array;
861
+					}
862
+				}
863
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
864
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
865
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
866
+					/** @noinspection TypeUnsafeComparisonInspection */
867
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
868
+						$index_in_cache = $index;
869
+					}
870
+				}
871
+			} else {
872
+				$index_in_cache = $object_to_remove_or_index_into_array;
873
+			}
874
+			// supposedly we've found it. But it could just be that the client code
875
+			// provided a bad index/object
876
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
879
+			} else {
880
+				// that thing was never cached anyways.
881
+				$obj_removed = null;
882
+			}
883
+		}
884
+		return $obj_removed;
885
+	}
886
+
887
+
888
+	/**
889
+	 * update_cache_after_object_save
890
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
891
+	 * obtained after being saved to the db
892
+	 *
893
+	 * @param string        $relationName       - the type of object that is cached
894
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
895
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
896
+	 * @return boolean TRUE on success, FALSE on fail
897
+	 * @throws ReflectionException
898
+	 * @throws InvalidArgumentException
899
+	 * @throws InvalidInterfaceException
900
+	 * @throws InvalidDataTypeException
901
+	 * @throws EE_Error
902
+	 */
903
+	public function update_cache_after_object_save(
904
+		$relationName,
905
+		EE_Base_Class $newly_saved_object,
906
+		$current_cache_id = ''
907
+	) {
908
+		// verify that incoming object is of the correct type
909
+		$obj_class = 'EE_' . $relationName;
910
+		if ($newly_saved_object instanceof $obj_class) {
911
+			/* @type EE_Base_Class $newly_saved_object */
912
+			// now get the type of relation
913
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
914
+			// if this is a 1:1 relationship
915
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916
+				// then just replace the cached object with the newly saved object
917
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
918
+				return true;
919
+				// or if it's some kind of sordid feral polyamorous relationship...
920
+			}
921
+			if (
922
+				is_array($this->_model_relations[ $relationName ])
923
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
+			) {
925
+				// then remove the current cached item
926
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
+				// and cache the newly saved object using it's new ID
928
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
+				return true;
930
+			}
931
+		}
932
+		return false;
933
+	}
934
+
935
+
936
+	/**
937
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
938
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
939
+	 *
940
+	 * @param string $relationName
941
+	 * @return EE_Base_Class
942
+	 */
943
+	public function get_one_from_cache($relationName)
944
+	{
945
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
+			? $this->_model_relations[ $relationName ]
947
+			: null;
948
+		if (is_array($cached_array_or_object)) {
949
+			return array_shift($cached_array_or_object);
950
+		}
951
+		return $cached_array_or_object;
952
+	}
953
+
954
+
955
+	/**
956
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
957
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
958
+	 *
959
+	 * @param string $relationName
960
+	 * @throws ReflectionException
961
+	 * @throws InvalidArgumentException
962
+	 * @throws InvalidInterfaceException
963
+	 * @throws InvalidDataTypeException
964
+	 * @throws EE_Error
965
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
966
+	 */
967
+	public function get_all_from_cache($relationName)
968
+	{
969
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
+		// if the result is not an array, but exists, make it an array
971
+		$objects = is_array($objects) ? $objects : array($objects);
972
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
973
+		// basically, if this model object was stored in the session, and these cached model objects
974
+		// already have IDs, let's make sure they're in their model's entity mapper
975
+		// otherwise we will have duplicates next time we call
976
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
977
+		$model = EE_Registry::instance()->load_model($relationName);
978
+		foreach ($objects as $model_object) {
979
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
980
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
981
+				if ($model_object->ID()) {
982
+					$model->add_to_entity_map($model_object);
983
+				}
984
+			} else {
985
+				throw new EE_Error(
986
+					sprintf(
987
+						esc_html__(
988
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
989
+							'event_espresso'
990
+						),
991
+						$relationName,
992
+						gettype($model_object)
993
+					)
994
+				);
995
+			}
996
+		}
997
+		return $objects;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1003
+	 * matching the given query conditions.
1004
+	 *
1005
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1006
+	 * @param int   $limit              How many objects to return.
1007
+	 * @param array $query_params       Any additional conditions on the query.
1008
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1009
+	 *                                  you can indicate just the columns you want returned
1010
+	 * @return array|EE_Base_Class[]
1011
+	 * @throws ReflectionException
1012
+	 * @throws InvalidArgumentException
1013
+	 * @throws InvalidInterfaceException
1014
+	 * @throws InvalidDataTypeException
1015
+	 * @throws EE_Error
1016
+	 */
1017
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1018
+	{
1019
+		$model = $this->get_model();
1020
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1021
+			? $model->get_primary_key_field()->get_name()
1022
+			: $field_to_order_by;
1023
+		$current_value = ! empty($field) ? $this->get($field) : null;
1024
+		if (empty($field) || empty($current_value)) {
1025
+			return array();
1026
+		}
1027
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1028
+	}
1029
+
1030
+
1031
+	/**
1032
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1033
+	 * matching the given query conditions.
1034
+	 *
1035
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1036
+	 * @param int   $limit              How many objects to return.
1037
+	 * @param array $query_params       Any additional conditions on the query.
1038
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1039
+	 *                                  you can indicate just the columns you want returned
1040
+	 * @return array|EE_Base_Class[]
1041
+	 * @throws ReflectionException
1042
+	 * @throws InvalidArgumentException
1043
+	 * @throws InvalidInterfaceException
1044
+	 * @throws InvalidDataTypeException
1045
+	 * @throws EE_Error
1046
+	 */
1047
+	public function previous_x(
1048
+		$field_to_order_by = null,
1049
+		$limit = 1,
1050
+		$query_params = array(),
1051
+		$columns_to_select = null
1052
+	) {
1053
+		$model = $this->get_model();
1054
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1055
+			? $model->get_primary_key_field()->get_name()
1056
+			: $field_to_order_by;
1057
+		$current_value = ! empty($field) ? $this->get($field) : null;
1058
+		if (empty($field) || empty($current_value)) {
1059
+			return array();
1060
+		}
1061
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1062
+	}
1063
+
1064
+
1065
+	/**
1066
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1067
+	 * matching the given query conditions.
1068
+	 *
1069
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1070
+	 * @param array $query_params       Any additional conditions on the query.
1071
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1072
+	 *                                  you can indicate just the columns you want returned
1073
+	 * @return array|EE_Base_Class
1074
+	 * @throws ReflectionException
1075
+	 * @throws InvalidArgumentException
1076
+	 * @throws InvalidInterfaceException
1077
+	 * @throws InvalidDataTypeException
1078
+	 * @throws EE_Error
1079
+	 */
1080
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1081
+	{
1082
+		$model = $this->get_model();
1083
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1084
+			? $model->get_primary_key_field()->get_name()
1085
+			: $field_to_order_by;
1086
+		$current_value = ! empty($field) ? $this->get($field) : null;
1087
+		if (empty($field) || empty($current_value)) {
1088
+			return array();
1089
+		}
1090
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1096
+	 * matching the given query conditions.
1097
+	 *
1098
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1099
+	 * @param array $query_params       Any additional conditions on the query.
1100
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1101
+	 *                                  you can indicate just the column you want returned
1102
+	 * @return array|EE_Base_Class
1103
+	 * @throws ReflectionException
1104
+	 * @throws InvalidArgumentException
1105
+	 * @throws InvalidInterfaceException
1106
+	 * @throws InvalidDataTypeException
1107
+	 * @throws EE_Error
1108
+	 */
1109
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1110
+	{
1111
+		$model = $this->get_model();
1112
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1113
+			? $model->get_primary_key_field()->get_name()
1114
+			: $field_to_order_by;
1115
+		$current_value = ! empty($field) ? $this->get($field) : null;
1116
+		if (empty($field) || empty($current_value)) {
1117
+			return array();
1118
+		}
1119
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1120
+	}
1121
+
1122
+
1123
+	/**
1124
+	 * Overrides parent because parent expects old models.
1125
+	 * This also doesn't do any validation, and won't work for serialized arrays
1126
+	 *
1127
+	 * @param string $field_name
1128
+	 * @param mixed  $field_value_from_db
1129
+	 * @throws ReflectionException
1130
+	 * @throws InvalidArgumentException
1131
+	 * @throws InvalidInterfaceException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws EE_Error
1134
+	 */
1135
+	public function set_from_db($field_name, $field_value_from_db)
1136
+	{
1137
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1138
+		if ($field_obj instanceof EE_Model_Field_Base) {
1139
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1140
+			// eg, a CPT model object could have an entry in the posts table, but no
1141
+			// entry in the meta table. Meaning that all its columns in the meta table
1142
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1143
+			if ($field_value_from_db === null) {
1144
+				if ($field_obj->is_nullable()) {
1145
+					// if the field allows nulls, then let it be null
1146
+					$field_value = null;
1147
+				} else {
1148
+					$field_value = $field_obj->get_default_value();
1149
+				}
1150
+			} else {
1151
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152
+			}
1153
+			$this->_fields[ $field_name ] = $field_value;
1154
+			$this->_clear_cached_property($field_name);
1155
+		}
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * verifies that the specified field is of the correct type
1161
+	 *
1162
+	 * @param string $field_name
1163
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
+	 *                                (in cases where the same property may be used for different outputs
1165
+	 *                                - i.e. datetime, money etc.)
1166
+	 * @return mixed
1167
+	 * @throws ReflectionException
1168
+	 * @throws InvalidArgumentException
1169
+	 * @throws InvalidInterfaceException
1170
+	 * @throws InvalidDataTypeException
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function get($field_name, $extra_cache_ref = null)
1174
+	{
1175
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1181
+	 *
1182
+	 * @param  string $field_name A valid fieldname
1183
+	 * @return mixed              Whatever the raw value stored on the property is.
1184
+	 * @throws ReflectionException
1185
+	 * @throws InvalidArgumentException
1186
+	 * @throws InvalidInterfaceException
1187
+	 * @throws InvalidDataTypeException
1188
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1189
+	 */
1190
+	public function get_raw($field_name)
1191
+	{
1192
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1193
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
+			? $this->_fields[ $field_name ]->format('U')
1195
+			: $this->_fields[ $field_name ];
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * This is used to return the internal DateTime object used for a field that is a
1201
+	 * EE_Datetime_Field.
1202
+	 *
1203
+	 * @param string $field_name               The field name retrieving the DateTime object.
1204
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1205
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1206
+	 *                                         EE_Datetime_Field and but the field value is null, then
1207
+	 *                                         just null is returned (because that indicates that likely
1208
+	 *                                         this field is nullable).
1209
+	 * @throws InvalidArgumentException
1210
+	 * @throws InvalidDataTypeException
1211
+	 * @throws InvalidInterfaceException
1212
+	 * @throws ReflectionException
1213
+	 */
1214
+	public function get_DateTime_object($field_name)
1215
+	{
1216
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1217
+		if (! $field_settings instanceof EE_Datetime_Field) {
1218
+			EE_Error::add_error(
1219
+				sprintf(
1220
+					esc_html__(
1221
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1222
+						'event_espresso'
1223
+					),
1224
+					$field_name
1225
+				),
1226
+				__FILE__,
1227
+				__FUNCTION__,
1228
+				__LINE__
1229
+			);
1230
+			return false;
1231
+		}
1232
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
+			? clone $this->_fields[ $field_name ]
1234
+			: null;
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * To be used in template to immediately echo out the value, and format it for output.
1240
+	 * Eg, should call stripslashes and whatnot before echoing
1241
+	 *
1242
+	 * @param string $field_name      the name of the field as it appears in the DB
1243
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1244
+	 *                                (in cases where the same property may be used for different outputs
1245
+	 *                                - i.e. datetime, money etc.)
1246
+	 * @return void
1247
+	 * @throws ReflectionException
1248
+	 * @throws InvalidArgumentException
1249
+	 * @throws InvalidInterfaceException
1250
+	 * @throws InvalidDataTypeException
1251
+	 * @throws EE_Error
1252
+	 */
1253
+	public function e($field_name, $extra_cache_ref = null)
1254
+	{
1255
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1256
+	}
1257
+
1258
+
1259
+	/**
1260
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1261
+	 * can be easily used as the value of form input.
1262
+	 *
1263
+	 * @param string $field_name
1264
+	 * @return void
1265
+	 * @throws ReflectionException
1266
+	 * @throws InvalidArgumentException
1267
+	 * @throws InvalidInterfaceException
1268
+	 * @throws InvalidDataTypeException
1269
+	 * @throws EE_Error
1270
+	 */
1271
+	public function f($field_name)
1272
+	{
1273
+		$this->e($field_name, 'form_input');
1274
+	}
1275
+
1276
+
1277
+	/**
1278
+	 * Same as `f()` but just returns the value instead of echoing it
1279
+	 *
1280
+	 * @param string $field_name
1281
+	 * @return string
1282
+	 * @throws ReflectionException
1283
+	 * @throws InvalidArgumentException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws InvalidDataTypeException
1286
+	 * @throws EE_Error
1287
+	 */
1288
+	public function get_f($field_name)
1289
+	{
1290
+		return (string) $this->get_pretty($field_name, 'form_input');
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1296
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1297
+	 * to see what options are available.
1298
+	 *
1299
+	 * @param string $field_name
1300
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1301
+	 *                                (in cases where the same property may be used for different outputs
1302
+	 *                                - i.e. datetime, money etc.)
1303
+	 * @return mixed
1304
+	 * @throws ReflectionException
1305
+	 * @throws InvalidArgumentException
1306
+	 * @throws InvalidInterfaceException
1307
+	 * @throws InvalidDataTypeException
1308
+	 * @throws EE_Error
1309
+	 */
1310
+	public function get_pretty($field_name, $extra_cache_ref = null)
1311
+	{
1312
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * This simply returns the datetime for the given field name
1318
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1319
+	 * (and the equivalent e_date, e_time, e_datetime).
1320
+	 *
1321
+	 * @access   protected
1322
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1323
+	 * @param string|null $date_format  valid datetime format used for date
1324
+	 *                                  (if '' then we just use the default on the field,
1325
+	 *                                  if NULL we use the last-used format)
1326
+	 * @param string|null $time_format  Same as above except this is for time format
1327
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1328
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1329
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1330
+	 *                                  if field is not a valid dtt field, or void if echoing
1331
+	 * @throws EE_Error
1332
+	 * @throws ReflectionException
1333
+	 */
1334
+	protected function _get_datetime(
1335
+		string $field_name,
1336
+		?string $date_format = '',
1337
+		?string $time_format = '',
1338
+		?string $date_or_time = '',
1339
+		?bool $echo = false
1340
+	) {
1341
+		// clear cached property
1342
+		$this->_clear_cached_property($field_name);
1343
+		// reset format properties because they are used in get()
1344
+		$this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1345
+		$this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1346
+		if ($echo) {
1347
+			$this->e($field_name, $date_or_time);
1348
+			return '';
1349
+		}
1350
+		return $this->get($field_name, $date_or_time);
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
+	 * other echoes the pretty value for dtt)
1358
+	 *
1359
+	 * @param  string $field_name name of model object datetime field holding the value
1360
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
+	 * @return string            datetime value formatted
1362
+	 * @throws ReflectionException
1363
+	 * @throws InvalidArgumentException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws InvalidDataTypeException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_date($field_name, $format = '')
1369
+	{
1370
+		return $this->_get_datetime($field_name, $format, null, 'D');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @param        $field_name
1376
+	 * @param string $format
1377
+	 * @throws ReflectionException
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws InvalidDataTypeException
1381
+	 * @throws EE_Error
1382
+	 */
1383
+	public function e_date($field_name, $format = '')
1384
+	{
1385
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
+	 * other echoes the pretty value for dtt)
1393
+	 *
1394
+	 * @param  string $field_name name of model object datetime field holding the value
1395
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
+	 * @return string             datetime value formatted
1397
+	 * @throws ReflectionException
1398
+	 * @throws InvalidArgumentException
1399
+	 * @throws InvalidInterfaceException
1400
+	 * @throws InvalidDataTypeException
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	public function get_time($field_name, $format = '')
1404
+	{
1405
+		return $this->_get_datetime($field_name, null, $format, 'T');
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * @param        $field_name
1411
+	 * @param string $format
1412
+	 * @throws ReflectionException
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws InvalidDataTypeException
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function e_time($field_name, $format = '')
1419
+	{
1420
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
+	 * other echoes the pretty value for dtt)
1428
+	 *
1429
+	 * @param  string $field_name name of model object datetime field holding the value
1430
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
+	 * @return string             datetime value formatted
1433
+	 * @throws ReflectionException
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidInterfaceException
1436
+	 * @throws InvalidDataTypeException
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
+	{
1441
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * @param string $field_name
1447
+	 * @param string $dt_frmt
1448
+	 * @param string $tm_frmt
1449
+	 * @throws ReflectionException
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidInterfaceException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
+	{
1457
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
+	}
1459
+
1460
+
1461
+	/**
1462
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
+	 *
1464
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
+	 *                           on the object will be used.
1467
+	 * @return string Date and time string in set locale or false if no field exists for the given
1468
+	 * @throws ReflectionException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidInterfaceException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws EE_Error
1473
+	 *                           field name.
1474
+	 */
1475
+	public function get_i18n_datetime($field_name, $format = '')
1476
+	{
1477
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
+		return date_i18n(
1479
+			$format,
1480
+			EEH_DTT_Helper::get_timestamp_with_offset(
1481
+				$this->get_raw($field_name),
1482
+				$this->_timezone
1483
+			)
1484
+		);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
+	 * thrown.
1492
+	 *
1493
+	 * @param  string $field_name The field name being checked
1494
+	 * @throws ReflectionException
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidInterfaceException
1497
+	 * @throws InvalidDataTypeException
1498
+	 * @throws EE_Error
1499
+	 * @return EE_Datetime_Field
1500
+	 */
1501
+	protected function _get_dtt_field_settings($field_name)
1502
+	{
1503
+		$field = $this->get_model()->field_settings_for($field_name);
1504
+		// check if field is dtt
1505
+		if ($field instanceof EE_Datetime_Field) {
1506
+			return $field;
1507
+		}
1508
+		throw new EE_Error(
1509
+			sprintf(
1510
+				esc_html__(
1511
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
+					'event_espresso'
1513
+				),
1514
+				$field_name,
1515
+				self::_get_model_classname(get_class($this))
1516
+			)
1517
+		);
1518
+	}
1519
+
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * NOTE ABOUT BELOW:
1525
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
+	 * method and make sure you send the entire datetime value for setting.
1529
+	 */
1530
+	/**
1531
+	 * sets the time on a datetime property
1532
+	 *
1533
+	 * @access protected
1534
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
+	 * @throws ReflectionException
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidInterfaceException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	protected function _set_time_for($time, $fieldname)
1543
+	{
1544
+		$this->_set_date_time('T', $time, $fieldname);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * sets the date on a datetime property
1550
+	 *
1551
+	 * @access protected
1552
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
+	 * @throws ReflectionException
1555
+	 * @throws InvalidArgumentException
1556
+	 * @throws InvalidInterfaceException
1557
+	 * @throws InvalidDataTypeException
1558
+	 * @throws EE_Error
1559
+	 */
1560
+	protected function _set_date_for($date, $fieldname)
1561
+	{
1562
+		$this->_set_date_time('D', $date, $fieldname);
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1568
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1574
+	 *                                        EE_Datetime_Field property)
1575
+	 * @throws ReflectionException
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1582
+	{
1583
+		$field = $this->_get_dtt_field_settings($field_name);
1584
+		$field->set_timezone($this->_timezone);
1585
+		$field->set_date_format($this->_dt_frmt);
1586
+		$field->set_time_format($this->_tm_frmt);
1587
+		switch ($what) {
1588
+			case 'T':
1589
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1590
+					$datetime_value,
1591
+					$this->_fields[ $field_name ]
1592
+				);
1593
+				$this->_has_changes = true;
1594
+				break;
1595
+			case 'D':
1596
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1597
+					$datetime_value,
1598
+					$this->_fields[ $field_name ]
1599
+				);
1600
+				$this->_has_changes = true;
1601
+				break;
1602
+			case 'B':
1603
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1604
+				$this->_has_changes = true;
1605
+				break;
1606
+		}
1607
+		$this->_clear_cached_property($field_name);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
+	 * that could lead to some unexpected results!
1616
+	 *
1617
+	 * @access public
1618
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
+	 *                                         value being returned.
1620
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1623
+	 * @param string $append                   You can include something to append on the timestamp
1624
+	 * @throws ReflectionException
1625
+	 * @throws InvalidArgumentException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws InvalidDataTypeException
1628
+	 * @throws EE_Error
1629
+	 * @return string timestamp
1630
+	 */
1631
+	public function display_in_my_timezone(
1632
+		$field_name,
1633
+		$callback = 'get_datetime',
1634
+		$args = null,
1635
+		$prepend = '',
1636
+		$append = ''
1637
+	) {
1638
+		$timezone = EEH_DTT_Helper::get_timezone();
1639
+		if ($timezone === $this->_timezone) {
1640
+			return '';
1641
+		}
1642
+		$original_timezone = $this->_timezone;
1643
+		$this->set_timezone($timezone);
1644
+		$fn = (array) $field_name;
1645
+		$args = array_merge($fn, (array) $args);
1646
+		if (! method_exists($this, $callback)) {
1647
+			throw new EE_Error(
1648
+				sprintf(
1649
+					esc_html__(
1650
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
+						'event_espresso'
1652
+					),
1653
+					$callback
1654
+				)
1655
+			);
1656
+		}
1657
+		$args = (array) $args;
1658
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
+		$this->set_timezone($original_timezone);
1660
+		return $return;
1661
+	}
1662
+
1663
+
1664
+	/**
1665
+	 * Deletes this model object.
1666
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
+	 * override
1668
+	 * `EE_Base_Class::_delete` NOT this class.
1669
+	 *
1670
+	 * @return boolean | int
1671
+	 * @throws ReflectionException
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidInterfaceException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	public function delete()
1678
+	{
1679
+		/**
1680
+		 * Called just before the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1688
+		 */
1689
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
+		$result = $this->_delete();
1691
+		/**
1692
+		 * Called just after the `EE_Base_Class::_delete` method call.
1693
+		 * Note:
1694
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
+		 * should be aware that `_delete` may not always result in a permanent delete.
1696
+		 * For example `EE_Soft_Base_Class::_delete`
1697
+		 * soft deletes (trash) the object and does not permanently delete it.
1698
+		 *
1699
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1700
+		 * @param boolean       $result
1701
+		 */
1702
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
+		return $result;
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Calls the specific delete method for the instantiated class.
1709
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
+	 * `EE_Base_Class::delete`
1712
+	 *
1713
+	 * @return bool|int
1714
+	 * @throws ReflectionException
1715
+	 * @throws InvalidArgumentException
1716
+	 * @throws InvalidInterfaceException
1717
+	 * @throws InvalidDataTypeException
1718
+	 * @throws EE_Error
1719
+	 */
1720
+	protected function _delete()
1721
+	{
1722
+		return $this->delete_permanently();
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * Deletes this model object permanently from db
1728
+	 * (but keep in mind related models may block the delete and return an error)
1729
+	 *
1730
+	 * @return bool | int
1731
+	 * @throws ReflectionException
1732
+	 * @throws InvalidArgumentException
1733
+	 * @throws InvalidInterfaceException
1734
+	 * @throws InvalidDataTypeException
1735
+	 * @throws EE_Error
1736
+	 */
1737
+	public function delete_permanently()
1738
+	{
1739
+		/**
1740
+		 * Called just before HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
+		$model = $this->get_model();
1746
+		$result = $model->delete_permanently_by_ID($this->ID());
1747
+		$this->refresh_cache_of_related_objects();
1748
+		/**
1749
+		 * Called just after HARD deleting a model object
1750
+		 *
1751
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1752
+		 * @param boolean       $result
1753
+		 */
1754
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
+		return $result;
1756
+	}
1757
+
1758
+
1759
+	/**
1760
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
+	 * related model objects
1762
+	 *
1763
+	 * @throws ReflectionException
1764
+	 * @throws InvalidArgumentException
1765
+	 * @throws InvalidInterfaceException
1766
+	 * @throws InvalidDataTypeException
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function refresh_cache_of_related_objects()
1770
+	{
1771
+		$model = $this->get_model();
1772
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
+			if (! empty($this->_model_relations[ $relation_name ])) {
1774
+				$related_objects = $this->_model_relations[ $relation_name ];
1775
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
+					// this relation only stores a single model object, not an array
1777
+					// but let's make it consistent
1778
+					$related_objects = array($related_objects);
1779
+				}
1780
+				foreach ($related_objects as $related_object) {
1781
+					// only refresh their cache if they're in memory
1782
+					if ($related_object instanceof EE_Base_Class) {
1783
+						$related_object->clear_cache(
1784
+							$model->get_this_model_name(),
1785
+							$this
1786
+						);
1787
+					}
1788
+				}
1789
+			}
1790
+		}
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1796
+	 * object just before saving.
1797
+	 *
1798
+	 * @access public
1799
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1800
+	 *                                 if provided during the save() method (often client code will change the fields'
1801
+	 *                                 values before calling save)
1802
+	 * @return bool|int|string         1 on a successful update
1803
+	 *                                 the ID of the new entry on insert
1804
+	 *                                 0 on failure or if the model object isn't allowed to persist
1805
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1806
+	 * @throws InvalidInterfaceException
1807
+	 * @throws InvalidDataTypeException
1808
+	 * @throws EE_Error
1809
+	 * @throws InvalidArgumentException
1810
+	 * @throws ReflectionException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 */
1814
+	public function save($set_cols_n_values = array())
1815
+	{
1816
+		$model = $this->get_model();
1817
+		/**
1818
+		 * Filters the fields we're about to save on the model object
1819
+		 *
1820
+		 * @param array         $set_cols_n_values
1821
+		 * @param EE_Base_Class $model_object
1822
+		 */
1823
+		$set_cols_n_values = (array) apply_filters(
1824
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
+			$set_cols_n_values,
1826
+			$this
1827
+		);
1828
+		// set attributes as provided in $set_cols_n_values
1829
+		foreach ($set_cols_n_values as $column => $value) {
1830
+			$this->set($column, $value);
1831
+		}
1832
+		// no changes ? then don't do anything
1833
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
+			return 0;
1835
+		}
1836
+		/**
1837
+		 * Saving a model object.
1838
+		 * Before we perform a save, this action is fired.
1839
+		 *
1840
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1841
+		 */
1842
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
+		if (! $this->allow_persist()) {
1844
+			return 0;
1845
+		}
1846
+		// now get current attribute values
1847
+		$save_cols_n_values = $this->_fields;
1848
+		// if the object already has an ID, update it. Otherwise, insert it
1849
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
+		// They have been
1851
+		$old_assumption_concerning_value_preparation = $model
1852
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1853
+		$model->assume_values_already_prepared_by_model_object(true);
1854
+		// does this model have an autoincrement PK?
1855
+		if ($model->has_primary_key_field()) {
1856
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1857
+				// ok check if it's set, if so: update; if not, insert
1858
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
+				} else {
1861
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
+					$results = $model->insert($save_cols_n_values);
1863
+					if ($results) {
1864
+						// if successful, set the primary key
1865
+						// but don't use the normal SET method, because it will check if
1866
+						// an item with the same ID exists in the mapper & db, then
1867
+						// will find it in the db (because we just added it) and THAT object
1868
+						// will get added to the mapper before we can add this one!
1869
+						// but if we just avoid using the SET method, all that headache can be avoided
1870
+						$pk_field_name = $model->primary_key_name();
1871
+						$this->_fields[ $pk_field_name ] = $results;
1872
+						$this->_clear_cached_property($pk_field_name);
1873
+						$model->add_to_entity_map($this);
1874
+						$this->_update_cached_related_model_objs_fks();
1875
+					}
1876
+				}
1877
+			} else {// PK is NOT auto-increment
1878
+				// so check if one like it already exists in the db
1879
+				if ($model->exists_by_ID($this->ID())) {
1880
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1881
+						throw new EE_Error(
1882
+							sprintf(
1883
+								esc_html__(
1884
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
+									'event_espresso'
1886
+								),
1887
+								get_class($this),
1888
+								get_class($model) . '::instance()->add_to_entity_map()',
1889
+								get_class($model) . '::instance()->get_one_by_ID()',
1890
+								'<br />'
1891
+							)
1892
+						);
1893
+					}
1894
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
+				} else {
1896
+					$results = $model->insert($save_cols_n_values);
1897
+					$this->_update_cached_related_model_objs_fks();
1898
+				}
1899
+			}
1900
+		} else {// there is NO primary key
1901
+			$already_in_db = false;
1902
+			foreach ($model->unique_indexes() as $index) {
1903
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
+				if ($model->exists(array($uniqueness_where_params))) {
1905
+					$already_in_db = true;
1906
+				}
1907
+			}
1908
+			if ($already_in_db) {
1909
+				$combined_pk_fields_n_values = array_intersect_key(
1910
+					$save_cols_n_values,
1911
+					$model->get_combined_primary_key_fields()
1912
+				);
1913
+				$results = $model->update(
1914
+					$save_cols_n_values,
1915
+					$combined_pk_fields_n_values
1916
+				);
1917
+			} else {
1918
+				$results = $model->insert($save_cols_n_values);
1919
+			}
1920
+		}
1921
+		// restore the old assumption about values being prepared by the model object
1922
+		$model->assume_values_already_prepared_by_model_object(
1923
+			$old_assumption_concerning_value_preparation
1924
+		);
1925
+		/**
1926
+		 * After saving the model object this action is called
1927
+		 *
1928
+		 * @param EE_Base_Class $model_object which was just saved
1929
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
+		 */
1932
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
+		$this->_has_changes = false;
1934
+		return $results;
1935
+	}
1936
+
1937
+
1938
+	/**
1939
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
+	 *
1947
+	 * @return void
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 */
1954
+	protected function _update_cached_related_model_objs_fks()
1955
+	{
1956
+		$model = $this->get_model();
1957
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
+						$model->get_this_model_name()
1962
+					);
1963
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
+					if ($related_model_obj_in_cache->ID()) {
1965
+						$related_model_obj_in_cache->save();
1966
+					}
1967
+				}
1968
+			}
1969
+		}
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Saves this model object and its NEW cached relations to the database.
1975
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1977
+	 * because otherwise, there's a potential for infinite looping of saving
1978
+	 * Saves the cached related model objects, and ensures the relation between them
1979
+	 * and this object and properly setup
1980
+	 *
1981
+	 * @return int ID of new model object on save; 0 on failure+
1982
+	 * @throws ReflectionException
1983
+	 * @throws InvalidArgumentException
1984
+	 * @throws InvalidInterfaceException
1985
+	 * @throws InvalidDataTypeException
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public function save_new_cached_related_model_objs()
1989
+	{
1990
+		// make sure this has been saved
1991
+		if (! $this->ID()) {
1992
+			$id = $this->save();
1993
+		} else {
1994
+			$id = $this->ID();
1995
+		}
1996
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
+			if ($this->_model_relations[ $relationName ]) {
1999
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
+				/* @var $related_model_obj EE_Base_Class */
2002
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2004
+					// but ONLY if it DOES NOT exist in the DB
2005
+					$related_model_obj = $this->_model_relations[ $relationName ];
2006
+					// if( ! $related_model_obj->ID()){
2007
+					$this->_add_relation_to($related_model_obj, $relationName);
2008
+					$related_model_obj->save_new_cached_related_model_objs();
2009
+					// }
2010
+				} else {
2011
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2013
+						// but ONLY if it DOES NOT exist in the DB
2014
+						// if( ! $related_model_obj->ID()){
2015
+						$this->_add_relation_to($related_model_obj, $relationName);
2016
+						$related_model_obj->save_new_cached_related_model_objs();
2017
+						// }
2018
+					}
2019
+				}
2020
+			}
2021
+		}
2022
+		return $id;
2023
+	}
2024
+
2025
+
2026
+	/**
2027
+	 * for getting a model while instantiated.
2028
+	 *
2029
+	 * @return EEM_Base | EEM_CPT_Base
2030
+	 * @throws ReflectionException
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidInterfaceException
2033
+	 * @throws InvalidDataTypeException
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function get_model()
2037
+	{
2038
+		if (! $this->_model) {
2039
+			$modelName = self::_get_model_classname(get_class($this));
2040
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
+		} else {
2042
+			$this->_model->set_timezone($this->_timezone);
2043
+		}
2044
+		return $this->_model;
2045
+	}
2046
+
2047
+
2048
+	/**
2049
+	 * @param $props_n_values
2050
+	 * @param $classname
2051
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
+	 * @throws ReflectionException
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 */
2058
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
+	{
2060
+		// TODO: will not work for Term_Relationships because they have no PK!
2061
+		$primary_id_ref = self::_get_primary_key_name($classname);
2062
+		if (
2063
+			array_key_exists($primary_id_ref, $props_n_values)
2064
+			&& ! empty($props_n_values[ $primary_id_ref ])
2065
+		) {
2066
+			$id = $props_n_values[ $primary_id_ref ];
2067
+			return self::_get_model($classname)->get_from_entity_map($id);
2068
+		}
2069
+		return false;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
+	 * we return false.
2078
+	 *
2079
+	 * @param  array  $props_n_values   incoming array of properties and their values
2080
+	 * @param  string $classname        the classname of the child class
2081
+	 * @param null    $timezone
2082
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
+	 *                                  date_format and the second value is the time format
2084
+	 * @return mixed (EE_Base_Class|bool)
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidInterfaceException
2087
+	 * @throws InvalidDataTypeException
2088
+	 * @throws EE_Error
2089
+	 * @throws ReflectionException
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 */
2093
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
+	{
2095
+		$existing = null;
2096
+		$model = self::_get_model($classname, $timezone);
2097
+		if ($model->has_primary_key_field()) {
2098
+			$primary_id_ref = self::_get_primary_key_name($classname);
2099
+			if (
2100
+				array_key_exists($primary_id_ref, $props_n_values)
2101
+				&& ! empty($props_n_values[ $primary_id_ref ])
2102
+			) {
2103
+				$existing = $model->get_one_by_ID(
2104
+					$props_n_values[ $primary_id_ref ]
2105
+				);
2106
+			}
2107
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
+			// no primary key on this model, but there's still a matching item in the DB
2109
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
+				self::_get_model($classname, $timezone)
2111
+					->get_index_primary_key_string($props_n_values)
2112
+			);
2113
+		}
2114
+		if ($existing) {
2115
+			// set date formats if present before setting values
2116
+			if (! empty($date_formats) && is_array($date_formats)) {
2117
+				$existing->set_date_format($date_formats[0]);
2118
+				$existing->set_time_format($date_formats[1]);
2119
+			} else {
2120
+				// set default formats for date and time
2121
+				$existing->set_date_format(get_option('date_format'));
2122
+				$existing->set_time_format(get_option('time_format'));
2123
+			}
2124
+			foreach ($props_n_values as $property => $field_value) {
2125
+				$existing->set($property, $field_value);
2126
+			}
2127
+			return $existing;
2128
+		}
2129
+		return false;
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Gets the EEM_*_Model for this class
2135
+	 *
2136
+	 * @access public now, as this is more convenient
2137
+	 * @param      $classname
2138
+	 * @param null $timezone
2139
+	 * @throws ReflectionException
2140
+	 * @throws InvalidArgumentException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws InvalidDataTypeException
2143
+	 * @throws EE_Error
2144
+	 * @return EEM_Base
2145
+	 */
2146
+	protected static function _get_model($classname, $timezone = null)
2147
+	{
2148
+		// find model for this class
2149
+		if (! $classname) {
2150
+			throw new EE_Error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
+						'event_espresso'
2155
+					),
2156
+					$classname
2157
+				)
2158
+			);
2159
+		}
2160
+		$modelName = self::_get_model_classname($classname);
2161
+		return self::_get_model_instance_with_name($modelName, $timezone);
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
+	 *
2168
+	 * @param string $model_classname
2169
+	 * @param null   $timezone
2170
+	 * @return EEM_Base
2171
+	 * @throws ReflectionException
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 */
2177
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
+	{
2179
+		$model_classname = str_replace('EEM_', '', $model_classname);
2180
+		$model = EE_Registry::instance()->load_model($model_classname);
2181
+		$model->set_timezone($timezone);
2182
+		return $model;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2188
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2189
+	 *
2190
+	 * @param null $model_name
2191
+	 * @return string like EEM_Attendee
2192
+	 */
2193
+	private static function _get_model_classname($model_name = null)
2194
+	{
2195
+		if (strpos($model_name, 'EE_') === 0) {
2196
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
+		} else {
2198
+			$model_classname = 'EEM_' . $model_name;
2199
+		}
2200
+		return $model_classname;
2201
+	}
2202
+
2203
+
2204
+	/**
2205
+	 * returns the name of the primary key attribute
2206
+	 *
2207
+	 * @param null $classname
2208
+	 * @throws ReflectionException
2209
+	 * @throws InvalidArgumentException
2210
+	 * @throws InvalidInterfaceException
2211
+	 * @throws InvalidDataTypeException
2212
+	 * @throws EE_Error
2213
+	 * @return string
2214
+	 */
2215
+	protected static function _get_primary_key_name($classname = null)
2216
+	{
2217
+		if (! $classname) {
2218
+			throw new EE_Error(
2219
+				sprintf(
2220
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
+					$classname
2222
+				)
2223
+			);
2224
+		}
2225
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
+	}
2227
+
2228
+
2229
+	/**
2230
+	 * Gets the value of the primary key.
2231
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
+	 *
2235
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
+	 * @throws ReflectionException
2237
+	 * @throws InvalidArgumentException
2238
+	 * @throws InvalidInterfaceException
2239
+	 * @throws InvalidDataTypeException
2240
+	 * @throws EE_Error
2241
+	 */
2242
+	public function ID()
2243
+	{
2244
+		$model = $this->get_model();
2245
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2246
+		if ($model->has_primary_key_field()) {
2247
+			return $this->_fields[ $model->primary_key_name() ];
2248
+		}
2249
+		return $model->get_index_primary_key_string($this->_fields);
2250
+	}
2251
+
2252
+
2253
+	/**
2254
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2255
+	 * @param string                   $relationName
2256
+	 * @return bool
2257
+	 * @throws EE_Error
2258
+	 * @throws ReflectionException
2259
+	 * @since   $VID:$
2260
+	 */
2261
+	public function hasRelation($otherModelObjectOrID, string $relationName): bool
2262
+	{
2263
+		$other_model = self::_get_model_instance_with_name(
2264
+			self::_get_model_classname($relationName),
2265
+			$this->_timezone
2266
+		);
2267
+		$primary_key = $other_model->primary_key_name();
2268
+		/** @var EE_Base_Class $otherModelObject */
2269
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2270
+		return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2271
+	}
2272
+
2273
+
2274
+	/**
2275
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2276
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2277
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2278
+	 *
2279
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2280
+	 * @param string $relationName                     eg 'Events','Question',etc.
2281
+	 *                                                 an attendee to a group, you also want to specify which role they
2282
+	 *                                                 will have in that group. So you would use this parameter to
2283
+	 *                                                 specify array('role-column-name'=>'role-id')
2284
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2285
+	 *                                                 allow you to further constrict the relation to being added.
2286
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2287
+	 *                                                 column on the JOIN table and currently only the HABTM models
2288
+	 *                                                 accept these additional conditions.  Also remember that if an
2289
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2290
+	 *                                                 NEW row is created in the join table.
2291
+	 * @param null   $cache_id
2292
+	 * @throws ReflectionException
2293
+	 * @throws InvalidArgumentException
2294
+	 * @throws InvalidInterfaceException
2295
+	 * @throws InvalidDataTypeException
2296
+	 * @throws EE_Error
2297
+	 * @return EE_Base_Class the object the relation was added to
2298
+	 */
2299
+	public function _add_relation_to(
2300
+		$otherObjectModelObjectOrID,
2301
+		$relationName,
2302
+		$extra_join_model_fields_n_values = array(),
2303
+		$cache_id = null
2304
+	) {
2305
+		$model = $this->get_model();
2306
+		// if this thing exists in the DB, save the relation to the DB
2307
+		if ($this->ID()) {
2308
+			$otherObject = $model->add_relationship_to(
2309
+				$this,
2310
+				$otherObjectModelObjectOrID,
2311
+				$relationName,
2312
+				$extra_join_model_fields_n_values
2313
+			);
2314
+			// clear cache so future get_many_related and get_first_related() return new results.
2315
+			$this->clear_cache($relationName, $otherObject, true);
2316
+			if ($otherObject instanceof EE_Base_Class) {
2317
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2318
+			}
2319
+		} else {
2320
+			// this thing doesn't exist in the DB,  so just cache it
2321
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2322
+				throw new EE_Error(
2323
+					sprintf(
2324
+						esc_html__(
2325
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2326
+							'event_espresso'
2327
+						),
2328
+						$otherObjectModelObjectOrID,
2329
+						get_class($this)
2330
+					)
2331
+				);
2332
+			}
2333
+			$otherObject = $otherObjectModelObjectOrID;
2334
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2335
+		}
2336
+		if ($otherObject instanceof EE_Base_Class) {
2337
+			// fix the reciprocal relation too
2338
+			if ($otherObject->ID()) {
2339
+				// its saved so assumed relations exist in the DB, so we can just
2340
+				// clear the cache so future queries use the updated info in the DB
2341
+				$otherObject->clear_cache(
2342
+					$model->get_this_model_name(),
2343
+					null,
2344
+					true
2345
+				);
2346
+			} else {
2347
+				// it's not saved, so it caches relations like this
2348
+				$otherObject->cache($model->get_this_model_name(), $this);
2349
+			}
2350
+		}
2351
+		return $otherObject;
2352
+	}
2353
+
2354
+
2355
+	/**
2356
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2357
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2358
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2359
+	 * from the cache
2360
+	 *
2361
+	 * @param mixed  $otherObjectModelObjectOrID
2362
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2363
+	 *                to the DB yet
2364
+	 * @param string $relationName
2365
+	 * @param array  $where_query
2366
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2367
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2368
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2369
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2370
+	 *                deleted.
2371
+	 * @return EE_Base_Class the relation was removed from
2372
+	 * @throws ReflectionException
2373
+	 * @throws InvalidArgumentException
2374
+	 * @throws InvalidInterfaceException
2375
+	 * @throws InvalidDataTypeException
2376
+	 * @throws EE_Error
2377
+	 */
2378
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2379
+	{
2380
+		if ($this->ID()) {
2381
+			// if this exists in the DB, save the relation change to the DB too
2382
+			$otherObject = $this->get_model()->remove_relationship_to(
2383
+				$this,
2384
+				$otherObjectModelObjectOrID,
2385
+				$relationName,
2386
+				$where_query
2387
+			);
2388
+			$this->clear_cache(
2389
+				$relationName,
2390
+				$otherObject
2391
+			);
2392
+		} else {
2393
+			// this doesn't exist in the DB, just remove it from the cache
2394
+			$otherObject = $this->clear_cache(
2395
+				$relationName,
2396
+				$otherObjectModelObjectOrID
2397
+			);
2398
+		}
2399
+		if ($otherObject instanceof EE_Base_Class) {
2400
+			$otherObject->clear_cache(
2401
+				$this->get_model()->get_this_model_name(),
2402
+				$this
2403
+			);
2404
+		}
2405
+		return $otherObject;
2406
+	}
2407
+
2408
+
2409
+	/**
2410
+	 * Removes ALL the related things for the $relationName.
2411
+	 *
2412
+	 * @param string $relationName
2413
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2414
+	 * @return EE_Base_Class
2415
+	 * @throws ReflectionException
2416
+	 * @throws InvalidArgumentException
2417
+	 * @throws InvalidInterfaceException
2418
+	 * @throws InvalidDataTypeException
2419
+	 * @throws EE_Error
2420
+	 */
2421
+	public function _remove_relations($relationName, $where_query_params = array())
2422
+	{
2423
+		if ($this->ID()) {
2424
+			// if this exists in the DB, save the relation change to the DB too
2425
+			$otherObjects = $this->get_model()->remove_relations(
2426
+				$this,
2427
+				$relationName,
2428
+				$where_query_params
2429
+			);
2430
+			$this->clear_cache(
2431
+				$relationName,
2432
+				null,
2433
+				true
2434
+			);
2435
+		} else {
2436
+			// this doesn't exist in the DB, just remove it from the cache
2437
+			$otherObjects = $this->clear_cache(
2438
+				$relationName,
2439
+				null,
2440
+				true
2441
+			);
2442
+		}
2443
+		if (is_array($otherObjects)) {
2444
+			foreach ($otherObjects as $otherObject) {
2445
+				$otherObject->clear_cache(
2446
+					$this->get_model()->get_this_model_name(),
2447
+					$this
2448
+				);
2449
+			}
2450
+		}
2451
+		return $otherObjects;
2452
+	}
2453
+
2454
+
2455
+	/**
2456
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2457
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2458
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2459
+	 * because we want to get even deleted items etc.
2460
+	 *
2461
+	 * @param string $relationName key in the model's _model_relations array
2462
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2463
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2464
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2465
+	 *                             results if you want IDs
2466
+	 * @throws ReflectionException
2467
+	 * @throws InvalidArgumentException
2468
+	 * @throws InvalidInterfaceException
2469
+	 * @throws InvalidDataTypeException
2470
+	 * @throws EE_Error
2471
+	 */
2472
+	public function get_many_related($relationName, $query_params = array())
2473
+	{
2474
+		if ($this->ID()) {
2475
+			// this exists in the DB, so get the related things from either the cache or the DB
2476
+			// if there are query parameters, forget about caching the related model objects.
2477
+			if ($query_params) {
2478
+				$related_model_objects = $this->get_model()->get_all_related(
2479
+					$this,
2480
+					$relationName,
2481
+					$query_params
2482
+				);
2483
+			} else {
2484
+				// did we already cache the result of this query?
2485
+				$cached_results = $this->get_all_from_cache($relationName);
2486
+				if (! $cached_results) {
2487
+					$related_model_objects = $this->get_model()->get_all_related(
2488
+						$this,
2489
+						$relationName,
2490
+						$query_params
2491
+					);
2492
+					// if no query parameters were passed, then we got all the related model objects
2493
+					// for that relation. We can cache them then.
2494
+					foreach ($related_model_objects as $related_model_object) {
2495
+						$this->cache($relationName, $related_model_object);
2496
+					}
2497
+				} else {
2498
+					$related_model_objects = $cached_results;
2499
+				}
2500
+			}
2501
+		} else {
2502
+			// this doesn't exist in the DB, so just get the related things from the cache
2503
+			$related_model_objects = $this->get_all_from_cache($relationName);
2504
+		}
2505
+		return $related_model_objects;
2506
+	}
2507
+
2508
+
2509
+	/**
2510
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2511
+	 * unless otherwise specified in the $query_params
2512
+	 *
2513
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2514
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2515
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2516
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2517
+	 *                               that by the setting $distinct to TRUE;
2518
+	 * @return int
2519
+	 * @throws ReflectionException
2520
+	 * @throws InvalidArgumentException
2521
+	 * @throws InvalidInterfaceException
2522
+	 * @throws InvalidDataTypeException
2523
+	 * @throws EE_Error
2524
+	 */
2525
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2526
+	{
2527
+		return $this->get_model()->count_related(
2528
+			$this,
2529
+			$relation_name,
2530
+			$query_params,
2531
+			$field_to_count,
2532
+			$distinct
2533
+		);
2534
+	}
2535
+
2536
+
2537
+	/**
2538
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2539
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2540
+	 *
2541
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2542
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2543
+	 * @param string $field_to_sum  name of field to count by.
2544
+	 *                              By default, uses primary key
2545
+	 *                              (which doesn't make much sense, so you should probably change it)
2546
+	 * @return int
2547
+	 * @throws ReflectionException
2548
+	 * @throws InvalidArgumentException
2549
+	 * @throws InvalidInterfaceException
2550
+	 * @throws InvalidDataTypeException
2551
+	 * @throws EE_Error
2552
+	 */
2553
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2554
+	{
2555
+		return $this->get_model()->sum_related(
2556
+			$this,
2557
+			$relation_name,
2558
+			$query_params,
2559
+			$field_to_sum
2560
+		);
2561
+	}
2562
+
2563
+
2564
+	/**
2565
+	 * Gets the first (ie, one) related model object of the specified type.
2566
+	 *
2567
+	 * @param string $relationName key in the model's _model_relations array
2568
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2569
+	 * @return EE_Base_Class (not an array, a single object)
2570
+	 * @throws ReflectionException
2571
+	 * @throws InvalidArgumentException
2572
+	 * @throws InvalidInterfaceException
2573
+	 * @throws InvalidDataTypeException
2574
+	 * @throws EE_Error
2575
+	 */
2576
+	public function get_first_related($relationName, $query_params = array())
2577
+	{
2578
+		$model = $this->get_model();
2579
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2580
+			// if they've provided some query parameters, don't bother trying to cache the result
2581
+			// also make sure we're not caching the result of get_first_related
2582
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2583
+			if (
2584
+				$query_params
2585
+				|| ! $model->related_settings_for($relationName)
2586
+					 instanceof
2587
+					 EE_Belongs_To_Relation
2588
+			) {
2589
+				$related_model_object = $model->get_first_related(
2590
+					$this,
2591
+					$relationName,
2592
+					$query_params
2593
+				);
2594
+			} else {
2595
+				// first, check if we've already cached the result of this query
2596
+				$cached_result = $this->get_one_from_cache($relationName);
2597
+				if (! $cached_result) {
2598
+					$related_model_object = $model->get_first_related(
2599
+						$this,
2600
+						$relationName,
2601
+						$query_params
2602
+					);
2603
+					$this->cache($relationName, $related_model_object);
2604
+				} else {
2605
+					$related_model_object = $cached_result;
2606
+				}
2607
+			}
2608
+		} else {
2609
+			$related_model_object = null;
2610
+			// this doesn't exist in the Db,
2611
+			// but maybe the relation is of type belongs to, and so the related thing might
2612
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2613
+				$related_model_object = $model->get_first_related(
2614
+					$this,
2615
+					$relationName,
2616
+					$query_params
2617
+				);
2618
+			}
2619
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2620
+			// just get what's cached on this object
2621
+			if (! $related_model_object) {
2622
+				$related_model_object = $this->get_one_from_cache($relationName);
2623
+			}
2624
+		}
2625
+		return $related_model_object;
2626
+	}
2627
+
2628
+
2629
+	/**
2630
+	 * Does a delete on all related objects of type $relationName and removes
2631
+	 * the current model object's relation to them. If they can't be deleted (because
2632
+	 * of blocking related model objects) does nothing. If the related model objects are
2633
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2634
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2635
+	 *
2636
+	 * @param string $relationName
2637
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
+	 * @return int how many deleted
2639
+	 * @throws ReflectionException
2640
+	 * @throws InvalidArgumentException
2641
+	 * @throws InvalidInterfaceException
2642
+	 * @throws InvalidDataTypeException
2643
+	 * @throws EE_Error
2644
+	 */
2645
+	public function delete_related($relationName, $query_params = array())
2646
+	{
2647
+		if ($this->ID()) {
2648
+			$count = $this->get_model()->delete_related(
2649
+				$this,
2650
+				$relationName,
2651
+				$query_params
2652
+			);
2653
+		} else {
2654
+			$count = count($this->get_all_from_cache($relationName));
2655
+			$this->clear_cache($relationName, null, true);
2656
+		}
2657
+		return $count;
2658
+	}
2659
+
2660
+
2661
+	/**
2662
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2663
+	 * the current model object's relation to them. If they can't be deleted (because
2664
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2665
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2666
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2667
+	 *
2668
+	 * @param string $relationName
2669
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
+	 * @return int how many deleted (including those soft deleted)
2671
+	 * @throws ReflectionException
2672
+	 * @throws InvalidArgumentException
2673
+	 * @throws InvalidInterfaceException
2674
+	 * @throws InvalidDataTypeException
2675
+	 * @throws EE_Error
2676
+	 */
2677
+	public function delete_related_permanently($relationName, $query_params = array())
2678
+	{
2679
+		if ($this->ID()) {
2680
+			$count = $this->get_model()->delete_related_permanently(
2681
+				$this,
2682
+				$relationName,
2683
+				$query_params
2684
+			);
2685
+		} else {
2686
+			$count = count($this->get_all_from_cache($relationName));
2687
+		}
2688
+		$this->clear_cache($relationName, null, true);
2689
+		return $count;
2690
+	}
2691
+
2692
+
2693
+	/**
2694
+	 * is_set
2695
+	 * Just a simple utility function children can use for checking if property exists
2696
+	 *
2697
+	 * @access  public
2698
+	 * @param  string $field_name property to check
2699
+	 * @return bool                              TRUE if existing,FALSE if not.
2700
+	 */
2701
+	public function is_set($field_name)
2702
+	{
2703
+		return isset($this->_fields[ $field_name ]);
2704
+	}
2705
+
2706
+
2707
+	/**
2708
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2709
+	 * EE_Error exception if they don't
2710
+	 *
2711
+	 * @param  mixed (string|array) $properties properties to check
2712
+	 * @throws EE_Error
2713
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2714
+	 */
2715
+	protected function _property_exists($properties)
2716
+	{
2717
+		foreach ((array) $properties as $property_name) {
2718
+			// first make sure this property exists
2719
+			if (! $this->_fields[ $property_name ]) {
2720
+				throw new EE_Error(
2721
+					sprintf(
2722
+						esc_html__(
2723
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2724
+							'event_espresso'
2725
+						),
2726
+						$property_name
2727
+					)
2728
+				);
2729
+			}
2730
+		}
2731
+		return true;
2732
+	}
2733
+
2734
+
2735
+	/**
2736
+	 * This simply returns an array of model fields for this object
2737
+	 *
2738
+	 * @return array
2739
+	 * @throws ReflectionException
2740
+	 * @throws InvalidArgumentException
2741
+	 * @throws InvalidInterfaceException
2742
+	 * @throws InvalidDataTypeException
2743
+	 * @throws EE_Error
2744
+	 */
2745
+	public function model_field_array()
2746
+	{
2747
+		$fields = $this->get_model()->field_settings(false);
2748
+		$properties = array();
2749
+		// remove prepended underscore
2750
+		foreach ($fields as $field_name => $settings) {
2751
+			$properties[ $field_name ] = $this->get($field_name);
2752
+		}
2753
+		return $properties;
2754
+	}
2755
+
2756
+
2757
+	/**
2758
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2759
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2760
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2761
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2762
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2763
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2764
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2765
+	 * and accepts 2 arguments: the object on which the function was called,
2766
+	 * and an array of the original arguments passed to the function.
2767
+	 * Whatever their callback function returns will be returned by this function.
2768
+	 * Example: in functions.php (or in a plugin):
2769
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2770
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2771
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2772
+	 *          return $previousReturnValue.$returnString;
2773
+	 *      }
2774
+	 * require('EE_Answer.class.php');
2775
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2776
+	 *      ->my_callback('monkeys',100);
2777
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2778
+	 *
2779
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2780
+	 * @param array  $args       array of original arguments passed to the function
2781
+	 * @throws EE_Error
2782
+	 * @return mixed whatever the plugin which calls add_filter decides
2783
+	 */
2784
+	public function __call($methodName, $args)
2785
+	{
2786
+		$className = get_class($this);
2787
+		$tagName = "FHEE__{$className}__{$methodName}";
2788
+		if (! has_filter($tagName)) {
2789
+			throw new EE_Error(
2790
+				sprintf(
2791
+					esc_html__(
2792
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2793
+						'event_espresso'
2794
+					),
2795
+					$methodName,
2796
+					$className,
2797
+					$tagName
2798
+				)
2799
+			);
2800
+		}
2801
+		return apply_filters($tagName, null, $this, $args);
2802
+	}
2803
+
2804
+
2805
+	/**
2806
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2807
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2808
+	 *
2809
+	 * @param string $meta_key
2810
+	 * @param mixed  $meta_value
2811
+	 * @param mixed  $previous_value
2812
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2813
+	 *                  NOTE: if the values haven't changed, returns 0
2814
+	 * @throws InvalidArgumentException
2815
+	 * @throws InvalidInterfaceException
2816
+	 * @throws InvalidDataTypeException
2817
+	 * @throws EE_Error
2818
+	 * @throws ReflectionException
2819
+	 */
2820
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2821
+	{
2822
+		$query_params = array(
2823
+			array(
2824
+				'EXM_key'  => $meta_key,
2825
+				'OBJ_ID'   => $this->ID(),
2826
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2827
+			),
2828
+		);
2829
+		if ($previous_value !== null) {
2830
+			$query_params[0]['EXM_value'] = $meta_value;
2831
+		}
2832
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2833
+		if (! $existing_rows_like_that) {
2834
+			return $this->add_extra_meta($meta_key, $meta_value);
2835
+		}
2836
+		foreach ($existing_rows_like_that as $existing_row) {
2837
+			$existing_row->save(array('EXM_value' => $meta_value));
2838
+		}
2839
+		return count($existing_rows_like_that);
2840
+	}
2841
+
2842
+
2843
+	/**
2844
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2845
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2846
+	 * extra meta row was entered, false if not
2847
+	 *
2848
+	 * @param string  $meta_key
2849
+	 * @param mixed   $meta_value
2850
+	 * @param boolean $unique
2851
+	 * @return boolean
2852
+	 * @throws InvalidArgumentException
2853
+	 * @throws InvalidInterfaceException
2854
+	 * @throws InvalidDataTypeException
2855
+	 * @throws EE_Error
2856
+	 * @throws ReflectionException
2857
+	 * @throws ReflectionException
2858
+	 */
2859
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2860
+	{
2861
+		if ($unique) {
2862
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2863
+				array(
2864
+					array(
2865
+						'EXM_key'  => $meta_key,
2866
+						'OBJ_ID'   => $this->ID(),
2867
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2868
+					),
2869
+				)
2870
+			);
2871
+			if ($existing_extra_meta) {
2872
+				return false;
2873
+			}
2874
+		}
2875
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2876
+			array(
2877
+				'EXM_key'   => $meta_key,
2878
+				'EXM_value' => $meta_value,
2879
+				'OBJ_ID'    => $this->ID(),
2880
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2881
+			)
2882
+		);
2883
+		$new_extra_meta->save();
2884
+		return true;
2885
+	}
2886
+
2887
+
2888
+	/**
2889
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2890
+	 * is specified, only deletes extra meta records with that value.
2891
+	 *
2892
+	 * @param string $meta_key
2893
+	 * @param mixed  $meta_value
2894
+	 * @return int number of extra meta rows deleted
2895
+	 * @throws InvalidArgumentException
2896
+	 * @throws InvalidInterfaceException
2897
+	 * @throws InvalidDataTypeException
2898
+	 * @throws EE_Error
2899
+	 * @throws ReflectionException
2900
+	 */
2901
+	public function delete_extra_meta($meta_key, $meta_value = null)
2902
+	{
2903
+		$query_params = array(
2904
+			array(
2905
+				'EXM_key'  => $meta_key,
2906
+				'OBJ_ID'   => $this->ID(),
2907
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2908
+			),
2909
+		);
2910
+		if ($meta_value !== null) {
2911
+			$query_params[0]['EXM_value'] = $meta_value;
2912
+		}
2913
+		return EEM_Extra_Meta::instance()->delete($query_params);
2914
+	}
2915
+
2916
+
2917
+	/**
2918
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2919
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2920
+	 * You can specify $default is case you haven't found the extra meta
2921
+	 *
2922
+	 * @param string  $meta_key
2923
+	 * @param boolean $single
2924
+	 * @param mixed   $default if we don't find anything, what should we return?
2925
+	 * @return mixed single value if $single; array if ! $single
2926
+	 * @throws ReflectionException
2927
+	 * @throws InvalidArgumentException
2928
+	 * @throws InvalidInterfaceException
2929
+	 * @throws InvalidDataTypeException
2930
+	 * @throws EE_Error
2931
+	 */
2932
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2933
+	{
2934
+		if ($single) {
2935
+			$result = $this->get_first_related(
2936
+				'Extra_Meta',
2937
+				array(array('EXM_key' => $meta_key))
2938
+			);
2939
+			if ($result instanceof EE_Extra_Meta) {
2940
+				return $result->value();
2941
+			}
2942
+		} else {
2943
+			$results = $this->get_many_related(
2944
+				'Extra_Meta',
2945
+				array(array('EXM_key' => $meta_key))
2946
+			);
2947
+			if ($results) {
2948
+				$values = array();
2949
+				foreach ($results as $result) {
2950
+					if ($result instanceof EE_Extra_Meta) {
2951
+						$values[ $result->ID() ] = $result->value();
2952
+					}
2953
+				}
2954
+				return $values;
2955
+			}
2956
+		}
2957
+		// if nothing discovered yet return default.
2958
+		return apply_filters(
2959
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2960
+			$default,
2961
+			$meta_key,
2962
+			$single,
2963
+			$this
2964
+		);
2965
+	}
2966
+
2967
+
2968
+	/**
2969
+	 * Returns a simple array of all the extra meta associated with this model object.
2970
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2971
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2972
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2973
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2974
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2975
+	 * finally the extra meta's value as each sub-value. (eg
2976
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2977
+	 *
2978
+	 * @param boolean $one_of_each_key
2979
+	 * @return array
2980
+	 * @throws ReflectionException
2981
+	 * @throws InvalidArgumentException
2982
+	 * @throws InvalidInterfaceException
2983
+	 * @throws InvalidDataTypeException
2984
+	 * @throws EE_Error
2985
+	 */
2986
+	public function all_extra_meta_array($one_of_each_key = true)
2987
+	{
2988
+		$return_array = array();
2989
+		if ($one_of_each_key) {
2990
+			$extra_meta_objs = $this->get_many_related(
2991
+				'Extra_Meta',
2992
+				array('group_by' => 'EXM_key')
2993
+			);
2994
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2995
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2996
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2997
+				}
2998
+			}
2999
+		} else {
3000
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
3001
+			foreach ($extra_meta_objs as $extra_meta_obj) {
3002
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
3003
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
3004
+						$return_array[ $extra_meta_obj->key() ] = array();
3005
+					}
3006
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
3007
+				}
3008
+			}
3009
+		}
3010
+		return $return_array;
3011
+	}
3012
+
3013
+
3014
+	/**
3015
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3016
+	 *
3017
+	 * @return string
3018
+	 * @throws ReflectionException
3019
+	 * @throws InvalidArgumentException
3020
+	 * @throws InvalidInterfaceException
3021
+	 * @throws InvalidDataTypeException
3022
+	 * @throws EE_Error
3023
+	 */
3024
+	public function name()
3025
+	{
3026
+		// find a field that's not a text field
3027
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3028
+		if ($field_we_can_use) {
3029
+			return $this->get($field_we_can_use->get_name());
3030
+		}
3031
+		$first_few_properties = $this->model_field_array();
3032
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3033
+		$name_parts = array();
3034
+		foreach ($first_few_properties as $name => $value) {
3035
+			$name_parts[] = "$name:$value";
3036
+		}
3037
+		return implode(',', $name_parts);
3038
+	}
3039
+
3040
+
3041
+	/**
3042
+	 * in_entity_map
3043
+	 * Checks if this model object has been proven to already be in the entity map
3044
+	 *
3045
+	 * @return boolean
3046
+	 * @throws ReflectionException
3047
+	 * @throws InvalidArgumentException
3048
+	 * @throws InvalidInterfaceException
3049
+	 * @throws InvalidDataTypeException
3050
+	 * @throws EE_Error
3051
+	 */
3052
+	public function in_entity_map()
3053
+	{
3054
+		// well, if we looked, did we find it in the entity map?
3055
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3056
+	}
3057
+
3058
+
3059
+	/**
3060
+	 * refresh_from_db
3061
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3062
+	 *
3063
+	 * @throws ReflectionException
3064
+	 * @throws InvalidArgumentException
3065
+	 * @throws InvalidInterfaceException
3066
+	 * @throws InvalidDataTypeException
3067
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3068
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3069
+	 */
3070
+	public function refresh_from_db()
3071
+	{
3072
+		if ($this->ID() && $this->in_entity_map()) {
3073
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3074
+		} else {
3075
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3076
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3077
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3078
+			// absolutely nothing in it for this ID
3079
+			if (WP_DEBUG) {
3080
+				throw new EE_Error(
3081
+					sprintf(
3082
+						esc_html__(
3083
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3084
+							'event_espresso'
3085
+						),
3086
+						$this->ID(),
3087
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3088
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3089
+					)
3090
+				);
3091
+			}
3092
+		}
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3098
+	 *
3099
+	 * @since 4.9.80.p
3100
+	 * @param EE_Model_Field_Base[] $fields
3101
+	 * @param string $new_value_sql
3102
+	 *      example: 'column_name=123',
3103
+	 *      or 'column_name=column_name+1',
3104
+	 *      or 'column_name= CASE
3105
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3106
+	 *          THEN `column_name` + 5
3107
+	 *          ELSE `column_name`
3108
+	 *      END'
3109
+	 *      Also updates $field on this model object with the latest value from the database.
3110
+	 * @return bool
3111
+	 * @throws EE_Error
3112
+	 * @throws InvalidArgumentException
3113
+	 * @throws InvalidDataTypeException
3114
+	 * @throws InvalidInterfaceException
3115
+	 * @throws ReflectionException
3116
+	 */
3117
+	protected function updateFieldsInDB($fields, $new_value_sql)
3118
+	{
3119
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3120
+		// if it wasn't even there to start off.
3121
+		if (! $this->ID()) {
3122
+			$this->save();
3123
+		}
3124
+		global $wpdb;
3125
+		if (empty($fields)) {
3126
+			throw new InvalidArgumentException(
3127
+				esc_html__(
3128
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3129
+					'event_espresso'
3130
+				)
3131
+			);
3132
+		}
3133
+		$first_field = reset($fields);
3134
+		$table_alias = $first_field->get_table_alias();
3135
+		foreach ($fields as $field) {
3136
+			if ($table_alias !== $field->get_table_alias()) {
3137
+				throw new InvalidArgumentException(
3138
+					sprintf(
3139
+						esc_html__(
3140
+							// @codingStandardsIgnoreStart
3141
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3142
+							// @codingStandardsIgnoreEnd
3143
+							'event_espresso'
3144
+						),
3145
+						$table_alias,
3146
+						$field->get_table_alias()
3147
+					)
3148
+				);
3149
+			}
3150
+		}
3151
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3152
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3153
+		$table_pk_value = $this->ID();
3154
+		$table_name = $table_obj->get_table_name();
3155
+		if ($table_obj instanceof EE_Secondary_Table) {
3156
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3157
+		} else {
3158
+			$table_pk_field_name = $table_obj->get_pk_column();
3159
+		}
3160
+
3161
+		$query =
3162
+			"UPDATE `{$table_name}`
3163 3163
             SET "
3164
-            . $new_value_sql
3165
-            . $wpdb->prepare(
3166
-                "
3164
+			. $new_value_sql
3165
+			. $wpdb->prepare(
3166
+				"
3167 3167
             WHERE `{$table_pk_field_name}` = %d;",
3168
-                $table_pk_value
3169
-            );
3170
-        $result = $wpdb->query($query);
3171
-        foreach ($fields as $field) {
3172
-            // If it was successful, we'd like to know the new value.
3173
-            // If it failed, we'd also like to know the new value.
3174
-            $new_value = $this->get_model()->get_var(
3175
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3176
-                    $this->get_model()->get_index_primary_key_string(
3177
-                        $this->model_field_array()
3178
-                    ),
3179
-                    array(
3180
-                        'default_where_conditions' => 'minimum',
3181
-                    )
3182
-                ),
3183
-                $field->get_name()
3184
-            );
3185
-            $this->set_from_db(
3186
-                $field->get_name(),
3187
-                $new_value
3188
-            );
3189
-        }
3190
-        return (bool) $result;
3191
-    }
3192
-
3193
-
3194
-    /**
3195
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3196
-     * Does not allow negative values, however.
3197
-     *
3198
-     * @since 4.9.80.p
3199
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3200
-     *                                   (positive or negative). One important gotcha: all these values must be
3201
-     *                                   on the same table (eg don't pass in one field for the posts table and
3202
-     *                                   another for the event meta table.)
3203
-     * @return bool
3204
-     * @throws EE_Error
3205
-     * @throws InvalidArgumentException
3206
-     * @throws InvalidDataTypeException
3207
-     * @throws InvalidInterfaceException
3208
-     * @throws ReflectionException
3209
-     */
3210
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3211
-    {
3212
-        global $wpdb;
3213
-        if (empty($fields_n_quantities)) {
3214
-            // No fields to update? Well sure, we updated them to that value just fine.
3215
-            return true;
3216
-        }
3217
-        $fields = [];
3218
-        $set_sql_statements = [];
3219
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3220
-            $field = $this->get_model()->field_settings_for($field_name, true);
3221
-            $fields[] = $field;
3222
-            $column_name = $field->get_table_column();
3223
-
3224
-            $abs_qty = absint($quantity);
3225
-            if ($quantity > 0) {
3226
-                // don't let the value be negative as often these fields are unsigned
3227
-                $set_sql_statements[] = $wpdb->prepare(
3228
-                    "`{$column_name}` = `{$column_name}` + %d",
3229
-                    $abs_qty
3230
-                );
3231
-            } else {
3232
-                $set_sql_statements[] = $wpdb->prepare(
3233
-                    "`{$column_name}` = CASE
3168
+				$table_pk_value
3169
+			);
3170
+		$result = $wpdb->query($query);
3171
+		foreach ($fields as $field) {
3172
+			// If it was successful, we'd like to know the new value.
3173
+			// If it failed, we'd also like to know the new value.
3174
+			$new_value = $this->get_model()->get_var(
3175
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3176
+					$this->get_model()->get_index_primary_key_string(
3177
+						$this->model_field_array()
3178
+					),
3179
+					array(
3180
+						'default_where_conditions' => 'minimum',
3181
+					)
3182
+				),
3183
+				$field->get_name()
3184
+			);
3185
+			$this->set_from_db(
3186
+				$field->get_name(),
3187
+				$new_value
3188
+			);
3189
+		}
3190
+		return (bool) $result;
3191
+	}
3192
+
3193
+
3194
+	/**
3195
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3196
+	 * Does not allow negative values, however.
3197
+	 *
3198
+	 * @since 4.9.80.p
3199
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3200
+	 *                                   (positive or negative). One important gotcha: all these values must be
3201
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3202
+	 *                                   another for the event meta table.)
3203
+	 * @return bool
3204
+	 * @throws EE_Error
3205
+	 * @throws InvalidArgumentException
3206
+	 * @throws InvalidDataTypeException
3207
+	 * @throws InvalidInterfaceException
3208
+	 * @throws ReflectionException
3209
+	 */
3210
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3211
+	{
3212
+		global $wpdb;
3213
+		if (empty($fields_n_quantities)) {
3214
+			// No fields to update? Well sure, we updated them to that value just fine.
3215
+			return true;
3216
+		}
3217
+		$fields = [];
3218
+		$set_sql_statements = [];
3219
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3220
+			$field = $this->get_model()->field_settings_for($field_name, true);
3221
+			$fields[] = $field;
3222
+			$column_name = $field->get_table_column();
3223
+
3224
+			$abs_qty = absint($quantity);
3225
+			if ($quantity > 0) {
3226
+				// don't let the value be negative as often these fields are unsigned
3227
+				$set_sql_statements[] = $wpdb->prepare(
3228
+					"`{$column_name}` = `{$column_name}` + %d",
3229
+					$abs_qty
3230
+				);
3231
+			} else {
3232
+				$set_sql_statements[] = $wpdb->prepare(
3233
+					"`{$column_name}` = CASE
3234 3234
                        WHEN (`{$column_name}` >= %d)
3235 3235
                        THEN `{$column_name}` - %d
3236 3236
                        ELSE 0
3237 3237
                     END",
3238
-                    $abs_qty,
3239
-                    $abs_qty
3240
-                );
3241
-            }
3242
-        }
3243
-        return $this->updateFieldsInDB(
3244
-            $fields,
3245
-            implode(', ', $set_sql_statements)
3246
-        );
3247
-    }
3248
-
3249
-
3250
-    /**
3251
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3252
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3253
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3254
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3255
-     * Otherwise returns false.
3256
-     *
3257
-     * @since 4.9.80.p
3258
-     * @param string $field_name_to_bump
3259
-     * @param string $field_name_affecting_total
3260
-     * @param string $limit_field_name
3261
-     * @param int    $quantity
3262
-     * @return bool
3263
-     * @throws EE_Error
3264
-     * @throws InvalidArgumentException
3265
-     * @throws InvalidDataTypeException
3266
-     * @throws InvalidInterfaceException
3267
-     * @throws ReflectionException
3268
-     */
3269
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3270
-    {
3271
-        global $wpdb;
3272
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3273
-        $column_name = $field->get_table_column();
3274
-
3275
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3276
-        $column_affecting_total = $field_affecting_total->get_table_column();
3277
-
3278
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3279
-        $limiting_column = $limiting_field->get_table_column();
3280
-        return $this->updateFieldsInDB(
3281
-            [$field],
3282
-            $wpdb->prepare(
3283
-                "`{$column_name}` =
3238
+					$abs_qty,
3239
+					$abs_qty
3240
+				);
3241
+			}
3242
+		}
3243
+		return $this->updateFieldsInDB(
3244
+			$fields,
3245
+			implode(', ', $set_sql_statements)
3246
+		);
3247
+	}
3248
+
3249
+
3250
+	/**
3251
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3252
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3253
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3254
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3255
+	 * Otherwise returns false.
3256
+	 *
3257
+	 * @since 4.9.80.p
3258
+	 * @param string $field_name_to_bump
3259
+	 * @param string $field_name_affecting_total
3260
+	 * @param string $limit_field_name
3261
+	 * @param int    $quantity
3262
+	 * @return bool
3263
+	 * @throws EE_Error
3264
+	 * @throws InvalidArgumentException
3265
+	 * @throws InvalidDataTypeException
3266
+	 * @throws InvalidInterfaceException
3267
+	 * @throws ReflectionException
3268
+	 */
3269
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3270
+	{
3271
+		global $wpdb;
3272
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3273
+		$column_name = $field->get_table_column();
3274
+
3275
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3276
+		$column_affecting_total = $field_affecting_total->get_table_column();
3277
+
3278
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3279
+		$limiting_column = $limiting_field->get_table_column();
3280
+		return $this->updateFieldsInDB(
3281
+			[$field],
3282
+			$wpdb->prepare(
3283
+				"`{$column_name}` =
3284 3284
             CASE
3285 3285
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3286 3286
                THEN `{$column_name}` + %d
3287 3287
                ELSE `{$column_name}`
3288 3288
             END",
3289
-                $quantity,
3290
-                EE_INF_IN_DB,
3291
-                $quantity
3292
-            )
3293
-        );
3294
-    }
3295
-
3296
-
3297
-    /**
3298
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3299
-     * (probably a bad assumption they have made, oh well)
3300
-     *
3301
-     * @return string
3302
-     */
3303
-    public function __toString()
3304
-    {
3305
-        try {
3306
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3307
-        } catch (Exception $e) {
3308
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3309
-            return '';
3310
-        }
3311
-    }
3312
-
3313
-
3314
-    /**
3315
-     * Clear related model objects if they're already in the DB, because otherwise when we
3316
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3317
-     * This means if we have made changes to those related model objects, and want to unserialize
3318
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3319
-     * Instead, those related model objects should be directly serialized and stored.
3320
-     * Eg, the following won't work:
3321
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3322
-     * $att = $reg->attendee();
3323
-     * $att->set( 'ATT_fname', 'Dirk' );
3324
-     * update_option( 'my_option', serialize( $reg ) );
3325
-     * //END REQUEST
3326
-     * //START NEXT REQUEST
3327
-     * $reg = get_option( 'my_option' );
3328
-     * $reg->attendee()->save();
3329
-     * And would need to be replace with:
3330
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3331
-     * $att = $reg->attendee();
3332
-     * $att->set( 'ATT_fname', 'Dirk' );
3333
-     * update_option( 'my_option', serialize( $reg ) );
3334
-     * //END REQUEST
3335
-     * //START NEXT REQUEST
3336
-     * $att = get_option( 'my_option' );
3337
-     * $att->save();
3338
-     *
3339
-     * @return array
3340
-     * @throws ReflectionException
3341
-     * @throws InvalidArgumentException
3342
-     * @throws InvalidInterfaceException
3343
-     * @throws InvalidDataTypeException
3344
-     * @throws EE_Error
3345
-     */
3346
-    public function __sleep()
3347
-    {
3348
-        $model = $this->get_model();
3349
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3350
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3351
-                $classname = 'EE_' . $model->get_this_model_name();
3352
-                if (
3353
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3354
-                    && $this->get_one_from_cache($relation_name)->ID()
3355
-                ) {
3356
-                    $this->clear_cache(
3357
-                        $relation_name,
3358
-                        $this->get_one_from_cache($relation_name)->ID()
3359
-                    );
3360
-                }
3361
-            }
3362
-        }
3363
-        $this->_props_n_values_provided_in_constructor = array();
3364
-        $properties_to_serialize = get_object_vars($this);
3365
-        // don't serialize the model. It's big and that risks recursion
3366
-        unset($properties_to_serialize['_model']);
3367
-        return array_keys($properties_to_serialize);
3368
-    }
3369
-
3370
-
3371
-    /**
3372
-     * restore _props_n_values_provided_in_constructor
3373
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3374
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3375
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3376
-     */
3377
-    public function __wakeup()
3378
-    {
3379
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3380
-    }
3381
-
3382
-
3383
-    /**
3384
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3385
-     * distinct with the clone host instance are also cloned.
3386
-     */
3387
-    public function __clone()
3388
-    {
3389
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3390
-        foreach ($this->_fields as $field => $value) {
3391
-            if ($value instanceof DateTime) {
3392
-                $this->_fields[ $field ] = clone $value;
3393
-            }
3394
-        }
3395
-    }
3289
+				$quantity,
3290
+				EE_INF_IN_DB,
3291
+				$quantity
3292
+			)
3293
+		);
3294
+	}
3295
+
3296
+
3297
+	/**
3298
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3299
+	 * (probably a bad assumption they have made, oh well)
3300
+	 *
3301
+	 * @return string
3302
+	 */
3303
+	public function __toString()
3304
+	{
3305
+		try {
3306
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3307
+		} catch (Exception $e) {
3308
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3309
+			return '';
3310
+		}
3311
+	}
3312
+
3313
+
3314
+	/**
3315
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3316
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3317
+	 * This means if we have made changes to those related model objects, and want to unserialize
3318
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3319
+	 * Instead, those related model objects should be directly serialized and stored.
3320
+	 * Eg, the following won't work:
3321
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3322
+	 * $att = $reg->attendee();
3323
+	 * $att->set( 'ATT_fname', 'Dirk' );
3324
+	 * update_option( 'my_option', serialize( $reg ) );
3325
+	 * //END REQUEST
3326
+	 * //START NEXT REQUEST
3327
+	 * $reg = get_option( 'my_option' );
3328
+	 * $reg->attendee()->save();
3329
+	 * And would need to be replace with:
3330
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3331
+	 * $att = $reg->attendee();
3332
+	 * $att->set( 'ATT_fname', 'Dirk' );
3333
+	 * update_option( 'my_option', serialize( $reg ) );
3334
+	 * //END REQUEST
3335
+	 * //START NEXT REQUEST
3336
+	 * $att = get_option( 'my_option' );
3337
+	 * $att->save();
3338
+	 *
3339
+	 * @return array
3340
+	 * @throws ReflectionException
3341
+	 * @throws InvalidArgumentException
3342
+	 * @throws InvalidInterfaceException
3343
+	 * @throws InvalidDataTypeException
3344
+	 * @throws EE_Error
3345
+	 */
3346
+	public function __sleep()
3347
+	{
3348
+		$model = $this->get_model();
3349
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3350
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3351
+				$classname = 'EE_' . $model->get_this_model_name();
3352
+				if (
3353
+					$this->get_one_from_cache($relation_name) instanceof $classname
3354
+					&& $this->get_one_from_cache($relation_name)->ID()
3355
+				) {
3356
+					$this->clear_cache(
3357
+						$relation_name,
3358
+						$this->get_one_from_cache($relation_name)->ID()
3359
+					);
3360
+				}
3361
+			}
3362
+		}
3363
+		$this->_props_n_values_provided_in_constructor = array();
3364
+		$properties_to_serialize = get_object_vars($this);
3365
+		// don't serialize the model. It's big and that risks recursion
3366
+		unset($properties_to_serialize['_model']);
3367
+		return array_keys($properties_to_serialize);
3368
+	}
3369
+
3370
+
3371
+	/**
3372
+	 * restore _props_n_values_provided_in_constructor
3373
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3374
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3375
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3376
+	 */
3377
+	public function __wakeup()
3378
+	{
3379
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3380
+	}
3381
+
3382
+
3383
+	/**
3384
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3385
+	 * distinct with the clone host instance are also cloned.
3386
+	 */
3387
+	public function __clone()
3388
+	{
3389
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3390
+		foreach ($this->_fields as $field => $value) {
3391
+			if ($value instanceof DateTime) {
3392
+				$this->_fields[ $field ] = clone $value;
3393
+			}
3394
+		}
3395
+	}
3396 3396
 }
Please login to merge, or discard this patch.
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147 147
         // verify client code has not passed any invalid field names
148 148
         foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
149
+            if ( ! isset($model_fields[$field_name])) {
150 150
                 throw new EE_Error(
151 151
                     sprintf(
152 152
                         esc_html__(
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
             }
162 162
         }
163 163
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
164
+        if ( ! empty($date_formats) && is_array($date_formats)) {
165 165
             [$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166 166
         } else {
167 167
             // set default formats for date and time
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             foreach ($model_fields as $fieldName => $field) {
175 175
                 $this->set_from_db(
176 176
                     $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
177
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
178 178
                 );
179 179
             }
180 180
         } else {
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             foreach ($model_fields as $fieldName => $field) {
184 184
                 $this->set(
185 185
                     $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
186
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null,
187 187
                     true
188 188
                 );
189 189
             }
@@ -191,15 +191,15 @@  discard block
 block discarded – undo
191 191
         // remember what values were passed to this constructor
192 192
         $this->_props_n_values_provided_in_constructor = $fieldValues;
193 193
         // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
194
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
195 195
             $model->add_to_entity_map($this);
196 196
         }
197 197
         // setup all the relations
198 198
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199 199
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
200
+                $this->_model_relations[$relation_name] = null;
201 201
             } else {
202
-                $this->_model_relations[ $relation_name ] = array();
202
+                $this->_model_relations[$relation_name] = array();
203 203
             }
204 204
         }
205 205
         /**
@@ -251,10 +251,10 @@  discard block
 block discarded – undo
251 251
     public function get_original($field_name)
252 252
     {
253 253
         if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
255 255
             && $field_settings = $this->get_model()->field_settings_for($field_name)
256 256
         ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258 258
         }
259 259
         return null;
260 260
     }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         // then don't do anything
292 292
         if (
293 293
             ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
294
+            && $this->_fields[$field_name] === $field_value
295 295
             && $this->ID()
296 296
         ) {
297 297
             return;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             $holder_of_value = $field_obj->prepare_for_set($field_value);
310 310
             // should the value be null?
311 311
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
312
+                $this->_fields[$field_name] = $field_obj->get_default_value();
313 313
                 /**
314 314
                  * To save having to refactor all the models, if a default value is used for a
315 315
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -320,15 +320,15 @@  discard block
 block discarded – undo
320 320
                  */
321 321
                 if (
322 322
                     $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
323
+                    && $this->_fields[$field_name] !== null
324
+                    && ! $this->_fields[$field_name] instanceof DateTime
325 325
                 ) {
326
-                    empty($this->_fields[ $field_name ])
326
+                    empty($this->_fields[$field_name])
327 327
                         ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
328
+                        : $this->set($field_name, $this->_fields[$field_name]);
329 329
                 }
330 330
             } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
331
+                $this->_fields[$field_name] = $holder_of_value;
332 332
             }
333 333
             // if we're not in the constructor...
334 334
             // now check if what we set was a primary key
@@ -391,8 +391,8 @@  discard block
 block discarded – undo
391 391
      */
392 392
     public function getCustomSelect($alias)
393 393
     {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
394
+        return isset($this->custom_selection_results[$alias])
395
+            ? $this->custom_selection_results[$alias]
396 396
             : null;
397 397
     }
398 398
 
@@ -479,8 +479,8 @@  discard block
 block discarded – undo
479 479
         foreach ($model_fields as $field_name => $field_obj) {
480 480
             if ($field_obj instanceof EE_Datetime_Field) {
481 481
                 $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
482
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
483
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
484 484
                 }
485 485
             }
486 486
         }
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
      */
539 539
     public function get_format($full = true)
540 540
     {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
541
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542 542
     }
543 543
 
544 544
 
@@ -564,11 +564,11 @@  discard block
 block discarded – undo
564 564
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565 565
     {
566 566
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
567
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
568 568
             return false;
569 569
         }
570 570
         // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
571
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572 572
             throw new EE_Error(
573 573
                 sprintf(
574 574
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -582,38 +582,38 @@  discard block
 block discarded – undo
582 582
             // if it's a "belongs to" relationship, then there's only one related model object
583 583
             // eg, if this is a registration, there's only 1 attendee for it
584 584
             // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
585
+            $this->_model_relations[$relationName] = $object_to_cache;
586 586
             $return = true;
587 587
         } else {
588 588
             // otherwise, this is the "many" side of a one to many relationship,
589 589
             // so we'll add the object to the array of related objects for that type.
590 590
             // eg: if this is an event, there are many registrations for that event,
591 591
             // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
592
+            if ( ! is_array($this->_model_relations[$relationName])) {
593 593
                 // if for some reason, the cached item is a model object,
594 594
                 // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
595
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
596 596
                                                            instanceof
597 597
                                                            EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
598
+                    ? array($this->_model_relations[$relationName]) : array();
599 599
             }
600 600
             // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
601
+            if ( ! empty($cache_id)) {
602 602
                 // if the cache_id exists, then it means we are purposely trying to cache this
603 603
                 // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
604
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
605 605
                 $return = $cache_id;
606 606
             } elseif ($object_to_cache->ID()) {
607 607
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
608
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
609 609
                 $return = $object_to_cache->ID();
610 610
             } else {
611 611
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
612
+                $this->_model_relations[$relationName][] = $object_to_cache;
613 613
                 // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
614
+                end($this->_model_relations[$relationName]);
615 615
                 // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
616
+                $return = key($this->_model_relations[$relationName]);
617 617
             }
618 618
         }
619 619
         return $return;
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
         // first make sure this property exists
640 640
         $this->get_model()->field_settings_for($fieldname);
641 641
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
642
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
643 643
     }
644 644
 
645 645
 
@@ -668,9 +668,9 @@  discard block
 block discarded – undo
668 668
         $model = $this->get_model();
669 669
         $model->field_settings_for($fieldname);
670 670
         $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
671
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
672
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
673
+            return $this->_cached_properties[$fieldname][$cache_type];
674 674
         }
675 675
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676 676
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -698,12 +698,12 @@  discard block
 block discarded – undo
698 698
         if ($field_obj instanceof EE_Datetime_Field) {
699 699
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700 700
         }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
701
+        if ( ! isset($this->_fields[$fieldname])) {
702
+            $this->_fields[$fieldname] = null;
703 703
         }
704 704
         return $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
705
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
706
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
707 707
     }
708 708
 
709 709
 
@@ -759,8 +759,8 @@  discard block
 block discarded – undo
759 759
      */
760 760
     protected function _clear_cached_property($property_name)
761 761
     {
762
-        if (isset($this->_cached_properties[ $property_name ])) {
763
-            unset($this->_cached_properties[ $property_name ]);
762
+        if (isset($this->_cached_properties[$property_name])) {
763
+            unset($this->_cached_properties[$property_name]);
764 764
         }
765 765
     }
766 766
 
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
     {
813 813
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
814 814
         $index_in_cache = '';
815
-        if (! $relationship_to_model) {
815
+        if ( ! $relationship_to_model) {
816 816
             throw new EE_Error(
817 817
                 sprintf(
818 818
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -823,10 +823,10 @@  discard block
 block discarded – undo
823 823
         }
824 824
         if ($clear_all) {
825 825
             $obj_removed = true;
826
-            $this->_model_relations[ $relationName ] = null;
826
+            $this->_model_relations[$relationName] = null;
827 827
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
-            $obj_removed = $this->_model_relations[ $relationName ];
829
-            $this->_model_relations[ $relationName ] = null;
828
+            $obj_removed = $this->_model_relations[$relationName];
829
+            $this->_model_relations[$relationName] = null;
830 830
         } else {
831 831
             if (
832 832
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -834,12 +834,12 @@  discard block
 block discarded – undo
834 834
             ) {
835 835
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
836 836
                 if (
837
-                    is_array($this->_model_relations[ $relationName ])
838
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
837
+                    is_array($this->_model_relations[$relationName])
838
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
839 839
                 ) {
840 840
                     $index_found_at = null;
841 841
                     // find this object in the array even though it has a different key
842
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
842
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
843 843
                         /** @noinspection TypeUnsafeComparisonInspection */
844 844
                         if (
845 845
                             $obj instanceof EE_Base_Class
@@ -873,9 +873,9 @@  discard block
 block discarded – undo
873 873
             }
874 874
             // supposedly we've found it. But it could just be that the client code
875 875
             // provided a bad index/object
876
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
876
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
877
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
878
+                unset($this->_model_relations[$relationName][$index_in_cache]);
879 879
             } else {
880 880
                 // that thing was never cached anyways.
881 881
                 $obj_removed = null;
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
         $current_cache_id = ''
907 907
     ) {
908 908
         // verify that incoming object is of the correct type
909
-        $obj_class = 'EE_' . $relationName;
909
+        $obj_class = 'EE_'.$relationName;
910 910
         if ($newly_saved_object instanceof $obj_class) {
911 911
             /* @type EE_Base_Class $newly_saved_object */
912 912
             // now get the type of relation
@@ -914,18 +914,18 @@  discard block
 block discarded – undo
914 914
             // if this is a 1:1 relationship
915 915
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916 916
                 // then just replace the cached object with the newly saved object
917
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
917
+                $this->_model_relations[$relationName] = $newly_saved_object;
918 918
                 return true;
919 919
                 // or if it's some kind of sordid feral polyamorous relationship...
920 920
             }
921 921
             if (
922
-                is_array($this->_model_relations[ $relationName ])
923
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
922
+                is_array($this->_model_relations[$relationName])
923
+                && isset($this->_model_relations[$relationName][$current_cache_id])
924 924
             ) {
925 925
                 // then remove the current cached item
926
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
926
+                unset($this->_model_relations[$relationName][$current_cache_id]);
927 927
                 // and cache the newly saved object using it's new ID
928
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
928
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
929 929
                 return true;
930 930
             }
931 931
         }
@@ -942,8 +942,8 @@  discard block
 block discarded – undo
942 942
      */
943 943
     public function get_one_from_cache($relationName)
944 944
     {
945
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
-            ? $this->_model_relations[ $relationName ]
945
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
946
+            ? $this->_model_relations[$relationName]
947 947
             : null;
948 948
         if (is_array($cached_array_or_object)) {
949 949
             return array_shift($cached_array_or_object);
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
      */
967 967
     public function get_all_from_cache($relationName)
968 968
     {
969
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
969
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
970 970
         // if the result is not an array, but exists, make it an array
971 971
         $objects = is_array($objects) ? $objects : array($objects);
972 972
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1150,7 +1150,7 @@  discard block
 block discarded – undo
1150 1150
             } else {
1151 1151
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152 1152
             }
1153
-            $this->_fields[ $field_name ] = $field_value;
1153
+            $this->_fields[$field_name] = $field_value;
1154 1154
             $this->_clear_cached_property($field_name);
1155 1155
         }
1156 1156
     }
@@ -1190,9 +1190,9 @@  discard block
 block discarded – undo
1190 1190
     public function get_raw($field_name)
1191 1191
     {
1192 1192
         $field_settings = $this->get_model()->field_settings_for($field_name);
1193
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
-            ? $this->_fields[ $field_name ]->format('U')
1195
-            : $this->_fields[ $field_name ];
1193
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1194
+            ? $this->_fields[$field_name]->format('U')
1195
+            : $this->_fields[$field_name];
1196 1196
     }
1197 1197
 
1198 1198
 
@@ -1214,7 +1214,7 @@  discard block
 block discarded – undo
1214 1214
     public function get_DateTime_object($field_name)
1215 1215
     {
1216 1216
         $field_settings = $this->get_model()->field_settings_for($field_name);
1217
-        if (! $field_settings instanceof EE_Datetime_Field) {
1217
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1218 1218
             EE_Error::add_error(
1219 1219
                 sprintf(
1220 1220
                     esc_html__(
@@ -1229,8 +1229,8 @@  discard block
 block discarded – undo
1229 1229
             );
1230 1230
             return false;
1231 1231
         }
1232
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
-            ? clone $this->_fields[ $field_name ]
1232
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1233
+            ? clone $this->_fields[$field_name]
1234 1234
             : null;
1235 1235
     }
1236 1236
 
@@ -1474,7 +1474,7 @@  discard block
 block discarded – undo
1474 1474
      */
1475 1475
     public function get_i18n_datetime($field_name, $format = '')
1476 1476
     {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1477
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1478 1478
         return date_i18n(
1479 1479
             $format,
1480 1480
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1586,21 +1586,21 @@  discard block
 block discarded – undo
1586 1586
         $field->set_time_format($this->_tm_frmt);
1587 1587
         switch ($what) {
1588 1588
             case 'T':
1589
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1589
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1590 1590
                     $datetime_value,
1591
-                    $this->_fields[ $field_name ]
1591
+                    $this->_fields[$field_name]
1592 1592
                 );
1593 1593
                 $this->_has_changes = true;
1594 1594
                 break;
1595 1595
             case 'D':
1596
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1596
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1597 1597
                     $datetime_value,
1598
-                    $this->_fields[ $field_name ]
1598
+                    $this->_fields[$field_name]
1599 1599
                 );
1600 1600
                 $this->_has_changes = true;
1601 1601
                 break;
1602 1602
             case 'B':
1603
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1603
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1604 1604
                 $this->_has_changes = true;
1605 1605
                 break;
1606 1606
         }
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
         $this->set_timezone($timezone);
1644 1644
         $fn = (array) $field_name;
1645 1645
         $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1646
+        if ( ! method_exists($this, $callback)) {
1647 1647
             throw new EE_Error(
1648 1648
                 sprintf(
1649 1649
                     esc_html__(
@@ -1655,7 +1655,7 @@  discard block
 block discarded – undo
1655 1655
             );
1656 1656
         }
1657 1657
         $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1658
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1659 1659
         $this->set_timezone($original_timezone);
1660 1660
         return $return;
1661 1661
     }
@@ -1770,8 +1770,8 @@  discard block
 block discarded – undo
1770 1770
     {
1771 1771
         $model = $this->get_model();
1772 1772
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1773
+            if ( ! empty($this->_model_relations[$relation_name])) {
1774
+                $related_objects = $this->_model_relations[$relation_name];
1775 1775
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776 1776
                     // this relation only stores a single model object, not an array
1777 1777
                     // but let's make it consistent
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
             $this->set($column, $value);
1831 1831
         }
1832 1832
         // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1833
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834 1834
             return 0;
1835 1835
         }
1836 1836
         /**
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
          * @param EE_Base_Class $model_object the model object about to be saved.
1841 1841
          */
1842 1842
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1843
+        if ( ! $this->allow_persist()) {
1844 1844
             return 0;
1845 1845
         }
1846 1846
         // now get current attribute values
@@ -1855,10 +1855,10 @@  discard block
 block discarded – undo
1855 1855
         if ($model->has_primary_key_field()) {
1856 1856
             if ($model->get_primary_key_field()->is_auto_increment()) {
1857 1857
                 // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1858
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1859 1859
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860 1860
                 } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1861
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1862 1862
                     $results = $model->insert($save_cols_n_values);
1863 1863
                     if ($results) {
1864 1864
                         // if successful, set the primary key
@@ -1868,7 +1868,7 @@  discard block
 block discarded – undo
1868 1868
                         // will get added to the mapper before we can add this one!
1869 1869
                         // but if we just avoid using the SET method, all that headache can be avoided
1870 1870
                         $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1871
+                        $this->_fields[$pk_field_name] = $results;
1872 1872
                         $this->_clear_cached_property($pk_field_name);
1873 1873
                         $model->add_to_entity_map($this);
1874 1874
                         $this->_update_cached_related_model_objs_fks();
@@ -1885,8 +1885,8 @@  discard block
 block discarded – undo
1885 1885
                                     'event_espresso'
1886 1886
                                 ),
1887 1887
                                 get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1888
+                                get_class($model).'::instance()->add_to_entity_map()',
1889
+                                get_class($model).'::instance()->get_one_by_ID()',
1890 1890
                                 '<br />'
1891 1891
                             )
1892 1892
                         );
@@ -1988,27 +1988,27 @@  discard block
 block discarded – undo
1988 1988
     public function save_new_cached_related_model_objs()
1989 1989
     {
1990 1990
         // make sure this has been saved
1991
-        if (! $this->ID()) {
1991
+        if ( ! $this->ID()) {
1992 1992
             $id = $this->save();
1993 1993
         } else {
1994 1994
             $id = $this->ID();
1995 1995
         }
1996 1996
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997 1997
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1998
+            if ($this->_model_relations[$relationName]) {
1999 1999
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000 2000
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001 2001
                 /* @var $related_model_obj EE_Base_Class */
2002 2002
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2003 2003
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2004 2004
                     // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2005
+                    $related_model_obj = $this->_model_relations[$relationName];
2006 2006
                     // if( ! $related_model_obj->ID()){
2007 2007
                     $this->_add_relation_to($related_model_obj, $relationName);
2008 2008
                     $related_model_obj->save_new_cached_related_model_objs();
2009 2009
                     // }
2010 2010
                 } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2011
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2012 2012
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2013 2013
                         // but ONLY if it DOES NOT exist in the DB
2014 2014
                         // if( ! $related_model_obj->ID()){
@@ -2035,7 +2035,7 @@  discard block
 block discarded – undo
2035 2035
      */
2036 2036
     public function get_model()
2037 2037
     {
2038
-        if (! $this->_model) {
2038
+        if ( ! $this->_model) {
2039 2039
             $modelName = self::_get_model_classname(get_class($this));
2040 2040
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041 2041
         } else {
@@ -2061,9 +2061,9 @@  discard block
 block discarded – undo
2061 2061
         $primary_id_ref = self::_get_primary_key_name($classname);
2062 2062
         if (
2063 2063
             array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2064
+            && ! empty($props_n_values[$primary_id_ref])
2065 2065
         ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2066
+            $id = $props_n_values[$primary_id_ref];
2067 2067
             return self::_get_model($classname)->get_from_entity_map($id);
2068 2068
         }
2069 2069
         return false;
@@ -2098,10 +2098,10 @@  discard block
 block discarded – undo
2098 2098
             $primary_id_ref = self::_get_primary_key_name($classname);
2099 2099
             if (
2100 2100
                 array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2101
+                && ! empty($props_n_values[$primary_id_ref])
2102 2102
             ) {
2103 2103
                 $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2104
+                    $props_n_values[$primary_id_ref]
2105 2105
                 );
2106 2106
             }
2107 2107
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2113,7 +2113,7 @@  discard block
 block discarded – undo
2113 2113
         }
2114 2114
         if ($existing) {
2115 2115
             // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2116
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2117 2117
                 $existing->set_date_format($date_formats[0]);
2118 2118
                 $existing->set_time_format($date_formats[1]);
2119 2119
             } else {
@@ -2146,7 +2146,7 @@  discard block
 block discarded – undo
2146 2146
     protected static function _get_model($classname, $timezone = null)
2147 2147
     {
2148 2148
         // find model for this class
2149
-        if (! $classname) {
2149
+        if ( ! $classname) {
2150 2150
             throw new EE_Error(
2151 2151
                 sprintf(
2152 2152
                     esc_html__(
@@ -2195,7 +2195,7 @@  discard block
 block discarded – undo
2195 2195
         if (strpos($model_name, 'EE_') === 0) {
2196 2196
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
2197 2197
         } else {
2198
-            $model_classname = 'EEM_' . $model_name;
2198
+            $model_classname = 'EEM_'.$model_name;
2199 2199
         }
2200 2200
         return $model_classname;
2201 2201
     }
@@ -2214,7 +2214,7 @@  discard block
 block discarded – undo
2214 2214
      */
2215 2215
     protected static function _get_primary_key_name($classname = null)
2216 2216
     {
2217
-        if (! $classname) {
2217
+        if ( ! $classname) {
2218 2218
             throw new EE_Error(
2219 2219
                 sprintf(
2220 2220
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2244,7 +2244,7 @@  discard block
 block discarded – undo
2244 2244
         $model = $this->get_model();
2245 2245
         // now that we know the name of the variable, use a variable variable to get its value and return its
2246 2246
         if ($model->has_primary_key_field()) {
2247
-            return $this->_fields[ $model->primary_key_name() ];
2247
+            return $this->_fields[$model->primary_key_name()];
2248 2248
         }
2249 2249
         return $model->get_index_primary_key_string($this->_fields);
2250 2250
     }
@@ -2318,7 +2318,7 @@  discard block
 block discarded – undo
2318 2318
             }
2319 2319
         } else {
2320 2320
             // this thing doesn't exist in the DB,  so just cache it
2321
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2322 2322
                 throw new EE_Error(
2323 2323
                     sprintf(
2324 2324
                         esc_html__(
@@ -2483,7 +2483,7 @@  discard block
 block discarded – undo
2483 2483
             } else {
2484 2484
                 // did we already cache the result of this query?
2485 2485
                 $cached_results = $this->get_all_from_cache($relationName);
2486
-                if (! $cached_results) {
2486
+                if ( ! $cached_results) {
2487 2487
                     $related_model_objects = $this->get_model()->get_all_related(
2488 2488
                         $this,
2489 2489
                         $relationName,
@@ -2594,7 +2594,7 @@  discard block
 block discarded – undo
2594 2594
             } else {
2595 2595
                 // first, check if we've already cached the result of this query
2596 2596
                 $cached_result = $this->get_one_from_cache($relationName);
2597
-                if (! $cached_result) {
2597
+                if ( ! $cached_result) {
2598 2598
                     $related_model_object = $model->get_first_related(
2599 2599
                         $this,
2600 2600
                         $relationName,
@@ -2618,7 +2618,7 @@  discard block
 block discarded – undo
2618 2618
             }
2619 2619
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2620 2620
             // just get what's cached on this object
2621
-            if (! $related_model_object) {
2621
+            if ( ! $related_model_object) {
2622 2622
                 $related_model_object = $this->get_one_from_cache($relationName);
2623 2623
             }
2624 2624
         }
@@ -2700,7 +2700,7 @@  discard block
 block discarded – undo
2700 2700
      */
2701 2701
     public function is_set($field_name)
2702 2702
     {
2703
-        return isset($this->_fields[ $field_name ]);
2703
+        return isset($this->_fields[$field_name]);
2704 2704
     }
2705 2705
 
2706 2706
 
@@ -2716,7 +2716,7 @@  discard block
 block discarded – undo
2716 2716
     {
2717 2717
         foreach ((array) $properties as $property_name) {
2718 2718
             // first make sure this property exists
2719
-            if (! $this->_fields[ $property_name ]) {
2719
+            if ( ! $this->_fields[$property_name]) {
2720 2720
                 throw new EE_Error(
2721 2721
                     sprintf(
2722 2722
                         esc_html__(
@@ -2748,7 +2748,7 @@  discard block
 block discarded – undo
2748 2748
         $properties = array();
2749 2749
         // remove prepended underscore
2750 2750
         foreach ($fields as $field_name => $settings) {
2751
-            $properties[ $field_name ] = $this->get($field_name);
2751
+            $properties[$field_name] = $this->get($field_name);
2752 2752
         }
2753 2753
         return $properties;
2754 2754
     }
@@ -2785,7 +2785,7 @@  discard block
 block discarded – undo
2785 2785
     {
2786 2786
         $className = get_class($this);
2787 2787
         $tagName = "FHEE__{$className}__{$methodName}";
2788
-        if (! has_filter($tagName)) {
2788
+        if ( ! has_filter($tagName)) {
2789 2789
             throw new EE_Error(
2790 2790
                 sprintf(
2791 2791
                     esc_html__(
@@ -2830,7 +2830,7 @@  discard block
 block discarded – undo
2830 2830
             $query_params[0]['EXM_value'] = $meta_value;
2831 2831
         }
2832 2832
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2833
-        if (! $existing_rows_like_that) {
2833
+        if ( ! $existing_rows_like_that) {
2834 2834
             return $this->add_extra_meta($meta_key, $meta_value);
2835 2835
         }
2836 2836
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2948,7 +2948,7 @@  discard block
 block discarded – undo
2948 2948
                 $values = array();
2949 2949
                 foreach ($results as $result) {
2950 2950
                     if ($result instanceof EE_Extra_Meta) {
2951
-                        $values[ $result->ID() ] = $result->value();
2951
+                        $values[$result->ID()] = $result->value();
2952 2952
                     }
2953 2953
                 }
2954 2954
                 return $values;
@@ -2993,17 +2993,17 @@  discard block
 block discarded – undo
2993 2993
             );
2994 2994
             foreach ($extra_meta_objs as $extra_meta_obj) {
2995 2995
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2996
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2996
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2997 2997
                 }
2998 2998
             }
2999 2999
         } else {
3000 3000
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
3001 3001
             foreach ($extra_meta_objs as $extra_meta_obj) {
3002 3002
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
3003
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
3004
-                        $return_array[ $extra_meta_obj->key() ] = array();
3003
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
3004
+                        $return_array[$extra_meta_obj->key()] = array();
3005 3005
                     }
3006
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
3006
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
3007 3007
                 }
3008 3008
             }
3009 3009
         }
@@ -3084,8 +3084,8 @@  discard block
 block discarded – undo
3084 3084
                             'event_espresso'
3085 3085
                         ),
3086 3086
                         $this->ID(),
3087
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3088
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3087
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3088
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3089 3089
                     )
3090 3090
                 );
3091 3091
             }
@@ -3118,7 +3118,7 @@  discard block
 block discarded – undo
3118 3118
     {
3119 3119
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3120 3120
         // if it wasn't even there to start off.
3121
-        if (! $this->ID()) {
3121
+        if ( ! $this->ID()) {
3122 3122
             $this->save();
3123 3123
         }
3124 3124
         global $wpdb;
@@ -3348,7 +3348,7 @@  discard block
 block discarded – undo
3348 3348
         $model = $this->get_model();
3349 3349
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3350 3350
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3351
-                $classname = 'EE_' . $model->get_this_model_name();
3351
+                $classname = 'EE_'.$model->get_this_model_name();
3352 3352
                 if (
3353 3353
                     $this->get_one_from_cache($relation_name) instanceof $classname
3354 3354
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3389,7 +3389,7 @@  discard block
 block discarded – undo
3389 3389
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3390 3390
         foreach ($this->_fields as $field => $value) {
3391 3391
             if ($value instanceof DateTime) {
3392
-                $this->_fields[ $field ] = clone $value;
3392
+                $this->_fields[$field] = clone $value;
3393 3393
             }
3394 3394
         }
3395 3395
     }
Please login to merge, or discard this patch.